blob: fb65dd822b0aabcfda14705e6ba49b45797ff98b [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000034#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000035#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner58258242008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattnerb0d38442008-04-12 23:52:44 +000043namespace {
44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
45 /// the default argument of a parameter to determine whether it
46 /// contains any ill-formed subexpressions. For example, this will
47 /// diagnose the use of local variables or parameters within the
48 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000053
Chris Lattnerb0d38442008-04-12 23:52:44 +000054 public:
Mike Stump11289f42009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000057
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 };
Chris Lattner58258242008-04-10 02:22:51 +000062
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 /// VisitExpr - Visit all of the children of this expression.
64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
65 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000066 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000067 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000068 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000069 }
70
Chris Lattnerb0d38442008-04-12 23:52:44 +000071 /// VisitDeclRefExpr - Visit a reference to a declaration, to
72 /// determine whether this declaration can be used in the default
73 /// argument expression.
74 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000075 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000076 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
77 // C++ [dcl.fct.default]p9
78 // Default arguments are evaluated each time the function is
79 // called. The order of evaluation of function arguments is
80 // unspecified. Consequently, parameters of a function shall not
81 // be used in default argument expressions, even if they are not
82 // evaluated. Parameters of a function declared before a default
83 // argument expression are in scope and can hide namespace and
84 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000085 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000086 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000087 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000088 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000089 // C++ [dcl.fct.default]p7
90 // Local variables shall not be used in default argument
91 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000092 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000093 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000094 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000095 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000096 }
Chris Lattner58258242008-04-10 02:22:51 +000097
Douglas Gregor8e12c382008-11-04 13:41:56 +000098 return false;
99 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000100
Douglas Gregor97a9c812008-11-04 14:32:21 +0000101 /// VisitCXXThisExpr - Visit a C++ "this" expression.
102 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
103 // C++ [dcl.fct.default]p8:
104 // The keyword this shall not be used in a default argument of a
105 // member function.
106 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000107 diag::err_param_default_argument_references_this)
108 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000109 }
Chris Lattner58258242008-04-10 02:22:51 +0000110}
111
Anders Carlssonc80a1272009-08-25 02:29:20 +0000112bool
John McCallb268a282010-08-23 23:25:46 +0000113Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000114 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000115 if (RequireCompleteType(Param->getLocation(), Param->getType(),
116 diag::err_typecheck_decl_incomplete_type)) {
117 Param->setInvalidDecl();
118 return true;
119 }
120
Anders Carlssonc80a1272009-08-25 02:29:20 +0000121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000127 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
128 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000129 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
130 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000131 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000132 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000133 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000134 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000135 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000136 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000137
John McCallacf0ee52010-10-08 02:01:28 +0000138 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000139 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000140
Anders Carlssonc80a1272009-08-25 02:29:20 +0000141 // Okay: add the default argument to the parameter
142 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000143
Douglas Gregor758cb672010-10-12 18:23:32 +0000144 // We have already instantiated this parameter; provide each of the
145 // instantiations with the uninstantiated default argument.
146 UnparsedDefaultArgInstantiationsMap::iterator InstPos
147 = UnparsedDefaultArgInstantiations.find(Param);
148 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
149 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
150 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
151
152 // We're done tracking this parameter's instantiations.
153 UnparsedDefaultArgInstantiations.erase(InstPos);
154 }
155
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000156 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000157}
158
Chris Lattner58258242008-04-10 02:22:51 +0000159/// ActOnParamDefaultArgument - Check whether the default argument
160/// provided for a function parameter is well-formed. If so, attach it
161/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000162void
John McCall48871652010-08-21 09:40:31 +0000163Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000164 Expr *DefaultArg) {
165 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000166 return;
Mike Stump11289f42009-09-09 15:08:12 +0000167
John McCall48871652010-08-21 09:40:31 +0000168 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000169 UnparsedDefaultArgLocs.erase(Param);
170
Chris Lattner199abbc2008-04-08 05:04:30 +0000171 // Default arguments are only permitted in C++
172 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000173 Diag(EqualLoc, diag::err_param_default_argument)
174 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000175 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000176 return;
177 }
178
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000179 // Check for unexpanded parameter packs.
180 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
181 Param->setInvalidDecl();
182 return;
183 }
184
Anders Carlssonf1c26952009-08-25 01:02:06 +0000185 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000186 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
187 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000188 Param->setInvalidDecl();
189 return;
190 }
Mike Stump11289f42009-09-09 15:08:12 +0000191
John McCallb268a282010-08-23 23:25:46 +0000192 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000193}
194
Douglas Gregor58354032008-12-24 00:01:03 +0000195/// ActOnParamUnparsedDefaultArgument - We've seen a default
196/// argument for a function parameter, but we can't parse it yet
197/// because we're inside a class definition. Note that this default
198/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000199void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000200 SourceLocation EqualLoc,
201 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000202 if (!param)
203 return;
Mike Stump11289f42009-09-09 15:08:12 +0000204
John McCall48871652010-08-21 09:40:31 +0000205 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000206 if (Param)
207 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000208
Anders Carlsson84613c42009-06-12 16:51:40 +0000209 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000210}
211
Douglas Gregor4d87df52008-12-16 21:30:33 +0000212/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
213/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000214void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000215 if (!param)
216 return;
Mike Stump11289f42009-09-09 15:08:12 +0000217
John McCall48871652010-08-21 09:40:31 +0000218 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000219
Anders Carlsson84613c42009-06-12 16:51:40 +0000220 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000221
Anders Carlsson84613c42009-06-12 16:51:40 +0000222 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000223}
224
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000225/// CheckExtraCXXDefaultArguments - Check for any extra default
226/// arguments in the declarator, which is not a function declaration
227/// or definition and therefore is not permitted to have default
228/// arguments. This routine should be invoked for every declarator
229/// that is not a function declaration or definition.
230void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
231 // C++ [dcl.fct.default]p3
232 // A default argument expression shall be specified only in the
233 // parameter-declaration-clause of a function declaration or in a
234 // template-parameter (14.1). It shall not be specified for a
235 // parameter pack. If it is specified in a
236 // parameter-declaration-clause, it shall not occur within a
237 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000238 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000239 DeclaratorChunk &chunk = D.getTypeObject(i);
240 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000241 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
242 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000243 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000244 if (Param->hasUnparsedDefaultArg()) {
245 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000246 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
247 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
248 delete Toks;
249 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000250 } else if (Param->getDefaultArg()) {
251 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
252 << Param->getDefaultArg()->getSourceRange();
253 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000254 }
255 }
256 }
257 }
258}
259
Chris Lattner199abbc2008-04-08 05:04:30 +0000260// MergeCXXFunctionDecl - Merge two declarations of the same C++
261// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000262// type. Subroutine of MergeFunctionDecl. Returns true if there was an
263// error, false otherwise.
264bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
265 bool Invalid = false;
266
Chris Lattner199abbc2008-04-08 05:04:30 +0000267 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000268 // For non-template functions, default arguments can be added in
269 // later declarations of a function in the same
270 // scope. Declarations in different scopes have completely
271 // distinct sets of default arguments. That is, declarations in
272 // inner scopes do not acquire default arguments from
273 // declarations in outer scopes, and vice versa. In a given
274 // function declaration, all parameters subsequent to a
275 // parameter with a default argument shall have default
276 // arguments supplied in this or previous declarations. A
277 // default argument shall not be redefined by a later
278 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000279 //
280 // C++ [dcl.fct.default]p6:
281 // Except for member functions of class templates, the default arguments
282 // in a member function definition that appears outside of the class
283 // definition are added to the set of default arguments provided by the
284 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000285 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
286 ParmVarDecl *OldParam = Old->getParamDecl(p);
287 ParmVarDecl *NewParam = New->getParamDecl(p);
288
Douglas Gregorc732aba2009-09-11 18:44:32 +0000289 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-01-13 00:12:48 +0000290 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
291 // hint here. Alternatively, we could walk the type-source information
292 // for NewParam to find the last source location in the type... but it
293 // isn't worth the effort right now. This is the kind of test case that
294 // is hard to get right:
295
296 // int f(int);
297 // void g(int (*fp)(int) = f);
298 // void g(int (*fp)(int) = &f);
Mike Stump11289f42009-09-09 15:08:12 +0000299 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000300 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000301 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000302
303 // Look for the function declaration where the default argument was
304 // actually written, which may be a declaration prior to Old.
305 for (FunctionDecl *Older = Old->getPreviousDeclaration();
306 Older; Older = Older->getPreviousDeclaration()) {
307 if (!Older->getParamDecl(p)->hasDefaultArg())
308 break;
309
310 OldParam = Older->getParamDecl(p);
311 }
312
313 Diag(OldParam->getLocation(), diag::note_previous_definition)
314 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000315 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000316 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000317 // Merge the old default argument into the new parameter.
318 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000319 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000320 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000321 if (OldParam->hasUninstantiatedDefaultArg())
322 NewParam->setUninstantiatedDefaultArg(
323 OldParam->getUninstantiatedDefaultArg());
324 else
John McCalle61b02b2010-05-04 01:53:42 +0000325 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000326 } else if (NewParam->hasDefaultArg()) {
327 if (New->getDescribedFunctionTemplate()) {
328 // Paragraph 4, quoted above, only applies to non-template functions.
329 Diag(NewParam->getLocation(),
330 diag::err_param_default_argument_template_redecl)
331 << NewParam->getDefaultArgRange();
332 Diag(Old->getLocation(), diag::note_template_prev_declaration)
333 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000334 } else if (New->getTemplateSpecializationKind()
335 != TSK_ImplicitInstantiation &&
336 New->getTemplateSpecializationKind() != TSK_Undeclared) {
337 // C++ [temp.expr.spec]p21:
338 // Default function arguments shall not be specified in a declaration
339 // or a definition for one of the following explicit specializations:
340 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000341 // - the explicit specialization of a member function template;
342 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000343 // template where the class template specialization to which the
344 // member function specialization belongs is implicitly
345 // instantiated.
346 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
347 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
348 << New->getDeclName()
349 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000350 } else if (New->getDeclContext()->isDependentContext()) {
351 // C++ [dcl.fct.default]p6 (DR217):
352 // Default arguments for a member function of a class template shall
353 // be specified on the initial declaration of the member function
354 // within the class template.
355 //
356 // Reading the tea leaves a bit in DR217 and its reference to DR205
357 // leads me to the conclusion that one cannot add default function
358 // arguments for an out-of-line definition of a member function of a
359 // dependent type.
360 int WhichKind = 2;
361 if (CXXRecordDecl *Record
362 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
363 if (Record->getDescribedClassTemplate())
364 WhichKind = 0;
365 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
366 WhichKind = 1;
367 else
368 WhichKind = 2;
369 }
370
371 Diag(NewParam->getLocation(),
372 diag::err_param_default_argument_member_template_redecl)
373 << WhichKind
374 << NewParam->getDefaultArgRange();
375 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000376 }
377 }
378
Douglas Gregorf40863c2010-02-12 07:32:17 +0000379 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000380 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000381
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000382 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000383}
384
385/// CheckCXXDefaultArguments - Verify that the default arguments for a
386/// function declaration are well-formed according to C++
387/// [dcl.fct.default].
388void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
389 unsigned NumParams = FD->getNumParams();
390 unsigned p;
391
392 // Find first parameter with a default argument
393 for (p = 0; p < NumParams; ++p) {
394 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000395 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000396 break;
397 }
398
399 // C++ [dcl.fct.default]p4:
400 // In a given function declaration, all parameters
401 // subsequent to a parameter with a default argument shall
402 // have default arguments supplied in this or previous
403 // declarations. A default argument shall not be redefined
404 // by a later declaration (not even to the same value).
405 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000406 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000407 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000408 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000409 if (Param->isInvalidDecl())
410 /* We already complained about this parameter. */;
411 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000412 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000413 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000414 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000415 else
Mike Stump11289f42009-09-09 15:08:12 +0000416 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000417 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000418
Chris Lattner199abbc2008-04-08 05:04:30 +0000419 LastMissingDefaultArg = p;
420 }
421 }
422
423 if (LastMissingDefaultArg > 0) {
424 // Some default arguments were missing. Clear out all of the
425 // default arguments up to (and including) the last missing
426 // default argument, so that we leave the function parameters
427 // in a semantically valid state.
428 for (p = 0; p <= LastMissingDefaultArg; ++p) {
429 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000430 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000431 Param->setDefaultArg(0);
432 }
433 }
434 }
435}
Douglas Gregor556877c2008-04-13 21:30:24 +0000436
Douglas Gregor61956c42008-10-31 09:07:45 +0000437/// isCurrentClassName - Determine whether the identifier II is the
438/// name of the class type currently being defined. In the case of
439/// nested classes, this will only return true if II is the name of
440/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000441bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
442 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000443 assert(getLangOptions().CPlusPlus && "No class names in C!");
444
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000445 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000446 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000447 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000448 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
449 } else
450 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
451
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000452 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000453 return &II == CurDecl->getIdentifier();
454 else
455 return false;
456}
457
Mike Stump11289f42009-09-09 15:08:12 +0000458/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000459///
460/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
461/// and returns NULL otherwise.
462CXXBaseSpecifier *
463Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
464 SourceRange SpecifierRange,
465 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000466 TypeSourceInfo *TInfo,
467 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +0000468 QualType BaseType = TInfo->getType();
469
Douglas Gregor463421d2009-03-03 04:44:36 +0000470 // C++ [class.union]p1:
471 // A union shall not have base classes.
472 if (Class->isUnion()) {
473 Diag(Class->getLocation(), diag::err_base_clause_on_union)
474 << SpecifierRange;
475 return 0;
476 }
477
Douglas Gregor752a5952011-01-03 22:36:02 +0000478 if (EllipsisLoc.isValid() &&
479 !TInfo->getType()->containsUnexpandedParameterPack()) {
480 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
481 << TInfo->getTypeLoc().getSourceRange();
482 EllipsisLoc = SourceLocation();
483 }
484
Douglas Gregor463421d2009-03-03 04:44:36 +0000485 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000486 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000487 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000488 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +0000489
490 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000491
492 // Base specifiers must be record types.
493 if (!BaseType->isRecordType()) {
494 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
495 return 0;
496 }
497
498 // C++ [class.union]p1:
499 // A union shall not be used as a base class.
500 if (BaseType->isUnionType()) {
501 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
502 return 0;
503 }
504
505 // C++ [class.derived]p2:
506 // The class-name in a base-specifier shall not be an incompletely
507 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000508 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000509 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000510 << SpecifierRange)) {
511 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000512 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000513 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000514
Eli Friedmanc96d4962009-08-15 21:55:26 +0000515 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000516 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000517 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000518 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000519 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000520 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
521 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000522
Anders Carlssonfc1eef42011-01-22 17:51:53 +0000523 // C++ [class.derived]p2:
524 // If a class is marked with the class-virt-specifier final and it appears
525 // as a base-type-specifier in a base-clause (10 class.derived), the program
526 // is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000527 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-01-22 17:51:53 +0000528 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
529 << CXXBaseDecl->getDeclName();
530 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
531 << CXXBaseDecl->getDeclName();
532 return 0;
533 }
534
John McCall3696dcb2010-08-17 07:23:57 +0000535 if (BaseDecl->isInvalidDecl())
536 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000537
538 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000539 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000540 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000541 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000542}
543
Douglas Gregor556877c2008-04-13 21:30:24 +0000544/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
545/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000546/// example:
547/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000548/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000549BaseResult
John McCall48871652010-08-21 09:40:31 +0000550Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000551 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000552 ParsedType basetype, SourceLocation BaseLoc,
553 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000554 if (!classdecl)
555 return true;
556
Douglas Gregorc40290e2009-03-09 23:48:35 +0000557 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000558 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000559 if (!Class)
560 return true;
561
Nick Lewycky19b9f952010-07-26 16:56:01 +0000562 TypeSourceInfo *TInfo = 0;
563 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000564
Douglas Gregor752a5952011-01-03 22:36:02 +0000565 if (EllipsisLoc.isInvalid() &&
566 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000567 UPPC_BaseType))
568 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000569
Douglas Gregor463421d2009-03-03 04:44:36 +0000570 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000571 Virtual, Access, TInfo,
572 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000573 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000574
Douglas Gregor463421d2009-03-03 04:44:36 +0000575 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000576}
Douglas Gregor556877c2008-04-13 21:30:24 +0000577
Douglas Gregor463421d2009-03-03 04:44:36 +0000578/// \brief Performs the actual work of attaching the given base class
579/// specifiers to a C++ class.
580bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
581 unsigned NumBases) {
582 if (NumBases == 0)
583 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000584
585 // Used to keep track of which base types we have already seen, so
586 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000587 // that the key is always the unqualified canonical type of the base
588 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000589 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
590
591 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000592 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000593 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000594 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000595 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000596 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000597 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000598 if (!Class->hasObjectMember()) {
599 if (const RecordType *FDTTy =
600 NewBaseType.getTypePtr()->getAs<RecordType>())
601 if (FDTTy->getDecl()->hasObjectMember())
602 Class->setHasObjectMember(true);
603 }
604
Douglas Gregor29a92472008-10-22 17:49:05 +0000605 if (KnownBaseTypes[NewBaseType]) {
606 // C++ [class.mi]p3:
607 // A class shall not be specified as a direct base class of a
608 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000609 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000610 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000611 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000612 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000613
614 // Delete the duplicate base class specifier; we're going to
615 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000616 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000617
618 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000619 } else {
620 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000621 KnownBaseTypes[NewBaseType] = Bases[idx];
622 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000623 }
624 }
625
626 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000627 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000628
629 // Delete the remaining (good) base class specifiers, since their
630 // data has been copied into the CXXRecordDecl.
631 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000632 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000633
634 return Invalid;
635}
636
637/// ActOnBaseSpecifiers - Attach the given base specifiers to the
638/// class, after checking whether there are any duplicate base
639/// classes.
John McCall48871652010-08-21 09:40:31 +0000640void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000641 unsigned NumBases) {
642 if (!ClassDecl || !Bases || !NumBases)
643 return;
644
645 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000646 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000647 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000648}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000649
John McCalle78aac42010-03-10 03:28:59 +0000650static CXXRecordDecl *GetClassForType(QualType T) {
651 if (const RecordType *RT = T->getAs<RecordType>())
652 return cast<CXXRecordDecl>(RT->getDecl());
653 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
654 return ICT->getDecl();
655 else
656 return 0;
657}
658
Douglas Gregor36d1b142009-10-06 17:59:45 +0000659/// \brief Determine whether the type \p Derived is a C++ class that is
660/// derived from the type \p Base.
661bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
662 if (!getLangOptions().CPlusPlus)
663 return false;
John McCalle78aac42010-03-10 03:28:59 +0000664
665 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
666 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000667 return false;
668
John McCalle78aac42010-03-10 03:28:59 +0000669 CXXRecordDecl *BaseRD = GetClassForType(Base);
670 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000671 return false;
672
John McCall67da35c2010-02-04 22:26:26 +0000673 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
674 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000675}
676
677/// \brief Determine whether the type \p Derived is a C++ class that is
678/// derived from the type \p Base.
679bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
680 if (!getLangOptions().CPlusPlus)
681 return false;
682
John McCalle78aac42010-03-10 03:28:59 +0000683 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
684 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000685 return false;
686
John McCalle78aac42010-03-10 03:28:59 +0000687 CXXRecordDecl *BaseRD = GetClassForType(Base);
688 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000689 return false;
690
Douglas Gregor36d1b142009-10-06 17:59:45 +0000691 return DerivedRD->isDerivedFrom(BaseRD, Paths);
692}
693
Anders Carlssona70cff62010-04-24 19:06:50 +0000694void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000695 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000696 assert(BasePathArray.empty() && "Base path array must be empty!");
697 assert(Paths.isRecordingPaths() && "Must record paths!");
698
699 const CXXBasePath &Path = Paths.front();
700
701 // We first go backward and check if we have a virtual base.
702 // FIXME: It would be better if CXXBasePath had the base specifier for
703 // the nearest virtual base.
704 unsigned Start = 0;
705 for (unsigned I = Path.size(); I != 0; --I) {
706 if (Path[I - 1].Base->isVirtual()) {
707 Start = I - 1;
708 break;
709 }
710 }
711
712 // Now add all bases.
713 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000714 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000715}
716
Douglas Gregor88d292c2010-05-13 16:44:06 +0000717/// \brief Determine whether the given base path includes a virtual
718/// base class.
John McCallcf142162010-08-07 06:22:56 +0000719bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
720 for (CXXCastPath::const_iterator B = BasePath.begin(),
721 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000722 B != BEnd; ++B)
723 if ((*B)->isVirtual())
724 return true;
725
726 return false;
727}
728
Douglas Gregor36d1b142009-10-06 17:59:45 +0000729/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
730/// conversion (where Derived and Base are class types) is
731/// well-formed, meaning that the conversion is unambiguous (and
732/// that all of the base classes are accessible). Returns true
733/// and emits a diagnostic if the code is ill-formed, returns false
734/// otherwise. Loc is the location where this routine should point to
735/// if there is an error, and Range is the source range to highlight
736/// if there is an error.
737bool
738Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000739 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000740 unsigned AmbigiousBaseConvID,
741 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000742 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000743 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000744 // First, determine whether the path from Derived to Base is
745 // ambiguous. This is slightly more expensive than checking whether
746 // the Derived to Base conversion exists, because here we need to
747 // explore multiple paths to determine if there is an ambiguity.
748 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
749 /*DetectVirtual=*/false);
750 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
751 assert(DerivationOkay &&
752 "Can only be used with a derived-to-base conversion");
753 (void)DerivationOkay;
754
755 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000756 if (InaccessibleBaseID) {
757 // Check that the base class can be accessed.
758 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
759 InaccessibleBaseID)) {
760 case AR_inaccessible:
761 return true;
762 case AR_accessible:
763 case AR_dependent:
764 case AR_delayed:
765 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000766 }
John McCall5b0829a2010-02-10 09:31:12 +0000767 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000768
769 // Build a base path if necessary.
770 if (BasePath)
771 BuildBasePathArray(Paths, *BasePath);
772 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000773 }
774
775 // We know that the derived-to-base conversion is ambiguous, and
776 // we're going to produce a diagnostic. Perform the derived-to-base
777 // search just one more time to compute all of the possible paths so
778 // that we can print them out. This is more expensive than any of
779 // the previous derived-to-base checks we've done, but at this point
780 // performance isn't as much of an issue.
781 Paths.clear();
782 Paths.setRecordingPaths(true);
783 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
784 assert(StillOkay && "Can only be used with a derived-to-base conversion");
785 (void)StillOkay;
786
787 // Build up a textual representation of the ambiguous paths, e.g.,
788 // D -> B -> A, that will be used to illustrate the ambiguous
789 // conversions in the diagnostic. We only print one of the paths
790 // to each base class subobject.
791 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
792
793 Diag(Loc, AmbigiousBaseConvID)
794 << Derived << Base << PathDisplayStr << Range << Name;
795 return true;
796}
797
798bool
799Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000800 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000801 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000802 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000803 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000804 IgnoreAccess ? 0
805 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000806 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000807 Loc, Range, DeclarationName(),
808 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000809}
810
811
812/// @brief Builds a string representing ambiguous paths from a
813/// specific derived class to different subobjects of the same base
814/// class.
815///
816/// This function builds a string that can be used in error messages
817/// to show the different paths that one can take through the
818/// inheritance hierarchy to go from the derived class to different
819/// subobjects of a base class. The result looks something like this:
820/// @code
821/// struct D -> struct B -> struct A
822/// struct D -> struct C -> struct A
823/// @endcode
824std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
825 std::string PathDisplayStr;
826 std::set<unsigned> DisplayedPaths;
827 for (CXXBasePaths::paths_iterator Path = Paths.begin();
828 Path != Paths.end(); ++Path) {
829 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
830 // We haven't displayed a path to this particular base
831 // class subobject yet.
832 PathDisplayStr += "\n ";
833 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
834 for (CXXBasePath::const_iterator Element = Path->begin();
835 Element != Path->end(); ++Element)
836 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
837 }
838 }
839
840 return PathDisplayStr;
841}
842
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000843//===----------------------------------------------------------------------===//
844// C++ class member Handling
845//===----------------------------------------------------------------------===//
846
Abramo Bagnarad7340582010-06-05 05:09:32 +0000847/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000848Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
849 SourceLocation ASLoc,
850 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000851 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000852 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000853 ASLoc, ColonLoc);
854 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000855 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000856}
857
Anders Carlssonfd835532011-01-20 05:57:14 +0000858/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +0000859void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlssonfd835532011-01-20 05:57:14 +0000860 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
861 if (!MD || !MD->isVirtual())
862 return;
863
Anders Carlssonfa8e5d32011-01-20 06:33:26 +0000864 if (MD->isDependentContext())
865 return;
866
Anders Carlssonfd835532011-01-20 05:57:14 +0000867 // C++0x [class.virtual]p3:
868 // If a virtual function is marked with the virt-specifier override and does
869 // not override a member function of a base class,
870 // the program is ill-formed.
871 bool HasOverriddenMethods =
872 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlsson1eb95962011-01-24 16:26:15 +0000873 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +0000874 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +0000875 diag::err_function_marked_override_not_overriding)
876 << MD->getDeclName();
877 return;
878 }
Anders Carlsson7d59a682011-01-22 22:23:37 +0000879
880 // C++0x [class.derived]p8:
881 // In a class definition marked with the class-virt-specifier explicit,
882 // if a virtual member function that is neither implicitly-declared nor a
883 // destructor overrides a member function of a base class and it is not
884 // marked with the virt-specifier override, the program is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000885 if (MD->getParent()->hasAttr<ExplicitAttr>() && !isa<CXXDestructorDecl>(MD) &&
886 HasOverriddenMethods && !MD->hasAttr<OverrideAttr>()) {
Anders Carlsson7d59a682011-01-22 22:23:37 +0000887 llvm::SmallVector<const CXXMethodDecl*, 4>
888 OverriddenMethods(MD->begin_overridden_methods(),
889 MD->end_overridden_methods());
890
891 Diag(MD->getLocation(), diag::err_function_overriding_without_override)
892 << MD->getDeclName()
893 << (unsigned)OverriddenMethods.size();
894
895 for (unsigned I = 0; I != OverriddenMethods.size(); ++I)
896 Diag(OverriddenMethods[I]->getLocation(),
897 diag::note_overridden_virtual_function);
898 }
Anders Carlssonfd835532011-01-20 05:57:14 +0000899}
900
Anders Carlsson3f610c72011-01-20 16:25:36 +0000901/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
902/// function overrides a virtual member function marked 'final', according to
903/// C++0x [class.virtual]p3.
904bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
905 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +0000906 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +0000907 return false;
908
909 Diag(New->getLocation(), diag::err_final_function_overridden)
910 << New->getDeclName();
911 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
912 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +0000913}
914
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000915/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
916/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
917/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000918/// any.
John McCall48871652010-08-21 09:40:31 +0000919Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000920Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000921 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +0000922 ExprTy *BW, const VirtSpecifiers &VS,
923 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld6f78502009-11-24 23:38:44 +0000924 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000925 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000926 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
927 DeclarationName Name = NameInfo.getName();
928 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000929
930 // For anonymous bitfields, the location should point to the type.
931 if (Loc.isInvalid())
932 Loc = D.getSourceRange().getBegin();
933
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000934 Expr *BitWidth = static_cast<Expr*>(BW);
935 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000936
John McCallb1cd7da2010-06-04 08:34:12 +0000937 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000938 assert(!DS.isFriendSpecified());
939
John McCallb1cd7da2010-06-04 08:34:12 +0000940 bool isFunc = false;
941 if (D.isFunctionDeclarator())
942 isFunc = true;
943 else if (D.getNumTypeObjects() == 0 &&
944 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000945 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000946 isFunc = TDType->isFunctionType();
947 }
948
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000949 // C++ 9.2p6: A member shall not be declared to have automatic storage
950 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000951 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
952 // data members and cannot be applied to names declared const or static,
953 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000954 switch (DS.getStorageClassSpec()) {
955 case DeclSpec::SCS_unspecified:
956 case DeclSpec::SCS_typedef:
957 case DeclSpec::SCS_static:
958 // FALL THROUGH.
959 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000960 case DeclSpec::SCS_mutable:
961 if (isFunc) {
962 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000963 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000964 else
Chris Lattner3b054132008-11-19 05:08:23 +0000965 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000966
Sebastian Redl8071edb2008-11-17 23:24:37 +0000967 // FIXME: It would be nicer if the keyword was ignored only for this
968 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000969 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000970 }
971 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000972 default:
973 if (DS.getStorageClassSpecLoc().isValid())
974 Diag(DS.getStorageClassSpecLoc(),
975 diag::err_storageclass_invalid_for_member);
976 else
977 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
978 D.getMutableDeclSpec().ClearStorageClassSpecs();
979 }
980
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000981 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
982 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000983 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000984
985 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000986 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +0000987 CXXScopeSpec &SS = D.getCXXScopeSpec();
988
989
990 if (SS.isSet() && !SS.isInvalid()) {
991 // The user provided a superfluous scope specifier inside a class
992 // definition:
993 //
994 // class X {
995 // int X::member;
996 // };
997 DeclContext *DC = 0;
998 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
999 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1000 << Name << FixItHint::CreateRemoval(SS.getRange());
1001 else
1002 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1003 << Name << SS.getRange();
1004
1005 SS.clear();
1006 }
1007
Douglas Gregor3447e762009-08-20 22:52:58 +00001008 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +00001009 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001010 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1011 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001012 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001013 } else {
John McCall48871652010-08-21 09:40:31 +00001014 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001015 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001016 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001017 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001018
1019 // Non-instance-fields can't have a bitfield.
1020 if (BitWidth) {
1021 if (Member->isInvalidDecl()) {
1022 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001023 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001024 // C++ 9.6p3: A bit-field shall not be a static member.
1025 // "static member 'A' cannot be a bit-field"
1026 Diag(Loc, diag::err_static_not_bitfield)
1027 << Name << BitWidth->getSourceRange();
1028 } else if (isa<TypedefDecl>(Member)) {
1029 // "typedef member 'x' cannot be a bit-field"
1030 Diag(Loc, diag::err_typedef_not_bitfield)
1031 << Name << BitWidth->getSourceRange();
1032 } else {
1033 // A function typedef ("typedef int f(); f a;").
1034 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1035 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001036 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001037 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001038 }
Mike Stump11289f42009-09-09 15:08:12 +00001039
Chris Lattnerd26760a2009-03-05 23:01:03 +00001040 BitWidth = 0;
1041 Member->setInvalidDecl();
1042 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001043
1044 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001045
Douglas Gregor3447e762009-08-20 22:52:58 +00001046 // If we have declared a member function template, set the access of the
1047 // templated declaration as well.
1048 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1049 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001050 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001051
Anders Carlsson13a69102011-01-20 04:34:22 +00001052 if (VS.isOverrideSpecified()) {
1053 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1054 if (!MD || !MD->isVirtual()) {
1055 Diag(Member->getLocStart(),
1056 diag::override_keyword_only_allowed_on_virtual_member_functions)
1057 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001058 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001059 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001060 }
1061 if (VS.isFinalSpecified()) {
1062 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1063 if (!MD || !MD->isVirtual()) {
1064 Diag(Member->getLocStart(),
1065 diag::override_keyword_only_allowed_on_virtual_member_functions)
1066 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001067 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001068 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001069 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001070
Anders Carlssonc87f8612011-01-20 06:29:02 +00001071 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001072
Douglas Gregor92751d42008-11-17 22:58:34 +00001073 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001074
Douglas Gregor0c880302009-03-11 23:00:04 +00001075 if (Init)
Richard Smith30482bc2011-02-20 03:19:35 +00001076 AddInitializerToDecl(Member, Init, false,
1077 DS.getTypeSpecType() == DeclSpec::TST_auto);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001078 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +00001079 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001080
Richard Smithb2bc2e62011-02-21 20:05:19 +00001081 FinalizeDeclaration(Member);
1082
John McCall25849ca2011-02-15 07:12:36 +00001083 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001084 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001085 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001086}
1087
Douglas Gregor15e77a22009-12-31 09:10:24 +00001088/// \brief Find the direct and/or virtual base specifiers that
1089/// correspond to the given base type, for use in base initialization
1090/// within a constructor.
1091static bool FindBaseInitializer(Sema &SemaRef,
1092 CXXRecordDecl *ClassDecl,
1093 QualType BaseType,
1094 const CXXBaseSpecifier *&DirectBaseSpec,
1095 const CXXBaseSpecifier *&VirtualBaseSpec) {
1096 // First, check for a direct base class.
1097 DirectBaseSpec = 0;
1098 for (CXXRecordDecl::base_class_const_iterator Base
1099 = ClassDecl->bases_begin();
1100 Base != ClassDecl->bases_end(); ++Base) {
1101 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1102 // We found a direct base of this type. That's what we're
1103 // initializing.
1104 DirectBaseSpec = &*Base;
1105 break;
1106 }
1107 }
1108
1109 // Check for a virtual base class.
1110 // FIXME: We might be able to short-circuit this if we know in advance that
1111 // there are no virtual bases.
1112 VirtualBaseSpec = 0;
1113 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1114 // We haven't found a base yet; search the class hierarchy for a
1115 // virtual base class.
1116 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1117 /*DetectVirtual=*/false);
1118 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1119 BaseType, Paths)) {
1120 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1121 Path != Paths.end(); ++Path) {
1122 if (Path->back().Base->isVirtual()) {
1123 VirtualBaseSpec = Path->back().Base;
1124 break;
1125 }
1126 }
1127 }
1128 }
1129
1130 return DirectBaseSpec || VirtualBaseSpec;
1131}
1132
Douglas Gregore8381c02008-11-05 04:29:56 +00001133/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001134MemInitResult
John McCall48871652010-08-21 09:40:31 +00001135Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001136 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001137 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001138 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001139 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001140 SourceLocation IdLoc,
1141 SourceLocation LParenLoc,
1142 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001143 SourceLocation RParenLoc,
1144 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001145 if (!ConstructorD)
1146 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001147
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001148 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001149
1150 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001151 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001152 if (!Constructor) {
1153 // The user wrote a constructor initializer on a function that is
1154 // not a C++ constructor. Ignore the error for now, because we may
1155 // have more member initializers coming; we'll diagnose it just
1156 // once in ActOnMemInitializers.
1157 return true;
1158 }
1159
1160 CXXRecordDecl *ClassDecl = Constructor->getParent();
1161
1162 // C++ [class.base.init]p2:
1163 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001164 // constructor's class and, if not found in that scope, are looked
1165 // up in the scope containing the constructor's definition.
1166 // [Note: if the constructor's class contains a member with the
1167 // same name as a direct or virtual base class of the class, a
1168 // mem-initializer-id naming the member or base class and composed
1169 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001170 // mem-initializer-id for the hidden base class may be specified
1171 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001172 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001173 // Look for a member, first.
1174 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001175 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001176 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001177 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001178 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001179
Douglas Gregor44e7df62011-01-04 00:32:56 +00001180 if (Member) {
1181 if (EllipsisLoc.isValid())
1182 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1183 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1184
Francois Pichetd583da02010-12-04 09:14:42 +00001185 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001186 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001187 }
1188
Francois Pichetd583da02010-12-04 09:14:42 +00001189 // Handle anonymous union case.
1190 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001191 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1192 if (EllipsisLoc.isValid())
1193 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1194 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1195
Francois Pichetd583da02010-12-04 09:14:42 +00001196 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1197 NumArgs, IdLoc,
1198 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001199 }
Francois Pichetd583da02010-12-04 09:14:42 +00001200 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001201 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001202 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001203 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001204 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001205
1206 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001207 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001208 } else {
1209 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1210 LookupParsedName(R, S, &SS);
1211
1212 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1213 if (!TyD) {
1214 if (R.isAmbiguous()) return true;
1215
John McCallda6841b2010-04-09 19:01:14 +00001216 // We don't want access-control diagnostics here.
1217 R.suppressDiagnostics();
1218
Douglas Gregora3b624a2010-01-19 06:46:48 +00001219 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1220 bool NotUnknownSpecialization = false;
1221 DeclContext *DC = computeDeclContext(SS, false);
1222 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1223 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1224
1225 if (!NotUnknownSpecialization) {
1226 // When the scope specifier can refer to a member of an unknown
1227 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001228 BaseType = CheckTypenameType(ETK_None,
1229 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001230 *MemberOrBase, SourceLocation(),
1231 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001232 if (BaseType.isNull())
1233 return true;
1234
Douglas Gregora3b624a2010-01-19 06:46:48 +00001235 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001236 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001237 }
1238 }
1239
Douglas Gregor15e77a22009-12-31 09:10:24 +00001240 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001241 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001242 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1243 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001244 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001245 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001246 // We have found a non-static data member with a similar
1247 // name to what was typed; complain and initialize that
1248 // member.
1249 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1250 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001251 << FixItHint::CreateReplacement(R.getNameLoc(),
1252 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001253 Diag(Member->getLocation(), diag::note_previous_decl)
1254 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001255
1256 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1257 LParenLoc, RParenLoc);
1258 }
1259 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1260 const CXXBaseSpecifier *DirectBaseSpec;
1261 const CXXBaseSpecifier *VirtualBaseSpec;
1262 if (FindBaseInitializer(*this, ClassDecl,
1263 Context.getTypeDeclType(Type),
1264 DirectBaseSpec, VirtualBaseSpec)) {
1265 // We have found a direct or virtual base class with a
1266 // similar name to what was typed; complain and initialize
1267 // that base class.
1268 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1269 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001270 << FixItHint::CreateReplacement(R.getNameLoc(),
1271 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001272
1273 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1274 : VirtualBaseSpec;
1275 Diag(BaseSpec->getSourceRange().getBegin(),
1276 diag::note_base_class_specified_here)
1277 << BaseSpec->getType()
1278 << BaseSpec->getSourceRange();
1279
Douglas Gregor15e77a22009-12-31 09:10:24 +00001280 TyD = Type;
1281 }
1282 }
1283 }
1284
Douglas Gregora3b624a2010-01-19 06:46:48 +00001285 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001286 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1287 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1288 return true;
1289 }
John McCallb5a0d312009-12-21 10:41:20 +00001290 }
1291
Douglas Gregora3b624a2010-01-19 06:46:48 +00001292 if (BaseType.isNull()) {
1293 BaseType = Context.getTypeDeclType(TyD);
1294 if (SS.isSet()) {
1295 NestedNameSpecifier *Qualifier =
1296 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001297
Douglas Gregora3b624a2010-01-19 06:46:48 +00001298 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001299 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001300 }
John McCallb5a0d312009-12-21 10:41:20 +00001301 }
1302 }
Mike Stump11289f42009-09-09 15:08:12 +00001303
John McCallbcd03502009-12-07 02:54:59 +00001304 if (!TInfo)
1305 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001306
John McCallbcd03502009-12-07 02:54:59 +00001307 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001308 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001309}
1310
John McCalle22a04a2009-11-04 23:02:40 +00001311/// Checks an initializer expression for use of uninitialized fields, such as
1312/// containing the field that is being initialized. Returns true if there is an
1313/// uninitialized field was used an updates the SourceLocation parameter; false
1314/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001315static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001316 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001317 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001318 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1319
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001320 if (isa<CallExpr>(S)) {
1321 // Do not descend into function calls or constructors, as the use
1322 // of an uninitialized field may be valid. One would have to inspect
1323 // the contents of the function/ctor to determine if it is safe or not.
1324 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1325 // may be safe, depending on what the function/ctor does.
1326 return false;
1327 }
1328 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1329 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001330
1331 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1332 // The member expression points to a static data member.
1333 assert(VD->isStaticDataMember() &&
1334 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001335 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001336 return false;
1337 }
1338
1339 if (isa<EnumConstantDecl>(RhsField)) {
1340 // The member expression points to an enum.
1341 return false;
1342 }
1343
John McCalle22a04a2009-11-04 23:02:40 +00001344 if (RhsField == LhsField) {
1345 // Initializing a field with itself. Throw a warning.
1346 // But wait; there are exceptions!
1347 // Exception #1: The field may not belong to this record.
1348 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001349 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001350 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1351 // Even though the field matches, it does not belong to this record.
1352 return false;
1353 }
1354 // None of the exceptions triggered; return true to indicate an
1355 // uninitialized field was used.
1356 *L = ME->getMemberLoc();
1357 return true;
1358 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001359 } else if (isa<SizeOfAlignOfExpr>(S)) {
1360 // sizeof/alignof doesn't reference contents, do not warn.
1361 return false;
1362 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1363 // address-of doesn't reference contents (the pointer may be dereferenced
1364 // in the same expression but it would be rare; and weird).
1365 if (UOE->getOpcode() == UO_AddrOf)
1366 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001367 }
John McCall8322c3a2011-02-13 04:07:26 +00001368 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001369 if (!*it) {
1370 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001371 continue;
1372 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001373 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1374 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001375 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001376 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001377}
1378
John McCallfaf5fb42010-08-26 23:41:50 +00001379MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001380Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001381 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001382 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001383 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001384 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1385 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1386 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001387 "Member must be a FieldDecl or IndirectFieldDecl");
1388
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001389 if (Member->isInvalidDecl())
1390 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001391
John McCalle22a04a2009-11-04 23:02:40 +00001392 // Diagnose value-uses of fields to initialize themselves, e.g.
1393 // foo(foo)
1394 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001395 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001396 for (unsigned i = 0; i < NumArgs; ++i) {
1397 SourceLocation L;
1398 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1399 // FIXME: Return true in the case when other fields are used before being
1400 // uninitialized. For example, let this field be the i'th field. When
1401 // initializing the i'th field, throw a warning if any of the >= i'th
1402 // fields are used, as they are not yet initialized.
1403 // Right now we are only handling the case where the i'th field uses
1404 // itself in its initializer.
1405 Diag(L, diag::warn_field_is_uninit);
1406 }
1407 }
1408
Eli Friedman8e1433b2009-07-29 19:44:27 +00001409 bool HasDependentArg = false;
1410 for (unsigned i = 0; i < NumArgs; i++)
1411 HasDependentArg |= Args[i]->isTypeDependent();
1412
Chandler Carruthd44c3102010-12-06 09:23:57 +00001413 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001414 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001415 // Can't check initialization for a member of dependent type or when
1416 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001417 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1418 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001419
1420 // Erase any temporaries within this evaluation context; we're not
1421 // going to track them in the AST, since we'll be rebuilding the
1422 // ASTs during template instantiation.
1423 ExprTemporaries.erase(
1424 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1425 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001426 } else {
1427 // Initialize the member.
1428 InitializedEntity MemberEntity =
1429 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1430 : InitializedEntity::InitializeMember(IndirectMember, 0);
1431 InitializationKind Kind =
1432 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001433
Chandler Carruthd44c3102010-12-06 09:23:57 +00001434 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1435
1436 ExprResult MemberInit =
1437 InitSeq.Perform(*this, MemberEntity, Kind,
1438 MultiExprArg(*this, Args, NumArgs), 0);
1439 if (MemberInit.isInvalid())
1440 return true;
1441
1442 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1443
1444 // C++0x [class.base.init]p7:
1445 // The initialization of each base and member constitutes a
1446 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001447 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001448 if (MemberInit.isInvalid())
1449 return true;
1450
1451 // If we are in a dependent context, template instantiation will
1452 // perform this type-checking again. Just save the arguments that we
1453 // received in a ParenListExpr.
1454 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1455 // of the information that we have about the member
1456 // initializer. However, deconstructing the ASTs is a dicey process,
1457 // and this approach is far more likely to get the corner cases right.
1458 if (CurContext->isDependentContext())
1459 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1460 RParenLoc);
1461 else
1462 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001463 }
1464
Chandler Carruthd44c3102010-12-06 09:23:57 +00001465 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001466 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001467 IdLoc, LParenLoc, Init,
1468 RParenLoc);
1469 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001470 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001471 IdLoc, LParenLoc, Init,
1472 RParenLoc);
1473 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001474}
1475
John McCallfaf5fb42010-08-26 23:41:50 +00001476MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001477Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1478 Expr **Args, unsigned NumArgs,
1479 SourceLocation LParenLoc,
1480 SourceLocation RParenLoc,
1481 CXXRecordDecl *ClassDecl,
1482 SourceLocation EllipsisLoc) {
1483 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1484 if (!LangOpts.CPlusPlus0x)
1485 return Diag(Loc, diag::err_delegation_0x_only)
1486 << TInfo->getTypeLoc().getLocalSourceRange();
1487
1488 return Diag(Loc, diag::err_delegation_unimplemented)
1489 << TInfo->getTypeLoc().getLocalSourceRange();
1490}
1491
1492MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001493Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001494 Expr **Args, unsigned NumArgs,
1495 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001496 CXXRecordDecl *ClassDecl,
1497 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001498 bool HasDependentArg = false;
1499 for (unsigned i = 0; i < NumArgs; i++)
1500 HasDependentArg |= Args[i]->isTypeDependent();
1501
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001502 SourceLocation BaseLoc
1503 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1504
1505 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1506 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1507 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1508
1509 // C++ [class.base.init]p2:
1510 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001511 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001512 // of that class, the mem-initializer is ill-formed. A
1513 // mem-initializer-list can initialize a base class using any
1514 // name that denotes that base class type.
1515 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1516
Douglas Gregor44e7df62011-01-04 00:32:56 +00001517 if (EllipsisLoc.isValid()) {
1518 // This is a pack expansion.
1519 if (!BaseType->containsUnexpandedParameterPack()) {
1520 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1521 << SourceRange(BaseLoc, RParenLoc);
1522
1523 EllipsisLoc = SourceLocation();
1524 }
1525 } else {
1526 // Check for any unexpanded parameter packs.
1527 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1528 return true;
1529
1530 for (unsigned I = 0; I != NumArgs; ++I)
1531 if (DiagnoseUnexpandedParameterPack(Args[I]))
1532 return true;
1533 }
1534
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001535 // Check for direct and virtual base classes.
1536 const CXXBaseSpecifier *DirectBaseSpec = 0;
1537 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1538 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001539 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1540 BaseType))
1541 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs,
1542 LParenLoc, RParenLoc, ClassDecl,
1543 EllipsisLoc);
1544
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001545 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1546 VirtualBaseSpec);
1547
1548 // C++ [base.class.init]p2:
1549 // Unless the mem-initializer-id names a nonstatic data member of the
1550 // constructor's class or a direct or virtual base of that class, the
1551 // mem-initializer is ill-formed.
1552 if (!DirectBaseSpec && !VirtualBaseSpec) {
1553 // If the class has any dependent bases, then it's possible that
1554 // one of those types will resolve to the same type as
1555 // BaseType. Therefore, just treat this as a dependent base
1556 // class initialization. FIXME: Should we try to check the
1557 // initialization anyway? It seems odd.
1558 if (ClassDecl->hasAnyDependentBases())
1559 Dependent = true;
1560 else
1561 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1562 << BaseType << Context.getTypeDeclType(ClassDecl)
1563 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1564 }
1565 }
1566
1567 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001568 // Can't check initialization for a base of dependent type or when
1569 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001570 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001571 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1572 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001573
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001574 // Erase any temporaries within this evaluation context; we're not
1575 // going to track them in the AST, since we'll be rebuilding the
1576 // ASTs during template instantiation.
1577 ExprTemporaries.erase(
1578 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1579 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001580
Alexis Hunt1d792652011-01-08 20:30:50 +00001581 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001582 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001583 LParenLoc,
1584 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001585 RParenLoc,
1586 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001587 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001588
1589 // C++ [base.class.init]p2:
1590 // If a mem-initializer-id is ambiguous because it designates both
1591 // a direct non-virtual base class and an inherited virtual base
1592 // class, the mem-initializer is ill-formed.
1593 if (DirectBaseSpec && VirtualBaseSpec)
1594 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001595 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001596
1597 CXXBaseSpecifier *BaseSpec
1598 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1599 if (!BaseSpec)
1600 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1601
1602 // Initialize the base.
1603 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001604 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001605 InitializationKind Kind =
1606 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1607
1608 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1609
John McCalldadc5752010-08-24 06:29:42 +00001610 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001611 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001612 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001613 if (BaseInit.isInvalid())
1614 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001615
1616 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001617
1618 // C++0x [class.base.init]p7:
1619 // The initialization of each base and member constitutes a
1620 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001621 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001622 if (BaseInit.isInvalid())
1623 return true;
1624
1625 // If we are in a dependent context, template instantiation will
1626 // perform this type-checking again. Just save the arguments that we
1627 // received in a ParenListExpr.
1628 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1629 // of the information that we have about the base
1630 // initializer. However, deconstructing the ASTs is a dicey process,
1631 // and this approach is far more likely to get the corner cases right.
1632 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001633 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001634 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1635 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001636 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001637 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001638 LParenLoc,
1639 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001640 RParenLoc,
1641 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001642 }
1643
Alexis Hunt1d792652011-01-08 20:30:50 +00001644 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001645 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001646 LParenLoc,
1647 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001648 RParenLoc,
1649 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001650}
1651
Anders Carlsson1b00e242010-04-23 03:10:23 +00001652/// ImplicitInitializerKind - How an implicit base or member initializer should
1653/// initialize its base or member.
1654enum ImplicitInitializerKind {
1655 IIK_Default,
1656 IIK_Copy,
1657 IIK_Move
1658};
1659
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001660static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001661BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001662 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001663 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001664 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001665 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001666 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001667 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1668 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001669
John McCalldadc5752010-08-24 06:29:42 +00001670 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001671
1672 switch (ImplicitInitKind) {
1673 case IIK_Default: {
1674 InitializationKind InitKind
1675 = InitializationKind::CreateDefault(Constructor->getLocation());
1676 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1677 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001678 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001679 break;
1680 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001681
Anders Carlsson1b00e242010-04-23 03:10:23 +00001682 case IIK_Copy: {
1683 ParmVarDecl *Param = Constructor->getParamDecl(0);
1684 QualType ParamType = Param->getType().getNonReferenceType();
1685
1686 Expr *CopyCtorArg =
1687 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001688 Constructor->getLocation(), ParamType,
1689 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001690
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001691 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001692 QualType ArgTy =
1693 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1694 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001695
1696 CXXCastPath BasePath;
1697 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001698 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001699 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001700 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001701
Anders Carlsson1b00e242010-04-23 03:10:23 +00001702 InitializationKind InitKind
1703 = InitializationKind::CreateDirect(Constructor->getLocation(),
1704 SourceLocation(), SourceLocation());
1705 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1706 &CopyCtorArg, 1);
1707 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001708 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001709 break;
1710 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001711
Anders Carlsson1b00e242010-04-23 03:10:23 +00001712 case IIK_Move:
1713 assert(false && "Unhandled initializer kind!");
1714 }
John McCallb268a282010-08-23 23:25:46 +00001715
Douglas Gregora40433a2010-12-07 00:41:46 +00001716 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001717 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001718 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001719
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001720 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001721 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001722 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1723 SourceLocation()),
1724 BaseSpec->isVirtual(),
1725 SourceLocation(),
1726 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001727 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001728 SourceLocation());
1729
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001730 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001731}
1732
Anders Carlsson3c1db572010-04-23 02:15:47 +00001733static bool
1734BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001735 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001736 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001737 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001738 if (Field->isInvalidDecl())
1739 return true;
1740
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001741 SourceLocation Loc = Constructor->getLocation();
1742
Anders Carlsson423f5d82010-04-23 16:04:08 +00001743 if (ImplicitInitKind == IIK_Copy) {
1744 ParmVarDecl *Param = Constructor->getParamDecl(0);
1745 QualType ParamType = Param->getType().getNonReferenceType();
1746
1747 Expr *MemberExprBase =
1748 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001749 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001750
1751 // Build a reference to this field within the parameter.
1752 CXXScopeSpec SS;
1753 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1754 Sema::LookupMemberName);
1755 MemberLookup.addDecl(Field, AS_public);
1756 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001757 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001758 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001759 ParamType, Loc,
1760 /*IsArrow=*/false,
1761 SS,
1762 /*FirstQualifierInScope=*/0,
1763 MemberLookup,
1764 /*TemplateArgs=*/0);
1765 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001766 return true;
1767
Douglas Gregor94f9a482010-05-05 05:51:00 +00001768 // When the field we are copying is an array, create index variables for
1769 // each dimension of the array. We use these index variables to subscript
1770 // the source array, and other clients (e.g., CodeGen) will perform the
1771 // necessary iteration with these index variables.
1772 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1773 QualType BaseType = Field->getType();
1774 QualType SizeType = SemaRef.Context.getSizeType();
1775 while (const ConstantArrayType *Array
1776 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1777 // Create the iteration variable for this array index.
1778 IdentifierInfo *IterationVarName = 0;
1779 {
1780 llvm::SmallString<8> Str;
1781 llvm::raw_svector_ostream OS(Str);
1782 OS << "__i" << IndexVariables.size();
1783 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1784 }
1785 VarDecl *IterationVar
1786 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1787 IterationVarName, SizeType,
1788 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001789 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001790 IndexVariables.push_back(IterationVar);
1791
1792 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001793 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001794 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001795 assert(!IterationVarRef.isInvalid() &&
1796 "Reference to invented variable cannot fail!");
1797
1798 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001799 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001800 Loc,
John McCallb268a282010-08-23 23:25:46 +00001801 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001802 Loc);
1803 if (CopyCtorArg.isInvalid())
1804 return true;
1805
1806 BaseType = Array->getElementType();
1807 }
1808
1809 // Construct the entity that we will be initializing. For an array, this
1810 // will be first element in the array, which may require several levels
1811 // of array-subscript entities.
1812 llvm::SmallVector<InitializedEntity, 4> Entities;
1813 Entities.reserve(1 + IndexVariables.size());
1814 Entities.push_back(InitializedEntity::InitializeMember(Field));
1815 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1816 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1817 0,
1818 Entities.back()));
1819
1820 // Direct-initialize to use the copy constructor.
1821 InitializationKind InitKind =
1822 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1823
1824 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1825 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1826 &CopyCtorArgE, 1);
1827
John McCalldadc5752010-08-24 06:29:42 +00001828 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001829 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001830 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001831 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001832 if (MemberInit.isInvalid())
1833 return true;
1834
1835 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001836 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001837 MemberInit.takeAs<Expr>(), Loc,
1838 IndexVariables.data(),
1839 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001840 return false;
1841 }
1842
Anders Carlsson423f5d82010-04-23 16:04:08 +00001843 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1844
Anders Carlsson3c1db572010-04-23 02:15:47 +00001845 QualType FieldBaseElementType =
1846 SemaRef.Context.getBaseElementType(Field->getType());
1847
Anders Carlsson3c1db572010-04-23 02:15:47 +00001848 if (FieldBaseElementType->isRecordType()) {
1849 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001850 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001851 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001852
1853 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001854 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001855 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001856
Douglas Gregora40433a2010-12-07 00:41:46 +00001857 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001858 if (MemberInit.isInvalid())
1859 return true;
1860
1861 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001862 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001863 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001864 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001865 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001866 return false;
1867 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001868
1869 if (FieldBaseElementType->isReferenceType()) {
1870 SemaRef.Diag(Constructor->getLocation(),
1871 diag::err_uninitialized_member_in_ctor)
1872 << (int)Constructor->isImplicit()
1873 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1874 << 0 << Field->getDeclName();
1875 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1876 return true;
1877 }
1878
1879 if (FieldBaseElementType.isConstQualified()) {
1880 SemaRef.Diag(Constructor->getLocation(),
1881 diag::err_uninitialized_member_in_ctor)
1882 << (int)Constructor->isImplicit()
1883 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1884 << 1 << Field->getDeclName();
1885 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1886 return true;
1887 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001888
1889 // Nothing to initialize.
1890 CXXMemberInit = 0;
1891 return false;
1892}
John McCallbc83b3f2010-05-20 23:23:51 +00001893
1894namespace {
1895struct BaseAndFieldInfo {
1896 Sema &S;
1897 CXXConstructorDecl *Ctor;
1898 bool AnyErrorsInInits;
1899 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00001900 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1901 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001902
1903 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1904 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1905 // FIXME: Handle implicit move constructors.
1906 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1907 IIK = IIK_Copy;
1908 else
1909 IIK = IIK_Default;
1910 }
1911};
1912}
1913
1914static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1915 FieldDecl *Top, FieldDecl *Field) {
1916
Chandler Carruth139e9622010-06-30 02:59:29 +00001917 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00001918 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001919 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001920 return false;
1921 }
1922
1923 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1924 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1925 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001926 CXXRecordDecl *FieldClassDecl
1927 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001928
1929 // Even though union members never have non-trivial default
1930 // constructions in C++03, we still build member initializers for aggregate
1931 // record types which can be union members, and C++0x allows non-trivial
1932 // default constructors for union members, so we ensure that only one
1933 // member is initialized for these.
1934 if (FieldClassDecl->isUnion()) {
1935 // First check for an explicit initializer for one field.
1936 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1937 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001938 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00001939 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00001940
1941 // Once we've initialized a field of an anonymous union, the union
1942 // field in the class is also initialized, so exit immediately.
1943 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001944 } else if ((*FA)->isAnonymousStructOrUnion()) {
1945 if (CollectFieldInitializer(Info, Top, *FA))
1946 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001947 }
1948 }
1949
1950 // Fallthrough and construct a default initializer for the union as
1951 // a whole, which can call its default constructor if such a thing exists
1952 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1953 // behavior going forward with C++0x, when anonymous unions there are
1954 // finalized, we should revisit this.
1955 } else {
1956 // For structs, we simply descend through to initialize all members where
1957 // necessary.
1958 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1959 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1960 if (CollectFieldInitializer(Info, Top, *FA))
1961 return true;
1962 }
1963 }
John McCallbc83b3f2010-05-20 23:23:51 +00001964 }
1965
1966 // Don't try to build an implicit initializer if there were semantic
1967 // errors in any of the initializers (and therefore we might be
1968 // missing some that the user actually wrote).
1969 if (Info.AnyErrorsInInits)
1970 return false;
1971
Alexis Hunt1d792652011-01-08 20:30:50 +00001972 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00001973 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1974 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001975
Francois Pichetd583da02010-12-04 09:14:42 +00001976 if (Init)
1977 Info.AllToInit.push_back(Init);
1978
John McCallbc83b3f2010-05-20 23:23:51 +00001979 return false;
1980}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001981
Eli Friedman9cf6b592009-11-09 19:20:36 +00001982bool
Alexis Hunt1d792652011-01-08 20:30:50 +00001983Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
1984 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001985 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001986 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001987 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001988 // Just store the initializers as written, they will be checked during
1989 // instantiation.
1990 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001991 Constructor->setNumCtorInitializers(NumInitializers);
1992 CXXCtorInitializer **baseOrMemberInitializers =
1993 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001994 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00001995 NumInitializers * sizeof(CXXCtorInitializer*));
1996 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001997 }
1998
1999 return false;
2000 }
2001
John McCallbc83b3f2010-05-20 23:23:51 +00002002 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002003
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002004 // We need to build the initializer AST according to order of construction
2005 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002006 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002007 if (!ClassDecl)
2008 return true;
2009
Eli Friedman9cf6b592009-11-09 19:20:36 +00002010 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002011
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002012 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002013 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002014
2015 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002016 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002017 else
Francois Pichetd583da02010-12-04 09:14:42 +00002018 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002019 }
2020
Anders Carlsson43c64af2010-04-21 19:52:01 +00002021 // Keep track of the direct virtual bases.
2022 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2023 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2024 E = ClassDecl->bases_end(); I != E; ++I) {
2025 if (I->isVirtual())
2026 DirectVBases.insert(I);
2027 }
2028
Anders Carlssondb0a9652010-04-02 06:26:44 +00002029 // Push virtual bases before others.
2030 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2031 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2032
Alexis Hunt1d792652011-01-08 20:30:50 +00002033 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002034 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2035 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002036 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002037 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002038 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002039 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002040 VBase, IsInheritedVirtualBase,
2041 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002042 HadError = true;
2043 continue;
2044 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002045
John McCallbc83b3f2010-05-20 23:23:51 +00002046 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002047 }
2048 }
Mike Stump11289f42009-09-09 15:08:12 +00002049
John McCallbc83b3f2010-05-20 23:23:51 +00002050 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002051 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2052 E = ClassDecl->bases_end(); Base != E; ++Base) {
2053 // Virtuals are in the virtual base list and already constructed.
2054 if (Base->isVirtual())
2055 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002056
Alexis Hunt1d792652011-01-08 20:30:50 +00002057 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002058 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2059 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002060 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002061 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002062 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002063 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002064 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002065 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002066 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002067 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002068
John McCallbc83b3f2010-05-20 23:23:51 +00002069 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002070 }
2071 }
Mike Stump11289f42009-09-09 15:08:12 +00002072
John McCallbc83b3f2010-05-20 23:23:51 +00002073 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002074 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002075 E = ClassDecl->field_end(); Field != E; ++Field) {
2076 if ((*Field)->getType()->isIncompleteArrayType()) {
2077 assert(ClassDecl->hasFlexibleArrayMember() &&
2078 "Incomplete array type is not valid");
2079 continue;
2080 }
John McCallbc83b3f2010-05-20 23:23:51 +00002081 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002082 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002083 }
Mike Stump11289f42009-09-09 15:08:12 +00002084
John McCallbc83b3f2010-05-20 23:23:51 +00002085 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002086 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002087 Constructor->setNumCtorInitializers(NumInitializers);
2088 CXXCtorInitializer **baseOrMemberInitializers =
2089 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002090 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002091 NumInitializers * sizeof(CXXCtorInitializer*));
2092 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002093
John McCalla6309952010-03-16 21:39:52 +00002094 // Constructors implicitly reference the base and member
2095 // destructors.
2096 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2097 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002098 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002099
2100 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002101}
2102
Eli Friedman952c15d2009-07-21 19:28:10 +00002103static void *GetKeyForTopLevelField(FieldDecl *Field) {
2104 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002105 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002106 if (RT->getDecl()->isAnonymousStructOrUnion())
2107 return static_cast<void *>(RT->getDecl());
2108 }
2109 return static_cast<void *>(Field);
2110}
2111
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002112static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002113 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002114}
2115
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002116static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002117 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002118 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002119 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002120
Eli Friedman952c15d2009-07-21 19:28:10 +00002121 // For fields injected into the class via declaration of an anonymous union,
2122 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002123 FieldDecl *Field = Member->getAnyMember();
2124
John McCall23eebd92010-04-10 09:28:51 +00002125 // If the field is a member of an anonymous struct or union, our key
2126 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002127 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002128 if (RD->isAnonymousStructOrUnion()) {
2129 while (true) {
2130 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2131 if (Parent->isAnonymousStructOrUnion())
2132 RD = Parent;
2133 else
2134 break;
2135 }
2136
Anders Carlsson83ac3122010-03-30 16:19:37 +00002137 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002138 }
Mike Stump11289f42009-09-09 15:08:12 +00002139
Anders Carlssona942dcd2010-03-30 15:39:27 +00002140 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002141}
2142
Anders Carlssone857b292010-04-02 03:37:03 +00002143static void
2144DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002145 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002146 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002147 unsigned NumInits) {
2148 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002149 return;
Mike Stump11289f42009-09-09 15:08:12 +00002150
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002151 // Don't check initializers order unless the warning is enabled at the
2152 // location of at least one initializer.
2153 bool ShouldCheckOrder = false;
2154 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002155 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002156 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2157 Init->getSourceLocation())
2158 != Diagnostic::Ignored) {
2159 ShouldCheckOrder = true;
2160 break;
2161 }
2162 }
2163 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002164 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002165
John McCallbb7b6582010-04-10 07:37:23 +00002166 // Build the list of bases and members in the order that they'll
2167 // actually be initialized. The explicit initializers should be in
2168 // this same order but may be missing things.
2169 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002170
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002171 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2172
John McCallbb7b6582010-04-10 07:37:23 +00002173 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002174 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002175 ClassDecl->vbases_begin(),
2176 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002177 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002178
John McCallbb7b6582010-04-10 07:37:23 +00002179 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002180 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002181 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002182 if (Base->isVirtual())
2183 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002184 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002185 }
Mike Stump11289f42009-09-09 15:08:12 +00002186
John McCallbb7b6582010-04-10 07:37:23 +00002187 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002188 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2189 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002190 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002191
John McCallbb7b6582010-04-10 07:37:23 +00002192 unsigned NumIdealInits = IdealInitKeys.size();
2193 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002194
Alexis Hunt1d792652011-01-08 20:30:50 +00002195 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002196 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002197 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002198 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002199
2200 // Scan forward to try to find this initializer in the idealized
2201 // initializers list.
2202 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2203 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002204 break;
John McCallbb7b6582010-04-10 07:37:23 +00002205
2206 // If we didn't find this initializer, it must be because we
2207 // scanned past it on a previous iteration. That can only
2208 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002209 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002210 Sema::SemaDiagnosticBuilder D =
2211 SemaRef.Diag(PrevInit->getSourceLocation(),
2212 diag::warn_initializer_out_of_order);
2213
Francois Pichetd583da02010-12-04 09:14:42 +00002214 if (PrevInit->isAnyMemberInitializer())
2215 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002216 else
2217 D << 1 << PrevInit->getBaseClassInfo()->getType();
2218
Francois Pichetd583da02010-12-04 09:14:42 +00002219 if (Init->isAnyMemberInitializer())
2220 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002221 else
2222 D << 1 << Init->getBaseClassInfo()->getType();
2223
2224 // Move back to the initializer's location in the ideal list.
2225 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2226 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002227 break;
John McCallbb7b6582010-04-10 07:37:23 +00002228
2229 assert(IdealIndex != NumIdealInits &&
2230 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002231 }
John McCallbb7b6582010-04-10 07:37:23 +00002232
2233 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002234 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002235}
2236
John McCall23eebd92010-04-10 09:28:51 +00002237namespace {
2238bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002239 CXXCtorInitializer *Init,
2240 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002241 if (!PrevInit) {
2242 PrevInit = Init;
2243 return false;
2244 }
2245
2246 if (FieldDecl *Field = Init->getMember())
2247 S.Diag(Init->getSourceLocation(),
2248 diag::err_multiple_mem_initialization)
2249 << Field->getDeclName()
2250 << Init->getSourceRange();
2251 else {
John McCall424cec92011-01-19 06:33:43 +00002252 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002253 assert(BaseClass && "neither field nor base");
2254 S.Diag(Init->getSourceLocation(),
2255 diag::err_multiple_base_initialization)
2256 << QualType(BaseClass, 0)
2257 << Init->getSourceRange();
2258 }
2259 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2260 << 0 << PrevInit->getSourceRange();
2261
2262 return true;
2263}
2264
Alexis Hunt1d792652011-01-08 20:30:50 +00002265typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002266typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2267
2268bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002269 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002270 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002271 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002272 RecordDecl *Parent = Field->getParent();
2273 if (!Parent->isAnonymousStructOrUnion())
2274 return false;
2275
2276 NamedDecl *Child = Field;
2277 do {
2278 if (Parent->isUnion()) {
2279 UnionEntry &En = Unions[Parent];
2280 if (En.first && En.first != Child) {
2281 S.Diag(Init->getSourceLocation(),
2282 diag::err_multiple_mem_union_initialization)
2283 << Field->getDeclName()
2284 << Init->getSourceRange();
2285 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2286 << 0 << En.second->getSourceRange();
2287 return true;
2288 } else if (!En.first) {
2289 En.first = Child;
2290 En.second = Init;
2291 }
2292 }
2293
2294 Child = Parent;
2295 Parent = cast<RecordDecl>(Parent->getDeclContext());
2296 } while (Parent->isAnonymousStructOrUnion());
2297
2298 return false;
2299}
2300}
2301
Anders Carlssone857b292010-04-02 03:37:03 +00002302/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002303void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002304 SourceLocation ColonLoc,
2305 MemInitTy **meminits, unsigned NumMemInits,
2306 bool AnyErrors) {
2307 if (!ConstructorDecl)
2308 return;
2309
2310 AdjustDeclIfTemplate(ConstructorDecl);
2311
2312 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002313 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002314
2315 if (!Constructor) {
2316 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2317 return;
2318 }
2319
Alexis Hunt1d792652011-01-08 20:30:50 +00002320 CXXCtorInitializer **MemInits =
2321 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002322
2323 // Mapping for the duplicate initializers check.
2324 // For member initializers, this is keyed with a FieldDecl*.
2325 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002326 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002327
2328 // Mapping for the inconsistent anonymous-union initializers check.
2329 RedundantUnionMap MemberUnions;
2330
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002331 bool HadError = false;
2332 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002333 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002334
Abramo Bagnara341d7832010-05-26 18:09:23 +00002335 // Set the source order index.
2336 Init->setSourceOrder(i);
2337
Francois Pichetd583da02010-12-04 09:14:42 +00002338 if (Init->isAnyMemberInitializer()) {
2339 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002340 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2341 CheckRedundantUnionInit(*this, Init, MemberUnions))
2342 HadError = true;
2343 } else {
2344 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2345 if (CheckRedundantInit(*this, Init, Members[Key]))
2346 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002347 }
Anders Carlssone857b292010-04-02 03:37:03 +00002348 }
2349
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002350 if (HadError)
2351 return;
2352
Anders Carlssone857b292010-04-02 03:37:03 +00002353 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002354
Alexis Hunt1d792652011-01-08 20:30:50 +00002355 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002356}
2357
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002358void
John McCalla6309952010-03-16 21:39:52 +00002359Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2360 CXXRecordDecl *ClassDecl) {
2361 // Ignore dependent contexts.
2362 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002363 return;
John McCall1064d7e2010-03-16 05:22:47 +00002364
2365 // FIXME: all the access-control diagnostics are positioned on the
2366 // field/base declaration. That's probably good; that said, the
2367 // user might reasonably want to know why the destructor is being
2368 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002369
Anders Carlssondee9a302009-11-17 04:44:12 +00002370 // Non-static data members.
2371 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2372 E = ClassDecl->field_end(); I != E; ++I) {
2373 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002374 if (Field->isInvalidDecl())
2375 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002376 QualType FieldType = Context.getBaseElementType(Field->getType());
2377
2378 const RecordType* RT = FieldType->getAs<RecordType>();
2379 if (!RT)
2380 continue;
2381
2382 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2383 if (FieldClassDecl->hasTrivialDestructor())
2384 continue;
2385
Douglas Gregore71edda2010-07-01 22:47:18 +00002386 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002387 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002388 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002389 << Field->getDeclName()
2390 << FieldType);
2391
John McCalla6309952010-03-16 21:39:52 +00002392 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002393 }
2394
John McCall1064d7e2010-03-16 05:22:47 +00002395 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2396
Anders Carlssondee9a302009-11-17 04:44:12 +00002397 // Bases.
2398 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2399 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002400 // Bases are always records in a well-formed non-dependent class.
2401 const RecordType *RT = Base->getType()->getAs<RecordType>();
2402
2403 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002404 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002405 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002406
2407 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002408 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002409 if (BaseClassDecl->hasTrivialDestructor())
2410 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002411
Douglas Gregore71edda2010-07-01 22:47:18 +00002412 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002413
2414 // FIXME: caret should be on the start of the class name
2415 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002416 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002417 << Base->getType()
2418 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002419
John McCalla6309952010-03-16 21:39:52 +00002420 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002421 }
2422
2423 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002424 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2425 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002426
2427 // Bases are always records in a well-formed non-dependent class.
2428 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2429
2430 // Ignore direct virtual bases.
2431 if (DirectVirtualBases.count(RT))
2432 continue;
2433
Anders Carlssondee9a302009-11-17 04:44:12 +00002434 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002435 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002436 if (BaseClassDecl->hasTrivialDestructor())
2437 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002438
Douglas Gregore71edda2010-07-01 22:47:18 +00002439 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002440 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002441 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002442 << VBase->getType());
2443
John McCalla6309952010-03-16 21:39:52 +00002444 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002445 }
2446}
2447
John McCall48871652010-08-21 09:40:31 +00002448void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002449 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002450 return;
Mike Stump11289f42009-09-09 15:08:12 +00002451
Mike Stump11289f42009-09-09 15:08:12 +00002452 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002453 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002454 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002455}
2456
Mike Stump11289f42009-09-09 15:08:12 +00002457bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002458 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002459 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002460 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002461 else
John McCall02db245d2010-08-18 09:41:07 +00002462 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002463}
2464
Anders Carlssoneabf7702009-08-27 00:13:57 +00002465bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002466 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002467 if (!getLangOptions().CPlusPlus)
2468 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002469
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002470 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002471 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002472
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002473 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002474 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002475 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002476 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002477
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002478 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002479 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002480 }
Mike Stump11289f42009-09-09 15:08:12 +00002481
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002482 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002483 if (!RT)
2484 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002485
John McCall67da35c2010-02-04 22:26:26 +00002486 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002487
John McCall02db245d2010-08-18 09:41:07 +00002488 // We can't answer whether something is abstract until it has a
2489 // definition. If it's currently being defined, we'll walk back
2490 // over all the declarations when we have a full definition.
2491 const CXXRecordDecl *Def = RD->getDefinition();
2492 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002493 return false;
2494
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002495 if (!RD->isAbstract())
2496 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002497
Anders Carlssoneabf7702009-08-27 00:13:57 +00002498 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002499 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002500
John McCall02db245d2010-08-18 09:41:07 +00002501 return true;
2502}
2503
2504void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2505 // Check if we've already emitted the list of pure virtual functions
2506 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002507 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002508 return;
Mike Stump11289f42009-09-09 15:08:12 +00002509
Douglas Gregor4165bd62010-03-23 23:47:56 +00002510 CXXFinalOverriderMap FinalOverriders;
2511 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002512
Anders Carlssona2f74f32010-06-03 01:00:02 +00002513 // Keep a set of seen pure methods so we won't diagnose the same method
2514 // more than once.
2515 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2516
Douglas Gregor4165bd62010-03-23 23:47:56 +00002517 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2518 MEnd = FinalOverriders.end();
2519 M != MEnd;
2520 ++M) {
2521 for (OverridingMethods::iterator SO = M->second.begin(),
2522 SOEnd = M->second.end();
2523 SO != SOEnd; ++SO) {
2524 // C++ [class.abstract]p4:
2525 // A class is abstract if it contains or inherits at least one
2526 // pure virtual function for which the final overrider is pure
2527 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002528
Douglas Gregor4165bd62010-03-23 23:47:56 +00002529 //
2530 if (SO->second.size() != 1)
2531 continue;
2532
2533 if (!SO->second.front().Method->isPure())
2534 continue;
2535
Anders Carlssona2f74f32010-06-03 01:00:02 +00002536 if (!SeenPureMethods.insert(SO->second.front().Method))
2537 continue;
2538
Douglas Gregor4165bd62010-03-23 23:47:56 +00002539 Diag(SO->second.front().Method->getLocation(),
2540 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00002541 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00002542 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002543 }
2544
2545 if (!PureVirtualClassDiagSet)
2546 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2547 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002548}
2549
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002550namespace {
John McCall02db245d2010-08-18 09:41:07 +00002551struct AbstractUsageInfo {
2552 Sema &S;
2553 CXXRecordDecl *Record;
2554 CanQualType AbstractType;
2555 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002556
John McCall02db245d2010-08-18 09:41:07 +00002557 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2558 : S(S), Record(Record),
2559 AbstractType(S.Context.getCanonicalType(
2560 S.Context.getTypeDeclType(Record))),
2561 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002562
John McCall02db245d2010-08-18 09:41:07 +00002563 void DiagnoseAbstractType() {
2564 if (Invalid) return;
2565 S.DiagnoseAbstractType(Record);
2566 Invalid = true;
2567 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002568
John McCall02db245d2010-08-18 09:41:07 +00002569 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2570};
2571
2572struct CheckAbstractUsage {
2573 AbstractUsageInfo &Info;
2574 const NamedDecl *Ctx;
2575
2576 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2577 : Info(Info), Ctx(Ctx) {}
2578
2579 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2580 switch (TL.getTypeLocClass()) {
2581#define ABSTRACT_TYPELOC(CLASS, PARENT)
2582#define TYPELOC(CLASS, PARENT) \
2583 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2584#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002585 }
John McCall02db245d2010-08-18 09:41:07 +00002586 }
Mike Stump11289f42009-09-09 15:08:12 +00002587
John McCall02db245d2010-08-18 09:41:07 +00002588 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2589 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2590 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00002591 if (!TL.getArg(I))
2592 continue;
2593
John McCall02db245d2010-08-18 09:41:07 +00002594 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2595 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002596 }
John McCall02db245d2010-08-18 09:41:07 +00002597 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002598
John McCall02db245d2010-08-18 09:41:07 +00002599 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2600 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2601 }
Mike Stump11289f42009-09-09 15:08:12 +00002602
John McCall02db245d2010-08-18 09:41:07 +00002603 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2604 // Visit the type parameters from a permissive context.
2605 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2606 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2607 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2608 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2609 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2610 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002611 }
John McCall02db245d2010-08-18 09:41:07 +00002612 }
Mike Stump11289f42009-09-09 15:08:12 +00002613
John McCall02db245d2010-08-18 09:41:07 +00002614 // Visit pointee types from a permissive context.
2615#define CheckPolymorphic(Type) \
2616 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2617 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2618 }
2619 CheckPolymorphic(PointerTypeLoc)
2620 CheckPolymorphic(ReferenceTypeLoc)
2621 CheckPolymorphic(MemberPointerTypeLoc)
2622 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002623
John McCall02db245d2010-08-18 09:41:07 +00002624 /// Handle all the types we haven't given a more specific
2625 /// implementation for above.
2626 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2627 // Every other kind of type that we haven't called out already
2628 // that has an inner type is either (1) sugar or (2) contains that
2629 // inner type in some way as a subobject.
2630 if (TypeLoc Next = TL.getNextTypeLoc())
2631 return Visit(Next, Sel);
2632
2633 // If there's no inner type and we're in a permissive context,
2634 // don't diagnose.
2635 if (Sel == Sema::AbstractNone) return;
2636
2637 // Check whether the type matches the abstract type.
2638 QualType T = TL.getType();
2639 if (T->isArrayType()) {
2640 Sel = Sema::AbstractArrayType;
2641 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002642 }
John McCall02db245d2010-08-18 09:41:07 +00002643 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2644 if (CT != Info.AbstractType) return;
2645
2646 // It matched; do some magic.
2647 if (Sel == Sema::AbstractArrayType) {
2648 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2649 << T << TL.getSourceRange();
2650 } else {
2651 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2652 << Sel << T << TL.getSourceRange();
2653 }
2654 Info.DiagnoseAbstractType();
2655 }
2656};
2657
2658void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2659 Sema::AbstractDiagSelID Sel) {
2660 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2661}
2662
2663}
2664
2665/// Check for invalid uses of an abstract type in a method declaration.
2666static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2667 CXXMethodDecl *MD) {
2668 // No need to do the check on definitions, which require that
2669 // the return/param types be complete.
2670 if (MD->isThisDeclarationADefinition())
2671 return;
2672
2673 // For safety's sake, just ignore it if we don't have type source
2674 // information. This should never happen for non-implicit methods,
2675 // but...
2676 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2677 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2678}
2679
2680/// Check for invalid uses of an abstract type within a class definition.
2681static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2682 CXXRecordDecl *RD) {
2683 for (CXXRecordDecl::decl_iterator
2684 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2685 Decl *D = *I;
2686 if (D->isImplicit()) continue;
2687
2688 // Methods and method templates.
2689 if (isa<CXXMethodDecl>(D)) {
2690 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2691 } else if (isa<FunctionTemplateDecl>(D)) {
2692 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2693 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2694
2695 // Fields and static variables.
2696 } else if (isa<FieldDecl>(D)) {
2697 FieldDecl *FD = cast<FieldDecl>(D);
2698 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2699 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2700 } else if (isa<VarDecl>(D)) {
2701 VarDecl *VD = cast<VarDecl>(D);
2702 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2703 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2704
2705 // Nested classes and class templates.
2706 } else if (isa<CXXRecordDecl>(D)) {
2707 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2708 } else if (isa<ClassTemplateDecl>(D)) {
2709 CheckAbstractClassUsage(Info,
2710 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2711 }
2712 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002713}
2714
Douglas Gregorc99f1552009-12-03 18:33:45 +00002715/// \brief Perform semantic checks on a class definition that has been
2716/// completing, introducing implicitly-declared members, checking for
2717/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002718void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002719 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002720 return;
2721
John McCall02db245d2010-08-18 09:41:07 +00002722 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2723 AbstractUsageInfo Info(*this, Record);
2724 CheckAbstractClassUsage(Info, Record);
2725 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002726
2727 // If this is not an aggregate type and has no user-declared constructor,
2728 // complain about any non-static data members of reference or const scalar
2729 // type, since they will never get initializers.
2730 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2731 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2732 bool Complained = false;
2733 for (RecordDecl::field_iterator F = Record->field_begin(),
2734 FEnd = Record->field_end();
2735 F != FEnd; ++F) {
2736 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002737 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002738 if (!Complained) {
2739 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2740 << Record->getTagKind() << Record;
2741 Complained = true;
2742 }
2743
2744 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2745 << F->getType()->isReferenceType()
2746 << F->getDeclName();
2747 }
2748 }
2749 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002750
Anders Carlssone771e762011-01-25 18:08:22 +00002751 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00002752 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002753
2754 if (Record->getIdentifier()) {
2755 // C++ [class.mem]p13:
2756 // If T is the name of a class, then each of the following shall have a
2757 // name different from T:
2758 // - every member of every anonymous union that is a member of class T.
2759 //
2760 // C++ [class.mem]p14:
2761 // In addition, if class T has a user-declared constructor (12.1), every
2762 // non-static data member of class T shall have a name different from T.
2763 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002764 R.first != R.second; ++R.first) {
2765 NamedDecl *D = *R.first;
2766 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2767 isa<IndirectFieldDecl>(D)) {
2768 Diag(D->getLocation(), diag::err_member_name_of_class)
2769 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002770 break;
2771 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002772 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002773 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002774
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002775 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00002776 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002777 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002778 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002779 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2780 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2781 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002782
2783 // See if a method overloads virtual methods in a base
2784 /// class without overriding any.
2785 if (!Record->isDependentType()) {
2786 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2787 MEnd = Record->method_end();
2788 M != MEnd; ++M) {
2789 DiagnoseHiddenVirtualMethods(Record, *M);
2790 }
2791 }
Sebastian Redl08905022011-02-05 19:23:19 +00002792
2793 // Declare inherited constructors. We do this eagerly here because:
2794 // - The standard requires an eager diagnostic for conflicting inherited
2795 // constructors from different classes.
2796 // - The lazy declaration of the other implicit constructors is so as to not
2797 // waste space and performance on classes that are not meant to be
2798 // instantiated (e.g. meta-functions). This doesn't apply to classes that
2799 // have inherited constructors.
2800 DeclareInheritedConstructors(Record);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002801}
2802
2803/// \brief Data used with FindHiddenVirtualMethod
2804struct FindHiddenVirtualMethodData {
2805 Sema *S;
2806 CXXMethodDecl *Method;
2807 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
2808 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2809};
2810
2811/// \brief Member lookup function that determines whether a given C++
2812/// method overloads virtual methods in a base class without overriding any,
2813/// to be used with CXXRecordDecl::lookupInBases().
2814static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
2815 CXXBasePath &Path,
2816 void *UserData) {
2817 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2818
2819 FindHiddenVirtualMethodData &Data
2820 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
2821
2822 DeclarationName Name = Data.Method->getDeclName();
2823 assert(Name.getNameKind() == DeclarationName::Identifier);
2824
2825 bool foundSameNameMethod = false;
2826 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
2827 for (Path.Decls = BaseRecord->lookup(Name);
2828 Path.Decls.first != Path.Decls.second;
2829 ++Path.Decls.first) {
2830 NamedDecl *D = *Path.Decls.first;
2831 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00002832 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002833 foundSameNameMethod = true;
2834 // Interested only in hidden virtual methods.
2835 if (!MD->isVirtual())
2836 continue;
2837 // If the method we are checking overrides a method from its base
2838 // don't warn about the other overloaded methods.
2839 if (!Data.S->IsOverload(Data.Method, MD, false))
2840 return true;
2841 // Collect the overload only if its hidden.
2842 if (!Data.OverridenAndUsingBaseMethods.count(MD))
2843 overloadedMethods.push_back(MD);
2844 }
2845 }
2846
2847 if (foundSameNameMethod)
2848 Data.OverloadedMethods.append(overloadedMethods.begin(),
2849 overloadedMethods.end());
2850 return foundSameNameMethod;
2851}
2852
2853/// \brief See if a method overloads virtual methods in a base class without
2854/// overriding any.
2855void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2856 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
2857 MD->getLocation()) == Diagnostic::Ignored)
2858 return;
2859 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
2860 return;
2861
2862 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
2863 /*bool RecordPaths=*/false,
2864 /*bool DetectVirtual=*/false);
2865 FindHiddenVirtualMethodData Data;
2866 Data.Method = MD;
2867 Data.S = this;
2868
2869 // Keep the base methods that were overriden or introduced in the subclass
2870 // by 'using' in a set. A base method not in this set is hidden.
2871 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
2872 res.first != res.second; ++res.first) {
2873 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
2874 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
2875 E = MD->end_overridden_methods();
2876 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00002877 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002878 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
2879 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00002880 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002881 }
2882
2883 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
2884 !Data.OverloadedMethods.empty()) {
2885 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
2886 << MD << (Data.OverloadedMethods.size() > 1);
2887
2888 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
2889 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
2890 Diag(overloadedMD->getLocation(),
2891 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
2892 }
2893 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002894}
2895
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002896void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002897 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002898 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002899 SourceLocation RBrac,
2900 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002901 if (!TagDecl)
2902 return;
Mike Stump11289f42009-09-09 15:08:12 +00002903
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002904 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002905
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002906 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002907 // strict aliasing violation!
2908 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002909 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002910
Douglas Gregor0be31a22010-07-02 17:43:08 +00002911 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002912 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002913}
2914
Douglas Gregor95755162010-07-01 05:10:53 +00002915namespace {
2916 /// \brief Helper class that collects exception specifications for
2917 /// implicitly-declared special member functions.
2918 class ImplicitExceptionSpecification {
2919 ASTContext &Context;
2920 bool AllowsAllExceptions;
2921 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2922 llvm::SmallVector<QualType, 4> Exceptions;
2923
2924 public:
2925 explicit ImplicitExceptionSpecification(ASTContext &Context)
2926 : Context(Context), AllowsAllExceptions(false) { }
2927
2928 /// \brief Whether the special member function should have any
2929 /// exception specification at all.
2930 bool hasExceptionSpecification() const {
2931 return !AllowsAllExceptions;
2932 }
2933
2934 /// \brief Whether the special member function should have a
2935 /// throw(...) exception specification (a Microsoft extension).
2936 bool hasAnyExceptionSpecification() const {
2937 return false;
2938 }
2939
2940 /// \brief The number of exceptions in the exception specification.
2941 unsigned size() const { return Exceptions.size(); }
2942
2943 /// \brief The set of exceptions in the exception specification.
2944 const QualType *data() const { return Exceptions.data(); }
2945
2946 /// \brief Note that
2947 void CalledDecl(CXXMethodDecl *Method) {
2948 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002949 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002950 return;
2951
2952 const FunctionProtoType *Proto
2953 = Method->getType()->getAs<FunctionProtoType>();
2954
2955 // If this function can throw any exceptions, make a note of that.
2956 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2957 AllowsAllExceptions = true;
2958 ExceptionsSeen.clear();
2959 Exceptions.clear();
2960 return;
2961 }
2962
2963 // Record the exceptions in this function's exception specification.
2964 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2965 EEnd = Proto->exception_end();
2966 E != EEnd; ++E)
2967 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2968 Exceptions.push_back(*E);
2969 }
2970 };
2971}
2972
2973
Douglas Gregor05379422008-11-03 17:51:48 +00002974/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2975/// special functions, such as the default constructor, copy
2976/// constructor, or destructor, to the given C++ class (C++
2977/// [special]p1). This routine can only be executed just before the
2978/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002979void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002980 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002981 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002982
Douglas Gregor54be3392010-07-01 17:57:27 +00002983 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002984 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002985
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002986 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2987 ++ASTContext::NumImplicitCopyAssignmentOperators;
2988
2989 // If we have a dynamic class, then the copy assignment operator may be
2990 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2991 // it shows up in the right place in the vtable and that we diagnose
2992 // problems with the implicit exception specification.
2993 if (ClassDecl->isDynamicClass())
2994 DeclareImplicitCopyAssignment(ClassDecl);
2995 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002996
Douglas Gregor7454c562010-07-02 20:37:36 +00002997 if (!ClassDecl->hasUserDeclaredDestructor()) {
2998 ++ASTContext::NumImplicitDestructors;
2999
3000 // If we have a dynamic class, then the destructor may be virtual, so we
3001 // have to declare the destructor immediately. This ensures that, e.g., it
3002 // shows up in the right place in the vtable and that we diagnose problems
3003 // with the implicit exception specification.
3004 if (ClassDecl->isDynamicClass())
3005 DeclareImplicitDestructor(ClassDecl);
3006 }
Douglas Gregor05379422008-11-03 17:51:48 +00003007}
3008
John McCall48871652010-08-21 09:40:31 +00003009void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00003010 if (!D)
3011 return;
3012
3013 TemplateParameterList *Params = 0;
3014 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3015 Params = Template->getTemplateParameters();
3016 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3017 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3018 Params = PartialSpec->getTemplateParameters();
3019 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003020 return;
3021
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003022 for (TemplateParameterList::iterator Param = Params->begin(),
3023 ParamEnd = Params->end();
3024 Param != ParamEnd; ++Param) {
3025 NamedDecl *Named = cast<NamedDecl>(*Param);
3026 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00003027 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003028 IdResolver.AddDecl(Named);
3029 }
3030 }
3031}
3032
John McCall48871652010-08-21 09:40:31 +00003033void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00003034 if (!RecordD) return;
3035 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00003036 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00003037 PushDeclContext(S, Record);
3038}
3039
John McCall48871652010-08-21 09:40:31 +00003040void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00003041 if (!RecordD) return;
3042 PopDeclContext();
3043}
3044
Douglas Gregor4d87df52008-12-16 21:30:33 +00003045/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3046/// parsing a top-level (non-nested) C++ class, and we are now
3047/// parsing those parts of the given Method declaration that could
3048/// not be parsed earlier (C++ [class.mem]p2), such as default
3049/// arguments. This action should enter the scope of the given
3050/// Method declaration as if we had just parsed the qualified method
3051/// name. However, it should not bring the parameters into scope;
3052/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00003053void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003054}
3055
3056/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3057/// C++ method declaration. We're (re-)introducing the given
3058/// function parameter into scope for use in parsing later parts of
3059/// the method declaration. For example, we could see an
3060/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00003061void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003062 if (!ParamD)
3063 return;
Mike Stump11289f42009-09-09 15:08:12 +00003064
John McCall48871652010-08-21 09:40:31 +00003065 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00003066
3067 // If this parameter has an unparsed default argument, clear it out
3068 // to make way for the parsed default argument.
3069 if (Param->hasUnparsedDefaultArg())
3070 Param->setDefaultArg(0);
3071
John McCall48871652010-08-21 09:40:31 +00003072 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003073 if (Param->getDeclName())
3074 IdResolver.AddDecl(Param);
3075}
3076
3077/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3078/// processing the delayed method declaration for Method. The method
3079/// declaration is now considered finished. There may be a separate
3080/// ActOnStartOfFunctionDef action later (not necessarily
3081/// immediately!) for this method, if it was also defined inside the
3082/// class body.
John McCall48871652010-08-21 09:40:31 +00003083void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003084 if (!MethodD)
3085 return;
Mike Stump11289f42009-09-09 15:08:12 +00003086
Douglas Gregorc8c277a2009-08-24 11:57:43 +00003087 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00003088
John McCall48871652010-08-21 09:40:31 +00003089 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003090
3091 // Now that we have our default arguments, check the constructor
3092 // again. It could produce additional diagnostics or affect whether
3093 // the class has implicitly-declared destructors, among other
3094 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003095 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3096 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003097
3098 // Check the default arguments, which we may have added.
3099 if (!Method->isInvalidDecl())
3100 CheckCXXDefaultArguments(Method);
3101}
3102
Douglas Gregor831c93f2008-11-05 20:51:48 +00003103/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00003104/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00003105/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003106/// emit diagnostics and set the invalid bit to true. In any case, the type
3107/// will be updated to reflect a well-formed type for the constructor and
3108/// returned.
3109QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003110 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003111 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003112
3113 // C++ [class.ctor]p3:
3114 // A constructor shall not be virtual (10.3) or static (9.4). A
3115 // constructor can be invoked for a const, volatile or const
3116 // volatile object. A constructor shall not be declared const,
3117 // volatile, or const volatile (9.3.2).
3118 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003119 if (!D.isInvalidType())
3120 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3121 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3122 << SourceRange(D.getIdentifierLoc());
3123 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003124 }
John McCall8e7d6562010-08-26 03:08:43 +00003125 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003126 if (!D.isInvalidType())
3127 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3128 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3129 << SourceRange(D.getIdentifierLoc());
3130 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003131 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003132 }
Mike Stump11289f42009-09-09 15:08:12 +00003133
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003134 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003135 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00003136 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003137 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3138 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003139 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003140 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3141 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003142 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003143 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3144 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00003145 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003146 }
Mike Stump11289f42009-09-09 15:08:12 +00003147
Douglas Gregordb9d6642011-01-26 05:01:58 +00003148 // C++0x [class.ctor]p4:
3149 // A constructor shall not be declared with a ref-qualifier.
3150 if (FTI.hasRefQualifier()) {
3151 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3152 << FTI.RefQualifierIsLValueRef
3153 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3154 D.setInvalidType();
3155 }
3156
Douglas Gregor831c93f2008-11-05 20:51:48 +00003157 // Rebuild the function type "R" without any type qualifiers (in
3158 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00003159 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00003160 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003161 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3162 return R;
3163
3164 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3165 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00003166 EPI.RefQualifier = RQ_None;
3167
Chris Lattner38378bf2009-04-25 08:28:21 +00003168 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00003169 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003170}
3171
Douglas Gregor4d87df52008-12-16 21:30:33 +00003172/// CheckConstructor - Checks a fully-formed constructor for
3173/// well-formedness, issuing any diagnostics required. Returns true if
3174/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003175void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00003176 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003177 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3178 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003179 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003180
3181 // C++ [class.copy]p3:
3182 // A declaration of a constructor for a class X is ill-formed if
3183 // its first parameter is of type (optionally cv-qualified) X and
3184 // either there are no other parameters or else all other
3185 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003186 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00003187 ((Constructor->getNumParams() == 1) ||
3188 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00003189 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3190 Constructor->getTemplateSpecializationKind()
3191 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003192 QualType ParamType = Constructor->getParamDecl(0)->getType();
3193 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3194 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00003195 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00003196 const char *ConstRef
3197 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3198 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00003199 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00003200 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00003201
3202 // FIXME: Rather that making the constructor invalid, we should endeavor
3203 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003204 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003205 }
3206 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00003207}
3208
John McCalldeb646e2010-08-04 01:04:25 +00003209/// CheckDestructor - Checks a fully-formed destructor definition for
3210/// well-formedness, issuing any diagnostics required. Returns true
3211/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00003212bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00003213 CXXRecordDecl *RD = Destructor->getParent();
3214
3215 if (Destructor->isVirtual()) {
3216 SourceLocation Loc;
3217
3218 if (!Destructor->isImplicit())
3219 Loc = Destructor->getLocation();
3220 else
3221 Loc = RD->getLocation();
3222
3223 // If we have a virtual destructor, look up the deallocation function
3224 FunctionDecl *OperatorDelete = 0;
3225 DeclarationName Name =
3226 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003227 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003228 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003229
3230 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003231
3232 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003233 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003234
3235 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003236}
3237
Mike Stump11289f42009-09-09 15:08:12 +00003238static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003239FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3240 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3241 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003242 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003243}
3244
Douglas Gregor831c93f2008-11-05 20:51:48 +00003245/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3246/// the well-formednes of the destructor declarator @p D with type @p
3247/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003248/// emit diagnostics and set the declarator to invalid. Even if this happens,
3249/// will be updated to reflect a well-formed type for the destructor and
3250/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003251QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003252 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003253 // C++ [class.dtor]p1:
3254 // [...] A typedef-name that names a class is a class-name
3255 // (7.1.3); however, a typedef-name that names a class shall not
3256 // be used as the identifier in the declarator for a destructor
3257 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003258 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00003259 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00003260 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003261 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003262
3263 // C++ [class.dtor]p2:
3264 // A destructor is used to destroy objects of its class type. A
3265 // destructor takes no parameters, and no return type can be
3266 // specified for it (not even void). The address of a destructor
3267 // shall not be taken. A destructor shall not be static. A
3268 // destructor can be invoked for a const, volatile or const
3269 // volatile object. A destructor shall not be declared const,
3270 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00003271 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003272 if (!D.isInvalidType())
3273 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3274 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003275 << SourceRange(D.getIdentifierLoc())
3276 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3277
John McCall8e7d6562010-08-26 03:08:43 +00003278 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003279 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003280 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003281 // Destructors don't have return types, but the parser will
3282 // happily parse something like:
3283 //
3284 // class X {
3285 // float ~X();
3286 // };
3287 //
3288 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003289 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3290 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3291 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003292 }
Mike Stump11289f42009-09-09 15:08:12 +00003293
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003294 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003295 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003296 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003297 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3298 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003299 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003300 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3301 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003302 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003303 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3304 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003305 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003306 }
3307
Douglas Gregordb9d6642011-01-26 05:01:58 +00003308 // C++0x [class.dtor]p2:
3309 // A destructor shall not be declared with a ref-qualifier.
3310 if (FTI.hasRefQualifier()) {
3311 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3312 << FTI.RefQualifierIsLValueRef
3313 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3314 D.setInvalidType();
3315 }
3316
Douglas Gregor831c93f2008-11-05 20:51:48 +00003317 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003318 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003319 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3320
3321 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003322 FTI.freeArgs();
3323 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003324 }
3325
Mike Stump11289f42009-09-09 15:08:12 +00003326 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003327 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003328 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003329 D.setInvalidType();
3330 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003331
3332 // Rebuild the function type "R" without any type qualifiers or
3333 // parameters (in case any of the errors above fired) and with
3334 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003335 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003336 if (!D.isInvalidType())
3337 return R;
3338
Douglas Gregor95755162010-07-01 05:10:53 +00003339 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003340 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3341 EPI.Variadic = false;
3342 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00003343 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00003344 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003345}
3346
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003347/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3348/// well-formednes of the conversion function declarator @p D with
3349/// type @p R. If there are any errors in the declarator, this routine
3350/// will emit diagnostics and return true. Otherwise, it will return
3351/// false. Either way, the type @p R will be updated to reflect a
3352/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003353void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003354 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003355 // C++ [class.conv.fct]p1:
3356 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003357 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003358 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003359 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003360 if (!D.isInvalidType())
3361 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3362 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3363 << SourceRange(D.getIdentifierLoc());
3364 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003365 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003366 }
John McCall212fa2e2010-04-13 00:04:31 +00003367
3368 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3369
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003370 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003371 // Conversion functions don't have return types, but the parser will
3372 // happily parse something like:
3373 //
3374 // class X {
3375 // float operator bool();
3376 // };
3377 //
3378 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003379 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3380 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3381 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003382 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003383 }
3384
John McCall212fa2e2010-04-13 00:04:31 +00003385 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3386
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003387 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003388 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003389 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3390
3391 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003392 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003393 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003394 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003395 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003396 D.setInvalidType();
3397 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003398
John McCall212fa2e2010-04-13 00:04:31 +00003399 // Diagnose "&operator bool()" and other such nonsense. This
3400 // is actually a gcc extension which we don't support.
3401 if (Proto->getResultType() != ConvType) {
3402 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3403 << Proto->getResultType();
3404 D.setInvalidType();
3405 ConvType = Proto->getResultType();
3406 }
3407
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003408 // C++ [class.conv.fct]p4:
3409 // The conversion-type-id shall not represent a function type nor
3410 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003411 if (ConvType->isArrayType()) {
3412 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3413 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003414 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003415 } else if (ConvType->isFunctionType()) {
3416 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3417 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003418 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003419 }
3420
3421 // Rebuild the function type "R" without any parameters (in case any
3422 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003423 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003424 if (D.isInvalidType())
3425 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003426
Douglas Gregor5fb53972009-01-14 15:45:31 +00003427 // C++0x explicit conversion operators.
3428 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003429 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003430 diag::warn_explicit_conversion_functions)
3431 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003432}
3433
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003434/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3435/// the declaration of the given C++ conversion function. This routine
3436/// is responsible for recording the conversion function in the C++
3437/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003438Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003439 assert(Conversion && "Expected to receive a conversion function declaration");
3440
Douglas Gregor4287b372008-12-12 08:25:50 +00003441 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003442
3443 // Make sure we aren't redeclaring the conversion function.
3444 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003445
3446 // C++ [class.conv.fct]p1:
3447 // [...] A conversion function is never used to convert a
3448 // (possibly cv-qualified) object to the (possibly cv-qualified)
3449 // same object type (or a reference to it), to a (possibly
3450 // cv-qualified) base class of that type (or a reference to it),
3451 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003452 // FIXME: Suppress this warning if the conversion function ends up being a
3453 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003454 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003455 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003456 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003457 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003458 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3459 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003460 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003461 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003462 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3463 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003464 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003465 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003466 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003467 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003468 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003469 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003470 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003471 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003472 }
3473
Douglas Gregor457104e2010-09-29 04:25:11 +00003474 if (FunctionTemplateDecl *ConversionTemplate
3475 = Conversion->getDescribedFunctionTemplate())
3476 return ConversionTemplate;
3477
John McCall48871652010-08-21 09:40:31 +00003478 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003479}
3480
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003481//===----------------------------------------------------------------------===//
3482// Namespace Handling
3483//===----------------------------------------------------------------------===//
3484
John McCallb1be5232010-08-26 09:15:37 +00003485
3486
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003487/// ActOnStartNamespaceDef - This is called at the start of a namespace
3488/// definition.
John McCall48871652010-08-21 09:40:31 +00003489Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003490 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003491 SourceLocation IdentLoc,
3492 IdentifierInfo *II,
3493 SourceLocation LBrace,
3494 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003495 // anonymous namespace starts at its left brace
3496 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3497 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003498 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003499 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003500
3501 Scope *DeclRegionScope = NamespcScope->getParent();
3502
Anders Carlssona7bcade2010-02-07 01:09:23 +00003503 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3504
John McCall2faf32c2010-12-10 02:59:44 +00003505 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3506 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003507
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003508 if (II) {
3509 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003510 // The identifier in an original-namespace-definition shall not
3511 // have been previously defined in the declarative region in
3512 // which the original-namespace-definition appears. The
3513 // identifier in an original-namespace-definition is the name of
3514 // the namespace. Subsequently in that declarative region, it is
3515 // treated as an original-namespace-name.
3516 //
3517 // Since namespace names are unique in their scope, and we don't
3518 // look through using directives, just
3519 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3520 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003521
Douglas Gregor91f84212008-12-11 16:49:14 +00003522 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3523 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003524 if (Namespc->isInline() != OrigNS->isInline()) {
3525 // inline-ness must match
3526 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3527 << Namespc->isInline();
3528 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3529 Namespc->setInvalidDecl();
3530 // Recover by ignoring the new namespace's inline status.
3531 Namespc->setInline(OrigNS->isInline());
3532 }
3533
Douglas Gregor91f84212008-12-11 16:49:14 +00003534 // Attach this namespace decl to the chain of extended namespace
3535 // definitions.
3536 OrigNS->setNextNamespace(Namespc);
3537 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003538
Mike Stump11289f42009-09-09 15:08:12 +00003539 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003540 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003541 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003542 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003543 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003544 } else if (PrevDecl) {
3545 // This is an invalid name redefinition.
3546 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3547 << Namespc->getDeclName();
3548 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3549 Namespc->setInvalidDecl();
3550 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003551 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003552 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003553 // This is the first "real" definition of the namespace "std", so update
3554 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003555 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003556 // We had already defined a dummy namespace "std". Link this new
3557 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003558 StdNS->setNextNamespace(Namespc);
3559 StdNS->setLocation(IdentLoc);
3560 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003561 }
3562
3563 // Make our StdNamespace cache point at the first real definition of the
3564 // "std" namespace.
3565 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003566 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003567
3568 PushOnScopeChains(Namespc, DeclRegionScope);
3569 } else {
John McCall4fa53422009-10-01 00:25:31 +00003570 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003571 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003572
3573 // Link the anonymous namespace into its parent.
3574 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003575 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003576 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3577 PrevDecl = TU->getAnonymousNamespace();
3578 TU->setAnonymousNamespace(Namespc);
3579 } else {
3580 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3581 PrevDecl = ND->getAnonymousNamespace();
3582 ND->setAnonymousNamespace(Namespc);
3583 }
3584
3585 // Link the anonymous namespace with its previous declaration.
3586 if (PrevDecl) {
3587 assert(PrevDecl->isAnonymousNamespace());
3588 assert(!PrevDecl->getNextNamespace());
3589 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3590 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003591
3592 if (Namespc->isInline() != PrevDecl->isInline()) {
3593 // inline-ness must match
3594 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3595 << Namespc->isInline();
3596 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3597 Namespc->setInvalidDecl();
3598 // Recover by ignoring the new namespace's inline status.
3599 Namespc->setInline(PrevDecl->isInline());
3600 }
John McCall0db42252009-12-16 02:06:49 +00003601 }
John McCall4fa53422009-10-01 00:25:31 +00003602
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003603 CurContext->addDecl(Namespc);
3604
John McCall4fa53422009-10-01 00:25:31 +00003605 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3606 // behaves as if it were replaced by
3607 // namespace unique { /* empty body */ }
3608 // using namespace unique;
3609 // namespace unique { namespace-body }
3610 // where all occurrences of 'unique' in a translation unit are
3611 // replaced by the same identifier and this identifier differs
3612 // from all other identifiers in the entire program.
3613
3614 // We just create the namespace with an empty name and then add an
3615 // implicit using declaration, just like the standard suggests.
3616 //
3617 // CodeGen enforces the "universally unique" aspect by giving all
3618 // declarations semantically contained within an anonymous
3619 // namespace internal linkage.
3620
John McCall0db42252009-12-16 02:06:49 +00003621 if (!PrevDecl) {
3622 UsingDirectiveDecl* UD
3623 = UsingDirectiveDecl::Create(Context, CurContext,
3624 /* 'using' */ LBrace,
3625 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00003626 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00003627 /* identifier */ SourceLocation(),
3628 Namespc,
3629 /* Ancestor */ CurContext);
3630 UD->setImplicit();
3631 CurContext->addDecl(UD);
3632 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003633 }
3634
3635 // Although we could have an invalid decl (i.e. the namespace name is a
3636 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003637 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3638 // for the namespace has the declarations that showed up in that particular
3639 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003640 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003641 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003642}
3643
Sebastian Redla6602e92009-11-23 15:34:23 +00003644/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3645/// is a namespace alias, returns the namespace it points to.
3646static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3647 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3648 return AD->getNamespace();
3649 return dyn_cast_or_null<NamespaceDecl>(D);
3650}
3651
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003652/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3653/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003654void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003655 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3656 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3657 Namespc->setRBracLoc(RBrace);
3658 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003659 if (Namespc->hasAttr<VisibilityAttr>())
3660 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003661}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003662
John McCall28a0cf72010-08-25 07:42:41 +00003663CXXRecordDecl *Sema::getStdBadAlloc() const {
3664 return cast_or_null<CXXRecordDecl>(
3665 StdBadAlloc.get(Context.getExternalSource()));
3666}
3667
3668NamespaceDecl *Sema::getStdNamespace() const {
3669 return cast_or_null<NamespaceDecl>(
3670 StdNamespace.get(Context.getExternalSource()));
3671}
3672
Douglas Gregorcdf87022010-06-29 17:53:46 +00003673/// \brief Retrieve the special "std" namespace, which may require us to
3674/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003675NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003676 if (!StdNamespace) {
3677 // The "std" namespace has not yet been defined, so build one implicitly.
3678 StdNamespace = NamespaceDecl::Create(Context,
3679 Context.getTranslationUnitDecl(),
3680 SourceLocation(),
3681 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003682 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003683 }
3684
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003685 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003686}
3687
John McCall48871652010-08-21 09:40:31 +00003688Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003689 SourceLocation UsingLoc,
3690 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003691 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003692 SourceLocation IdentLoc,
3693 IdentifierInfo *NamespcName,
3694 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003695 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3696 assert(NamespcName && "Invalid NamespcName.");
3697 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003698
3699 // This can only happen along a recovery path.
3700 while (S->getFlags() & Scope::TemplateParamScope)
3701 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003702 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003703
Douglas Gregor889ceb72009-02-03 19:21:40 +00003704 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003705 NestedNameSpecifier *Qualifier = 0;
3706 if (SS.isSet())
3707 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3708
Douglas Gregor34074322009-01-14 22:20:51 +00003709 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003710 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3711 LookupParsedName(R, S, &SS);
3712 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003713 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003714
Douglas Gregorcdf87022010-06-29 17:53:46 +00003715 if (R.empty()) {
3716 // Allow "using namespace std;" or "using namespace ::std;" even if
3717 // "std" hasn't been defined yet, for GCC compatibility.
3718 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3719 NamespcName->isStr("std")) {
3720 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003721 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003722 R.resolveKind();
3723 }
3724 // Otherwise, attempt typo correction.
3725 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3726 CTC_NoKeywords, 0)) {
3727 if (R.getAsSingle<NamespaceDecl>() ||
3728 R.getAsSingle<NamespaceAliasDecl>()) {
3729 if (DeclContext *DC = computeDeclContext(SS, false))
3730 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3731 << NamespcName << DC << Corrected << SS.getRange()
3732 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3733 else
3734 Diag(IdentLoc, diag::err_using_directive_suggest)
3735 << NamespcName << Corrected
3736 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3737 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3738 << Corrected;
3739
3740 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003741 } else {
3742 R.clear();
3743 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003744 }
3745 }
3746 }
3747
John McCall9f3059a2009-10-09 21:13:30 +00003748 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003749 NamedDecl *Named = R.getFoundDecl();
3750 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3751 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003752 // C++ [namespace.udir]p1:
3753 // A using-directive specifies that the names in the nominated
3754 // namespace can be used in the scope in which the
3755 // using-directive appears after the using-directive. During
3756 // unqualified name lookup (3.4.1), the names appear as if they
3757 // were declared in the nearest enclosing namespace which
3758 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003759 // namespace. [Note: in this context, "contains" means "contains
3760 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003761
3762 // Find enclosing context containing both using-directive and
3763 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003764 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003765 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3766 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3767 CommonAncestor = CommonAncestor->getParent();
3768
Sebastian Redla6602e92009-11-23 15:34:23 +00003769 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00003770 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00003771 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003772 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003773 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003774 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003775 }
3776
Douglas Gregor889ceb72009-02-03 19:21:40 +00003777 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003778 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003779}
3780
3781void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3782 // If scope has associated entity, then using directive is at namespace
3783 // or translation unit scope. We add UsingDirectiveDecls, into
3784 // it's lookup structure.
3785 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003786 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003787 else
3788 // Otherwise it is block-sope. using-directives will affect lookup
3789 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003790 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003791}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003792
Douglas Gregorfec52632009-06-20 00:51:54 +00003793
John McCall48871652010-08-21 09:40:31 +00003794Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003795 AccessSpecifier AS,
3796 bool HasUsingKeyword,
3797 SourceLocation UsingLoc,
3798 CXXScopeSpec &SS,
3799 UnqualifiedId &Name,
3800 AttributeList *AttrList,
3801 bool IsTypeName,
3802 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003803 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003804
Douglas Gregor220f4272009-11-04 16:30:06 +00003805 switch (Name.getKind()) {
3806 case UnqualifiedId::IK_Identifier:
3807 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003808 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003809 case UnqualifiedId::IK_ConversionFunctionId:
3810 break;
3811
3812 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003813 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003814 // C++0x inherited constructors.
3815 if (getLangOptions().CPlusPlus0x) break;
3816
Douglas Gregor220f4272009-11-04 16:30:06 +00003817 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3818 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003819 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003820
3821 case UnqualifiedId::IK_DestructorName:
3822 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3823 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003824 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003825
3826 case UnqualifiedId::IK_TemplateId:
3827 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3828 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003829 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003830 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003831
3832 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3833 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003834 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003835 return 0;
John McCall3969e302009-12-08 07:46:18 +00003836
John McCalla0097262009-12-11 02:10:03 +00003837 // Warn about using declarations.
3838 // TODO: store that the declaration was written without 'using' and
3839 // talk about access decls instead of using decls in the
3840 // diagnostics.
3841 if (!HasUsingKeyword) {
3842 UsingLoc = Name.getSourceRange().getBegin();
3843
3844 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003845 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003846 }
3847
Douglas Gregorc4356532010-12-16 00:46:58 +00003848 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
3849 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
3850 return 0;
3851
John McCall3f746822009-11-17 05:59:44 +00003852 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003853 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003854 /* IsInstantiation */ false,
3855 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003856 if (UD)
3857 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003858
John McCall48871652010-08-21 09:40:31 +00003859 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003860}
3861
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003862/// \brief Determine whether a using declaration considers the given
3863/// declarations as "equivalent", e.g., if they are redeclarations of
3864/// the same entity or are both typedefs of the same type.
3865static bool
3866IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3867 bool &SuppressRedeclaration) {
3868 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3869 SuppressRedeclaration = false;
3870 return true;
3871 }
3872
3873 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3874 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3875 SuppressRedeclaration = true;
3876 return Context.hasSameType(TD1->getUnderlyingType(),
3877 TD2->getUnderlyingType());
3878 }
3879
3880 return false;
3881}
3882
3883
John McCall84d87672009-12-10 09:41:52 +00003884/// Determines whether to create a using shadow decl for a particular
3885/// decl, given the set of decls existing prior to this using lookup.
3886bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3887 const LookupResult &Previous) {
3888 // Diagnose finding a decl which is not from a base class of the
3889 // current class. We do this now because there are cases where this
3890 // function will silently decide not to build a shadow decl, which
3891 // will pre-empt further diagnostics.
3892 //
3893 // We don't need to do this in C++0x because we do the check once on
3894 // the qualifier.
3895 //
3896 // FIXME: diagnose the following if we care enough:
3897 // struct A { int foo; };
3898 // struct B : A { using A::foo; };
3899 // template <class T> struct C : A {};
3900 // template <class T> struct D : C<T> { using B::foo; } // <---
3901 // This is invalid (during instantiation) in C++03 because B::foo
3902 // resolves to the using decl in B, which is not a base class of D<T>.
3903 // We can't diagnose it immediately because C<T> is an unknown
3904 // specialization. The UsingShadowDecl in D<T> then points directly
3905 // to A::foo, which will look well-formed when we instantiate.
3906 // The right solution is to not collapse the shadow-decl chain.
3907 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3908 DeclContext *OrigDC = Orig->getDeclContext();
3909
3910 // Handle enums and anonymous structs.
3911 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3912 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3913 while (OrigRec->isAnonymousStructOrUnion())
3914 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3915
3916 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3917 if (OrigDC == CurContext) {
3918 Diag(Using->getLocation(),
3919 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00003920 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00003921 Diag(Orig->getLocation(), diag::note_using_decl_target);
3922 return true;
3923 }
3924
Douglas Gregora9d87bc2011-02-25 00:36:19 +00003925 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00003926 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00003927 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00003928 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00003929 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00003930 Diag(Orig->getLocation(), diag::note_using_decl_target);
3931 return true;
3932 }
3933 }
3934
3935 if (Previous.empty()) return false;
3936
3937 NamedDecl *Target = Orig;
3938 if (isa<UsingShadowDecl>(Target))
3939 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3940
John McCalla17e83e2009-12-11 02:33:26 +00003941 // If the target happens to be one of the previous declarations, we
3942 // don't have a conflict.
3943 //
3944 // FIXME: but we might be increasing its access, in which case we
3945 // should redeclare it.
3946 NamedDecl *NonTag = 0, *Tag = 0;
3947 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3948 I != E; ++I) {
3949 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003950 bool Result;
3951 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3952 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003953
3954 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3955 }
3956
John McCall84d87672009-12-10 09:41:52 +00003957 if (Target->isFunctionOrFunctionTemplate()) {
3958 FunctionDecl *FD;
3959 if (isa<FunctionTemplateDecl>(Target))
3960 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3961 else
3962 FD = cast<FunctionDecl>(Target);
3963
3964 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003965 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003966 case Ovl_Overload:
3967 return false;
3968
3969 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003970 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003971 break;
3972
3973 // We found a decl with the exact signature.
3974 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003975 // If we're in a record, we want to hide the target, so we
3976 // return true (without a diagnostic) to tell the caller not to
3977 // build a shadow decl.
3978 if (CurContext->isRecord())
3979 return true;
3980
3981 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003982 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003983 break;
3984 }
3985
3986 Diag(Target->getLocation(), diag::note_using_decl_target);
3987 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3988 return true;
3989 }
3990
3991 // Target is not a function.
3992
John McCall84d87672009-12-10 09:41:52 +00003993 if (isa<TagDecl>(Target)) {
3994 // No conflict between a tag and a non-tag.
3995 if (!Tag) return false;
3996
John McCalle29c5cd2009-12-10 19:51:03 +00003997 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003998 Diag(Target->getLocation(), diag::note_using_decl_target);
3999 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
4000 return true;
4001 }
4002
4003 // No conflict between a tag and a non-tag.
4004 if (!NonTag) return false;
4005
John McCalle29c5cd2009-12-10 19:51:03 +00004006 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004007 Diag(Target->getLocation(), diag::note_using_decl_target);
4008 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4009 return true;
4010}
4011
John McCall3f746822009-11-17 05:59:44 +00004012/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00004013UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00004014 UsingDecl *UD,
4015 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00004016
4017 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00004018 NamedDecl *Target = Orig;
4019 if (isa<UsingShadowDecl>(Target)) {
4020 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4021 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00004022 }
4023
4024 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00004025 = UsingShadowDecl::Create(Context, CurContext,
4026 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00004027 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00004028
4029 Shadow->setAccess(UD->getAccess());
4030 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4031 Shadow->setInvalidDecl();
4032
John McCall3f746822009-11-17 05:59:44 +00004033 if (S)
John McCall3969e302009-12-08 07:46:18 +00004034 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00004035 else
John McCall3969e302009-12-08 07:46:18 +00004036 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00004037
John McCall3969e302009-12-08 07:46:18 +00004038
John McCall84d87672009-12-10 09:41:52 +00004039 return Shadow;
4040}
John McCall3969e302009-12-08 07:46:18 +00004041
John McCall84d87672009-12-10 09:41:52 +00004042/// Hides a using shadow declaration. This is required by the current
4043/// using-decl implementation when a resolvable using declaration in a
4044/// class is followed by a declaration which would hide or override
4045/// one or more of the using decl's targets; for example:
4046///
4047/// struct Base { void foo(int); };
4048/// struct Derived : Base {
4049/// using Base::foo;
4050/// void foo(int);
4051/// };
4052///
4053/// The governing language is C++03 [namespace.udecl]p12:
4054///
4055/// When a using-declaration brings names from a base class into a
4056/// derived class scope, member functions in the derived class
4057/// override and/or hide member functions with the same name and
4058/// parameter types in a base class (rather than conflicting).
4059///
4060/// There are two ways to implement this:
4061/// (1) optimistically create shadow decls when they're not hidden
4062/// by existing declarations, or
4063/// (2) don't create any shadow decls (or at least don't make them
4064/// visible) until we've fully parsed/instantiated the class.
4065/// The problem with (1) is that we might have to retroactively remove
4066/// a shadow decl, which requires several O(n) operations because the
4067/// decl structures are (very reasonably) not designed for removal.
4068/// (2) avoids this but is very fiddly and phase-dependent.
4069void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00004070 if (Shadow->getDeclName().getNameKind() ==
4071 DeclarationName::CXXConversionFunctionName)
4072 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4073
John McCall84d87672009-12-10 09:41:52 +00004074 // Remove it from the DeclContext...
4075 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00004076
John McCall84d87672009-12-10 09:41:52 +00004077 // ...and the scope, if applicable...
4078 if (S) {
John McCall48871652010-08-21 09:40:31 +00004079 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00004080 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00004081 }
4082
John McCall84d87672009-12-10 09:41:52 +00004083 // ...and the using decl.
4084 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4085
4086 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00004087 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00004088}
4089
John McCalle61f2ba2009-11-18 02:36:19 +00004090/// Builds a using declaration.
4091///
4092/// \param IsInstantiation - Whether this call arises from an
4093/// instantiation of an unresolved using declaration. We treat
4094/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00004095NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4096 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004097 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004098 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00004099 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00004100 bool IsInstantiation,
4101 bool IsTypeName,
4102 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00004103 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004104 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00004105 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00004106
Anders Carlssonf038fc22009-08-28 05:49:21 +00004107 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00004108
Anders Carlsson59140b32009-08-28 03:16:11 +00004109 if (SS.isEmpty()) {
4110 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00004111 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00004112 }
Mike Stump11289f42009-09-09 15:08:12 +00004113
John McCall84d87672009-12-10 09:41:52 +00004114 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004115 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00004116 ForRedeclaration);
4117 Previous.setHideTags(false);
4118 if (S) {
4119 LookupName(Previous, S);
4120
4121 // It is really dumb that we have to do this.
4122 LookupResult::Filter F = Previous.makeFilter();
4123 while (F.hasNext()) {
4124 NamedDecl *D = F.next();
4125 if (!isDeclInScope(D, CurContext, S))
4126 F.erase();
4127 }
4128 F.done();
4129 } else {
4130 assert(IsInstantiation && "no scope in non-instantiation");
4131 assert(CurContext->isRecord() && "scope not record in instantiation");
4132 LookupQualifiedName(Previous, CurContext);
4133 }
4134
John McCall84d87672009-12-10 09:41:52 +00004135 // Check for invalid redeclarations.
4136 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4137 return 0;
4138
4139 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00004140 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4141 return 0;
4142
John McCall84c16cf2009-11-12 03:15:40 +00004143 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004144 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004145 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00004146 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00004147 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00004148 // FIXME: not all declaration name kinds are legal here
4149 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4150 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004151 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004152 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00004153 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004154 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
4155 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00004156 }
John McCallb96ec562009-12-04 22:46:56 +00004157 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004158 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
4159 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00004160 }
John McCallb96ec562009-12-04 22:46:56 +00004161 D->setAccess(AS);
4162 CurContext->addDecl(D);
4163
4164 if (!LookupContext) return D;
4165 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00004166
John McCall0b66eb32010-05-01 00:40:08 +00004167 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00004168 UD->setInvalidDecl();
4169 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00004170 }
4171
Sebastian Redl08905022011-02-05 19:23:19 +00004172 // Constructor inheriting using decls get special treatment.
4173 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
4174 if (CheckInheritedConstructorUsingDecl(UD))
4175 UD->setInvalidDecl();
4176 return UD;
4177 }
4178
4179 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00004180
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004181 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00004182
John McCall3969e302009-12-08 07:46:18 +00004183 // Unlike most lookups, we don't always want to hide tag
4184 // declarations: tag names are visible through the using declaration
4185 // even if hidden by ordinary names, *except* in a dependent context
4186 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00004187 if (!IsInstantiation)
4188 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00004189
John McCall27b18f82009-11-17 02:14:36 +00004190 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00004191
John McCall9f3059a2009-10-09 21:13:30 +00004192 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00004193 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004194 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004195 UD->setInvalidDecl();
4196 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004197 }
4198
John McCallb96ec562009-12-04 22:46:56 +00004199 if (R.isAmbiguous()) {
4200 UD->setInvalidDecl();
4201 return UD;
4202 }
Mike Stump11289f42009-09-09 15:08:12 +00004203
John McCalle61f2ba2009-11-18 02:36:19 +00004204 if (IsTypeName) {
4205 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00004206 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004207 Diag(IdentLoc, diag::err_using_typename_non_type);
4208 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4209 Diag((*I)->getUnderlyingDecl()->getLocation(),
4210 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004211 UD->setInvalidDecl();
4212 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004213 }
4214 } else {
4215 // If we asked for a non-typename and we got a type, error out,
4216 // but only if this is an instantiation of an unresolved using
4217 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00004218 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004219 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4220 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004221 UD->setInvalidDecl();
4222 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004223 }
Anders Carlsson59140b32009-08-28 03:16:11 +00004224 }
4225
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004226 // C++0x N2914 [namespace.udecl]p6:
4227 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00004228 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004229 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4230 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004231 UD->setInvalidDecl();
4232 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004233 }
Mike Stump11289f42009-09-09 15:08:12 +00004234
John McCall84d87672009-12-10 09:41:52 +00004235 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4236 if (!CheckUsingShadowDecl(UD, *I, Previous))
4237 BuildUsingShadowDecl(S, UD, *I);
4238 }
John McCall3f746822009-11-17 05:59:44 +00004239
4240 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004241}
4242
Sebastian Redl08905022011-02-05 19:23:19 +00004243/// Additional checks for a using declaration referring to a constructor name.
4244bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4245 if (UD->isTypeName()) {
4246 // FIXME: Cannot specify typename when specifying constructor
4247 return true;
4248 }
4249
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004250 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00004251 assert(SourceType &&
4252 "Using decl naming constructor doesn't have type in scope spec.");
4253 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4254
4255 // Check whether the named type is a direct base class.
4256 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4257 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4258 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4259 BaseIt != BaseE; ++BaseIt) {
4260 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4261 if (CanonicalSourceType == BaseType)
4262 break;
4263 }
4264
4265 if (BaseIt == BaseE) {
4266 // Did not find SourceType in the bases.
4267 Diag(UD->getUsingLocation(),
4268 diag::err_using_decl_constructor_not_in_direct_base)
4269 << UD->getNameInfo().getSourceRange()
4270 << QualType(SourceType, 0) << TargetClass;
4271 return true;
4272 }
4273
4274 BaseIt->setInheritConstructors();
4275
4276 return false;
4277}
4278
John McCall84d87672009-12-10 09:41:52 +00004279/// Checks that the given using declaration is not an invalid
4280/// redeclaration. Note that this is checking only for the using decl
4281/// itself, not for any ill-formedness among the UsingShadowDecls.
4282bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4283 bool isTypeName,
4284 const CXXScopeSpec &SS,
4285 SourceLocation NameLoc,
4286 const LookupResult &Prev) {
4287 // C++03 [namespace.udecl]p8:
4288 // C++0x [namespace.udecl]p10:
4289 // A using-declaration is a declaration and can therefore be used
4290 // repeatedly where (and only where) multiple declarations are
4291 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004292 //
John McCall032092f2010-11-29 18:01:58 +00004293 // That's in non-member contexts.
4294 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004295 return false;
4296
4297 NestedNameSpecifier *Qual
4298 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4299
4300 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4301 NamedDecl *D = *I;
4302
4303 bool DTypename;
4304 NestedNameSpecifier *DQual;
4305 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4306 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004307 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004308 } else if (UnresolvedUsingValueDecl *UD
4309 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4310 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004311 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004312 } else if (UnresolvedUsingTypenameDecl *UD
4313 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4314 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004315 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004316 } else continue;
4317
4318 // using decls differ if one says 'typename' and the other doesn't.
4319 // FIXME: non-dependent using decls?
4320 if (isTypeName != DTypename) continue;
4321
4322 // using decls differ if they name different scopes (but note that
4323 // template instantiation can cause this check to trigger when it
4324 // didn't before instantiation).
4325 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4326 Context.getCanonicalNestedNameSpecifier(DQual))
4327 continue;
4328
4329 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004330 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004331 return true;
4332 }
4333
4334 return false;
4335}
4336
John McCall3969e302009-12-08 07:46:18 +00004337
John McCallb96ec562009-12-04 22:46:56 +00004338/// Checks that the given nested-name qualifier used in a using decl
4339/// in the current context is appropriately related to the current
4340/// scope. If an error is found, diagnoses it and returns true.
4341bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4342 const CXXScopeSpec &SS,
4343 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004344 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004345
John McCall3969e302009-12-08 07:46:18 +00004346 if (!CurContext->isRecord()) {
4347 // C++03 [namespace.udecl]p3:
4348 // C++0x [namespace.udecl]p8:
4349 // A using-declaration for a class member shall be a member-declaration.
4350
4351 // If we weren't able to compute a valid scope, it must be a
4352 // dependent class scope.
4353 if (!NamedContext || NamedContext->isRecord()) {
4354 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4355 << SS.getRange();
4356 return true;
4357 }
4358
4359 // Otherwise, everything is known to be fine.
4360 return false;
4361 }
4362
4363 // The current scope is a record.
4364
4365 // If the named context is dependent, we can't decide much.
4366 if (!NamedContext) {
4367 // FIXME: in C++0x, we can diagnose if we can prove that the
4368 // nested-name-specifier does not refer to a base class, which is
4369 // still possible in some cases.
4370
4371 // Otherwise we have to conservatively report that things might be
4372 // okay.
4373 return false;
4374 }
4375
4376 if (!NamedContext->isRecord()) {
4377 // Ideally this would point at the last name in the specifier,
4378 // but we don't have that level of source info.
4379 Diag(SS.getRange().getBegin(),
4380 diag::err_using_decl_nested_name_specifier_is_not_class)
4381 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4382 return true;
4383 }
4384
Douglas Gregor7c842292010-12-21 07:41:49 +00004385 if (!NamedContext->isDependentContext() &&
4386 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4387 return true;
4388
John McCall3969e302009-12-08 07:46:18 +00004389 if (getLangOptions().CPlusPlus0x) {
4390 // C++0x [namespace.udecl]p3:
4391 // In a using-declaration used as a member-declaration, the
4392 // nested-name-specifier shall name a base class of the class
4393 // being defined.
4394
4395 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4396 cast<CXXRecordDecl>(NamedContext))) {
4397 if (CurContext == NamedContext) {
4398 Diag(NameLoc,
4399 diag::err_using_decl_nested_name_specifier_is_current_class)
4400 << SS.getRange();
4401 return true;
4402 }
4403
4404 Diag(SS.getRange().getBegin(),
4405 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4406 << (NestedNameSpecifier*) SS.getScopeRep()
4407 << cast<CXXRecordDecl>(CurContext)
4408 << SS.getRange();
4409 return true;
4410 }
4411
4412 return false;
4413 }
4414
4415 // C++03 [namespace.udecl]p4:
4416 // A using-declaration used as a member-declaration shall refer
4417 // to a member of a base class of the class being defined [etc.].
4418
4419 // Salient point: SS doesn't have to name a base class as long as
4420 // lookup only finds members from base classes. Therefore we can
4421 // diagnose here only if we can prove that that can't happen,
4422 // i.e. if the class hierarchies provably don't intersect.
4423
4424 // TODO: it would be nice if "definitely valid" results were cached
4425 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4426 // need to be repeated.
4427
4428 struct UserData {
4429 llvm::DenseSet<const CXXRecordDecl*> Bases;
4430
4431 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4432 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4433 Data->Bases.insert(Base);
4434 return true;
4435 }
4436
4437 bool hasDependentBases(const CXXRecordDecl *Class) {
4438 return !Class->forallBases(collect, this);
4439 }
4440
4441 /// Returns true if the base is dependent or is one of the
4442 /// accumulated base classes.
4443 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4444 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4445 return !Data->Bases.count(Base);
4446 }
4447
4448 bool mightShareBases(const CXXRecordDecl *Class) {
4449 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4450 }
4451 };
4452
4453 UserData Data;
4454
4455 // Returns false if we find a dependent base.
4456 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4457 return false;
4458
4459 // Returns false if the class has a dependent base or if it or one
4460 // of its bases is present in the base set of the current context.
4461 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4462 return false;
4463
4464 Diag(SS.getRange().getBegin(),
4465 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4466 << (NestedNameSpecifier*) SS.getScopeRep()
4467 << cast<CXXRecordDecl>(CurContext)
4468 << SS.getRange();
4469
4470 return true;
John McCallb96ec562009-12-04 22:46:56 +00004471}
4472
John McCall48871652010-08-21 09:40:31 +00004473Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004474 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004475 SourceLocation AliasLoc,
4476 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004477 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004478 SourceLocation IdentLoc,
4479 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004480
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004481 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004482 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4483 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004484
Anders Carlssondca83c42009-03-28 06:23:46 +00004485 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004486 NamedDecl *PrevDecl
4487 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4488 ForRedeclaration);
4489 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4490 PrevDecl = 0;
4491
4492 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004493 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004494 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004495 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004496 // FIXME: At some point, we'll want to create the (redundant)
4497 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004498 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004499 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004500 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004501 }
Mike Stump11289f42009-09-09 15:08:12 +00004502
Anders Carlssondca83c42009-03-28 06:23:46 +00004503 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4504 diag::err_redefinition_different_kind;
4505 Diag(AliasLoc, DiagID) << Alias;
4506 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004507 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004508 }
4509
John McCall27b18f82009-11-17 02:14:36 +00004510 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004511 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004512
John McCall9f3059a2009-10-09 21:13:30 +00004513 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004514 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4515 CTC_NoKeywords, 0)) {
4516 if (R.getAsSingle<NamespaceDecl>() ||
4517 R.getAsSingle<NamespaceAliasDecl>()) {
4518 if (DeclContext *DC = computeDeclContext(SS, false))
4519 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4520 << Ident << DC << Corrected << SS.getRange()
4521 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4522 else
4523 Diag(IdentLoc, diag::err_using_directive_suggest)
4524 << Ident << Corrected
4525 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4526
4527 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4528 << Corrected;
4529
4530 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004531 } else {
4532 R.clear();
4533 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004534 }
4535 }
4536
4537 if (R.empty()) {
4538 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004539 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004540 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004541 }
Mike Stump11289f42009-09-09 15:08:12 +00004542
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004543 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004544 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4545 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004546 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004547 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004548
John McCalld8d0d432010-02-16 06:53:13 +00004549 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004550 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004551}
4552
Douglas Gregora57478e2010-05-01 15:04:51 +00004553namespace {
4554 /// \brief Scoped object used to handle the state changes required in Sema
4555 /// to implicitly define the body of a C++ member function;
4556 class ImplicitlyDefinedFunctionScope {
4557 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00004558 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00004559
4560 public:
4561 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00004562 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00004563 {
Douglas Gregora57478e2010-05-01 15:04:51 +00004564 S.PushFunctionScope();
4565 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4566 }
4567
4568 ~ImplicitlyDefinedFunctionScope() {
4569 S.PopExpressionEvaluationContext();
4570 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00004571 }
4572 };
4573}
4574
Sebastian Redlc15c3262010-09-13 22:02:47 +00004575static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4576 CXXRecordDecl *D) {
4577 ASTContext &Context = Self.Context;
4578 QualType ClassType = Context.getTypeDeclType(D);
4579 DeclarationName ConstructorName
4580 = Context.DeclarationNames.getCXXConstructorName(
4581 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4582
4583 DeclContext::lookup_const_iterator Con, ConEnd;
4584 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4585 Con != ConEnd; ++Con) {
4586 // FIXME: In C++0x, a constructor template can be a default constructor.
4587 if (isa<FunctionTemplateDecl>(*Con))
4588 continue;
4589
4590 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4591 if (Constructor->isDefaultConstructor())
4592 return Constructor;
4593 }
4594 return 0;
4595}
4596
Douglas Gregor0be31a22010-07-02 17:43:08 +00004597CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4598 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004599 // C++ [class.ctor]p5:
4600 // A default constructor for a class X is a constructor of class X
4601 // that can be called without an argument. If there is no
4602 // user-declared constructor for class X, a default constructor is
4603 // implicitly declared. An implicitly-declared default constructor
4604 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004605 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4606 "Should not build implicit default constructor!");
4607
Douglas Gregor6d880b12010-07-01 22:31:05 +00004608 // C++ [except.spec]p14:
4609 // An implicitly declared special member function (Clause 12) shall have an
4610 // exception-specification. [...]
4611 ImplicitExceptionSpecification ExceptSpec(Context);
4612
4613 // Direct base-class destructors.
4614 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4615 BEnd = ClassDecl->bases_end();
4616 B != BEnd; ++B) {
4617 if (B->isVirtual()) // Handled below.
4618 continue;
4619
Douglas Gregor9672f922010-07-03 00:47:00 +00004620 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4621 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4622 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4623 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004624 else if (CXXConstructorDecl *Constructor
4625 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004626 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004627 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004628 }
4629
4630 // Virtual base-class destructors.
4631 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4632 BEnd = ClassDecl->vbases_end();
4633 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004634 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4635 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4636 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4637 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4638 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004639 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004640 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004641 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004642 }
4643
4644 // Field destructors.
4645 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4646 FEnd = ClassDecl->field_end();
4647 F != FEnd; ++F) {
4648 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004649 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4650 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4651 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4652 ExceptSpec.CalledDecl(
4653 DeclareImplicitDefaultConstructor(FieldClassDecl));
4654 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004655 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004656 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004657 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004658 }
John McCalldb40c7f2010-12-14 08:05:40 +00004659
4660 FunctionProtoType::ExtProtoInfo EPI;
4661 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4662 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4663 EPI.NumExceptions = ExceptSpec.size();
4664 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor6d880b12010-07-01 22:31:05 +00004665
4666 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004667 CanQualType ClassType
4668 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4669 DeclarationName Name
4670 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004671 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004672 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004673 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004674 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004675 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004676 /*TInfo=*/0,
4677 /*isExplicit=*/false,
4678 /*isInline=*/true,
4679 /*isImplicitlyDeclared=*/true);
4680 DefaultCon->setAccess(AS_public);
4681 DefaultCon->setImplicit();
4682 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004683
4684 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004685 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4686
Douglas Gregor0be31a22010-07-02 17:43:08 +00004687 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004688 PushOnScopeChains(DefaultCon, S, false);
4689 ClassDecl->addDecl(DefaultCon);
4690
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004691 return DefaultCon;
4692}
4693
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004694void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4695 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004696 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004697 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004698 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004699
Anders Carlsson423f5d82010-04-23 16:04:08 +00004700 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004701 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004702
Douglas Gregora57478e2010-05-01 15:04:51 +00004703 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004704 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00004705 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00004706 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004707 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004708 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004709 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004710 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004711 }
Douglas Gregor73193272010-09-20 16:48:21 +00004712
4713 SourceLocation Loc = Constructor->getLocation();
4714 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4715
4716 Constructor->setUsed();
4717 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004718}
4719
Sebastian Redl08905022011-02-05 19:23:19 +00004720void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
4721 // We start with an initial pass over the base classes to collect those that
4722 // inherit constructors from. If there are none, we can forgo all further
4723 // processing.
4724 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
4725 BasesVector BasesToInheritFrom;
4726 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
4727 BaseE = ClassDecl->bases_end();
4728 BaseIt != BaseE; ++BaseIt) {
4729 if (BaseIt->getInheritConstructors()) {
4730 QualType Base = BaseIt->getType();
4731 if (Base->isDependentType()) {
4732 // If we inherit constructors from anything that is dependent, just
4733 // abort processing altogether. We'll get another chance for the
4734 // instantiations.
4735 return;
4736 }
4737 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
4738 }
4739 }
4740 if (BasesToInheritFrom.empty())
4741 return;
4742
4743 // Now collect the constructors that we already have in the current class.
4744 // Those take precedence over inherited constructors.
4745 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
4746 // unless there is a user-declared constructor with the same signature in
4747 // the class where the using-declaration appears.
4748 llvm::SmallSet<const Type *, 8> ExistingConstructors;
4749 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
4750 CtorE = ClassDecl->ctor_end();
4751 CtorIt != CtorE; ++CtorIt) {
4752 ExistingConstructors.insert(
4753 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
4754 }
4755
4756 Scope *S = getScopeForContext(ClassDecl);
4757 DeclarationName CreatedCtorName =
4758 Context.DeclarationNames.getCXXConstructorName(
4759 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
4760
4761 // Now comes the true work.
4762 // First, we keep a map from constructor types to the base that introduced
4763 // them. Needed for finding conflicting constructors. We also keep the
4764 // actually inserted declarations in there, for pretty diagnostics.
4765 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
4766 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
4767 ConstructorToSourceMap InheritedConstructors;
4768 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
4769 BaseE = BasesToInheritFrom.end();
4770 BaseIt != BaseE; ++BaseIt) {
4771 const RecordType *Base = *BaseIt;
4772 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
4773 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
4774 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
4775 CtorE = BaseDecl->ctor_end();
4776 CtorIt != CtorE; ++CtorIt) {
4777 // Find the using declaration for inheriting this base's constructors.
4778 DeclarationName Name =
4779 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
4780 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
4781 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
4782 SourceLocation UsingLoc = UD ? UD->getLocation() :
4783 ClassDecl->getLocation();
4784
4785 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
4786 // from the class X named in the using-declaration consists of actual
4787 // constructors and notional constructors that result from the
4788 // transformation of defaulted parameters as follows:
4789 // - all non-template default constructors of X, and
4790 // - for each non-template constructor of X that has at least one
4791 // parameter with a default argument, the set of constructors that
4792 // results from omitting any ellipsis parameter specification and
4793 // successively omitting parameters with a default argument from the
4794 // end of the parameter-type-list.
4795 CXXConstructorDecl *BaseCtor = *CtorIt;
4796 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
4797 const FunctionProtoType *BaseCtorType =
4798 BaseCtor->getType()->getAs<FunctionProtoType>();
4799
4800 for (unsigned params = BaseCtor->getMinRequiredArguments(),
4801 maxParams = BaseCtor->getNumParams();
4802 params <= maxParams; ++params) {
4803 // Skip default constructors. They're never inherited.
4804 if (params == 0)
4805 continue;
4806 // Skip copy and move constructors for the same reason.
4807 if (CanBeCopyOrMove && params == 1)
4808 continue;
4809
4810 // Build up a function type for this particular constructor.
4811 // FIXME: The working paper does not consider that the exception spec
4812 // for the inheriting constructor might be larger than that of the
4813 // source. This code doesn't yet, either.
4814 const Type *NewCtorType;
4815 if (params == maxParams)
4816 NewCtorType = BaseCtorType;
4817 else {
4818 llvm::SmallVector<QualType, 16> Args;
4819 for (unsigned i = 0; i < params; ++i) {
4820 Args.push_back(BaseCtorType->getArgType(i));
4821 }
4822 FunctionProtoType::ExtProtoInfo ExtInfo =
4823 BaseCtorType->getExtProtoInfo();
4824 ExtInfo.Variadic = false;
4825 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
4826 Args.data(), params, ExtInfo)
4827 .getTypePtr();
4828 }
4829 const Type *CanonicalNewCtorType =
4830 Context.getCanonicalType(NewCtorType);
4831
4832 // Now that we have the type, first check if the class already has a
4833 // constructor with this signature.
4834 if (ExistingConstructors.count(CanonicalNewCtorType))
4835 continue;
4836
4837 // Then we check if we have already declared an inherited constructor
4838 // with this signature.
4839 std::pair<ConstructorToSourceMap::iterator, bool> result =
4840 InheritedConstructors.insert(std::make_pair(
4841 CanonicalNewCtorType,
4842 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
4843 if (!result.second) {
4844 // Already in the map. If it came from a different class, that's an
4845 // error. Not if it's from the same.
4846 CanQualType PreviousBase = result.first->second.first;
4847 if (CanonicalBase != PreviousBase) {
4848 const CXXConstructorDecl *PrevCtor = result.first->second.second;
4849 const CXXConstructorDecl *PrevBaseCtor =
4850 PrevCtor->getInheritedConstructor();
4851 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
4852
4853 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
4854 Diag(BaseCtor->getLocation(),
4855 diag::note_using_decl_constructor_conflict_current_ctor);
4856 Diag(PrevBaseCtor->getLocation(),
4857 diag::note_using_decl_constructor_conflict_previous_ctor);
4858 Diag(PrevCtor->getLocation(),
4859 diag::note_using_decl_constructor_conflict_previous_using);
4860 }
4861 continue;
4862 }
4863
4864 // OK, we're there, now add the constructor.
4865 // C++0x [class.inhctor]p8: [...] that would be performed by a
4866 // user-writtern inline constructor [...]
4867 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
4868 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
4869 Context, ClassDecl, DNI, QualType(NewCtorType, 0), /*TInfo=*/0,
4870 BaseCtor->isExplicit(), /*Inline=*/true,
4871 /*ImplicitlyDeclared=*/true);
4872 NewCtor->setAccess(BaseCtor->getAccess());
4873
4874 // Build up the parameter decls and add them.
4875 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
4876 for (unsigned i = 0; i < params; ++i) {
4877 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor, UsingLoc,
4878 /*IdentifierInfo=*/0,
4879 BaseCtorType->getArgType(i),
4880 /*TInfo=*/0, SC_None,
4881 SC_None, /*DefaultArg=*/0));
4882 }
4883 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
4884 NewCtor->setInheritedConstructor(BaseCtor);
4885
4886 PushOnScopeChains(NewCtor, S, false);
4887 ClassDecl->addDecl(NewCtor);
4888 result.first->second.second = NewCtor;
4889 }
4890 }
4891 }
4892}
4893
Douglas Gregor0be31a22010-07-02 17:43:08 +00004894CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004895 // C++ [class.dtor]p2:
4896 // If a class has no user-declared destructor, a destructor is
4897 // declared implicitly. An implicitly-declared destructor is an
4898 // inline public member of its class.
4899
4900 // C++ [except.spec]p14:
4901 // An implicitly declared special member function (Clause 12) shall have
4902 // an exception-specification.
4903 ImplicitExceptionSpecification ExceptSpec(Context);
4904
4905 // Direct base-class destructors.
4906 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4907 BEnd = ClassDecl->bases_end();
4908 B != BEnd; ++B) {
4909 if (B->isVirtual()) // Handled below.
4910 continue;
4911
4912 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4913 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004914 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004915 }
4916
4917 // Virtual base-class destructors.
4918 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4919 BEnd = ClassDecl->vbases_end();
4920 B != BEnd; ++B) {
4921 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4922 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004923 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004924 }
4925
4926 // Field destructors.
4927 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4928 FEnd = ClassDecl->field_end();
4929 F != FEnd; ++F) {
4930 if (const RecordType *RecordTy
4931 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4932 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004933 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004934 }
4935
Douglas Gregor7454c562010-07-02 20:37:36 +00004936 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00004937 FunctionProtoType::ExtProtoInfo EPI;
4938 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
4939 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
4940 EPI.NumExceptions = ExceptSpec.size();
4941 EPI.Exceptions = ExceptSpec.data();
4942 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregorf1203042010-07-01 19:09:28 +00004943
4944 CanQualType ClassType
4945 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4946 DeclarationName Name
4947 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004948 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004949 CXXDestructorDecl *Destructor
Craig Silversteinaf8808d2010-10-21 00:44:50 +00004950 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0,
Douglas Gregorf1203042010-07-01 19:09:28 +00004951 /*isInline=*/true,
4952 /*isImplicitlyDeclared=*/true);
4953 Destructor->setAccess(AS_public);
4954 Destructor->setImplicit();
4955 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004956
4957 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004958 ++ASTContext::NumImplicitDestructorsDeclared;
4959
4960 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004961 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004962 PushOnScopeChains(Destructor, S, false);
4963 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004964
4965 // This could be uniqued if it ever proves significant.
4966 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4967
4968 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004969
Douglas Gregorf1203042010-07-01 19:09:28 +00004970 return Destructor;
4971}
4972
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004973void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004974 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004975 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004976 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004977 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004978 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004979
Douglas Gregor54818f02010-05-12 16:39:35 +00004980 if (Destructor->isInvalidDecl())
4981 return;
4982
Douglas Gregora57478e2010-05-01 15:04:51 +00004983 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004984
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004985 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00004986 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4987 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004988
Douglas Gregor54818f02010-05-12 16:39:35 +00004989 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004990 Diag(CurrentLocation, diag::note_member_synthesized_at)
4991 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4992
4993 Destructor->setInvalidDecl();
4994 return;
4995 }
4996
Douglas Gregor73193272010-09-20 16:48:21 +00004997 SourceLocation Loc = Destructor->getLocation();
4998 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4999
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005000 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00005001 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005002}
5003
Douglas Gregorb139cd52010-05-01 20:49:11 +00005004/// \brief Builds a statement that copies the given entity from \p From to
5005/// \c To.
5006///
5007/// This routine is used to copy the members of a class with an
5008/// implicitly-declared copy assignment operator. When the entities being
5009/// copied are arrays, this routine builds for loops to copy them.
5010///
5011/// \param S The Sema object used for type-checking.
5012///
5013/// \param Loc The location where the implicit copy is being generated.
5014///
5015/// \param T The type of the expressions being copied. Both expressions must
5016/// have this type.
5017///
5018/// \param To The expression we are copying to.
5019///
5020/// \param From The expression we are copying from.
5021///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005022/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5023/// Otherwise, it's a non-static member subobject.
5024///
Douglas Gregorb139cd52010-05-01 20:49:11 +00005025/// \param Depth Internal parameter recording the depth of the recursion.
5026///
5027/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00005028static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00005029BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00005030 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005031 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005032 // C++0x [class.copy]p30:
5033 // Each subobject is assigned in the manner appropriate to its type:
5034 //
5035 // - if the subobject is of class type, the copy assignment operator
5036 // for the class is used (as if by explicit qualification; that is,
5037 // ignoring any possible virtual overriding functions in more derived
5038 // classes);
5039 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5040 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5041
5042 // Look for operator=.
5043 DeclarationName Name
5044 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5045 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5046 S.LookupQualifiedName(OpLookup, ClassDecl, false);
5047
5048 // Filter out any result that isn't a copy-assignment operator.
5049 LookupResult::Filter F = OpLookup.makeFilter();
5050 while (F.hasNext()) {
5051 NamedDecl *D = F.next();
5052 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5053 if (Method->isCopyAssignmentOperator())
5054 continue;
5055
5056 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00005057 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005058 F.done();
5059
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005060 // Suppress the protected check (C++ [class.protected]) for each of the
5061 // assignment operators we found. This strange dance is required when
5062 // we're assigning via a base classes's copy-assignment operator. To
5063 // ensure that we're getting the right base class subobject (without
5064 // ambiguities), we need to cast "this" to that subobject type; to
5065 // ensure that we don't go through the virtual call mechanism, we need
5066 // to qualify the operator= name with the base class (see below). However,
5067 // this means that if the base class has a protected copy assignment
5068 // operator, the protected member access check will fail. So, we
5069 // rewrite "protected" access to "public" access in this case, since we
5070 // know by construction that we're calling from a derived class.
5071 if (CopyingBaseSubobject) {
5072 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5073 L != LEnd; ++L) {
5074 if (L.getAccess() == AS_protected)
5075 L.setAccess(AS_public);
5076 }
5077 }
5078
Douglas Gregorb139cd52010-05-01 20:49:11 +00005079 // Create the nested-name-specifier that will be used to qualify the
5080 // reference to operator=; this is required to suppress the virtual
5081 // call mechanism.
5082 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005083 SS.MakeTrivial(S.Context,
5084 NestedNameSpecifier::Create(S.Context, 0, false,
5085 T.getTypePtr()),
5086 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005087
5088 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00005089 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00005090 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005091 /*FirstQualifierInScope=*/0, OpLookup,
5092 /*TemplateArgs=*/0,
5093 /*SuppressQualifierCheck=*/true);
5094 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005095 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005096
5097 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00005098
John McCalldadc5752010-08-24 06:29:42 +00005099 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00005100 OpEqualRef.takeAs<Expr>(),
5101 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005102 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005103 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005104
5105 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005106 }
John McCallab8c2732010-03-16 06:11:48 +00005107
Douglas Gregorb139cd52010-05-01 20:49:11 +00005108 // - if the subobject is of scalar type, the built-in assignment
5109 // operator is used.
5110 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5111 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00005112 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005113 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005114 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005115
5116 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005117 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005118
5119 // - if the subobject is an array, each element is assigned, in the
5120 // manner appropriate to the element type;
5121
5122 // Construct a loop over the array bounds, e.g.,
5123 //
5124 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5125 //
5126 // that will copy each of the array elements.
5127 QualType SizeType = S.Context.getSizeType();
5128
5129 // Create the iteration variable.
5130 IdentifierInfo *IterationVarName = 0;
5131 {
5132 llvm::SmallString<8> Str;
5133 llvm::raw_svector_ostream OS(Str);
5134 OS << "__i" << Depth;
5135 IterationVarName = &S.Context.Idents.get(OS.str());
5136 }
5137 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
5138 IterationVarName, SizeType,
5139 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00005140 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005141
5142 // Initialize the iteration variable to zero.
5143 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005144 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00005145
5146 // Create a reference to the iteration variable; we'll use this several
5147 // times throughout.
5148 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00005149 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005150 assert(IterationVarRef && "Reference to invented variable cannot fail!");
5151
5152 // Create the DeclStmt that holds the iteration variable.
5153 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5154
5155 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005156 llvm::APInt Upper
5157 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00005158 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00005159 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00005160 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5161 BO_NE, S.Context.BoolTy,
5162 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005163
5164 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00005165 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00005166 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5167 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005168
5169 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00005170 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5171 IterationVarRef, Loc));
5172 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5173 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00005174
5175 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00005176 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5177 To, From, CopyingBaseSubobject,
5178 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00005179 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005180 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005181
5182 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00005183 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005184 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00005185 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00005186 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005187}
5188
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005189/// \brief Determine whether the given class has a copy assignment operator
5190/// that accepts a const-qualified argument.
5191static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5192 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5193
5194 if (!Class->hasDeclaredCopyAssignment())
5195 S.DeclareImplicitCopyAssignment(Class);
5196
5197 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5198 DeclarationName OpName
5199 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5200
5201 DeclContext::lookup_const_iterator Op, OpEnd;
5202 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5203 // C++ [class.copy]p9:
5204 // A user-declared copy assignment operator is a non-static non-template
5205 // member function of class X with exactly one parameter of type X, X&,
5206 // const X&, volatile X& or const volatile X&.
5207 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5208 if (!Method)
5209 continue;
5210
5211 if (Method->isStatic())
5212 continue;
5213 if (Method->getPrimaryTemplate())
5214 continue;
5215 const FunctionProtoType *FnType =
5216 Method->getType()->getAs<FunctionProtoType>();
5217 assert(FnType && "Overloaded operator has no prototype.");
5218 // Don't assert on this; an invalid decl might have been left in the AST.
5219 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5220 continue;
5221 bool AcceptsConst = true;
5222 QualType ArgType = FnType->getArgType(0);
5223 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5224 ArgType = Ref->getPointeeType();
5225 // Is it a non-const lvalue reference?
5226 if (!ArgType.isConstQualified())
5227 AcceptsConst = false;
5228 }
5229 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5230 continue;
5231
5232 // We have a single argument of type cv X or cv X&, i.e. we've found the
5233 // copy assignment operator. Return whether it accepts const arguments.
5234 return AcceptsConst;
5235 }
5236 assert(Class->isInvalidDecl() &&
5237 "No copy assignment operator declared in valid code.");
5238 return false;
5239}
5240
Douglas Gregor0be31a22010-07-02 17:43:08 +00005241CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005242 // Note: The following rules are largely analoguous to the copy
5243 // constructor rules. Note that virtual bases are not taken into account
5244 // for determining the argument type of the operator. Note also that
5245 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00005246
5247
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005248 // C++ [class.copy]p10:
5249 // If the class definition does not explicitly declare a copy
5250 // assignment operator, one is declared implicitly.
5251 // The implicitly-defined copy assignment operator for a class X
5252 // will have the form
5253 //
5254 // X& X::operator=(const X&)
5255 //
5256 // if
5257 bool HasConstCopyAssignment = true;
5258
5259 // -- each direct base class B of X has a copy assignment operator
5260 // whose parameter is of type const B&, const volatile B& or B,
5261 // and
5262 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5263 BaseEnd = ClassDecl->bases_end();
5264 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5265 assert(!Base->getType()->isDependentType() &&
5266 "Cannot generate implicit members for class with dependent bases.");
5267 const CXXRecordDecl *BaseClassDecl
5268 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005269 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005270 }
5271
5272 // -- for all the nonstatic data members of X that are of a class
5273 // type M (or array thereof), each such class type has a copy
5274 // assignment operator whose parameter is of type const M&,
5275 // const volatile M& or M.
5276 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5277 FieldEnd = ClassDecl->field_end();
5278 HasConstCopyAssignment && Field != FieldEnd;
5279 ++Field) {
5280 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5281 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5282 const CXXRecordDecl *FieldClassDecl
5283 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005284 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005285 }
5286 }
5287
5288 // Otherwise, the implicitly declared copy assignment operator will
5289 // have the form
5290 //
5291 // X& X::operator=(X&)
5292 QualType ArgType = Context.getTypeDeclType(ClassDecl);
5293 QualType RetType = Context.getLValueReferenceType(ArgType);
5294 if (HasConstCopyAssignment)
5295 ArgType = ArgType.withConst();
5296 ArgType = Context.getLValueReferenceType(ArgType);
5297
Douglas Gregor68e11362010-07-01 17:48:08 +00005298 // C++ [except.spec]p14:
5299 // An implicitly declared special member function (Clause 12) shall have an
5300 // exception-specification. [...]
5301 ImplicitExceptionSpecification ExceptSpec(Context);
5302 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5303 BaseEnd = ClassDecl->bases_end();
5304 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005305 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00005306 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005307
5308 if (!BaseClassDecl->hasDeclaredCopyAssignment())
5309 DeclareImplicitCopyAssignment(BaseClassDecl);
5310
Douglas Gregor68e11362010-07-01 17:48:08 +00005311 if (CXXMethodDecl *CopyAssign
5312 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5313 ExceptSpec.CalledDecl(CopyAssign);
5314 }
5315 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5316 FieldEnd = ClassDecl->field_end();
5317 Field != FieldEnd;
5318 ++Field) {
5319 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5320 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005321 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00005322 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005323
5324 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5325 DeclareImplicitCopyAssignment(FieldClassDecl);
5326
Douglas Gregor68e11362010-07-01 17:48:08 +00005327 if (CXXMethodDecl *CopyAssign
5328 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5329 ExceptSpec.CalledDecl(CopyAssign);
5330 }
5331 }
5332
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005333 // An implicitly-declared copy assignment operator is an inline public
5334 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005335 FunctionProtoType::ExtProtoInfo EPI;
5336 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5337 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5338 EPI.NumExceptions = ExceptSpec.size();
5339 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005340 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005341 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005342 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005343 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00005344 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005345 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00005346 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005347 /*isInline=*/true);
5348 CopyAssignment->setAccess(AS_public);
5349 CopyAssignment->setImplicit();
5350 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005351
5352 // Add the parameter to the operator.
5353 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
5354 ClassDecl->getLocation(),
5355 /*Id=*/0,
5356 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005357 SC_None,
5358 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005359 CopyAssignment->setParams(&FromParam, 1);
5360
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005361 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005362 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5363
Douglas Gregor0be31a22010-07-02 17:43:08 +00005364 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005365 PushOnScopeChains(CopyAssignment, S, false);
5366 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005367
5368 AddOverriddenMethods(ClassDecl, CopyAssignment);
5369 return CopyAssignment;
5370}
5371
Douglas Gregorb139cd52010-05-01 20:49:11 +00005372void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5373 CXXMethodDecl *CopyAssignOperator) {
5374 assert((CopyAssignOperator->isImplicit() &&
5375 CopyAssignOperator->isOverloadedOperator() &&
5376 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005377 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00005378 "DefineImplicitCopyAssignment called for wrong function");
5379
5380 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5381
5382 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5383 CopyAssignOperator->setInvalidDecl();
5384 return;
5385 }
5386
5387 CopyAssignOperator->setUsed();
5388
5389 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005390 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005391
5392 // C++0x [class.copy]p30:
5393 // The implicitly-defined or explicitly-defaulted copy assignment operator
5394 // for a non-union class X performs memberwise copy assignment of its
5395 // subobjects. The direct base classes of X are assigned first, in the
5396 // order of their declaration in the base-specifier-list, and then the
5397 // immediate non-static data members of X are assigned, in the order in
5398 // which they were declared in the class definition.
5399
5400 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00005401 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005402
5403 // The parameter for the "other" object, which we are copying from.
5404 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5405 Qualifiers OtherQuals = Other->getType().getQualifiers();
5406 QualType OtherRefType = Other->getType();
5407 if (const LValueReferenceType *OtherRef
5408 = OtherRefType->getAs<LValueReferenceType>()) {
5409 OtherRefType = OtherRef->getPointeeType();
5410 OtherQuals = OtherRefType.getQualifiers();
5411 }
5412
5413 // Our location for everything implicitly-generated.
5414 SourceLocation Loc = CopyAssignOperator->getLocation();
5415
5416 // Construct a reference to the "other" object. We'll be using this
5417 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00005418 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005419 assert(OtherRef && "Reference to parameter cannot fail!");
5420
5421 // Construct the "this" pointer. We'll be using this throughout the generated
5422 // ASTs.
5423 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5424 assert(This && "Reference to this cannot fail!");
5425
5426 // Assign base classes.
5427 bool Invalid = false;
5428 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5429 E = ClassDecl->bases_end(); Base != E; ++Base) {
5430 // Form the assignment:
5431 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5432 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00005433 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005434 Invalid = true;
5435 continue;
5436 }
5437
John McCallcf142162010-08-07 06:22:56 +00005438 CXXCastPath BasePath;
5439 BasePath.push_back(Base);
5440
Douglas Gregorb139cd52010-05-01 20:49:11 +00005441 // Construct the "from" expression, which is an implicit cast to the
5442 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00005443 Expr *From = OtherRef;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005444 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00005445 CK_UncheckedDerivedToBase,
5446 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005447
5448 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00005449 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005450
5451 // Implicitly cast "this" to the appropriately-qualified base type.
5452 Expr *ToE = To.takeAs<Expr>();
5453 ImpCastExprToType(ToE,
5454 Context.getCVRQualifiedType(BaseType,
5455 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00005456 CK_UncheckedDerivedToBase,
5457 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005458 To = Owned(ToE);
5459
5460 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00005461 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00005462 To.get(), From,
5463 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005464 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005465 Diag(CurrentLocation, diag::note_member_synthesized_at)
5466 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5467 CopyAssignOperator->setInvalidDecl();
5468 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005469 }
5470
5471 // Success! Record the copy.
5472 Statements.push_back(Copy.takeAs<Expr>());
5473 }
5474
5475 // \brief Reference to the __builtin_memcpy function.
5476 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005477 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005478 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005479
5480 // Assign non-static members.
5481 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5482 FieldEnd = ClassDecl->field_end();
5483 Field != FieldEnd; ++Field) {
5484 // Check for members of reference type; we can't copy those.
5485 if (Field->getType()->isReferenceType()) {
5486 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5487 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5488 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005489 Diag(CurrentLocation, diag::note_member_synthesized_at)
5490 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005491 Invalid = true;
5492 continue;
5493 }
5494
5495 // Check for members of const-qualified, non-class type.
5496 QualType BaseType = Context.getBaseElementType(Field->getType());
5497 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5498 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5499 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5500 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005501 Diag(CurrentLocation, diag::note_member_synthesized_at)
5502 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005503 Invalid = true;
5504 continue;
5505 }
5506
5507 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005508 if (FieldType->isIncompleteArrayType()) {
5509 assert(ClassDecl->hasFlexibleArrayMember() &&
5510 "Incomplete array type is not valid");
5511 continue;
5512 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005513
5514 // Build references to the field in the object we're copying from and to.
5515 CXXScopeSpec SS; // Intentionally empty
5516 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5517 LookupMemberName);
5518 MemberLookup.addDecl(*Field);
5519 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005520 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005521 Loc, /*IsArrow=*/false,
5522 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005523 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005524 Loc, /*IsArrow=*/true,
5525 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005526 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5527 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5528
5529 // If the field should be copied with __builtin_memcpy rather than via
5530 // explicit assignments, do so. This optimization only applies for arrays
5531 // of scalars and arrays of class type with trivial copy-assignment
5532 // operators.
5533 if (FieldType->isArrayType() &&
5534 (!BaseType->isRecordType() ||
5535 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5536 ->hasTrivialCopyAssignment())) {
5537 // Compute the size of the memory buffer to be copied.
5538 QualType SizeType = Context.getSizeType();
5539 llvm::APInt Size(Context.getTypeSize(SizeType),
5540 Context.getTypeSizeInChars(BaseType).getQuantity());
5541 for (const ConstantArrayType *Array
5542 = Context.getAsConstantArrayType(FieldType);
5543 Array;
5544 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005545 llvm::APInt ArraySize
5546 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005547 Size *= ArraySize;
5548 }
5549
5550 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005551 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5552 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005553
5554 bool NeedsCollectableMemCpy =
5555 (BaseType->isRecordType() &&
5556 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5557
5558 if (NeedsCollectableMemCpy) {
5559 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005560 // Create a reference to the __builtin_objc_memmove_collectable function.
5561 LookupResult R(*this,
5562 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005563 Loc, LookupOrdinaryName);
5564 LookupName(R, TUScope, true);
5565
5566 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5567 if (!CollectableMemCpy) {
5568 // Something went horribly wrong earlier, and we will have
5569 // complained about it.
5570 Invalid = true;
5571 continue;
5572 }
5573
5574 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5575 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005576 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005577 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5578 }
5579 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005580 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005581 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005582 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5583 LookupOrdinaryName);
5584 LookupName(R, TUScope, true);
5585
5586 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5587 if (!BuiltinMemCpy) {
5588 // Something went horribly wrong earlier, and we will have complained
5589 // about it.
5590 Invalid = true;
5591 continue;
5592 }
5593
5594 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5595 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005596 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005597 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5598 }
5599
John McCall37ad5512010-08-23 06:44:23 +00005600 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005601 CallArgs.push_back(To.takeAs<Expr>());
5602 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005603 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005604 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005605 if (NeedsCollectableMemCpy)
5606 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005607 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005608 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005609 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005610 else
5611 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005612 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005613 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005614 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005615
Douglas Gregorb139cd52010-05-01 20:49:11 +00005616 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5617 Statements.push_back(Call.takeAs<Expr>());
5618 continue;
5619 }
5620
5621 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005622 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005623 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005624 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005625 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005626 Diag(CurrentLocation, diag::note_member_synthesized_at)
5627 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5628 CopyAssignOperator->setInvalidDecl();
5629 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005630 }
5631
5632 // Success! Record the copy.
5633 Statements.push_back(Copy.takeAs<Stmt>());
5634 }
5635
5636 if (!Invalid) {
5637 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005638 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005639
John McCalldadc5752010-08-24 06:29:42 +00005640 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005641 if (Return.isInvalid())
5642 Invalid = true;
5643 else {
5644 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005645
5646 if (Trap.hasErrorOccurred()) {
5647 Diag(CurrentLocation, diag::note_member_synthesized_at)
5648 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5649 Invalid = true;
5650 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005651 }
5652 }
5653
5654 if (Invalid) {
5655 CopyAssignOperator->setInvalidDecl();
5656 return;
5657 }
5658
John McCalldadc5752010-08-24 06:29:42 +00005659 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005660 /*isStmtExpr=*/false);
5661 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5662 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005663}
5664
Douglas Gregor0be31a22010-07-02 17:43:08 +00005665CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5666 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005667 // C++ [class.copy]p4:
5668 // If the class definition does not explicitly declare a copy
5669 // constructor, one is declared implicitly.
5670
Douglas Gregor54be3392010-07-01 17:57:27 +00005671 // C++ [class.copy]p5:
5672 // The implicitly-declared copy constructor for a class X will
5673 // have the form
5674 //
5675 // X::X(const X&)
5676 //
5677 // if
5678 bool HasConstCopyConstructor = true;
5679
5680 // -- each direct or virtual base class B of X has a copy
5681 // constructor whose first parameter is of type const B& or
5682 // const volatile B&, and
5683 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5684 BaseEnd = ClassDecl->bases_end();
5685 HasConstCopyConstructor && Base != BaseEnd;
5686 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005687 // Virtual bases are handled below.
5688 if (Base->isVirtual())
5689 continue;
5690
Douglas Gregora6d69502010-07-02 23:41:54 +00005691 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005692 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005693 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5694 DeclareImplicitCopyConstructor(BaseClassDecl);
5695
Douglas Gregorcfe68222010-07-01 18:27:03 +00005696 HasConstCopyConstructor
5697 = BaseClassDecl->hasConstCopyConstructor(Context);
5698 }
5699
5700 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5701 BaseEnd = ClassDecl->vbases_end();
5702 HasConstCopyConstructor && Base != BaseEnd;
5703 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005704 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005705 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005706 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5707 DeclareImplicitCopyConstructor(BaseClassDecl);
5708
Douglas Gregor54be3392010-07-01 17:57:27 +00005709 HasConstCopyConstructor
5710 = BaseClassDecl->hasConstCopyConstructor(Context);
5711 }
5712
5713 // -- for all the nonstatic data members of X that are of a
5714 // class type M (or array thereof), each such class type
5715 // has a copy constructor whose first parameter is of type
5716 // const M& or const volatile M&.
5717 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5718 FieldEnd = ClassDecl->field_end();
5719 HasConstCopyConstructor && Field != FieldEnd;
5720 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005721 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005722 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005723 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005724 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005725 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5726 DeclareImplicitCopyConstructor(FieldClassDecl);
5727
Douglas Gregor54be3392010-07-01 17:57:27 +00005728 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005729 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005730 }
5731 }
5732
5733 // Otherwise, the implicitly declared copy constructor will have
5734 // the form
5735 //
5736 // X::X(X&)
5737 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5738 QualType ArgType = ClassType;
5739 if (HasConstCopyConstructor)
5740 ArgType = ArgType.withConst();
5741 ArgType = Context.getLValueReferenceType(ArgType);
5742
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005743 // C++ [except.spec]p14:
5744 // An implicitly declared special member function (Clause 12) shall have an
5745 // exception-specification. [...]
5746 ImplicitExceptionSpecification ExceptSpec(Context);
5747 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5748 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5749 BaseEnd = ClassDecl->bases_end();
5750 Base != BaseEnd;
5751 ++Base) {
5752 // Virtual bases are handled below.
5753 if (Base->isVirtual())
5754 continue;
5755
Douglas Gregora6d69502010-07-02 23:41:54 +00005756 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005757 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005758 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5759 DeclareImplicitCopyConstructor(BaseClassDecl);
5760
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005761 if (CXXConstructorDecl *CopyConstructor
5762 = BaseClassDecl->getCopyConstructor(Context, Quals))
5763 ExceptSpec.CalledDecl(CopyConstructor);
5764 }
5765 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5766 BaseEnd = ClassDecl->vbases_end();
5767 Base != BaseEnd;
5768 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005769 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005770 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005771 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5772 DeclareImplicitCopyConstructor(BaseClassDecl);
5773
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005774 if (CXXConstructorDecl *CopyConstructor
5775 = BaseClassDecl->getCopyConstructor(Context, Quals))
5776 ExceptSpec.CalledDecl(CopyConstructor);
5777 }
5778 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5779 FieldEnd = ClassDecl->field_end();
5780 Field != FieldEnd;
5781 ++Field) {
5782 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5783 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005784 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005785 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005786 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5787 DeclareImplicitCopyConstructor(FieldClassDecl);
5788
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005789 if (CXXConstructorDecl *CopyConstructor
5790 = FieldClassDecl->getCopyConstructor(Context, Quals))
5791 ExceptSpec.CalledDecl(CopyConstructor);
5792 }
5793 }
5794
Douglas Gregor54be3392010-07-01 17:57:27 +00005795 // An implicitly-declared copy constructor is an inline public
5796 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005797 FunctionProtoType::ExtProtoInfo EPI;
5798 EPI.HasExceptionSpec = ExceptSpec.hasExceptionSpecification();
5799 EPI.HasAnyExceptionSpec = ExceptSpec.hasAnyExceptionSpecification();
5800 EPI.NumExceptions = ExceptSpec.size();
5801 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00005802 DeclarationName Name
5803 = Context.DeclarationNames.getCXXConstructorName(
5804 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005805 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005806 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005807 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005808 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005809 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00005810 /*TInfo=*/0,
5811 /*isExplicit=*/false,
5812 /*isInline=*/true,
5813 /*isImplicitlyDeclared=*/true);
5814 CopyConstructor->setAccess(AS_public);
Douglas Gregor54be3392010-07-01 17:57:27 +00005815 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5816
Douglas Gregora6d69502010-07-02 23:41:54 +00005817 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005818 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5819
Douglas Gregor54be3392010-07-01 17:57:27 +00005820 // Add the parameter to the constructor.
5821 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5822 ClassDecl->getLocation(),
5823 /*IdentifierInfo=*/0,
5824 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005825 SC_None,
5826 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005827 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005828 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005829 PushOnScopeChains(CopyConstructor, S, false);
5830 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005831
5832 return CopyConstructor;
5833}
5834
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005835void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5836 CXXConstructorDecl *CopyConstructor,
5837 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005838 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005839 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005840 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005841 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005842
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005843 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005844 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005845
Douglas Gregora57478e2010-05-01 15:04:51 +00005846 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005847 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005848
Alexis Hunt1d792652011-01-08 20:30:50 +00005849 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00005850 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005851 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005852 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005853 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005854 } else {
5855 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5856 CopyConstructor->getLocation(),
5857 MultiStmtArg(*this, 0, 0),
5858 /*isStmtExpr=*/false)
5859 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005860 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005861
5862 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005863}
5864
John McCalldadc5752010-08-24 06:29:42 +00005865ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005866Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005867 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005868 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005869 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005870 unsigned ConstructKind,
5871 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005872 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005873
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005874 // C++0x [class.copy]p34:
5875 // When certain criteria are met, an implementation is allowed to
5876 // omit the copy/move construction of a class object, even if the
5877 // copy/move constructor and/or destructor for the object have
5878 // side effects. [...]
5879 // - when a temporary class object that has not been bound to a
5880 // reference (12.2) would be copied/moved to a class object
5881 // with the same cv-unqualified type, the copy/move operation
5882 // can be omitted by constructing the temporary object
5883 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005884 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00005885 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005886 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005887 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005888 }
Mike Stump11289f42009-09-09 15:08:12 +00005889
5890 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005891 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005892 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00005893}
5894
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005895/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5896/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005897ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005898Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5899 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005900 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005901 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005902 unsigned ConstructKind,
5903 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005904 unsigned NumExprs = ExprArgs.size();
5905 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005906
Douglas Gregor27381f32009-11-23 12:27:39 +00005907 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005908 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005909 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005910 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00005911 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
5912 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005913}
5914
Mike Stump11289f42009-09-09 15:08:12 +00005915bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005916 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005917 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00005918 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00005919 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005920 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00005921 move(Exprs), false, CXXConstructExpr::CK_Complete,
5922 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005923 if (TempResult.isInvalid())
5924 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005925
Anders Carlsson6eb55572009-08-25 05:12:04 +00005926 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00005927 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00005928 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00005929 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005930 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005931
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005932 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005933}
5934
John McCall03c48482010-02-02 09:10:11 +00005935void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5936 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005937 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005938 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005939 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005940 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005941 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005942 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005943 << VD->getDeclName()
5944 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005945
John McCall386dfc72010-09-18 05:25:11 +00005946 // TODO: this should be re-enabled for static locals by !CXAAtExit
5947 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005948 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005949 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005950}
5951
Mike Stump11289f42009-09-09 15:08:12 +00005952/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005953/// ActOnDeclarator, when a C++ direct initializer is present.
5954/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005955void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005956 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005957 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00005958 SourceLocation RParenLoc,
5959 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005960 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005961
5962 // If there is no declaration, there was an error parsing it. Just ignore
5963 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005964 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005965 return;
Mike Stump11289f42009-09-09 15:08:12 +00005966
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005967 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5968 if (!VDecl) {
5969 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5970 RealDecl->setInvalidDecl();
5971 return;
5972 }
5973
Richard Smith30482bc2011-02-20 03:19:35 +00005974 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
5975 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00005976 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
5977 if (Exprs.size() > 1) {
5978 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
5979 diag::err_auto_var_init_multiple_expressions)
5980 << VDecl->getDeclName() << VDecl->getType()
5981 << VDecl->getSourceRange();
5982 RealDecl->setInvalidDecl();
5983 return;
5984 }
5985
5986 Expr *Init = Exprs.get()[0];
5987 QualType DeducedType;
5988 if (!DeduceAutoType(VDecl->getType(), Init, DeducedType)) {
5989 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
5990 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5991 << Init->getSourceRange();
5992 RealDecl->setInvalidDecl();
5993 return;
5994 }
5995 VDecl->setType(DeducedType);
5996
5997 // If this is a redeclaration, check that the type we just deduced matches
5998 // the previously declared type.
5999 if (VarDecl *Old = VDecl->getPreviousDeclaration())
6000 MergeVarDeclTypes(VDecl, Old);
6001 }
6002
Douglas Gregor402250f2009-08-26 21:14:46 +00006003 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00006004 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006005 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6006 //
6007 // Clients that want to distinguish between the two forms, can check for
6008 // direct initializer using VarDecl::hasCXXDirectInitializer().
6009 // A major benefit is that clients that don't particularly care about which
6010 // exactly form was it (like the CodeGen) can handle both cases without
6011 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006012
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006013 // C++ 8.5p11:
6014 // The form of initialization (using parentheses or '=') is generally
6015 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006016 // class type.
6017
Douglas Gregor50dc2192010-02-11 22:55:30 +00006018 if (!VDecl->getType()->isDependentType() &&
6019 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00006020 diag::err_typecheck_decl_incomplete_type)) {
6021 VDecl->setInvalidDecl();
6022 return;
6023 }
6024
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006025 // The variable can not have an abstract class type.
6026 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6027 diag::err_abstract_type_in_decl,
6028 AbstractVariableType))
6029 VDecl->setInvalidDecl();
6030
Sebastian Redl5ca79842010-02-01 20:16:42 +00006031 const VarDecl *Def;
6032 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006033 Diag(VDecl->getLocation(), diag::err_redefinition)
6034 << VDecl->getDeclName();
6035 Diag(Def->getLocation(), diag::note_previous_definition);
6036 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006037 return;
6038 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00006039
Douglas Gregorf0f83692010-08-24 05:27:49 +00006040 // C++ [class.static.data]p4
6041 // If a static data member is of const integral or const
6042 // enumeration type, its declaration in the class definition can
6043 // specify a constant-initializer which shall be an integral
6044 // constant expression (5.19). In that case, the member can appear
6045 // in integral constant expressions. The member shall still be
6046 // defined in a namespace scope if it is used in the program and the
6047 // namespace scope definition shall not contain an initializer.
6048 //
6049 // We already performed a redefinition check above, but for static
6050 // data members we also need to check whether there was an in-class
6051 // declaration with an initializer.
6052 const VarDecl* PrevInit = 0;
6053 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6054 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6055 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6056 return;
6057 }
6058
Douglas Gregor71f39c92010-12-16 01:31:22 +00006059 bool IsDependent = false;
6060 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6061 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6062 VDecl->setInvalidDecl();
6063 return;
6064 }
6065
6066 if (Exprs.get()[I]->isTypeDependent())
6067 IsDependent = true;
6068 }
6069
Douglas Gregor50dc2192010-02-11 22:55:30 +00006070 // If either the declaration has a dependent type or if any of the
6071 // expressions is type-dependent, we represent the initialization
6072 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00006073 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00006074 // Let clients know that initialization was done with a direct initializer.
6075 VDecl->setCXXDirectInitializer(true);
6076
6077 // Store the initialization expressions as a ParenListExpr.
6078 unsigned NumExprs = Exprs.size();
6079 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6080 (Expr **)Exprs.release(),
6081 NumExprs, RParenLoc));
6082 return;
6083 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006084
6085 // Capture the variable that is being initialized and the style of
6086 // initialization.
6087 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6088
6089 // FIXME: Poor source location information.
6090 InitializationKind Kind
6091 = InitializationKind::CreateDirect(VDecl->getLocation(),
6092 LParenLoc, RParenLoc);
6093
6094 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00006095 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00006096 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006097 if (Result.isInvalid()) {
6098 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006099 return;
6100 }
John McCallacf0ee52010-10-08 02:01:28 +00006101
6102 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006103
Douglas Gregora40433a2010-12-07 00:41:46 +00006104 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00006105 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006106 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00006107
John McCall8b7fd8f12011-01-19 11:48:09 +00006108 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006109}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00006110
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006111/// \brief Given a constructor and the set of arguments provided for the
6112/// constructor, convert the arguments and add any required default arguments
6113/// to form a proper call to this constructor.
6114///
6115/// \returns true if an error occurred, false otherwise.
6116bool
6117Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6118 MultiExprArg ArgsPtr,
6119 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00006120 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006121 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6122 unsigned NumArgs = ArgsPtr.size();
6123 Expr **Args = (Expr **)ArgsPtr.get();
6124
6125 const FunctionProtoType *Proto
6126 = Constructor->getType()->getAs<FunctionProtoType>();
6127 assert(Proto && "Constructor without a prototype?");
6128 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006129
6130 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006131 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006132 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006133 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006134 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006135
6136 VariadicCallType CallType =
6137 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6138 llvm::SmallVector<Expr *, 8> AllArgs;
6139 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6140 Proto, 0, Args, NumArgs, AllArgs,
6141 CallType);
6142 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6143 ConvertedArgs.push_back(AllArgs[i]);
6144 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00006145}
6146
Anders Carlssone363c8e2009-12-12 00:32:00 +00006147static inline bool
6148CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6149 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006150 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00006151 if (isa<NamespaceDecl>(DC)) {
6152 return SemaRef.Diag(FnDecl->getLocation(),
6153 diag::err_operator_new_delete_declared_in_namespace)
6154 << FnDecl->getDeclName();
6155 }
6156
6157 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00006158 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00006159 return SemaRef.Diag(FnDecl->getLocation(),
6160 diag::err_operator_new_delete_declared_static)
6161 << FnDecl->getDeclName();
6162 }
6163
Anders Carlsson60659a82009-12-12 02:43:16 +00006164 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00006165}
6166
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006167static inline bool
6168CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6169 CanQualType ExpectedResultType,
6170 CanQualType ExpectedFirstParamType,
6171 unsigned DependentParamTypeDiag,
6172 unsigned InvalidParamTypeDiag) {
6173 QualType ResultType =
6174 FnDecl->getType()->getAs<FunctionType>()->getResultType();
6175
6176 // Check that the result type is not dependent.
6177 if (ResultType->isDependentType())
6178 return SemaRef.Diag(FnDecl->getLocation(),
6179 diag::err_operator_new_delete_dependent_result_type)
6180 << FnDecl->getDeclName() << ExpectedResultType;
6181
6182 // Check that the result type is what we expect.
6183 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6184 return SemaRef.Diag(FnDecl->getLocation(),
6185 diag::err_operator_new_delete_invalid_result_type)
6186 << FnDecl->getDeclName() << ExpectedResultType;
6187
6188 // A function template must have at least 2 parameters.
6189 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6190 return SemaRef.Diag(FnDecl->getLocation(),
6191 diag::err_operator_new_delete_template_too_few_parameters)
6192 << FnDecl->getDeclName();
6193
6194 // The function decl must have at least 1 parameter.
6195 if (FnDecl->getNumParams() == 0)
6196 return SemaRef.Diag(FnDecl->getLocation(),
6197 diag::err_operator_new_delete_too_few_parameters)
6198 << FnDecl->getDeclName();
6199
6200 // Check the the first parameter type is not dependent.
6201 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6202 if (FirstParamType->isDependentType())
6203 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6204 << FnDecl->getDeclName() << ExpectedFirstParamType;
6205
6206 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00006207 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006208 ExpectedFirstParamType)
6209 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6210 << FnDecl->getDeclName() << ExpectedFirstParamType;
6211
6212 return false;
6213}
6214
Anders Carlsson12308f42009-12-11 23:23:22 +00006215static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006216CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00006217 // C++ [basic.stc.dynamic.allocation]p1:
6218 // A program is ill-formed if an allocation function is declared in a
6219 // namespace scope other than global scope or declared static in global
6220 // scope.
6221 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6222 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006223
6224 CanQualType SizeTy =
6225 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
6226
6227 // C++ [basic.stc.dynamic.allocation]p1:
6228 // The return type shall be void*. The first parameter shall have type
6229 // std::size_t.
6230 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
6231 SizeTy,
6232 diag::err_operator_new_dependent_param_type,
6233 diag::err_operator_new_param_type))
6234 return true;
6235
6236 // C++ [basic.stc.dynamic.allocation]p1:
6237 // The first parameter shall not have an associated default argument.
6238 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00006239 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006240 diag::err_operator_new_default_arg)
6241 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
6242
6243 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00006244}
6245
6246static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00006247CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6248 // C++ [basic.stc.dynamic.deallocation]p1:
6249 // A program is ill-formed if deallocation functions are declared in a
6250 // namespace scope other than global scope or declared static in global
6251 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00006252 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6253 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00006254
6255 // C++ [basic.stc.dynamic.deallocation]p2:
6256 // Each deallocation function shall return void and its first parameter
6257 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006258 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6259 SemaRef.Context.VoidPtrTy,
6260 diag::err_operator_delete_dependent_param_type,
6261 diag::err_operator_delete_param_type))
6262 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00006263
Anders Carlsson12308f42009-12-11 23:23:22 +00006264 return false;
6265}
6266
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006267/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6268/// of this overloaded operator is well-formed. If so, returns false;
6269/// otherwise, emits appropriate diagnostics and returns true.
6270bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00006271 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006272 "Expected an overloaded operator declaration");
6273
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006274 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6275
Mike Stump11289f42009-09-09 15:08:12 +00006276 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006277 // The allocation and deallocation functions, operator new,
6278 // operator new[], operator delete and operator delete[], are
6279 // described completely in 3.7.3. The attributes and restrictions
6280 // found in the rest of this subclause do not apply to them unless
6281 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00006282 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00006283 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00006284
Anders Carlsson22f443f2009-12-12 00:26:23 +00006285 if (Op == OO_New || Op == OO_Array_New)
6286 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006287
6288 // C++ [over.oper]p6:
6289 // An operator function shall either be a non-static member
6290 // function or be a non-member function and have at least one
6291 // parameter whose type is a class, a reference to a class, an
6292 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00006293 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6294 if (MethodDecl->isStatic())
6295 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006296 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006297 } else {
6298 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00006299 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6300 ParamEnd = FnDecl->param_end();
6301 Param != ParamEnd; ++Param) {
6302 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00006303 if (ParamType->isDependentType() || ParamType->isRecordType() ||
6304 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006305 ClassOrEnumParam = true;
6306 break;
6307 }
6308 }
6309
Douglas Gregord69246b2008-11-17 16:14:12 +00006310 if (!ClassOrEnumParam)
6311 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00006312 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006313 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006314 }
6315
6316 // C++ [over.oper]p8:
6317 // An operator function cannot have default arguments (8.3.6),
6318 // except where explicitly stated below.
6319 //
Mike Stump11289f42009-09-09 15:08:12 +00006320 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006321 // (C++ [over.call]p1).
6322 if (Op != OO_Call) {
6323 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6324 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006325 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00006326 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00006327 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006328 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006329 }
6330 }
6331
Douglas Gregor6cf08062008-11-10 13:38:07 +00006332 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6333 { false, false, false }
6334#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6335 , { Unary, Binary, MemberOnly }
6336#include "clang/Basic/OperatorKinds.def"
6337 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006338
Douglas Gregor6cf08062008-11-10 13:38:07 +00006339 bool CanBeUnaryOperator = OperatorUses[Op][0];
6340 bool CanBeBinaryOperator = OperatorUses[Op][1];
6341 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006342
6343 // C++ [over.oper]p8:
6344 // [...] Operator functions cannot have more or fewer parameters
6345 // than the number required for the corresponding operator, as
6346 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00006347 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00006348 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006349 if (Op != OO_Call &&
6350 ((NumParams == 1 && !CanBeUnaryOperator) ||
6351 (NumParams == 2 && !CanBeBinaryOperator) ||
6352 (NumParams < 1) || (NumParams > 2))) {
6353 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006354 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00006355 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006356 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00006357 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006358 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00006359 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00006360 assert(CanBeBinaryOperator &&
6361 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006362 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00006363 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006364
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006365 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006366 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006367 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006368
Douglas Gregord69246b2008-11-17 16:14:12 +00006369 // Overloaded operators other than operator() cannot be variadic.
6370 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00006371 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00006372 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006373 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006374 }
6375
6376 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00006377 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6378 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00006379 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006380 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006381 }
6382
6383 // C++ [over.inc]p1:
6384 // The user-defined function called operator++ implements the
6385 // prefix and postfix ++ operator. If this function is a member
6386 // function with no parameters, or a non-member function with one
6387 // parameter of class or enumeration type, it defines the prefix
6388 // increment operator ++ for objects of that type. If the function
6389 // is a member function with one parameter (which shall be of type
6390 // int) or a non-member function with two parameters (the second
6391 // of which shall be of type int), it defines the postfix
6392 // increment operator ++ for objects of that type.
6393 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6394 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6395 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00006396 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006397 ParamIsInt = BT->getKind() == BuiltinType::Int;
6398
Chris Lattner2b786902008-11-21 07:50:02 +00006399 if (!ParamIsInt)
6400 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00006401 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006402 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006403 }
6404
Douglas Gregord69246b2008-11-17 16:14:12 +00006405 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006406}
Chris Lattner3b024a32008-12-17 07:09:26 +00006407
Alexis Huntc88db062010-01-13 09:01:02 +00006408/// CheckLiteralOperatorDeclaration - Check whether the declaration
6409/// of this literal operator function is well-formed. If so, returns
6410/// false; otherwise, emits appropriate diagnostics and returns true.
6411bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6412 DeclContext *DC = FnDecl->getDeclContext();
6413 Decl::Kind Kind = DC->getDeclKind();
6414 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6415 Kind != Decl::LinkageSpec) {
6416 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6417 << FnDecl->getDeclName();
6418 return true;
6419 }
6420
6421 bool Valid = false;
6422
Alexis Hunt7dd26172010-04-07 23:11:06 +00006423 // template <char...> type operator "" name() is the only valid template
6424 // signature, and the only valid signature with no parameters.
6425 if (FnDecl->param_size() == 0) {
6426 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6427 // Must have only one template parameter
6428 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6429 if (Params->size() == 1) {
6430 NonTypeTemplateParmDecl *PmDecl =
6431 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00006432
Alexis Hunt7dd26172010-04-07 23:11:06 +00006433 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00006434 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6435 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6436 Valid = true;
6437 }
6438 }
6439 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00006440 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00006441 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6442
Alexis Huntc88db062010-01-13 09:01:02 +00006443 QualType T = (*Param)->getType();
6444
Alexis Hunt079a6f72010-04-07 22:57:35 +00006445 // unsigned long long int, long double, and any character type are allowed
6446 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00006447 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6448 Context.hasSameType(T, Context.LongDoubleTy) ||
6449 Context.hasSameType(T, Context.CharTy) ||
6450 Context.hasSameType(T, Context.WCharTy) ||
6451 Context.hasSameType(T, Context.Char16Ty) ||
6452 Context.hasSameType(T, Context.Char32Ty)) {
6453 if (++Param == FnDecl->param_end())
6454 Valid = true;
6455 goto FinishedParams;
6456 }
6457
Alexis Hunt079a6f72010-04-07 22:57:35 +00006458 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00006459 const PointerType *PT = T->getAs<PointerType>();
6460 if (!PT)
6461 goto FinishedParams;
6462 T = PT->getPointeeType();
6463 if (!T.isConstQualified())
6464 goto FinishedParams;
6465 T = T.getUnqualifiedType();
6466
6467 // Move on to the second parameter;
6468 ++Param;
6469
6470 // If there is no second parameter, the first must be a const char *
6471 if (Param == FnDecl->param_end()) {
6472 if (Context.hasSameType(T, Context.CharTy))
6473 Valid = true;
6474 goto FinishedParams;
6475 }
6476
6477 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6478 // are allowed as the first parameter to a two-parameter function
6479 if (!(Context.hasSameType(T, Context.CharTy) ||
6480 Context.hasSameType(T, Context.WCharTy) ||
6481 Context.hasSameType(T, Context.Char16Ty) ||
6482 Context.hasSameType(T, Context.Char32Ty)))
6483 goto FinishedParams;
6484
6485 // The second and final parameter must be an std::size_t
6486 T = (*Param)->getType().getUnqualifiedType();
6487 if (Context.hasSameType(T, Context.getSizeType()) &&
6488 ++Param == FnDecl->param_end())
6489 Valid = true;
6490 }
6491
6492 // FIXME: This diagnostic is absolutely terrible.
6493FinishedParams:
6494 if (!Valid) {
6495 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6496 << FnDecl->getDeclName();
6497 return true;
6498 }
6499
6500 return false;
6501}
6502
Douglas Gregor07665a62009-01-05 19:45:36 +00006503/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6504/// linkage specification, including the language and (if present)
6505/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6506/// the location of the language string literal, which is provided
6507/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6508/// the '{' brace. Otherwise, this linkage specification does not
6509/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006510Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6511 SourceLocation LangLoc,
6512 llvm::StringRef Lang,
6513 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006514 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006515 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006516 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006517 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006518 Language = LinkageSpecDecl::lang_cxx;
6519 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006520 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006521 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006522 }
Mike Stump11289f42009-09-09 15:08:12 +00006523
Chris Lattner438e5012008-12-17 07:13:27 +00006524 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006525
Douglas Gregor07665a62009-01-05 19:45:36 +00006526 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00006527 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00006528 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006529 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006530 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006531 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006532}
6533
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006534/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006535/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6536/// valid, it's the position of the closing '}' brace in a linkage
6537/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006538Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6539 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00006540 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00006541 if (LinkageSpec)
6542 PopDeclContext();
6543 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006544}
6545
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006546/// \brief Perform semantic analysis for the variable declaration that
6547/// occurs within a C++ catch clause, returning the newly-created
6548/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006549VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006550 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006551 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006552 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006553 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006554 QualType ExDeclType = TInfo->getType();
6555
Sebastian Redl54c04d42008-12-22 19:15:10 +00006556 // Arrays and functions decay.
6557 if (ExDeclType->isArrayType())
6558 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6559 else if (ExDeclType->isFunctionType())
6560 ExDeclType = Context.getPointerType(ExDeclType);
6561
6562 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6563 // The exception-declaration shall not denote a pointer or reference to an
6564 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006565 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006566 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006567 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006568 Invalid = true;
6569 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006570
Douglas Gregor104ee002010-03-08 01:47:36 +00006571 // GCC allows catching pointers and references to incomplete types
6572 // as an extension; so do we, but we warn by default.
6573
Sebastian Redl54c04d42008-12-22 19:15:10 +00006574 QualType BaseType = ExDeclType;
6575 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006576 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006577 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006578 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006579 BaseType = Ptr->getPointeeType();
6580 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006581 DK = diag::ext_catch_incomplete_ptr;
6582 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006583 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006584 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006585 BaseType = Ref->getPointeeType();
6586 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006587 DK = diag::ext_catch_incomplete_ref;
6588 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006589 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006590 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006591 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6592 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006593 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006594
Mike Stump11289f42009-09-09 15:08:12 +00006595 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006596 RequireNonAbstractType(Loc, ExDeclType,
6597 diag::err_abstract_type_in_decl,
6598 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006599 Invalid = true;
6600
John McCall2ca705e2010-07-24 00:37:23 +00006601 // Only the non-fragile NeXT runtime currently supports C++ catches
6602 // of ObjC types, and no runtime supports catching ObjC types by value.
6603 if (!Invalid && getLangOptions().ObjC1) {
6604 QualType T = ExDeclType;
6605 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6606 T = RT->getPointeeType();
6607
6608 if (T->isObjCObjectType()) {
6609 Diag(Loc, diag::err_objc_object_catch);
6610 Invalid = true;
6611 } else if (T->isObjCObjectPointerType()) {
6612 if (!getLangOptions().NeXTRuntime) {
6613 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6614 Invalid = true;
6615 } else if (!getLangOptions().ObjCNonFragileABI) {
6616 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6617 Invalid = true;
6618 }
6619 }
6620 }
6621
Mike Stump11289f42009-09-09 15:08:12 +00006622 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006623 Name, ExDeclType, TInfo, SC_None,
6624 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006625 ExDecl->setExceptionVariable(true);
6626
Douglas Gregor6de584c2010-03-05 23:38:39 +00006627 if (!Invalid) {
John McCall1bf58462011-02-16 08:02:54 +00006628 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00006629 // C++ [except.handle]p16:
6630 // The object declared in an exception-declaration or, if the
6631 // exception-declaration does not specify a name, a temporary (12.2) is
6632 // copy-initialized (8.5) from the exception object. [...]
6633 // The object is destroyed when the handler exits, after the destruction
6634 // of any automatic objects initialized within the handler.
6635 //
6636 // We just pretend to initialize the object with itself, then make sure
6637 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00006638 QualType initType = ExDeclType;
6639
6640 InitializedEntity entity =
6641 InitializedEntity::InitializeVariable(ExDecl);
6642 InitializationKind initKind =
6643 InitializationKind::CreateCopy(Loc, SourceLocation());
6644
6645 Expr *opaqueValue =
6646 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
6647 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
6648 ExprResult result = sequence.Perform(*this, entity, initKind,
6649 MultiExprArg(&opaqueValue, 1));
6650 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00006651 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00006652 else {
6653 // If the constructor used was non-trivial, set this as the
6654 // "initializer".
6655 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
6656 if (!construct->getConstructor()->isTrivial()) {
6657 Expr *init = MaybeCreateExprWithCleanups(construct);
6658 ExDecl->setInit(init);
6659 }
6660
6661 // And make sure it's destructable.
6662 FinalizeVarWithDestructor(ExDecl, recordType);
6663 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00006664 }
6665 }
6666
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006667 if (Invalid)
6668 ExDecl->setInvalidDecl();
6669
6670 return ExDecl;
6671}
6672
6673/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6674/// handler.
John McCall48871652010-08-21 09:40:31 +00006675Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006676 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00006677 bool Invalid = D.isInvalidType();
6678
6679 // Check for unexpanded parameter packs.
6680 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6681 UPPC_ExceptionType)) {
6682 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6683 D.getIdentifierLoc());
6684 Invalid = true;
6685 }
6686
Sebastian Redl54c04d42008-12-22 19:15:10 +00006687 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006688 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006689 LookupOrdinaryName,
6690 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006691 // The scope should be freshly made just for us. There is just no way
6692 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006693 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006694 if (PrevDecl->isTemplateParameter()) {
6695 // Maybe we will complain about the shadowed template parameter.
6696 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006697 }
6698 }
6699
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006700 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006701 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6702 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006703 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006704 }
6705
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006706 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006707 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006708 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006709
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006710 if (Invalid)
6711 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006712
Sebastian Redl54c04d42008-12-22 19:15:10 +00006713 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006714 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006715 PushOnScopeChains(ExDecl, S);
6716 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006717 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006718
Douglas Gregor758a8692009-06-17 21:51:59 +00006719 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006720 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006721}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006722
John McCall48871652010-08-21 09:40:31 +00006723Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006724 Expr *AssertExpr,
6725 Expr *AssertMessageExpr_) {
6726 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006727
Anders Carlsson54b26982009-03-14 00:33:21 +00006728 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6729 llvm::APSInt Value(32);
6730 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6731 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6732 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006733 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006734 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006735
Anders Carlsson54b26982009-03-14 00:33:21 +00006736 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006737 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006738 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006739 }
6740 }
Mike Stump11289f42009-09-09 15:08:12 +00006741
Douglas Gregoref68fee2010-12-15 23:55:21 +00006742 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6743 return 0;
6744
Mike Stump11289f42009-09-09 15:08:12 +00006745 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006746 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006747
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006748 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006749 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006750}
Sebastian Redlf769df52009-03-24 22:27:57 +00006751
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006752/// \brief Perform semantic analysis of the given friend type declaration.
6753///
6754/// \returns A friend declaration that.
6755FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6756 TypeSourceInfo *TSInfo) {
6757 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6758
6759 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006760 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006761
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006762 if (!getLangOptions().CPlusPlus0x) {
6763 // C++03 [class.friend]p2:
6764 // An elaborated-type-specifier shall be used in a friend declaration
6765 // for a class.*
6766 //
6767 // * The class-key of the elaborated-type-specifier is required.
6768 if (!ActiveTemplateInstantiations.empty()) {
6769 // Do not complain about the form of friend template types during
6770 // template instantiation; we will already have complained when the
6771 // template was declared.
6772 } else if (!T->isElaboratedTypeSpecifier()) {
6773 // If we evaluated the type to a record type, suggest putting
6774 // a tag in front.
6775 if (const RecordType *RT = T->getAs<RecordType>()) {
6776 RecordDecl *RD = RT->getDecl();
6777
6778 std::string InsertionText = std::string(" ") + RD->getKindName();
6779
6780 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6781 << (unsigned) RD->getTagKind()
6782 << T
6783 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6784 InsertionText);
6785 } else {
6786 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6787 << T
6788 << SourceRange(FriendLoc, TypeRange.getEnd());
6789 }
6790 } else if (T->getAs<EnumType>()) {
6791 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006792 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006793 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006794 }
6795 }
6796
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006797 // C++0x [class.friend]p3:
6798 // If the type specifier in a friend declaration designates a (possibly
6799 // cv-qualified) class type, that class is declared as a friend; otherwise,
6800 // the friend declaration is ignored.
6801
6802 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6803 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006804
6805 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6806}
6807
John McCallace48cd2010-10-19 01:40:49 +00006808/// Handle a friend tag declaration where the scope specifier was
6809/// templated.
6810Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6811 unsigned TagSpec, SourceLocation TagLoc,
6812 CXXScopeSpec &SS,
6813 IdentifierInfo *Name, SourceLocation NameLoc,
6814 AttributeList *Attr,
6815 MultiTemplateParamsArg TempParamLists) {
6816 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6817
6818 bool isExplicitSpecialization = false;
6819 unsigned NumMatchedTemplateParamLists = TempParamLists.size();
6820 bool Invalid = false;
6821
6822 if (TemplateParameterList *TemplateParams
6823 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
6824 TempParamLists.get(),
6825 TempParamLists.size(),
6826 /*friend*/ true,
6827 isExplicitSpecialization,
6828 Invalid)) {
6829 --NumMatchedTemplateParamLists;
6830
6831 if (TemplateParams->size() > 0) {
6832 // This is a declaration of a class template.
6833 if (Invalid)
6834 return 0;
6835
6836 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
6837 SS, Name, NameLoc, Attr,
6838 TemplateParams, AS_public).take();
6839 } else {
6840 // The "template<>" header is extraneous.
6841 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
6842 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
6843 isExplicitSpecialization = true;
6844 }
6845 }
6846
6847 if (Invalid) return 0;
6848
6849 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
6850
6851 bool isAllExplicitSpecializations = true;
6852 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) {
6853 if (TempParamLists.get()[I]->size()) {
6854 isAllExplicitSpecializations = false;
6855 break;
6856 }
6857 }
6858
6859 // FIXME: don't ignore attributes.
6860
6861 // If it's explicit specializations all the way down, just forget
6862 // about the template header and build an appropriate non-templated
6863 // friend. TODO: for source fidelity, remember the headers.
6864 if (isAllExplicitSpecializations) {
6865 ElaboratedTypeKeyword Keyword
6866 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6867 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name,
6868 TagLoc, SS.getRange(), NameLoc);
6869 if (T.isNull())
6870 return 0;
6871
6872 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6873 if (isa<DependentNameType>(T)) {
6874 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6875 TL.setKeywordLoc(TagLoc);
6876 TL.setQualifierRange(SS.getRange());
6877 TL.setNameLoc(NameLoc);
6878 } else {
6879 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6880 TL.setKeywordLoc(TagLoc);
6881 TL.setQualifierRange(SS.getRange());
6882 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
6883 }
6884
6885 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6886 TSI, FriendLoc);
6887 Friend->setAccess(AS_public);
6888 CurContext->addDecl(Friend);
6889 return Friend;
6890 }
6891
6892 // Handle the case of a templated-scope friend class. e.g.
6893 // template <class T> class A<T>::B;
6894 // FIXME: we don't support these right now.
6895 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6896 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
6897 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6898 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6899 TL.setKeywordLoc(TagLoc);
6900 TL.setQualifierRange(SS.getRange());
6901 TL.setNameLoc(NameLoc);
6902
6903 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
6904 TSI, FriendLoc);
6905 Friend->setAccess(AS_public);
6906 Friend->setUnsupportedFriend(true);
6907 CurContext->addDecl(Friend);
6908 return Friend;
6909}
6910
6911
John McCall11083da2009-09-16 22:47:08 +00006912/// Handle a friend type declaration. This works in tandem with
6913/// ActOnTag.
6914///
6915/// Notes on friend class templates:
6916///
6917/// We generally treat friend class declarations as if they were
6918/// declaring a class. So, for example, the elaborated type specifier
6919/// in a friend declaration is required to obey the restrictions of a
6920/// class-head (i.e. no typedefs in the scope chain), template
6921/// parameters are required to match up with simple template-ids, &c.
6922/// However, unlike when declaring a template specialization, it's
6923/// okay to refer to a template specialization without an empty
6924/// template parameter declaration, e.g.
6925/// friend class A<T>::B<unsigned>;
6926/// We permit this as a special case; if there are any template
6927/// parameters present at all, require proper matching, i.e.
6928/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006929Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00006930 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006931 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006932
6933 assert(DS.isFriendSpecified());
6934 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6935
John McCall11083da2009-09-16 22:47:08 +00006936 // Try to convert the decl specifier to a type. This works for
6937 // friend templates because ActOnTag never produces a ClassTemplateDecl
6938 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006939 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006940 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6941 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006942 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006943 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006944
Douglas Gregor6c110f32010-12-16 01:14:37 +00006945 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
6946 return 0;
6947
John McCall11083da2009-09-16 22:47:08 +00006948 // This is definitely an error in C++98. It's probably meant to
6949 // be forbidden in C++0x, too, but the specification is just
6950 // poorly written.
6951 //
6952 // The problem is with declarations like the following:
6953 // template <T> friend A<T>::foo;
6954 // where deciding whether a class C is a friend or not now hinges
6955 // on whether there exists an instantiation of A that causes
6956 // 'foo' to equal C. There are restrictions on class-heads
6957 // (which we declare (by fiat) elaborated friend declarations to
6958 // be) that makes this tractable.
6959 //
6960 // FIXME: handle "template <> friend class A<T>;", which
6961 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006962 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006963 Diag(Loc, diag::err_tagless_friend_type_template)
6964 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006965 return 0;
John McCall11083da2009-09-16 22:47:08 +00006966 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006967
John McCallaa74a0c2009-08-28 07:59:38 +00006968 // C++98 [class.friend]p1: A friend of a class is a function
6969 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006970 // This is fixed in DR77, which just barely didn't make the C++03
6971 // deadline. It's also a very silly restriction that seriously
6972 // affects inner classes and which nobody else seems to implement;
6973 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006974 //
6975 // But note that we could warn about it: it's always useless to
6976 // friend one of your own members (it's not, however, worthless to
6977 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006978
John McCall11083da2009-09-16 22:47:08 +00006979 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006980 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006981 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006982 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00006983 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006984 TSI,
John McCall11083da2009-09-16 22:47:08 +00006985 DS.getFriendSpecLoc());
6986 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006987 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6988
6989 if (!D)
John McCall48871652010-08-21 09:40:31 +00006990 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006991
John McCall11083da2009-09-16 22:47:08 +00006992 D->setAccess(AS_public);
6993 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006994
John McCall48871652010-08-21 09:40:31 +00006995 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006996}
6997
John McCallde3fd222010-10-12 23:13:28 +00006998Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
6999 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00007000 const DeclSpec &DS = D.getDeclSpec();
7001
7002 assert(DS.isFriendSpecified());
7003 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7004
7005 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00007006 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7007 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00007008
7009 // C++ [class.friend]p1
7010 // A friend of a class is a function or class....
7011 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00007012 // It *doesn't* see through dependent types, which is correct
7013 // according to [temp.arg.type]p3:
7014 // If a declaration acquires a function type through a
7015 // type dependent on a template-parameter and this causes
7016 // a declaration that does not use the syntactic form of a
7017 // function declarator to have a function type, the program
7018 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00007019 if (!T->isFunctionType()) {
7020 Diag(Loc, diag::err_unexpected_friend);
7021
7022 // It might be worthwhile to try to recover by creating an
7023 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00007024 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007025 }
7026
7027 // C++ [namespace.memdef]p3
7028 // - If a friend declaration in a non-local class first declares a
7029 // class or function, the friend class or function is a member
7030 // of the innermost enclosing namespace.
7031 // - The name of the friend is not found by simple name lookup
7032 // until a matching declaration is provided in that namespace
7033 // scope (either before or after the class declaration granting
7034 // friendship).
7035 // - If a friend function is called, its name may be found by the
7036 // name lookup that considers functions from namespaces and
7037 // classes associated with the types of the function arguments.
7038 // - When looking for a prior declaration of a class or a function
7039 // declared as a friend, scopes outside the innermost enclosing
7040 // namespace scope are not considered.
7041
John McCallde3fd222010-10-12 23:13:28 +00007042 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007043 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7044 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00007045 assert(Name);
7046
Douglas Gregor6c110f32010-12-16 01:14:37 +00007047 // Check for unexpanded parameter packs.
7048 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7049 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7050 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7051 return 0;
7052
John McCall07e91c02009-08-06 02:15:43 +00007053 // The context we found the declaration in, or in which we should
7054 // create the declaration.
7055 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00007056 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007057 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00007058 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00007059
John McCallde3fd222010-10-12 23:13:28 +00007060 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00007061
John McCallde3fd222010-10-12 23:13:28 +00007062 // There are four cases here.
7063 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00007064 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00007065 // there as appropriate.
7066 // Recover from invalid scope qualifiers as if they just weren't there.
7067 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00007068 // C++0x [namespace.memdef]p3:
7069 // If the name in a friend declaration is neither qualified nor
7070 // a template-id and the declaration is a function or an
7071 // elaborated-type-specifier, the lookup to determine whether
7072 // the entity has been previously declared shall not consider
7073 // any scopes outside the innermost enclosing namespace.
7074 // C++0x [class.friend]p11:
7075 // If a friend declaration appears in a local class and the name
7076 // specified is an unqualified name, a prior declaration is
7077 // looked up without considering scopes that are outside the
7078 // innermost enclosing non-class scope. For a friend function
7079 // declaration, if there is no prior declaration, the program is
7080 // ill-formed.
7081 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00007082 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00007083
John McCallf7cfb222010-10-13 05:45:15 +00007084 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00007085 DC = CurContext;
7086 while (true) {
7087 // Skip class contexts. If someone can cite chapter and verse
7088 // for this behavior, that would be nice --- it's what GCC and
7089 // EDG do, and it seems like a reasonable intent, but the spec
7090 // really only says that checks for unqualified existing
7091 // declarations should stop at the nearest enclosing namespace,
7092 // not that they should only consider the nearest enclosing
7093 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007094 while (DC->isRecord())
7095 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00007096
John McCall1f82f242009-11-18 22:49:29 +00007097 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00007098
7099 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00007100 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00007101 break;
John McCallf7cfb222010-10-13 05:45:15 +00007102
John McCallf4776592010-10-14 22:22:28 +00007103 if (isTemplateId) {
7104 if (isa<TranslationUnitDecl>(DC)) break;
7105 } else {
7106 if (DC->isFileContext()) break;
7107 }
John McCall07e91c02009-08-06 02:15:43 +00007108 DC = DC->getParent();
7109 }
7110
7111 // C++ [class.friend]p1: A friend of a class is a function or
7112 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00007113 // C++0x changes this for both friend types and functions.
7114 // Most C++ 98 compilers do seem to give an error here, so
7115 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00007116 if (!Previous.empty() && DC->Equals(CurContext)
7117 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00007118 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00007119
John McCallccbc0322010-10-13 06:22:15 +00007120 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00007121
John McCallde3fd222010-10-12 23:13:28 +00007122 // - There's a non-dependent scope specifier, in which case we
7123 // compute it and do a previous lookup there for a function
7124 // or function template.
7125 } else if (!SS.getScopeRep()->isDependent()) {
7126 DC = computeDeclContext(SS);
7127 if (!DC) return 0;
7128
7129 if (RequireCompleteDeclContext(SS, DC)) return 0;
7130
7131 LookupQualifiedName(Previous, DC);
7132
7133 // Ignore things found implicitly in the wrong scope.
7134 // TODO: better diagnostics for this case. Suggesting the right
7135 // qualified scope would be nice...
7136 LookupResult::Filter F = Previous.makeFilter();
7137 while (F.hasNext()) {
7138 NamedDecl *D = F.next();
7139 if (!DC->InEnclosingNamespaceSetOf(
7140 D->getDeclContext()->getRedeclContext()))
7141 F.erase();
7142 }
7143 F.done();
7144
7145 if (Previous.empty()) {
7146 D.setInvalidType();
7147 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7148 return 0;
7149 }
7150
7151 // C++ [class.friend]p1: A friend of a class is a function or
7152 // class that is not a member of the class . . .
7153 if (DC->Equals(CurContext))
7154 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7155
7156 // - There's a scope specifier that does not match any template
7157 // parameter lists, in which case we use some arbitrary context,
7158 // create a method or method template, and wait for instantiation.
7159 // - There's a scope specifier that does match some template
7160 // parameter lists, which we don't handle right now.
7161 } else {
7162 DC = CurContext;
7163 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00007164 }
7165
John McCallf7cfb222010-10-13 05:45:15 +00007166 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00007167 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00007168 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7169 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7170 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00007171 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00007172 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7173 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00007174 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007175 }
John McCall07e91c02009-08-06 02:15:43 +00007176 }
7177
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007178 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00007179 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007180 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00007181 IsDefinition,
7182 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00007183 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00007184
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007185 assert(ND->getDeclContext() == DC);
7186 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00007187
John McCall759e32b2009-08-31 22:39:49 +00007188 // Add the function declaration to the appropriate lookup tables,
7189 // adjusting the redeclarations list as necessary. We don't
7190 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00007191 //
John McCall759e32b2009-08-31 22:39:49 +00007192 // Also update the scope-based lookup if the target context's
7193 // lookup context is in lexical scope.
7194 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007195 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007196 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00007197 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007198 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00007199 }
John McCallaa74a0c2009-08-28 07:59:38 +00007200
7201 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007202 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00007203 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00007204 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00007205 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00007206
John McCallde3fd222010-10-12 23:13:28 +00007207 if (ND->isInvalidDecl())
7208 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00007209 else {
7210 FunctionDecl *FD;
7211 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7212 FD = FTD->getTemplatedDecl();
7213 else
7214 FD = cast<FunctionDecl>(ND);
7215
7216 // Mark templated-scope function declarations as unsupported.
7217 if (FD->getNumTemplateParameterLists())
7218 FrD->setUnsupportedFriend(true);
7219 }
John McCallde3fd222010-10-12 23:13:28 +00007220
John McCall48871652010-08-21 09:40:31 +00007221 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00007222}
7223
John McCall48871652010-08-21 09:40:31 +00007224void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
7225 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00007226
Sebastian Redlf769df52009-03-24 22:27:57 +00007227 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
7228 if (!Fn) {
7229 Diag(DelLoc, diag::err_deleted_non_function);
7230 return;
7231 }
7232 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
7233 Diag(DelLoc, diag::err_deleted_decl_not_first);
7234 Diag(Prev->getLocation(), diag::note_previous_declaration);
7235 // If the declaration wasn't the first, we delete the function anyway for
7236 // recovery.
7237 }
7238 Fn->setDeleted();
7239}
Sebastian Redl4c018662009-04-27 21:33:24 +00007240
7241static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00007242 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +00007243 Stmt *SubStmt = *CI;
7244 if (!SubStmt)
7245 continue;
7246 if (isa<ReturnStmt>(SubStmt))
7247 Self.Diag(SubStmt->getSourceRange().getBegin(),
7248 diag::err_return_in_constructor_handler);
7249 if (!isa<Expr>(SubStmt))
7250 SearchForReturnInStmt(Self, SubStmt);
7251 }
7252}
7253
7254void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
7255 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
7256 CXXCatchStmt *Handler = TryBlock->getHandler(I);
7257 SearchForReturnInStmt(*this, Handler);
7258 }
7259}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007260
Mike Stump11289f42009-09-09 15:08:12 +00007261bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007262 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00007263 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7264 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007265
Chandler Carruth284bb2e2010-02-15 11:53:20 +00007266 if (Context.hasSameType(NewTy, OldTy) ||
7267 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007268 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007269
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007270 // Check if the return types are covariant
7271 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00007272
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007273 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007274 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7275 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007276 NewClassTy = NewPT->getPointeeType();
7277 OldClassTy = OldPT->getPointeeType();
7278 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007279 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7280 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7281 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7282 NewClassTy = NewRT->getPointeeType();
7283 OldClassTy = OldRT->getPointeeType();
7284 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007285 }
7286 }
Mike Stump11289f42009-09-09 15:08:12 +00007287
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007288 // The return types aren't either both pointers or references to a class type.
7289 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00007290 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007291 diag::err_different_return_type_for_overriding_virtual_function)
7292 << New->getDeclName() << NewTy << OldTy;
7293 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00007294
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007295 return true;
7296 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007297
Anders Carlssone60365b2009-12-31 18:34:24 +00007298 // C++ [class.virtual]p6:
7299 // If the return type of D::f differs from the return type of B::f, the
7300 // class type in the return type of D::f shall be complete at the point of
7301 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00007302 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7303 if (!RT->isBeingDefined() &&
7304 RequireCompleteType(New->getLocation(), NewClassTy,
7305 PDiag(diag::err_covariant_return_incomplete)
7306 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00007307 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00007308 }
Anders Carlssone60365b2009-12-31 18:34:24 +00007309
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007310 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007311 // Check if the new class derives from the old class.
7312 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7313 Diag(New->getLocation(),
7314 diag::err_covariant_return_not_derived)
7315 << New->getDeclName() << NewTy << OldTy;
7316 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7317 return true;
7318 }
Mike Stump11289f42009-09-09 15:08:12 +00007319
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007320 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00007321 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00007322 diag::err_covariant_return_inaccessible_base,
7323 diag::err_covariant_return_ambiguous_derived_to_base_conv,
7324 // FIXME: Should this point to the return type?
7325 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +00007326 // FIXME: this note won't trigger for delayed access control
7327 // diagnostics, and it's impossible to get an undelayed error
7328 // here from access control during the original parse because
7329 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007330 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7331 return true;
7332 }
7333 }
Mike Stump11289f42009-09-09 15:08:12 +00007334
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007335 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007336 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007337 Diag(New->getLocation(),
7338 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007339 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007340 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7341 return true;
7342 };
Mike Stump11289f42009-09-09 15:08:12 +00007343
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007344
7345 // The new class type must have the same or less qualifiers as the old type.
7346 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
7347 Diag(New->getLocation(),
7348 diag::err_covariant_return_type_class_type_more_qualified)
7349 << New->getDeclName() << NewTy << OldTy;
7350 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7351 return true;
7352 };
Mike Stump11289f42009-09-09 15:08:12 +00007353
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007354 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007355}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007356
Douglas Gregor21920e372009-12-01 17:24:26 +00007357/// \brief Mark the given method pure.
7358///
7359/// \param Method the method to be marked pure.
7360///
7361/// \param InitRange the source range that covers the "0" initializer.
7362bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
7363 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
7364 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00007365 return false;
7366 }
7367
7368 if (!Method->isInvalidDecl())
7369 Diag(Method->getLocation(), diag::err_non_virtual_pure)
7370 << Method->getDeclName() << InitRange;
7371 return true;
7372}
7373
John McCall1f4ee7b2009-12-19 09:28:58 +00007374/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7375/// an initializer for the out-of-line declaration 'Dcl'. The scope
7376/// is a fresh scope pushed for just this purpose.
7377///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007378/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7379/// static data member of class X, names should be looked up in the scope of
7380/// class X.
John McCall48871652010-08-21 09:40:31 +00007381void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007382 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00007383 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007384
John McCall1f4ee7b2009-12-19 09:28:58 +00007385 // We should only get called for declarations with scope specifiers, like:
7386 // int foo::bar;
7387 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00007388 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007389}
7390
7391/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00007392/// initializer for the out-of-line declaration 'D'.
7393void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007394 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00007395 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007396
John McCall1f4ee7b2009-12-19 09:28:58 +00007397 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00007398 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007399}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007400
7401/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7402/// C++ if/switch/while/for statement.
7403/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00007404DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007405 // C++ 6.4p2:
7406 // The declarator shall not specify a function or an array.
7407 // The type-specifier-seq shall not contain typedef and shall not declare a
7408 // new class or enumeration.
7409 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7410 "Parser allowed 'typedef' as storage class of condition decl.");
7411
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007412 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00007413 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7414 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007415
7416 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7417 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7418 // would be created and CXXConditionDeclExpr wants a VarDecl.
7419 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7420 << D.getSourceRange();
7421 return DeclResult();
7422 } else if (OwnedTag && OwnedTag->isDefinition()) {
7423 // The type-specifier-seq shall not declare a new class or enumeration.
7424 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7425 }
7426
John McCall48871652010-08-21 09:40:31 +00007427 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007428 if (!Dcl)
7429 return DeclResult();
7430
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007431 return Dcl;
7432}
Anders Carlssonf98849e2009-12-02 17:15:43 +00007433
Douglas Gregor88d292c2010-05-13 16:44:06 +00007434void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7435 bool DefinitionRequired) {
7436 // Ignore any vtable uses in unevaluated operands or for classes that do
7437 // not have a vtable.
7438 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7439 CurContext->isDependentContext() ||
7440 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00007441 return;
7442
Douglas Gregor88d292c2010-05-13 16:44:06 +00007443 // Try to insert this class into the map.
7444 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7445 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7446 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7447 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00007448 // If we already had an entry, check to see if we are promoting this vtable
7449 // to required a definition. If so, we need to reappend to the VTableUses
7450 // list, since we may have already processed the first entry.
7451 if (DefinitionRequired && !Pos.first->second) {
7452 Pos.first->second = true;
7453 } else {
7454 // Otherwise, we can early exit.
7455 return;
7456 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007457 }
7458
7459 // Local classes need to have their virtual members marked
7460 // immediately. For all other classes, we mark their virtual members
7461 // at the end of the translation unit.
7462 if (Class->isLocalClass())
7463 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00007464 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00007465 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00007466}
7467
Douglas Gregor88d292c2010-05-13 16:44:06 +00007468bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007469 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00007470 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00007471
Douglas Gregor88d292c2010-05-13 16:44:06 +00007472 // Note: The VTableUses vector could grow as a result of marking
7473 // the members of a class as "used", so we check the size each
7474 // time through the loop and prefer indices (with are stable) to
7475 // iterators (which are not).
7476 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00007477 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007478 if (!Class)
7479 continue;
7480
7481 SourceLocation Loc = VTableUses[I].second;
7482
7483 // If this class has a key function, but that key function is
7484 // defined in another translation unit, we don't need to emit the
7485 // vtable even though we're using it.
7486 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007487 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007488 switch (KeyFunction->getTemplateSpecializationKind()) {
7489 case TSK_Undeclared:
7490 case TSK_ExplicitSpecialization:
7491 case TSK_ExplicitInstantiationDeclaration:
7492 // The key function is in another translation unit.
7493 continue;
7494
7495 case TSK_ExplicitInstantiationDefinition:
7496 case TSK_ImplicitInstantiation:
7497 // We will be instantiating the key function.
7498 break;
7499 }
7500 } else if (!KeyFunction) {
7501 // If we have a class with no key function that is the subject
7502 // of an explicit instantiation declaration, suppress the
7503 // vtable; it will live with the explicit instantiation
7504 // definition.
7505 bool IsExplicitInstantiationDeclaration
7506 = Class->getTemplateSpecializationKind()
7507 == TSK_ExplicitInstantiationDeclaration;
7508 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7509 REnd = Class->redecls_end();
7510 R != REnd; ++R) {
7511 TemplateSpecializationKind TSK
7512 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7513 if (TSK == TSK_ExplicitInstantiationDeclaration)
7514 IsExplicitInstantiationDeclaration = true;
7515 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7516 IsExplicitInstantiationDeclaration = false;
7517 break;
7518 }
7519 }
7520
7521 if (IsExplicitInstantiationDeclaration)
7522 continue;
7523 }
7524
7525 // Mark all of the virtual members of this class as referenced, so
7526 // that we can build a vtable. Then, tell the AST consumer that a
7527 // vtable for this class is required.
7528 MarkVirtualMembersReferenced(Loc, Class);
7529 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7530 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7531
7532 // Optionally warn if we're emitting a weak vtable.
7533 if (Class->getLinkage() == ExternalLinkage &&
7534 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007535 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007536 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7537 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007538 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007539 VTableUses.clear();
7540
Anders Carlsson82fccd02009-12-07 08:24:59 +00007541 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007542}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007543
Rafael Espindola5b334082010-03-26 00:36:59 +00007544void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7545 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007546 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7547 e = RD->method_end(); i != e; ++i) {
7548 CXXMethodDecl *MD = *i;
7549
7550 // C++ [basic.def.odr]p2:
7551 // [...] A virtual member function is used if it is not pure. [...]
7552 if (MD->isVirtual() && !MD->isPure())
7553 MarkDeclarationReferenced(Loc, MD);
7554 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007555
7556 // Only classes that have virtual bases need a VTT.
7557 if (RD->getNumVBases() == 0)
7558 return;
7559
7560 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7561 e = RD->bases_end(); i != e; ++i) {
7562 const CXXRecordDecl *Base =
7563 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007564 if (Base->getNumVBases() == 0)
7565 continue;
7566 MarkVirtualMembersReferenced(Loc, Base);
7567 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007568}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007569
7570/// SetIvarInitializers - This routine builds initialization ASTs for the
7571/// Objective-C implementation whose ivars need be initialized.
7572void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7573 if (!getLangOptions().CPlusPlus)
7574 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007575 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007576 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7577 CollectIvarsToConstructOrDestruct(OID, ivars);
7578 if (ivars.empty())
7579 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00007580 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007581 for (unsigned i = 0; i < ivars.size(); i++) {
7582 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007583 if (Field->isInvalidDecl())
7584 continue;
7585
Alexis Hunt1d792652011-01-08 20:30:50 +00007586 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007587 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7588 InitializationKind InitKind =
7589 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7590
7591 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007592 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007593 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007594 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007595 // Note, MemberInit could actually come back empty if no initialization
7596 // is required (e.g., because it would call a trivial default constructor)
7597 if (!MemberInit.get() || MemberInit.isInvalid())
7598 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007599
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007600 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00007601 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7602 SourceLocation(),
7603 MemberInit.takeAs<Expr>(),
7604 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007605 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007606
7607 // Be sure that the destructor is accessible and is marked as referenced.
7608 if (const RecordType *RecordTy
7609 = Context.getBaseElementType(Field->getType())
7610 ->getAs<RecordType>()) {
7611 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007612 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007613 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7614 CheckDestructorAccess(Field->getLocation(), Destructor,
7615 PDiag(diag::err_access_dtor_ivar)
7616 << Context.getBaseElementType(Field->getType()));
7617 }
7618 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007619 }
7620 ObjCImplementation->setIvarInitializers(Context,
7621 AllToInit.data(), AllToInit.size());
7622 }
7623}