blob: d16d9e9763d897785c2cc36002e354a33d833b4d [file] [log] [blame]
Chris Lattner3d1cee32008-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 McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000034#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000035#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner8123a952008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattner9e979552008-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 Kramer85b45212009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 public:
Mike Stump1eb44332009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000057
Chris Lattner9e979552008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000061 };
Chris Lattner8123a952008-04-10 02:22:51 +000062
Chris Lattner9e979552008-04-12 23:52:44 +000063 /// VisitExpr - Visit all of the children of this expression.
64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
65 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000066 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000067 E = Node->child_end(); I != E; ++I)
68 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000070 }
71
Chris Lattner9e979552008-04-12 23:52:44 +000072 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000077 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000093 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000097 }
Chris Lattner8123a952008-04-10 02:22:51 +000098
Douglas Gregor3996f232008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattner9e979552008-04-12 23:52:44 +0000101
Douglas Gregor796da182008-11-04 14:32:21 +0000102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
106 // member function.
107 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000110 }
Chris Lattner8123a952008-04-10 02:22:51 +0000111}
112
Anders Carlssoned961f92009-08-25 02:29:20 +0000113bool
John McCall9ae2f072010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000116 if (RequireCompleteType(Param->getLocation(), Param->getType(),
117 diag::err_typecheck_decl_incomplete_type)) {
118 Param->setInvalidDecl();
119 return true;
120 }
121
Anders Carlssoned961f92009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Douglas Gregor99a2e602009-12-16 01:38:02 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
129 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
130 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000131 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000132 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +0000133 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000134 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000135 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000136 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000137
Anders Carlsson0ece4912009-12-15 20:51:39 +0000138 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Anders Carlssoned961f92009-08-25 02:29:20 +0000140 // Okay: add the default argument to the parameter
141 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Anders Carlsson9351c172009-08-25 03:18:48 +0000143 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000144}
145
Chris Lattner8123a952008-04-10 02:22:51 +0000146/// ActOnParamDefaultArgument - Check whether the default argument
147/// provided for a function parameter is well-formed. If so, attach it
148/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000149void
John McCalld226f652010-08-21 09:40:31 +0000150Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000151 Expr *DefaultArg) {
152 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000153 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000154
John McCalld226f652010-08-21 09:40:31 +0000155 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000156 UnparsedDefaultArgLocs.erase(Param);
157
Chris Lattner3d1cee32008-04-08 05:04:30 +0000158 // Default arguments are only permitted in C++
159 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000160 Diag(EqualLoc, diag::err_param_default_argument)
161 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000162 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000163 return;
164 }
165
Anders Carlsson66e30672009-08-25 01:02:06 +0000166 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000167 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
168 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000169 Param->setInvalidDecl();
170 return;
171 }
Mike Stump1eb44332009-09-09 15:08:12 +0000172
John McCall9ae2f072010-08-23 23:25:46 +0000173 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000174}
175
Douglas Gregor61366e92008-12-24 00:01:03 +0000176/// ActOnParamUnparsedDefaultArgument - We've seen a default
177/// argument for a function parameter, but we can't parse it yet
178/// because we're inside a class definition. Note that this default
179/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000180void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000181 SourceLocation EqualLoc,
182 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000183 if (!param)
184 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000185
John McCalld226f652010-08-21 09:40:31 +0000186 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000187 if (Param)
188 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Anders Carlsson5e300d12009-06-12 16:51:40 +0000190 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000191}
192
Douglas Gregor72b505b2008-12-16 21:30:33 +0000193/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
194/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000195void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000196 if (!param)
197 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000198
John McCalld226f652010-08-21 09:40:31 +0000199 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Anders Carlsson5e300d12009-06-12 16:51:40 +0000201 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Anders Carlsson5e300d12009-06-12 16:51:40 +0000203 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000204}
205
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000206/// CheckExtraCXXDefaultArguments - Check for any extra default
207/// arguments in the declarator, which is not a function declaration
208/// or definition and therefore is not permitted to have default
209/// arguments. This routine should be invoked for every declarator
210/// that is not a function declaration or definition.
211void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
212 // C++ [dcl.fct.default]p3
213 // A default argument expression shall be specified only in the
214 // parameter-declaration-clause of a function declaration or in a
215 // template-parameter (14.1). It shall not be specified for a
216 // parameter pack. If it is specified in a
217 // parameter-declaration-clause, it shall not occur within a
218 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000219 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000220 DeclaratorChunk &chunk = D.getTypeObject(i);
221 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000222 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
223 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000224 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000225 if (Param->hasUnparsedDefaultArg()) {
226 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000227 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
228 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
229 delete Toks;
230 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000231 } else if (Param->getDefaultArg()) {
232 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
233 << Param->getDefaultArg()->getSourceRange();
234 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000235 }
236 }
237 }
238 }
239}
240
Chris Lattner3d1cee32008-04-08 05:04:30 +0000241// MergeCXXFunctionDecl - Merge two declarations of the same C++
242// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000243// type. Subroutine of MergeFunctionDecl. Returns true if there was an
244// error, false otherwise.
245bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
246 bool Invalid = false;
247
Chris Lattner3d1cee32008-04-08 05:04:30 +0000248 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000249 // For non-template functions, default arguments can be added in
250 // later declarations of a function in the same
251 // scope. Declarations in different scopes have completely
252 // distinct sets of default arguments. That is, declarations in
253 // inner scopes do not acquire default arguments from
254 // declarations in outer scopes, and vice versa. In a given
255 // function declaration, all parameters subsequent to a
256 // parameter with a default argument shall have default
257 // arguments supplied in this or previous declarations. A
258 // default argument shall not be redefined by a later
259 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000260 //
261 // C++ [dcl.fct.default]p6:
262 // Except for member functions of class templates, the default arguments
263 // in a member function definition that appears outside of the class
264 // definition are added to the set of default arguments provided by the
265 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000266 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
267 ParmVarDecl *OldParam = Old->getParamDecl(p);
268 ParmVarDecl *NewParam = New->getParamDecl(p);
269
Douglas Gregor6cc15182009-09-11 18:44:32 +0000270 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000271 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
272 // hint here. Alternatively, we could walk the type-source information
273 // for NewParam to find the last source location in the type... but it
274 // isn't worth the effort right now. This is the kind of test case that
275 // is hard to get right:
276
277 // int f(int);
278 // void g(int (*fp)(int) = f);
279 // void g(int (*fp)(int) = &f);
Mike Stump1eb44332009-09-09 15:08:12 +0000280 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000281 diag::err_param_default_argument_redefinition)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000282 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000283
284 // Look for the function declaration where the default argument was
285 // actually written, which may be a declaration prior to Old.
286 for (FunctionDecl *Older = Old->getPreviousDeclaration();
287 Older; Older = Older->getPreviousDeclaration()) {
288 if (!Older->getParamDecl(p)->hasDefaultArg())
289 break;
290
291 OldParam = Older->getParamDecl(p);
292 }
293
294 Diag(OldParam->getLocation(), diag::note_previous_definition)
295 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000296 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000297 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000298 // Merge the old default argument into the new parameter.
299 // It's important to use getInit() here; getDefaultArg()
300 // strips off any top-level CXXExprWithTemporaries.
John McCallbf73b352010-03-12 18:31:32 +0000301 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000302 if (OldParam->hasUninstantiatedDefaultArg())
303 NewParam->setUninstantiatedDefaultArg(
304 OldParam->getUninstantiatedDefaultArg());
305 else
John McCall3d6c1782010-05-04 01:53:42 +0000306 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000307 } else if (NewParam->hasDefaultArg()) {
308 if (New->getDescribedFunctionTemplate()) {
309 // Paragraph 4, quoted above, only applies to non-template functions.
310 Diag(NewParam->getLocation(),
311 diag::err_param_default_argument_template_redecl)
312 << NewParam->getDefaultArgRange();
313 Diag(Old->getLocation(), diag::note_template_prev_declaration)
314 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000315 } else if (New->getTemplateSpecializationKind()
316 != TSK_ImplicitInstantiation &&
317 New->getTemplateSpecializationKind() != TSK_Undeclared) {
318 // C++ [temp.expr.spec]p21:
319 // Default function arguments shall not be specified in a declaration
320 // or a definition for one of the following explicit specializations:
321 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000322 // - the explicit specialization of a member function template;
323 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000324 // template where the class template specialization to which the
325 // member function specialization belongs is implicitly
326 // instantiated.
327 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
328 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
329 << New->getDeclName()
330 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000331 } else if (New->getDeclContext()->isDependentContext()) {
332 // C++ [dcl.fct.default]p6 (DR217):
333 // Default arguments for a member function of a class template shall
334 // be specified on the initial declaration of the member function
335 // within the class template.
336 //
337 // Reading the tea leaves a bit in DR217 and its reference to DR205
338 // leads me to the conclusion that one cannot add default function
339 // arguments for an out-of-line definition of a member function of a
340 // dependent type.
341 int WhichKind = 2;
342 if (CXXRecordDecl *Record
343 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
344 if (Record->getDescribedClassTemplate())
345 WhichKind = 0;
346 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
347 WhichKind = 1;
348 else
349 WhichKind = 2;
350 }
351
352 Diag(NewParam->getLocation(),
353 diag::err_param_default_argument_member_template_redecl)
354 << WhichKind
355 << NewParam->getDefaultArgRange();
356 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000357 }
358 }
359
Douglas Gregore13ad832010-02-12 07:32:17 +0000360 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000361 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000362
Douglas Gregorcda9c672009-02-16 17:45:42 +0000363 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000364}
365
366/// CheckCXXDefaultArguments - Verify that the default arguments for a
367/// function declaration are well-formed according to C++
368/// [dcl.fct.default].
369void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
370 unsigned NumParams = FD->getNumParams();
371 unsigned p;
372
373 // Find first parameter with a default argument
374 for (p = 0; p < NumParams; ++p) {
375 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000376 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000377 break;
378 }
379
380 // C++ [dcl.fct.default]p4:
381 // In a given function declaration, all parameters
382 // subsequent to a parameter with a default argument shall
383 // have default arguments supplied in this or previous
384 // declarations. A default argument shall not be redefined
385 // by a later declaration (not even to the same value).
386 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000387 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000388 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000389 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 if (Param->isInvalidDecl())
391 /* We already complained about this parameter. */;
392 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000393 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000394 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000395 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000396 else
Mike Stump1eb44332009-09-09 15:08:12 +0000397 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000398 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Chris Lattner3d1cee32008-04-08 05:04:30 +0000400 LastMissingDefaultArg = p;
401 }
402 }
403
404 if (LastMissingDefaultArg > 0) {
405 // Some default arguments were missing. Clear out all of the
406 // default arguments up to (and including) the last missing
407 // default argument, so that we leave the function parameters
408 // in a semantically valid state.
409 for (p = 0; p <= LastMissingDefaultArg; ++p) {
410 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000411 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000412 Param->setDefaultArg(0);
413 }
414 }
415 }
416}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000417
Douglas Gregorb48fe382008-10-31 09:07:45 +0000418/// isCurrentClassName - Determine whether the identifier II is the
419/// name of the class type currently being defined. In the case of
420/// nested classes, this will only return true if II is the name of
421/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000422bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
423 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000424 assert(getLangOptions().CPlusPlus && "No class names in C!");
425
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000426 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000427 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000428 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000429 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
430 } else
431 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
432
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000433 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000434 return &II == CurDecl->getIdentifier();
435 else
436 return false;
437}
438
Mike Stump1eb44332009-09-09 15:08:12 +0000439/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000440///
441/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
442/// and returns NULL otherwise.
443CXXBaseSpecifier *
444Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
445 SourceRange SpecifierRange,
446 bool Virtual, AccessSpecifier Access,
Nick Lewycky56062202010-07-26 16:56:01 +0000447 TypeSourceInfo *TInfo) {
448 QualType BaseType = TInfo->getType();
449
Douglas Gregor2943aed2009-03-03 04:44:36 +0000450 // C++ [class.union]p1:
451 // A union shall not have base classes.
452 if (Class->isUnion()) {
453 Diag(Class->getLocation(), diag::err_base_clause_on_union)
454 << SpecifierRange;
455 return 0;
456 }
457
458 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000459 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000460 Class->getTagKind() == TTK_Class,
461 Access, TInfo);
462
463 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000464
465 // Base specifiers must be record types.
466 if (!BaseType->isRecordType()) {
467 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
468 return 0;
469 }
470
471 // C++ [class.union]p1:
472 // A union shall not be used as a base class.
473 if (BaseType->isUnionType()) {
474 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
475 return 0;
476 }
477
478 // C++ [class.derived]p2:
479 // The class-name in a base-specifier shall not be an incompletely
480 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000481 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000482 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000483 << SpecifierRange)) {
484 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000485 return 0;
John McCall572fc622010-08-17 07:23:57 +0000486 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000487
Eli Friedman1d954f62009-08-15 21:55:26 +0000488 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000489 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000490 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000491 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000492 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000493 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
494 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000495
Sean Huntbbd37c62009-11-21 08:43:09 +0000496 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
497 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
498 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000499 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
500 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000501 return 0;
502 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000503
Eli Friedmand0137332009-12-05 23:03:49 +0000504 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
John McCall572fc622010-08-17 07:23:57 +0000505
506 if (BaseDecl->isInvalidDecl())
507 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000508
509 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000510 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000511 Class->getTagKind() == TTK_Class,
512 Access, TInfo);
Anders Carlsson51f94042009-12-03 17:49:57 +0000513}
514
515void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
516 const CXXRecordDecl *BaseClass,
517 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000518 // A class with a non-empty base class is not empty.
519 // FIXME: Standard ref?
520 if (!BaseClass->isEmpty())
521 Class->setEmpty(false);
522
523 // C++ [class.virtual]p1:
524 // A class that [...] inherits a virtual function is called a polymorphic
525 // class.
526 if (BaseClass->isPolymorphic())
527 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000528
Douglas Gregor2943aed2009-03-03 04:44:36 +0000529 // C++ [dcl.init.aggr]p1:
530 // An aggregate is [...] a class with [...] no base classes [...].
531 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000532
533 // C++ [class]p4:
534 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000535 Class->setPOD(false);
536
Anders Carlsson51f94042009-12-03 17:49:57 +0000537 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000538 // C++ [class.ctor]p5:
539 // A constructor is trivial if its class has no virtual base classes.
540 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000541
542 // C++ [class.copy]p6:
543 // A copy constructor is trivial if its class has no virtual base classes.
544 Class->setHasTrivialCopyConstructor(false);
545
546 // C++ [class.copy]p11:
547 // A copy assignment operator is trivial if its class has no virtual
548 // base classes.
549 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000550
551 // C++0x [meta.unary.prop] is_empty:
552 // T is a class type, but not a union type, with ... no virtual base
553 // classes
554 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000555 } else {
556 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000557 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000558 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000559 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000560 Class->setHasTrivialConstructor(false);
561
562 // C++ [class.copy]p6:
563 // A copy constructor is trivial if all the direct base classes of its
564 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000565 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000566 Class->setHasTrivialCopyConstructor(false);
567
568 // C++ [class.copy]p11:
569 // A copy assignment operator is trivial if all the direct base classes
570 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000571 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000572 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000573 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000574
575 // C++ [class.ctor]p3:
576 // A destructor is trivial if all the direct base classes of its class
577 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000578 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000579 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000580}
581
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000582/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
583/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000584/// example:
585/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000586/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000587BaseResult
John McCalld226f652010-08-21 09:40:31 +0000588Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000589 bool Virtual, AccessSpecifier Access,
John McCallb3d87482010-08-24 05:47:05 +0000590 ParsedType basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000591 if (!classdecl)
592 return true;
593
Douglas Gregor40808ce2009-03-09 23:48:35 +0000594 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000595 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000596 if (!Class)
597 return true;
598
Nick Lewycky56062202010-07-26 16:56:01 +0000599 TypeSourceInfo *TInfo = 0;
600 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000601 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Nick Lewycky56062202010-07-26 16:56:01 +0000602 Virtual, Access, TInfo))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000603 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Douglas Gregor2943aed2009-03-03 04:44:36 +0000605 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000606}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000607
Douglas Gregor2943aed2009-03-03 04:44:36 +0000608/// \brief Performs the actual work of attaching the given base class
609/// specifiers to a C++ class.
610bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
611 unsigned NumBases) {
612 if (NumBases == 0)
613 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000614
615 // Used to keep track of which base types we have already seen, so
616 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000617 // that the key is always the unqualified canonical type of the base
618 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000619 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
620
621 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000622 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000623 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000624 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000625 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000626 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000627 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-05-20 23:34:56 +0000628 if (!Class->hasObjectMember()) {
629 if (const RecordType *FDTTy =
630 NewBaseType.getTypePtr()->getAs<RecordType>())
631 if (FDTTy->getDecl()->hasObjectMember())
632 Class->setHasObjectMember(true);
633 }
634
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000635 if (KnownBaseTypes[NewBaseType]) {
636 // C++ [class.mi]p3:
637 // A class shall not be specified as a direct base class of a
638 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000639 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000640 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000641 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000642 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000643
644 // Delete the duplicate base class specifier; we're going to
645 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000646 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000647
648 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000649 } else {
650 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000651 KnownBaseTypes[NewBaseType] = Bases[idx];
652 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000653 }
654 }
655
656 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000657 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000658
659 // Delete the remaining (good) base class specifiers, since their
660 // data has been copied into the CXXRecordDecl.
661 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000662 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000663
664 return Invalid;
665}
666
667/// ActOnBaseSpecifiers - Attach the given base specifiers to the
668/// class, after checking whether there are any duplicate base
669/// classes.
John McCalld226f652010-08-21 09:40:31 +0000670void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000671 unsigned NumBases) {
672 if (!ClassDecl || !Bases || !NumBases)
673 return;
674
675 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000676 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000677 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000678}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000679
John McCall3cb0ebd2010-03-10 03:28:59 +0000680static CXXRecordDecl *GetClassForType(QualType T) {
681 if (const RecordType *RT = T->getAs<RecordType>())
682 return cast<CXXRecordDecl>(RT->getDecl());
683 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
684 return ICT->getDecl();
685 else
686 return 0;
687}
688
Douglas Gregora8f32e02009-10-06 17:59:45 +0000689/// \brief Determine whether the type \p Derived is a C++ class that is
690/// derived from the type \p Base.
691bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
692 if (!getLangOptions().CPlusPlus)
693 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000694
695 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
696 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000697 return false;
698
John McCall3cb0ebd2010-03-10 03:28:59 +0000699 CXXRecordDecl *BaseRD = GetClassForType(Base);
700 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000701 return false;
702
John McCall86ff3082010-02-04 22:26:26 +0000703 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
704 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000705}
706
707/// \brief Determine whether the type \p Derived is a C++ class that is
708/// derived from the type \p Base.
709bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
710 if (!getLangOptions().CPlusPlus)
711 return false;
712
John McCall3cb0ebd2010-03-10 03:28:59 +0000713 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
714 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000715 return false;
716
John McCall3cb0ebd2010-03-10 03:28:59 +0000717 CXXRecordDecl *BaseRD = GetClassForType(Base);
718 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000719 return false;
720
Douglas Gregora8f32e02009-10-06 17:59:45 +0000721 return DerivedRD->isDerivedFrom(BaseRD, Paths);
722}
723
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000724void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000725 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000726 assert(BasePathArray.empty() && "Base path array must be empty!");
727 assert(Paths.isRecordingPaths() && "Must record paths!");
728
729 const CXXBasePath &Path = Paths.front();
730
731 // We first go backward and check if we have a virtual base.
732 // FIXME: It would be better if CXXBasePath had the base specifier for
733 // the nearest virtual base.
734 unsigned Start = 0;
735 for (unsigned I = Path.size(); I != 0; --I) {
736 if (Path[I - 1].Base->isVirtual()) {
737 Start = I - 1;
738 break;
739 }
740 }
741
742 // Now add all bases.
743 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000744 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000745}
746
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000747/// \brief Determine whether the given base path includes a virtual
748/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000749bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
750 for (CXXCastPath::const_iterator B = BasePath.begin(),
751 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000752 B != BEnd; ++B)
753 if ((*B)->isVirtual())
754 return true;
755
756 return false;
757}
758
Douglas Gregora8f32e02009-10-06 17:59:45 +0000759/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
760/// conversion (where Derived and Base are class types) is
761/// well-formed, meaning that the conversion is unambiguous (and
762/// that all of the base classes are accessible). Returns true
763/// and emits a diagnostic if the code is ill-formed, returns false
764/// otherwise. Loc is the location where this routine should point to
765/// if there is an error, and Range is the source range to highlight
766/// if there is an error.
767bool
768Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000769 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000770 unsigned AmbigiousBaseConvID,
771 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000772 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000773 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000774 // First, determine whether the path from Derived to Base is
775 // ambiguous. This is slightly more expensive than checking whether
776 // the Derived to Base conversion exists, because here we need to
777 // explore multiple paths to determine if there is an ambiguity.
778 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
779 /*DetectVirtual=*/false);
780 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
781 assert(DerivationOkay &&
782 "Can only be used with a derived-to-base conversion");
783 (void)DerivationOkay;
784
785 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000786 if (InaccessibleBaseID) {
787 // Check that the base class can be accessed.
788 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
789 InaccessibleBaseID)) {
790 case AR_inaccessible:
791 return true;
792 case AR_accessible:
793 case AR_dependent:
794 case AR_delayed:
795 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000796 }
John McCall6b2accb2010-02-10 09:31:12 +0000797 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000798
799 // Build a base path if necessary.
800 if (BasePath)
801 BuildBasePathArray(Paths, *BasePath);
802 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000803 }
804
805 // We know that the derived-to-base conversion is ambiguous, and
806 // we're going to produce a diagnostic. Perform the derived-to-base
807 // search just one more time to compute all of the possible paths so
808 // that we can print them out. This is more expensive than any of
809 // the previous derived-to-base checks we've done, but at this point
810 // performance isn't as much of an issue.
811 Paths.clear();
812 Paths.setRecordingPaths(true);
813 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
814 assert(StillOkay && "Can only be used with a derived-to-base conversion");
815 (void)StillOkay;
816
817 // Build up a textual representation of the ambiguous paths, e.g.,
818 // D -> B -> A, that will be used to illustrate the ambiguous
819 // conversions in the diagnostic. We only print one of the paths
820 // to each base class subobject.
821 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
822
823 Diag(Loc, AmbigiousBaseConvID)
824 << Derived << Base << PathDisplayStr << Range << Name;
825 return true;
826}
827
828bool
829Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000830 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000831 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000832 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000833 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000834 IgnoreAccess ? 0
835 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000836 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000837 Loc, Range, DeclarationName(),
838 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000839}
840
841
842/// @brief Builds a string representing ambiguous paths from a
843/// specific derived class to different subobjects of the same base
844/// class.
845///
846/// This function builds a string that can be used in error messages
847/// to show the different paths that one can take through the
848/// inheritance hierarchy to go from the derived class to different
849/// subobjects of a base class. The result looks something like this:
850/// @code
851/// struct D -> struct B -> struct A
852/// struct D -> struct C -> struct A
853/// @endcode
854std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
855 std::string PathDisplayStr;
856 std::set<unsigned> DisplayedPaths;
857 for (CXXBasePaths::paths_iterator Path = Paths.begin();
858 Path != Paths.end(); ++Path) {
859 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
860 // We haven't displayed a path to this particular base
861 // class subobject yet.
862 PathDisplayStr += "\n ";
863 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
864 for (CXXBasePath::const_iterator Element = Path->begin();
865 Element != Path->end(); ++Element)
866 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
867 }
868 }
869
870 return PathDisplayStr;
871}
872
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000873//===----------------------------------------------------------------------===//
874// C++ class member Handling
875//===----------------------------------------------------------------------===//
876
Abramo Bagnara6206d532010-06-05 05:09:32 +0000877/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000878Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
879 SourceLocation ASLoc,
880 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000881 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000882 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000883 ASLoc, ColonLoc);
884 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000885 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000886}
887
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000888/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
889/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
890/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000891/// any.
John McCalld226f652010-08-21 09:40:31 +0000892Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000893Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000894 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000895 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
896 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000897 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +0000898 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
899 DeclarationName Name = NameInfo.getName();
900 SourceLocation Loc = NameInfo.getLoc();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000901 Expr *BitWidth = static_cast<Expr*>(BW);
902 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000903
John McCall4bde1e12010-06-04 08:34:12 +0000904 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +0000905 assert(!DS.isFriendSpecified());
906
John McCall4bde1e12010-06-04 08:34:12 +0000907 bool isFunc = false;
908 if (D.isFunctionDeclarator())
909 isFunc = true;
910 else if (D.getNumTypeObjects() == 0 &&
911 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +0000912 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +0000913 isFunc = TDType->isFunctionType();
914 }
915
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000916 // C++ 9.2p6: A member shall not be declared to have automatic storage
917 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000918 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
919 // data members and cannot be applied to names declared const or static,
920 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000921 switch (DS.getStorageClassSpec()) {
922 case DeclSpec::SCS_unspecified:
923 case DeclSpec::SCS_typedef:
924 case DeclSpec::SCS_static:
925 // FALL THROUGH.
926 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000927 case DeclSpec::SCS_mutable:
928 if (isFunc) {
929 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000930 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000931 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000932 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000933
Sebastian Redla11f42f2008-11-17 23:24:37 +0000934 // FIXME: It would be nicer if the keyword was ignored only for this
935 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000936 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +0000937 }
938 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000939 default:
940 if (DS.getStorageClassSpecLoc().isValid())
941 Diag(DS.getStorageClassSpecLoc(),
942 diag::err_storageclass_invalid_for_member);
943 else
944 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
945 D.getMutableDeclSpec().ClearStorageClassSpecs();
946 }
947
Sebastian Redl669d5d72008-11-14 23:42:31 +0000948 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
949 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000950 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000951
952 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000953 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000954 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000955 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
956 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000957 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000958 } else {
John McCalld226f652010-08-21 09:40:31 +0000959 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000960 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +0000961 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +0000962 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000963
964 // Non-instance-fields can't have a bitfield.
965 if (BitWidth) {
966 if (Member->isInvalidDecl()) {
967 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000968 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000969 // C++ 9.6p3: A bit-field shall not be a static member.
970 // "static member 'A' cannot be a bit-field"
971 Diag(Loc, diag::err_static_not_bitfield)
972 << Name << BitWidth->getSourceRange();
973 } else if (isa<TypedefDecl>(Member)) {
974 // "typedef member 'x' cannot be a bit-field"
975 Diag(Loc, diag::err_typedef_not_bitfield)
976 << Name << BitWidth->getSourceRange();
977 } else {
978 // A function typedef ("typedef int f(); f a;").
979 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
980 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000981 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000982 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000983 }
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Chris Lattner8b963ef2009-03-05 23:01:03 +0000985 BitWidth = 0;
986 Member->setInvalidDecl();
987 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000988
989 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Douglas Gregor37b372b2009-08-20 22:52:58 +0000991 // If we have declared a member function template, set the access of the
992 // templated declaration as well.
993 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
994 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000995 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000996
Douglas Gregor10bd3682008-11-17 22:58:34 +0000997 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000998
Douglas Gregor021c3b32009-03-11 23:00:04 +0000999 if (Init)
John McCall9ae2f072010-08-23 23:25:46 +00001000 AddInitializerToDecl(Member, Init, false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001001 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +00001002 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001003
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001004 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +00001005 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001006 return 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001007 }
John McCalld226f652010-08-21 09:40:31 +00001008 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001009}
1010
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001011/// \brief Find the direct and/or virtual base specifiers that
1012/// correspond to the given base type, for use in base initialization
1013/// within a constructor.
1014static bool FindBaseInitializer(Sema &SemaRef,
1015 CXXRecordDecl *ClassDecl,
1016 QualType BaseType,
1017 const CXXBaseSpecifier *&DirectBaseSpec,
1018 const CXXBaseSpecifier *&VirtualBaseSpec) {
1019 // First, check for a direct base class.
1020 DirectBaseSpec = 0;
1021 for (CXXRecordDecl::base_class_const_iterator Base
1022 = ClassDecl->bases_begin();
1023 Base != ClassDecl->bases_end(); ++Base) {
1024 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1025 // We found a direct base of this type. That's what we're
1026 // initializing.
1027 DirectBaseSpec = &*Base;
1028 break;
1029 }
1030 }
1031
1032 // Check for a virtual base class.
1033 // FIXME: We might be able to short-circuit this if we know in advance that
1034 // there are no virtual bases.
1035 VirtualBaseSpec = 0;
1036 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1037 // We haven't found a base yet; search the class hierarchy for a
1038 // virtual base class.
1039 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1040 /*DetectVirtual=*/false);
1041 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1042 BaseType, Paths)) {
1043 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1044 Path != Paths.end(); ++Path) {
1045 if (Path->back().Base->isVirtual()) {
1046 VirtualBaseSpec = Path->back().Base;
1047 break;
1048 }
1049 }
1050 }
1051 }
1052
1053 return DirectBaseSpec || VirtualBaseSpec;
1054}
1055
Douglas Gregor7ad83902008-11-05 04:29:56 +00001056/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001057MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001058Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001059 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001060 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001061 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001062 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001063 SourceLocation IdLoc,
1064 SourceLocation LParenLoc,
1065 ExprTy **Args, unsigned NumArgs,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001066 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001067 if (!ConstructorD)
1068 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001070 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001071
1072 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001073 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001074 if (!Constructor) {
1075 // The user wrote a constructor initializer on a function that is
1076 // not a C++ constructor. Ignore the error for now, because we may
1077 // have more member initializers coming; we'll diagnose it just
1078 // once in ActOnMemInitializers.
1079 return true;
1080 }
1081
1082 CXXRecordDecl *ClassDecl = Constructor->getParent();
1083
1084 // C++ [class.base.init]p2:
1085 // Names in a mem-initializer-id are looked up in the scope of the
1086 // constructor’s class and, if not found in that scope, are looked
1087 // up in the scope containing the constructor’s
1088 // definition. [Note: if the constructor’s class contains a member
1089 // with the same name as a direct or virtual base class of the
1090 // class, a mem-initializer-id naming the member or base class and
1091 // composed of a single identifier refers to the class member. A
1092 // mem-initializer-id for the hidden base class may be specified
1093 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001094 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001095 // Look for a member, first.
1096 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001097 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001098 = ClassDecl->lookup(MemberOrBase);
1099 if (Result.first != Result.second)
1100 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001101
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001102 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001103
Eli Friedman59c04372009-07-29 19:44:27 +00001104 if (Member)
1105 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001106 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001107 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001108 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001109 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001110 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001111
1112 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001113 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001114 } else {
1115 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1116 LookupParsedName(R, S, &SS);
1117
1118 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1119 if (!TyD) {
1120 if (R.isAmbiguous()) return true;
1121
John McCallfd225442010-04-09 19:01:14 +00001122 // We don't want access-control diagnostics here.
1123 R.suppressDiagnostics();
1124
Douglas Gregor7a886e12010-01-19 06:46:48 +00001125 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1126 bool NotUnknownSpecialization = false;
1127 DeclContext *DC = computeDeclContext(SS, false);
1128 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1129 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1130
1131 if (!NotUnknownSpecialization) {
1132 // When the scope specifier can refer to a member of an unknown
1133 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001134 BaseType = CheckTypenameType(ETK_None,
1135 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00001136 *MemberOrBase, SourceLocation(),
1137 SS.getRange(), IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001138 if (BaseType.isNull())
1139 return true;
1140
Douglas Gregor7a886e12010-01-19 06:46:48 +00001141 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001142 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001143 }
1144 }
1145
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001146 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001147 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001148 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1149 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001150 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001151 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001152 // We have found a non-static data member with a similar
1153 // name to what was typed; complain and initialize that
1154 // member.
1155 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1156 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001157 << FixItHint::CreateReplacement(R.getNameLoc(),
1158 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001159 Diag(Member->getLocation(), diag::note_previous_decl)
1160 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001161
1162 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1163 LParenLoc, RParenLoc);
1164 }
1165 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1166 const CXXBaseSpecifier *DirectBaseSpec;
1167 const CXXBaseSpecifier *VirtualBaseSpec;
1168 if (FindBaseInitializer(*this, ClassDecl,
1169 Context.getTypeDeclType(Type),
1170 DirectBaseSpec, VirtualBaseSpec)) {
1171 // We have found a direct or virtual base class with a
1172 // similar name to what was typed; complain and initialize
1173 // that base class.
1174 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1175 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001176 << FixItHint::CreateReplacement(R.getNameLoc(),
1177 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001178
1179 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1180 : VirtualBaseSpec;
1181 Diag(BaseSpec->getSourceRange().getBegin(),
1182 diag::note_base_class_specified_here)
1183 << BaseSpec->getType()
1184 << BaseSpec->getSourceRange();
1185
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001186 TyD = Type;
1187 }
1188 }
1189 }
1190
Douglas Gregor7a886e12010-01-19 06:46:48 +00001191 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001192 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1193 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1194 return true;
1195 }
John McCall2b194412009-12-21 10:41:20 +00001196 }
1197
Douglas Gregor7a886e12010-01-19 06:46:48 +00001198 if (BaseType.isNull()) {
1199 BaseType = Context.getTypeDeclType(TyD);
1200 if (SS.isSet()) {
1201 NestedNameSpecifier *Qualifier =
1202 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001203
Douglas Gregor7a886e12010-01-19 06:46:48 +00001204 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001205 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001206 }
John McCall2b194412009-12-21 10:41:20 +00001207 }
1208 }
Mike Stump1eb44332009-09-09 15:08:12 +00001209
John McCalla93c9342009-12-07 02:54:59 +00001210 if (!TInfo)
1211 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001212
John McCalla93c9342009-12-07 02:54:59 +00001213 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001214 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001215}
1216
John McCallb4190042009-11-04 23:02:40 +00001217/// Checks an initializer expression for use of uninitialized fields, such as
1218/// containing the field that is being initialized. Returns true if there is an
1219/// uninitialized field was used an updates the SourceLocation parameter; false
1220/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001221static bool InitExprContainsUninitializedFields(const Stmt *S,
1222 const FieldDecl *LhsField,
1223 SourceLocation *L) {
1224 if (isa<CallExpr>(S)) {
1225 // Do not descend into function calls or constructors, as the use
1226 // of an uninitialized field may be valid. One would have to inspect
1227 // the contents of the function/ctor to determine if it is safe or not.
1228 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1229 // may be safe, depending on what the function/ctor does.
1230 return false;
1231 }
1232 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1233 const NamedDecl *RhsField = ME->getMemberDecl();
John McCallb4190042009-11-04 23:02:40 +00001234 if (RhsField == LhsField) {
1235 // Initializing a field with itself. Throw a warning.
1236 // But wait; there are exceptions!
1237 // Exception #1: The field may not belong to this record.
1238 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001239 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001240 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1241 // Even though the field matches, it does not belong to this record.
1242 return false;
1243 }
1244 // None of the exceptions triggered; return true to indicate an
1245 // uninitialized field was used.
1246 *L = ME->getMemberLoc();
1247 return true;
1248 }
1249 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001250 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1251 it != e; ++it) {
1252 if (!*it) {
1253 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001254 continue;
1255 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001256 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1257 return true;
John McCallb4190042009-11-04 23:02:40 +00001258 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001259 return false;
John McCallb4190042009-11-04 23:02:40 +00001260}
1261
John McCallf312b1e2010-08-26 23:41:50 +00001262MemInitResult
Eli Friedman59c04372009-07-29 19:44:27 +00001263Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1264 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001265 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001266 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001267 // Diagnose value-uses of fields to initialize themselves, e.g.
1268 // foo(foo)
1269 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001270 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001271 for (unsigned i = 0; i < NumArgs; ++i) {
1272 SourceLocation L;
1273 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1274 // FIXME: Return true in the case when other fields are used before being
1275 // uninitialized. For example, let this field be the i'th field. When
1276 // initializing the i'th field, throw a warning if any of the >= i'th
1277 // fields are used, as they are not yet initialized.
1278 // Right now we are only handling the case where the i'th field uses
1279 // itself in its initializer.
1280 Diag(L, diag::warn_field_is_uninit);
1281 }
1282 }
1283
Eli Friedman59c04372009-07-29 19:44:27 +00001284 bool HasDependentArg = false;
1285 for (unsigned i = 0; i < NumArgs; i++)
1286 HasDependentArg |= Args[i]->isTypeDependent();
1287
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001288 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001289 // Can't check initialization for a member of dependent type or when
1290 // any of the arguments are type-dependent expressions.
John McCall9ae2f072010-08-23 23:25:46 +00001291 Expr *Init
1292 = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1293 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001294
1295 // Erase any temporaries within this evaluation context; we're not
1296 // going to track them in the AST, since we'll be rebuilding the
1297 // ASTs during template instantiation.
1298 ExprTemporaries.erase(
1299 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1300 ExprTemporaries.end());
1301
1302 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1303 LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001304 Init,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001305 RParenLoc);
1306
Douglas Gregor7ad83902008-11-05 04:29:56 +00001307 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001308
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001309 if (Member->isInvalidDecl())
1310 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001311
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001312 // Initialize the member.
1313 InitializedEntity MemberEntity =
1314 InitializedEntity::InitializeMember(Member, 0);
1315 InitializationKind Kind =
1316 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1317
1318 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1319
John McCall60d7b3a2010-08-24 06:29:42 +00001320 ExprResult MemberInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001321 InitSeq.Perform(*this, MemberEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001322 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001323 if (MemberInit.isInvalid())
1324 return true;
1325
1326 // C++0x [class.base.init]p7:
1327 // The initialization of each base and member constitutes a
1328 // full-expression.
John McCall9ae2f072010-08-23 23:25:46 +00001329 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001330 if (MemberInit.isInvalid())
1331 return true;
1332
1333 // If we are in a dependent context, template instantiation will
1334 // perform this type-checking again. Just save the arguments that we
1335 // received in a ParenListExpr.
1336 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1337 // of the information that we have about the member
1338 // initializer. However, deconstructing the ASTs is a dicey process,
1339 // and this approach is far more likely to get the corner cases right.
1340 if (CurContext->isDependentContext()) {
1341 // Bump the reference count of all of the arguments.
1342 for (unsigned I = 0; I != NumArgs; ++I)
1343 Args[I]->Retain();
1344
John McCall9ae2f072010-08-23 23:25:46 +00001345 Expr *Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1346 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001347 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1348 LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001349 Init,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001350 RParenLoc);
1351 }
1352
Douglas Gregor802ab452009-12-02 22:36:29 +00001353 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001354 LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001355 MemberInit.get(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001356 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001357}
1358
John McCallf312b1e2010-08-26 23:41:50 +00001359MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001360Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001361 Expr **Args, unsigned NumArgs,
1362 SourceLocation LParenLoc, SourceLocation RParenLoc,
1363 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001364 bool HasDependentArg = false;
1365 for (unsigned i = 0; i < NumArgs; i++)
1366 HasDependentArg |= Args[i]->isTypeDependent();
1367
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001368 SourceLocation BaseLoc
1369 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1370
1371 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1372 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1373 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1374
1375 // C++ [class.base.init]p2:
1376 // [...] Unless the mem-initializer-id names a nonstatic data
1377 // member of the constructor’s class or a direct or virtual base
1378 // of that class, the mem-initializer is ill-formed. A
1379 // mem-initializer-list can initialize a base class using any
1380 // name that denotes that base class type.
1381 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1382
1383 // Check for direct and virtual base classes.
1384 const CXXBaseSpecifier *DirectBaseSpec = 0;
1385 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1386 if (!Dependent) {
1387 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1388 VirtualBaseSpec);
1389
1390 // C++ [base.class.init]p2:
1391 // Unless the mem-initializer-id names a nonstatic data member of the
1392 // constructor's class or a direct or virtual base of that class, the
1393 // mem-initializer is ill-formed.
1394 if (!DirectBaseSpec && !VirtualBaseSpec) {
1395 // If the class has any dependent bases, then it's possible that
1396 // one of those types will resolve to the same type as
1397 // BaseType. Therefore, just treat this as a dependent base
1398 // class initialization. FIXME: Should we try to check the
1399 // initialization anyway? It seems odd.
1400 if (ClassDecl->hasAnyDependentBases())
1401 Dependent = true;
1402 else
1403 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1404 << BaseType << Context.getTypeDeclType(ClassDecl)
1405 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1406 }
1407 }
1408
1409 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001410 // Can't check initialization for a base of dependent type or when
1411 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001412 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001413 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1414 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001415
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001416 // Erase any temporaries within this evaluation context; we're not
1417 // going to track them in the AST, since we'll be rebuilding the
1418 // ASTs during template instantiation.
1419 ExprTemporaries.erase(
1420 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1421 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001422
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001423 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001424 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001425 LParenLoc,
1426 BaseInit.takeAs<Expr>(),
1427 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001428 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001429
1430 // C++ [base.class.init]p2:
1431 // If a mem-initializer-id is ambiguous because it designates both
1432 // a direct non-virtual base class and an inherited virtual base
1433 // class, the mem-initializer is ill-formed.
1434 if (DirectBaseSpec && VirtualBaseSpec)
1435 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001436 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001437
1438 CXXBaseSpecifier *BaseSpec
1439 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1440 if (!BaseSpec)
1441 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1442
1443 // Initialize the base.
1444 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001445 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001446 InitializationKind Kind =
1447 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1448
1449 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1450
John McCall60d7b3a2010-08-24 06:29:42 +00001451 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001452 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001453 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001454 if (BaseInit.isInvalid())
1455 return true;
1456
1457 // C++0x [class.base.init]p7:
1458 // The initialization of each base and member constitutes a
1459 // full-expression.
John McCall9ae2f072010-08-23 23:25:46 +00001460 BaseInit = MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001461 if (BaseInit.isInvalid())
1462 return true;
1463
1464 // If we are in a dependent context, template instantiation will
1465 // perform this type-checking again. Just save the arguments that we
1466 // received in a ParenListExpr.
1467 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1468 // of the information that we have about the base
1469 // initializer. However, deconstructing the ASTs is a dicey process,
1470 // and this approach is far more likely to get the corner cases right.
1471 if (CurContext->isDependentContext()) {
1472 // Bump the reference count of all of the arguments.
1473 for (unsigned I = 0; I != NumArgs; ++I)
1474 Args[I]->Retain();
1475
John McCall60d7b3a2010-08-24 06:29:42 +00001476 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001477 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1478 RParenLoc));
1479 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001480 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001481 LParenLoc,
1482 Init.takeAs<Expr>(),
1483 RParenLoc);
1484 }
1485
1486 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001487 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001488 LParenLoc,
1489 BaseInit.takeAs<Expr>(),
1490 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001491}
1492
Anders Carlssone5ef7402010-04-23 03:10:23 +00001493/// ImplicitInitializerKind - How an implicit base or member initializer should
1494/// initialize its base or member.
1495enum ImplicitInitializerKind {
1496 IIK_Default,
1497 IIK_Copy,
1498 IIK_Move
1499};
1500
Anders Carlssondefefd22010-04-23 02:00:02 +00001501static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001502BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001503 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001504 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001505 bool IsInheritedVirtualBase,
1506 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001507 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001508 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1509 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001510
John McCall60d7b3a2010-08-24 06:29:42 +00001511 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001512
1513 switch (ImplicitInitKind) {
1514 case IIK_Default: {
1515 InitializationKind InitKind
1516 = InitializationKind::CreateDefault(Constructor->getLocation());
1517 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1518 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001519 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001520 break;
1521 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001522
Anders Carlssone5ef7402010-04-23 03:10:23 +00001523 case IIK_Copy: {
1524 ParmVarDecl *Param = Constructor->getParamDecl(0);
1525 QualType ParamType = Param->getType().getNonReferenceType();
1526
1527 Expr *CopyCtorArg =
1528 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregor62b71f42010-05-03 15:43:53 +00001529 Constructor->getLocation(), ParamType, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001530
Anders Carlssonc7957502010-04-24 22:02:54 +00001531 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001532 QualType ArgTy =
1533 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1534 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001535
1536 CXXCastPath BasePath;
1537 BasePath.push_back(BaseSpec);
Sebastian Redl906082e2010-07-20 04:20:21 +00001538 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCall2de56d12010-08-25 11:45:40 +00001539 CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00001540 VK_LValue, &BasePath);
Anders Carlssonc7957502010-04-24 22:02:54 +00001541
Anders Carlssone5ef7402010-04-23 03:10:23 +00001542 InitializationKind InitKind
1543 = InitializationKind::CreateDirect(Constructor->getLocation(),
1544 SourceLocation(), SourceLocation());
1545 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1546 &CopyCtorArg, 1);
1547 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001548 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001549 break;
1550 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001551
Anders Carlssone5ef7402010-04-23 03:10:23 +00001552 case IIK_Move:
1553 assert(false && "Unhandled initializer kind!");
1554 }
John McCall9ae2f072010-08-23 23:25:46 +00001555
1556 if (BaseInit.isInvalid())
1557 return true;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001558
John McCall9ae2f072010-08-23 23:25:46 +00001559 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Anders Carlsson84688f22010-04-20 23:11:20 +00001560 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001561 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001562
Anders Carlssondefefd22010-04-23 02:00:02 +00001563 CXXBaseInit =
Anders Carlsson84688f22010-04-20 23:11:20 +00001564 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1565 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1566 SourceLocation()),
1567 BaseSpec->isVirtual(),
1568 SourceLocation(),
1569 BaseInit.takeAs<Expr>(),
1570 SourceLocation());
1571
Anders Carlssondefefd22010-04-23 02:00:02 +00001572 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001573}
1574
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001575static bool
1576BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001577 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001578 FieldDecl *Field,
1579 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001580 if (Field->isInvalidDecl())
1581 return true;
1582
Chandler Carruthf186b542010-06-29 23:50:44 +00001583 SourceLocation Loc = Constructor->getLocation();
1584
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001585 if (ImplicitInitKind == IIK_Copy) {
1586 ParmVarDecl *Param = Constructor->getParamDecl(0);
1587 QualType ParamType = Param->getType().getNonReferenceType();
1588
1589 Expr *MemberExprBase =
1590 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001591 Loc, ParamType, 0);
1592
1593 // Build a reference to this field within the parameter.
1594 CXXScopeSpec SS;
1595 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1596 Sema::LookupMemberName);
1597 MemberLookup.addDecl(Field, AS_public);
1598 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001599 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001600 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001601 ParamType, Loc,
1602 /*IsArrow=*/false,
1603 SS,
1604 /*FirstQualifierInScope=*/0,
1605 MemberLookup,
1606 /*TemplateArgs=*/0);
1607 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001608 return true;
1609
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001610 // When the field we are copying is an array, create index variables for
1611 // each dimension of the array. We use these index variables to subscript
1612 // the source array, and other clients (e.g., CodeGen) will perform the
1613 // necessary iteration with these index variables.
1614 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1615 QualType BaseType = Field->getType();
1616 QualType SizeType = SemaRef.Context.getSizeType();
1617 while (const ConstantArrayType *Array
1618 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1619 // Create the iteration variable for this array index.
1620 IdentifierInfo *IterationVarName = 0;
1621 {
1622 llvm::SmallString<8> Str;
1623 llvm::raw_svector_ostream OS(Str);
1624 OS << "__i" << IndexVariables.size();
1625 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1626 }
1627 VarDecl *IterationVar
1628 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1629 IterationVarName, SizeType,
1630 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001631 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001632 IndexVariables.push_back(IterationVar);
1633
1634 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001635 ExprResult IterationVarRef
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001636 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1637 assert(!IterationVarRef.isInvalid() &&
1638 "Reference to invented variable cannot fail!");
1639
1640 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001641 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001642 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001643 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001644 Loc);
1645 if (CopyCtorArg.isInvalid())
1646 return true;
1647
1648 BaseType = Array->getElementType();
1649 }
1650
1651 // Construct the entity that we will be initializing. For an array, this
1652 // will be first element in the array, which may require several levels
1653 // of array-subscript entities.
1654 llvm::SmallVector<InitializedEntity, 4> Entities;
1655 Entities.reserve(1 + IndexVariables.size());
1656 Entities.push_back(InitializedEntity::InitializeMember(Field));
1657 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1658 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1659 0,
1660 Entities.back()));
1661
1662 // Direct-initialize to use the copy constructor.
1663 InitializationKind InitKind =
1664 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1665
1666 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1667 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1668 &CopyCtorArgE, 1);
1669
John McCall60d7b3a2010-08-24 06:29:42 +00001670 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001671 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001672 MultiExprArg(&CopyCtorArgE, 1));
John McCall9ae2f072010-08-23 23:25:46 +00001673 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001674 if (MemberInit.isInvalid())
1675 return true;
1676
1677 CXXMemberInit
1678 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1679 MemberInit.takeAs<Expr>(), Loc,
1680 IndexVariables.data(),
1681 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001682 return false;
1683 }
1684
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001685 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1686
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001687 QualType FieldBaseElementType =
1688 SemaRef.Context.getBaseElementType(Field->getType());
1689
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001690 if (FieldBaseElementType->isRecordType()) {
1691 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001692 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001693 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001694
1695 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001696 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00001697 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00001698 if (MemberInit.isInvalid())
1699 return true;
1700
1701 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001702 if (MemberInit.isInvalid())
1703 return true;
1704
1705 CXXMemberInit =
1706 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001707 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001708 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001709 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001710 return false;
1711 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001712
1713 if (FieldBaseElementType->isReferenceType()) {
1714 SemaRef.Diag(Constructor->getLocation(),
1715 diag::err_uninitialized_member_in_ctor)
1716 << (int)Constructor->isImplicit()
1717 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1718 << 0 << Field->getDeclName();
1719 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1720 return true;
1721 }
1722
1723 if (FieldBaseElementType.isConstQualified()) {
1724 SemaRef.Diag(Constructor->getLocation(),
1725 diag::err_uninitialized_member_in_ctor)
1726 << (int)Constructor->isImplicit()
1727 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1728 << 1 << Field->getDeclName();
1729 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1730 return true;
1731 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001732
1733 // Nothing to initialize.
1734 CXXMemberInit = 0;
1735 return false;
1736}
John McCallf1860e52010-05-20 23:23:51 +00001737
1738namespace {
1739struct BaseAndFieldInfo {
1740 Sema &S;
1741 CXXConstructorDecl *Ctor;
1742 bool AnyErrorsInInits;
1743 ImplicitInitializerKind IIK;
1744 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1745 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1746
1747 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1748 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1749 // FIXME: Handle implicit move constructors.
1750 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1751 IIK = IIK_Copy;
1752 else
1753 IIK = IIK_Default;
1754 }
1755};
1756}
1757
Chandler Carruthe861c602010-06-30 02:59:29 +00001758static void RecordFieldInitializer(BaseAndFieldInfo &Info,
1759 FieldDecl *Top, FieldDecl *Field,
1760 CXXBaseOrMemberInitializer *Init) {
1761 // If the member doesn't need to be initialized, Init will still be null.
1762 if (!Init)
1763 return;
1764
1765 Info.AllToInit.push_back(Init);
1766 if (Field != Top) {
1767 Init->setMember(Top);
1768 Init->setAnonUnionMember(Field);
1769 }
1770}
1771
John McCallf1860e52010-05-20 23:23:51 +00001772static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1773 FieldDecl *Top, FieldDecl *Field) {
1774
Chandler Carruthe861c602010-06-30 02:59:29 +00001775 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallf1860e52010-05-20 23:23:51 +00001776 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Chandler Carruthe861c602010-06-30 02:59:29 +00001777 RecordFieldInitializer(Info, Top, Field, Init);
John McCallf1860e52010-05-20 23:23:51 +00001778 return false;
1779 }
1780
1781 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1782 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1783 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00001784 CXXRecordDecl *FieldClassDecl
1785 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00001786
1787 // Even though union members never have non-trivial default
1788 // constructions in C++03, we still build member initializers for aggregate
1789 // record types which can be union members, and C++0x allows non-trivial
1790 // default constructors for union members, so we ensure that only one
1791 // member is initialized for these.
1792 if (FieldClassDecl->isUnion()) {
1793 // First check for an explicit initializer for one field.
1794 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1795 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1796 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
1797 RecordFieldInitializer(Info, Top, *FA, Init);
1798
1799 // Once we've initialized a field of an anonymous union, the union
1800 // field in the class is also initialized, so exit immediately.
1801 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00001802 } else if ((*FA)->isAnonymousStructOrUnion()) {
1803 if (CollectFieldInitializer(Info, Top, *FA))
1804 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00001805 }
1806 }
1807
1808 // Fallthrough and construct a default initializer for the union as
1809 // a whole, which can call its default constructor if such a thing exists
1810 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1811 // behavior going forward with C++0x, when anonymous unions there are
1812 // finalized, we should revisit this.
1813 } else {
1814 // For structs, we simply descend through to initialize all members where
1815 // necessary.
1816 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1817 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1818 if (CollectFieldInitializer(Info, Top, *FA))
1819 return true;
1820 }
1821 }
John McCallf1860e52010-05-20 23:23:51 +00001822 }
1823
1824 // Don't try to build an implicit initializer if there were semantic
1825 // errors in any of the initializers (and therefore we might be
1826 // missing some that the user actually wrote).
1827 if (Info.AnyErrorsInInits)
1828 return false;
1829
1830 CXXBaseOrMemberInitializer *Init = 0;
1831 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1832 return true;
John McCallf1860e52010-05-20 23:23:51 +00001833
Chandler Carruthe861c602010-06-30 02:59:29 +00001834 RecordFieldInitializer(Info, Top, Field, Init);
John McCallf1860e52010-05-20 23:23:51 +00001835 return false;
1836}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001837
Eli Friedman80c30da2009-11-09 19:20:36 +00001838bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001839Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001840 CXXBaseOrMemberInitializer **Initializers,
1841 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001842 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001843 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001844 // Just store the initializers as written, they will be checked during
1845 // instantiation.
1846 if (NumInitializers > 0) {
1847 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1848 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1849 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1850 memcpy(baseOrMemberInitializers, Initializers,
1851 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1852 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1853 }
1854
1855 return false;
1856 }
1857
John McCallf1860e52010-05-20 23:23:51 +00001858 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001859
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001860 // We need to build the initializer AST according to order of construction
1861 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00001862 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00001863 if (!ClassDecl)
1864 return true;
1865
Eli Friedman80c30da2009-11-09 19:20:36 +00001866 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001868 for (unsigned i = 0; i < NumInitializers; i++) {
1869 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001870
1871 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00001872 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001873 else
John McCallf1860e52010-05-20 23:23:51 +00001874 Info.AllBaseFields[Member->getMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001875 }
1876
Anders Carlsson711f34a2010-04-21 19:52:01 +00001877 // Keep track of the direct virtual bases.
1878 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1879 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1880 E = ClassDecl->bases_end(); I != E; ++I) {
1881 if (I->isVirtual())
1882 DirectVBases.insert(I);
1883 }
1884
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001885 // Push virtual bases before others.
1886 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1887 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1888
1889 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001890 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1891 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001892 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00001893 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlssondefefd22010-04-23 02:00:02 +00001894 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001895 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001896 VBase, IsInheritedVirtualBase,
1897 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001898 HadError = true;
1899 continue;
1900 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001901
John McCallf1860e52010-05-20 23:23:51 +00001902 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001903 }
1904 }
Mike Stump1eb44332009-09-09 15:08:12 +00001905
John McCallf1860e52010-05-20 23:23:51 +00001906 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001907 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1908 E = ClassDecl->bases_end(); Base != E; ++Base) {
1909 // Virtuals are in the virtual base list and already constructed.
1910 if (Base->isVirtual())
1911 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001912
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001913 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001914 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1915 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001916 } else if (!AnyErrors) {
Anders Carlssondefefd22010-04-23 02:00:02 +00001917 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001918 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001919 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00001920 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001921 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001922 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001923 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001924
John McCallf1860e52010-05-20 23:23:51 +00001925 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001926 }
1927 }
Mike Stump1eb44332009-09-09 15:08:12 +00001928
John McCallf1860e52010-05-20 23:23:51 +00001929 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001930 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001931 E = ClassDecl->field_end(); Field != E; ++Field) {
1932 if ((*Field)->getType()->isIncompleteArrayType()) {
1933 assert(ClassDecl->hasFlexibleArrayMember() &&
1934 "Incomplete array type is not valid");
1935 continue;
1936 }
John McCallf1860e52010-05-20 23:23:51 +00001937 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001938 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001939 }
Mike Stump1eb44332009-09-09 15:08:12 +00001940
John McCallf1860e52010-05-20 23:23:51 +00001941 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001942 if (NumInitializers > 0) {
1943 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1944 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1945 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00001946 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCallef027fe2010-03-16 21:39:52 +00001947 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001948 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00001949
John McCallef027fe2010-03-16 21:39:52 +00001950 // Constructors implicitly reference the base and member
1951 // destructors.
1952 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1953 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001954 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001955
1956 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001957}
1958
Eli Friedman6347f422009-07-21 19:28:10 +00001959static void *GetKeyForTopLevelField(FieldDecl *Field) {
1960 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001961 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001962 if (RT->getDecl()->isAnonymousStructOrUnion())
1963 return static_cast<void *>(RT->getDecl());
1964 }
1965 return static_cast<void *>(Field);
1966}
1967
Anders Carlssonea356fb2010-04-02 05:42:15 +00001968static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1969 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001970}
1971
Anders Carlssonea356fb2010-04-02 05:42:15 +00001972static void *GetKeyForMember(ASTContext &Context,
1973 CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001974 bool MemberMaybeAnon = false) {
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001975 if (!Member->isMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00001976 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001977
Eli Friedman6347f422009-07-21 19:28:10 +00001978 // For fields injected into the class via declaration of an anonymous union,
1979 // use its anonymous union class declaration as the unique key.
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001980 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001982 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1983 // data member of the class. Data member used in the initializer list is
1984 // in AnonUnionMember field.
1985 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1986 Field = Member->getAnonUnionMember();
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001987
John McCall3c3ccdb2010-04-10 09:28:51 +00001988 // If the field is a member of an anonymous struct or union, our key
1989 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001990 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00001991 if (RD->isAnonymousStructOrUnion()) {
1992 while (true) {
1993 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1994 if (Parent->isAnonymousStructOrUnion())
1995 RD = Parent;
1996 else
1997 break;
1998 }
1999
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002000 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002001 }
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002003 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002004}
2005
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002006static void
2007DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002008 const CXXConstructorDecl *Constructor,
John McCalld6ca8da2010-04-10 07:37:23 +00002009 CXXBaseOrMemberInitializer **Inits,
2010 unsigned NumInits) {
2011 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002012 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002013
John McCalld6ca8da2010-04-10 07:37:23 +00002014 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
2015 == Diagnostic::Ignored)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002016 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002017
John McCalld6ca8da2010-04-10 07:37:23 +00002018 // Build the list of bases and members in the order that they'll
2019 // actually be initialized. The explicit initializers should be in
2020 // this same order but may be missing things.
2021 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Anders Carlsson071d6102010-04-02 03:38:04 +00002023 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2024
John McCalld6ca8da2010-04-10 07:37:23 +00002025 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002026 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002027 ClassDecl->vbases_begin(),
2028 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002029 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002030
John McCalld6ca8da2010-04-10 07:37:23 +00002031 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002032 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002033 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002034 if (Base->isVirtual())
2035 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002036 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002037 }
Mike Stump1eb44332009-09-09 15:08:12 +00002038
John McCalld6ca8da2010-04-10 07:37:23 +00002039 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002040 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2041 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002042 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002043
John McCalld6ca8da2010-04-10 07:37:23 +00002044 unsigned NumIdealInits = IdealInitKeys.size();
2045 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002046
John McCalld6ca8da2010-04-10 07:37:23 +00002047 CXXBaseOrMemberInitializer *PrevInit = 0;
2048 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2049 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2050 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
2051
2052 // Scan forward to try to find this initializer in the idealized
2053 // initializers list.
2054 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2055 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002056 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002057
2058 // If we didn't find this initializer, it must be because we
2059 // scanned past it on a previous iteration. That can only
2060 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002061 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002062 Sema::SemaDiagnosticBuilder D =
2063 SemaRef.Diag(PrevInit->getSourceLocation(),
2064 diag::warn_initializer_out_of_order);
2065
2066 if (PrevInit->isMemberInitializer())
2067 D << 0 << PrevInit->getMember()->getDeclName();
2068 else
2069 D << 1 << PrevInit->getBaseClassInfo()->getType();
2070
2071 if (Init->isMemberInitializer())
2072 D << 0 << Init->getMember()->getDeclName();
2073 else
2074 D << 1 << Init->getBaseClassInfo()->getType();
2075
2076 // Move back to the initializer's location in the ideal list.
2077 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2078 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002079 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002080
2081 assert(IdealIndex != NumIdealInits &&
2082 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002083 }
John McCalld6ca8da2010-04-10 07:37:23 +00002084
2085 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002086 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002087}
2088
John McCall3c3ccdb2010-04-10 09:28:51 +00002089namespace {
2090bool CheckRedundantInit(Sema &S,
2091 CXXBaseOrMemberInitializer *Init,
2092 CXXBaseOrMemberInitializer *&PrevInit) {
2093 if (!PrevInit) {
2094 PrevInit = Init;
2095 return false;
2096 }
2097
2098 if (FieldDecl *Field = Init->getMember())
2099 S.Diag(Init->getSourceLocation(),
2100 diag::err_multiple_mem_initialization)
2101 << Field->getDeclName()
2102 << Init->getSourceRange();
2103 else {
2104 Type *BaseClass = Init->getBaseClass();
2105 assert(BaseClass && "neither field nor base");
2106 S.Diag(Init->getSourceLocation(),
2107 diag::err_multiple_base_initialization)
2108 << QualType(BaseClass, 0)
2109 << Init->getSourceRange();
2110 }
2111 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2112 << 0 << PrevInit->getSourceRange();
2113
2114 return true;
2115}
2116
2117typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2118typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2119
2120bool CheckRedundantUnionInit(Sema &S,
2121 CXXBaseOrMemberInitializer *Init,
2122 RedundantUnionMap &Unions) {
2123 FieldDecl *Field = Init->getMember();
2124 RecordDecl *Parent = Field->getParent();
2125 if (!Parent->isAnonymousStructOrUnion())
2126 return false;
2127
2128 NamedDecl *Child = Field;
2129 do {
2130 if (Parent->isUnion()) {
2131 UnionEntry &En = Unions[Parent];
2132 if (En.first && En.first != Child) {
2133 S.Diag(Init->getSourceLocation(),
2134 diag::err_multiple_mem_union_initialization)
2135 << Field->getDeclName()
2136 << Init->getSourceRange();
2137 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2138 << 0 << En.second->getSourceRange();
2139 return true;
2140 } else if (!En.first) {
2141 En.first = Child;
2142 En.second = Init;
2143 }
2144 }
2145
2146 Child = Parent;
2147 Parent = cast<RecordDecl>(Parent->getDeclContext());
2148 } while (Parent->isAnonymousStructOrUnion());
2149
2150 return false;
2151}
2152}
2153
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002154/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002155void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002156 SourceLocation ColonLoc,
2157 MemInitTy **meminits, unsigned NumMemInits,
2158 bool AnyErrors) {
2159 if (!ConstructorDecl)
2160 return;
2161
2162 AdjustDeclIfTemplate(ConstructorDecl);
2163
2164 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002165 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002166
2167 if (!Constructor) {
2168 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2169 return;
2170 }
2171
2172 CXXBaseOrMemberInitializer **MemInits =
2173 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002174
2175 // Mapping for the duplicate initializers check.
2176 // For member initializers, this is keyed with a FieldDecl*.
2177 // For base initializers, this is keyed with a Type*.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002178 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002179
2180 // Mapping for the inconsistent anonymous-union initializers check.
2181 RedundantUnionMap MemberUnions;
2182
Anders Carlssonea356fb2010-04-02 05:42:15 +00002183 bool HadError = false;
2184 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002185 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002186
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002187 // Set the source order index.
2188 Init->setSourceOrder(i);
2189
John McCall3c3ccdb2010-04-10 09:28:51 +00002190 if (Init->isMemberInitializer()) {
2191 FieldDecl *Field = Init->getMember();
2192 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2193 CheckRedundantUnionInit(*this, Init, MemberUnions))
2194 HadError = true;
2195 } else {
2196 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2197 if (CheckRedundantInit(*this, Init, Members[Key]))
2198 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002199 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002200 }
2201
Anders Carlssonea356fb2010-04-02 05:42:15 +00002202 if (HadError)
2203 return;
2204
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002205 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002206
2207 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002208}
2209
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002210void
John McCallef027fe2010-03-16 21:39:52 +00002211Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2212 CXXRecordDecl *ClassDecl) {
2213 // Ignore dependent contexts.
2214 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002215 return;
John McCall58e6f342010-03-16 05:22:47 +00002216
2217 // FIXME: all the access-control diagnostics are positioned on the
2218 // field/base declaration. That's probably good; that said, the
2219 // user might reasonably want to know why the destructor is being
2220 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002221
Anders Carlsson9f853df2009-11-17 04:44:12 +00002222 // Non-static data members.
2223 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2224 E = ClassDecl->field_end(); I != E; ++I) {
2225 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002226 if (Field->isInvalidDecl())
2227 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002228 QualType FieldType = Context.getBaseElementType(Field->getType());
2229
2230 const RecordType* RT = FieldType->getAs<RecordType>();
2231 if (!RT)
2232 continue;
2233
2234 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2235 if (FieldClassDecl->hasTrivialDestructor())
2236 continue;
2237
Douglas Gregordb89f282010-07-01 22:47:18 +00002238 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002239 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002240 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002241 << Field->getDeclName()
2242 << FieldType);
2243
John McCallef027fe2010-03-16 21:39:52 +00002244 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002245 }
2246
John McCall58e6f342010-03-16 05:22:47 +00002247 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2248
Anders Carlsson9f853df2009-11-17 04:44:12 +00002249 // Bases.
2250 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2251 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002252 // Bases are always records in a well-formed non-dependent class.
2253 const RecordType *RT = Base->getType()->getAs<RecordType>();
2254
2255 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002256 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002257 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002258
2259 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002260 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002261 if (BaseClassDecl->hasTrivialDestructor())
2262 continue;
John McCall58e6f342010-03-16 05:22:47 +00002263
Douglas Gregordb89f282010-07-01 22:47:18 +00002264 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002265
2266 // FIXME: caret should be on the start of the class name
2267 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002268 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002269 << Base->getType()
2270 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002271
John McCallef027fe2010-03-16 21:39:52 +00002272 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002273 }
2274
2275 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002276 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2277 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002278
2279 // Bases are always records in a well-formed non-dependent class.
2280 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2281
2282 // Ignore direct virtual bases.
2283 if (DirectVirtualBases.count(RT))
2284 continue;
2285
Anders Carlsson9f853df2009-11-17 04:44:12 +00002286 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002287 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002288 if (BaseClassDecl->hasTrivialDestructor())
2289 continue;
John McCall58e6f342010-03-16 05:22:47 +00002290
Douglas Gregordb89f282010-07-01 22:47:18 +00002291 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002292 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002293 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002294 << VBase->getType());
2295
John McCallef027fe2010-03-16 21:39:52 +00002296 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002297 }
2298}
2299
John McCalld226f652010-08-21 09:40:31 +00002300void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002301 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002302 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002303
Mike Stump1eb44332009-09-09 15:08:12 +00002304 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002305 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlssonec3332b2010-04-02 03:43:34 +00002306 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002307}
2308
Mike Stump1eb44332009-09-09 15:08:12 +00002309bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002310 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002311 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002312 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002313 else
John McCall94c3b562010-08-18 09:41:07 +00002314 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002315}
2316
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002317bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002318 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002319 if (!getLangOptions().CPlusPlus)
2320 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002321
Anders Carlsson11f21a02009-03-23 19:10:31 +00002322 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002323 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002324
Ted Kremenek6217b802009-07-29 21:53:49 +00002325 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002326 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002327 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002328 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002329
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002330 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002331 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002332 }
Mike Stump1eb44332009-09-09 15:08:12 +00002333
Ted Kremenek6217b802009-07-29 21:53:49 +00002334 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002335 if (!RT)
2336 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002337
John McCall86ff3082010-02-04 22:26:26 +00002338 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002339
John McCall94c3b562010-08-18 09:41:07 +00002340 // We can't answer whether something is abstract until it has a
2341 // definition. If it's currently being defined, we'll walk back
2342 // over all the declarations when we have a full definition.
2343 const CXXRecordDecl *Def = RD->getDefinition();
2344 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002345 return false;
2346
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002347 if (!RD->isAbstract())
2348 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002349
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002350 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002351 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002352
John McCall94c3b562010-08-18 09:41:07 +00002353 return true;
2354}
2355
2356void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2357 // Check if we've already emitted the list of pure virtual functions
2358 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002359 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002360 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002361
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002362 CXXFinalOverriderMap FinalOverriders;
2363 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002364
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002365 // Keep a set of seen pure methods so we won't diagnose the same method
2366 // more than once.
2367 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2368
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002369 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2370 MEnd = FinalOverriders.end();
2371 M != MEnd;
2372 ++M) {
2373 for (OverridingMethods::iterator SO = M->second.begin(),
2374 SOEnd = M->second.end();
2375 SO != SOEnd; ++SO) {
2376 // C++ [class.abstract]p4:
2377 // A class is abstract if it contains or inherits at least one
2378 // pure virtual function for which the final overrider is pure
2379 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002381 //
2382 if (SO->second.size() != 1)
2383 continue;
2384
2385 if (!SO->second.front().Method->isPure())
2386 continue;
2387
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002388 if (!SeenPureMethods.insert(SO->second.front().Method))
2389 continue;
2390
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002391 Diag(SO->second.front().Method->getLocation(),
2392 diag::note_pure_virtual_function)
2393 << SO->second.front().Method->getDeclName();
2394 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002395 }
2396
2397 if (!PureVirtualClassDiagSet)
2398 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2399 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002400}
2401
Anders Carlsson8211eff2009-03-24 01:19:16 +00002402namespace {
John McCall94c3b562010-08-18 09:41:07 +00002403struct AbstractUsageInfo {
2404 Sema &S;
2405 CXXRecordDecl *Record;
2406 CanQualType AbstractType;
2407 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002408
John McCall94c3b562010-08-18 09:41:07 +00002409 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2410 : S(S), Record(Record),
2411 AbstractType(S.Context.getCanonicalType(
2412 S.Context.getTypeDeclType(Record))),
2413 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002414
John McCall94c3b562010-08-18 09:41:07 +00002415 void DiagnoseAbstractType() {
2416 if (Invalid) return;
2417 S.DiagnoseAbstractType(Record);
2418 Invalid = true;
2419 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002420
John McCall94c3b562010-08-18 09:41:07 +00002421 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2422};
2423
2424struct CheckAbstractUsage {
2425 AbstractUsageInfo &Info;
2426 const NamedDecl *Ctx;
2427
2428 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2429 : Info(Info), Ctx(Ctx) {}
2430
2431 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2432 switch (TL.getTypeLocClass()) {
2433#define ABSTRACT_TYPELOC(CLASS, PARENT)
2434#define TYPELOC(CLASS, PARENT) \
2435 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2436#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002437 }
John McCall94c3b562010-08-18 09:41:07 +00002438 }
Mike Stump1eb44332009-09-09 15:08:12 +00002439
John McCall94c3b562010-08-18 09:41:07 +00002440 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2441 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2442 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2443 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2444 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002445 }
John McCall94c3b562010-08-18 09:41:07 +00002446 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002447
John McCall94c3b562010-08-18 09:41:07 +00002448 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2449 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2450 }
Mike Stump1eb44332009-09-09 15:08:12 +00002451
John McCall94c3b562010-08-18 09:41:07 +00002452 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2453 // Visit the type parameters from a permissive context.
2454 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2455 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2456 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2457 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2458 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2459 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002460 }
John McCall94c3b562010-08-18 09:41:07 +00002461 }
Mike Stump1eb44332009-09-09 15:08:12 +00002462
John McCall94c3b562010-08-18 09:41:07 +00002463 // Visit pointee types from a permissive context.
2464#define CheckPolymorphic(Type) \
2465 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2466 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2467 }
2468 CheckPolymorphic(PointerTypeLoc)
2469 CheckPolymorphic(ReferenceTypeLoc)
2470 CheckPolymorphic(MemberPointerTypeLoc)
2471 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002472
John McCall94c3b562010-08-18 09:41:07 +00002473 /// Handle all the types we haven't given a more specific
2474 /// implementation for above.
2475 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2476 // Every other kind of type that we haven't called out already
2477 // that has an inner type is either (1) sugar or (2) contains that
2478 // inner type in some way as a subobject.
2479 if (TypeLoc Next = TL.getNextTypeLoc())
2480 return Visit(Next, Sel);
2481
2482 // If there's no inner type and we're in a permissive context,
2483 // don't diagnose.
2484 if (Sel == Sema::AbstractNone) return;
2485
2486 // Check whether the type matches the abstract type.
2487 QualType T = TL.getType();
2488 if (T->isArrayType()) {
2489 Sel = Sema::AbstractArrayType;
2490 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002491 }
John McCall94c3b562010-08-18 09:41:07 +00002492 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2493 if (CT != Info.AbstractType) return;
2494
2495 // It matched; do some magic.
2496 if (Sel == Sema::AbstractArrayType) {
2497 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2498 << T << TL.getSourceRange();
2499 } else {
2500 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2501 << Sel << T << TL.getSourceRange();
2502 }
2503 Info.DiagnoseAbstractType();
2504 }
2505};
2506
2507void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2508 Sema::AbstractDiagSelID Sel) {
2509 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2510}
2511
2512}
2513
2514/// Check for invalid uses of an abstract type in a method declaration.
2515static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2516 CXXMethodDecl *MD) {
2517 // No need to do the check on definitions, which require that
2518 // the return/param types be complete.
2519 if (MD->isThisDeclarationADefinition())
2520 return;
2521
2522 // For safety's sake, just ignore it if we don't have type source
2523 // information. This should never happen for non-implicit methods,
2524 // but...
2525 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2526 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2527}
2528
2529/// Check for invalid uses of an abstract type within a class definition.
2530static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2531 CXXRecordDecl *RD) {
2532 for (CXXRecordDecl::decl_iterator
2533 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2534 Decl *D = *I;
2535 if (D->isImplicit()) continue;
2536
2537 // Methods and method templates.
2538 if (isa<CXXMethodDecl>(D)) {
2539 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2540 } else if (isa<FunctionTemplateDecl>(D)) {
2541 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2542 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2543
2544 // Fields and static variables.
2545 } else if (isa<FieldDecl>(D)) {
2546 FieldDecl *FD = cast<FieldDecl>(D);
2547 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2548 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2549 } else if (isa<VarDecl>(D)) {
2550 VarDecl *VD = cast<VarDecl>(D);
2551 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2552 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2553
2554 // Nested classes and class templates.
2555 } else if (isa<CXXRecordDecl>(D)) {
2556 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2557 } else if (isa<ClassTemplateDecl>(D)) {
2558 CheckAbstractClassUsage(Info,
2559 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2560 }
2561 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002562}
2563
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002564/// \brief Perform semantic checks on a class definition that has been
2565/// completing, introducing implicitly-declared members, checking for
2566/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002567void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002568 if (!Record || Record->isInvalidDecl())
2569 return;
2570
Eli Friedmanff2d8782009-12-16 20:00:27 +00002571 if (!Record->isDependentType())
Douglas Gregor23c94db2010-07-02 17:43:08 +00002572 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002573
Eli Friedmanff2d8782009-12-16 20:00:27 +00002574 if (Record->isInvalidDecl())
2575 return;
2576
John McCall233a6412010-01-28 07:38:46 +00002577 // Set access bits correctly on the directly-declared conversions.
2578 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2579 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2580 Convs->setAccess(I, (*I)->getAccess());
2581
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002582 // Determine whether we need to check for final overriders. We do
2583 // this either when there are virtual base classes (in which case we
2584 // may end up finding multiple final overriders for a given virtual
2585 // function) or any of the base classes is abstract (in which case
2586 // we might detect that this class is abstract).
2587 bool CheckFinalOverriders = false;
2588 if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2589 !Record->isDependentType()) {
2590 if (Record->getNumVBases())
2591 CheckFinalOverriders = true;
2592 else if (!Record->isAbstract()) {
2593 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2594 BEnd = Record->bases_end();
2595 B != BEnd; ++B) {
2596 CXXRecordDecl *BaseDecl
2597 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2598 if (BaseDecl->isAbstract()) {
2599 CheckFinalOverriders = true;
2600 break;
2601 }
2602 }
2603 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002604 }
2605
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002606 if (CheckFinalOverriders) {
2607 CXXFinalOverriderMap FinalOverriders;
2608 Record->getFinalOverriders(FinalOverriders);
2609
2610 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2611 MEnd = FinalOverriders.end();
2612 M != MEnd; ++M) {
2613 for (OverridingMethods::iterator SO = M->second.begin(),
2614 SOEnd = M->second.end();
2615 SO != SOEnd; ++SO) {
2616 assert(SO->second.size() > 0 &&
2617 "All virtual functions have overridding virtual functions");
2618 if (SO->second.size() == 1) {
2619 // C++ [class.abstract]p4:
2620 // A class is abstract if it contains or inherits at least one
2621 // pure virtual function for which the final overrider is pure
2622 // virtual.
2623 if (SO->second.front().Method->isPure())
2624 Record->setAbstract(true);
2625 continue;
2626 }
2627
2628 // C++ [class.virtual]p2:
2629 // In a derived class, if a virtual member function of a base
2630 // class subobject has more than one final overrider the
2631 // program is ill-formed.
2632 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2633 << (NamedDecl *)M->first << Record;
2634 Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2635 for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2636 OMEnd = SO->second.end();
2637 OM != OMEnd; ++OM)
2638 Diag(OM->Method->getLocation(), diag::note_final_overrider)
2639 << (NamedDecl *)M->first << OM->Method->getParent();
2640
2641 Record->setInvalidDecl();
2642 }
2643 }
2644 }
2645
John McCall94c3b562010-08-18 09:41:07 +00002646 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2647 AbstractUsageInfo Info(*this, Record);
2648 CheckAbstractClassUsage(Info, Record);
2649 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002650
2651 // If this is not an aggregate type and has no user-declared constructor,
2652 // complain about any non-static data members of reference or const scalar
2653 // type, since they will never get initializers.
2654 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2655 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2656 bool Complained = false;
2657 for (RecordDecl::field_iterator F = Record->field_begin(),
2658 FEnd = Record->field_end();
2659 F != FEnd; ++F) {
2660 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002661 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002662 if (!Complained) {
2663 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2664 << Record->getTagKind() << Record;
2665 Complained = true;
2666 }
2667
2668 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2669 << F->getType()->isReferenceType()
2670 << F->getDeclName();
2671 }
2672 }
2673 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002674
2675 if (Record->isDynamicClass())
2676 DynamicClasses.push_back(Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002677}
2678
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002679void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00002680 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002681 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002682 SourceLocation RBrac,
2683 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002684 if (!TagDecl)
2685 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002686
Douglas Gregor42af25f2009-05-11 19:58:34 +00002687 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002688
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002689 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00002690 // strict aliasing violation!
2691 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002692 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002693
Douglas Gregor23c94db2010-07-02 17:43:08 +00002694 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00002695 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002696}
2697
Douglas Gregord92ec472010-07-01 05:10:53 +00002698namespace {
2699 /// \brief Helper class that collects exception specifications for
2700 /// implicitly-declared special member functions.
2701 class ImplicitExceptionSpecification {
2702 ASTContext &Context;
2703 bool AllowsAllExceptions;
2704 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2705 llvm::SmallVector<QualType, 4> Exceptions;
2706
2707 public:
2708 explicit ImplicitExceptionSpecification(ASTContext &Context)
2709 : Context(Context), AllowsAllExceptions(false) { }
2710
2711 /// \brief Whether the special member function should have any
2712 /// exception specification at all.
2713 bool hasExceptionSpecification() const {
2714 return !AllowsAllExceptions;
2715 }
2716
2717 /// \brief Whether the special member function should have a
2718 /// throw(...) exception specification (a Microsoft extension).
2719 bool hasAnyExceptionSpecification() const {
2720 return false;
2721 }
2722
2723 /// \brief The number of exceptions in the exception specification.
2724 unsigned size() const { return Exceptions.size(); }
2725
2726 /// \brief The set of exceptions in the exception specification.
2727 const QualType *data() const { return Exceptions.data(); }
2728
2729 /// \brief Note that
2730 void CalledDecl(CXXMethodDecl *Method) {
2731 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor4681ca82010-07-01 15:29:53 +00002732 if (AllowsAllExceptions || !Method)
Douglas Gregord92ec472010-07-01 05:10:53 +00002733 return;
2734
2735 const FunctionProtoType *Proto
2736 = Method->getType()->getAs<FunctionProtoType>();
2737
2738 // If this function can throw any exceptions, make a note of that.
2739 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2740 AllowsAllExceptions = true;
2741 ExceptionsSeen.clear();
2742 Exceptions.clear();
2743 return;
2744 }
2745
2746 // Record the exceptions in this function's exception specification.
2747 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2748 EEnd = Proto->exception_end();
2749 E != EEnd; ++E)
2750 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2751 Exceptions.push_back(*E);
2752 }
2753 };
2754}
2755
2756
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002757/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2758/// special functions, such as the default constructor, copy
2759/// constructor, or destructor, to the given C++ class (C++
2760/// [special]p1). This routine can only be executed just before the
2761/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002762void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00002763 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002764 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002765
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00002766 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00002767 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002768
Douglas Gregora376d102010-07-02 21:50:04 +00002769 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2770 ++ASTContext::NumImplicitCopyAssignmentOperators;
2771
2772 // If we have a dynamic class, then the copy assignment operator may be
2773 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2774 // it shows up in the right place in the vtable and that we diagnose
2775 // problems with the implicit exception specification.
2776 if (ClassDecl->isDynamicClass())
2777 DeclareImplicitCopyAssignment(ClassDecl);
2778 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002779
Douglas Gregor4923aa22010-07-02 20:37:36 +00002780 if (!ClassDecl->hasUserDeclaredDestructor()) {
2781 ++ASTContext::NumImplicitDestructors;
2782
2783 // If we have a dynamic class, then the destructor may be virtual, so we
2784 // have to declare the destructor immediately. This ensures that, e.g., it
2785 // shows up in the right place in the vtable and that we diagnose problems
2786 // with the implicit exception specification.
2787 if (ClassDecl->isDynamicClass())
2788 DeclareImplicitDestructor(ClassDecl);
2789 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002790}
2791
John McCalld226f652010-08-21 09:40:31 +00002792void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002793 if (!D)
2794 return;
2795
2796 TemplateParameterList *Params = 0;
2797 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2798 Params = Template->getTemplateParameters();
2799 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2800 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2801 Params = PartialSpec->getTemplateParameters();
2802 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002803 return;
2804
Douglas Gregor6569d682009-05-27 23:11:45 +00002805 for (TemplateParameterList::iterator Param = Params->begin(),
2806 ParamEnd = Params->end();
2807 Param != ParamEnd; ++Param) {
2808 NamedDecl *Named = cast<NamedDecl>(*Param);
2809 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00002810 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00002811 IdResolver.AddDecl(Named);
2812 }
2813 }
2814}
2815
John McCalld226f652010-08-21 09:40:31 +00002816void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002817 if (!RecordD) return;
2818 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00002819 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00002820 PushDeclContext(S, Record);
2821}
2822
John McCalld226f652010-08-21 09:40:31 +00002823void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002824 if (!RecordD) return;
2825 PopDeclContext();
2826}
2827
Douglas Gregor72b505b2008-12-16 21:30:33 +00002828/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2829/// parsing a top-level (non-nested) C++ class, and we are now
2830/// parsing those parts of the given Method declaration that could
2831/// not be parsed earlier (C++ [class.mem]p2), such as default
2832/// arguments. This action should enter the scope of the given
2833/// Method declaration as if we had just parsed the qualified method
2834/// name. However, it should not bring the parameters into scope;
2835/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00002836void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002837}
2838
2839/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2840/// C++ method declaration. We're (re-)introducing the given
2841/// function parameter into scope for use in parsing later parts of
2842/// the method declaration. For example, we could see an
2843/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00002844void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002845 if (!ParamD)
2846 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002847
John McCalld226f652010-08-21 09:40:31 +00002848 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00002849
2850 // If this parameter has an unparsed default argument, clear it out
2851 // to make way for the parsed default argument.
2852 if (Param->hasUnparsedDefaultArg())
2853 Param->setDefaultArg(0);
2854
John McCalld226f652010-08-21 09:40:31 +00002855 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002856 if (Param->getDeclName())
2857 IdResolver.AddDecl(Param);
2858}
2859
2860/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2861/// processing the delayed method declaration for Method. The method
2862/// declaration is now considered finished. There may be a separate
2863/// ActOnStartOfFunctionDef action later (not necessarily
2864/// immediately!) for this method, if it was also defined inside the
2865/// class body.
John McCalld226f652010-08-21 09:40:31 +00002866void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002867 if (!MethodD)
2868 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002869
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002870 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002871
John McCalld226f652010-08-21 09:40:31 +00002872 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002873
2874 // Now that we have our default arguments, check the constructor
2875 // again. It could produce additional diagnostics or affect whether
2876 // the class has implicitly-declared destructors, among other
2877 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002878 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2879 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002880
2881 // Check the default arguments, which we may have added.
2882 if (!Method->isInvalidDecl())
2883 CheckCXXDefaultArguments(Method);
2884}
2885
Douglas Gregor42a552f2008-11-05 20:51:48 +00002886/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002887/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002888/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002889/// emit diagnostics and set the invalid bit to true. In any case, the type
2890/// will be updated to reflect a well-formed type for the constructor and
2891/// returned.
2892QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00002893 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002894 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002895
2896 // C++ [class.ctor]p3:
2897 // A constructor shall not be virtual (10.3) or static (9.4). A
2898 // constructor can be invoked for a const, volatile or const
2899 // volatile object. A constructor shall not be declared const,
2900 // volatile, or const volatile (9.3.2).
2901 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002902 if (!D.isInvalidType())
2903 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2904 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2905 << SourceRange(D.getIdentifierLoc());
2906 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002907 }
John McCalld931b082010-08-26 03:08:43 +00002908 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002909 if (!D.isInvalidType())
2910 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2911 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2912 << SourceRange(D.getIdentifierLoc());
2913 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00002914 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002915 }
Mike Stump1eb44332009-09-09 15:08:12 +00002916
Chris Lattner65401802009-04-25 08:28:21 +00002917 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2918 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002919 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002920 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2921 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002922 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002923 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2924 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002925 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002926 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2927 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002928 }
Mike Stump1eb44332009-09-09 15:08:12 +00002929
Douglas Gregor42a552f2008-11-05 20:51:48 +00002930 // Rebuild the function type "R" without any type qualifiers (in
2931 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00002932 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00002933 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002934 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2935 Proto->getNumArgs(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002936 Proto->isVariadic(), 0,
2937 Proto->hasExceptionSpec(),
2938 Proto->hasAnyExceptionSpec(),
2939 Proto->getNumExceptions(),
2940 Proto->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00002941 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002942}
2943
Douglas Gregor72b505b2008-12-16 21:30:33 +00002944/// CheckConstructor - Checks a fully-formed constructor for
2945/// well-formedness, issuing any diagnostics required. Returns true if
2946/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002947void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002948 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002949 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2950 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002951 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002952
2953 // C++ [class.copy]p3:
2954 // A declaration of a constructor for a class X is ill-formed if
2955 // its first parameter is of type (optionally cv-qualified) X and
2956 // either there are no other parameters or else all other
2957 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002958 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002959 ((Constructor->getNumParams() == 1) ||
2960 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002961 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2962 Constructor->getTemplateSpecializationKind()
2963 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002964 QualType ParamType = Constructor->getParamDecl(0)->getType();
2965 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2966 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002967 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002968 const char *ConstRef
2969 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2970 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00002971 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002972 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002973
2974 // FIXME: Rather that making the constructor invalid, we should endeavor
2975 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002976 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002977 }
2978 }
Mike Stump1eb44332009-09-09 15:08:12 +00002979
John McCall3d043362010-04-13 07:45:41 +00002980 // Notify the class that we've added a constructor. In principle we
2981 // don't need to do this for out-of-line declarations; in practice
2982 // we only instantiate the most recent declaration of a method, so
2983 // we have to call this for everything but friends.
2984 if (!Constructor->getFriendObjectKind())
2985 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002986}
2987
John McCall15442822010-08-04 01:04:25 +00002988/// CheckDestructor - Checks a fully-formed destructor definition for
2989/// well-formedness, issuing any diagnostics required. Returns true
2990/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002991bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002992 CXXRecordDecl *RD = Destructor->getParent();
2993
2994 if (Destructor->isVirtual()) {
2995 SourceLocation Loc;
2996
2997 if (!Destructor->isImplicit())
2998 Loc = Destructor->getLocation();
2999 else
3000 Loc = RD->getLocation();
3001
3002 // If we have a virtual destructor, look up the deallocation function
3003 FunctionDecl *OperatorDelete = 0;
3004 DeclarationName Name =
3005 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003006 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00003007 return true;
John McCall5efd91a2010-07-03 18:33:00 +00003008
3009 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00003010
3011 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00003012 }
Anders Carlsson37909802009-11-30 21:24:50 +00003013
3014 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00003015}
3016
Mike Stump1eb44332009-09-09 15:08:12 +00003017static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003018FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3019 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3020 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00003021 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003022}
3023
Douglas Gregor42a552f2008-11-05 20:51:48 +00003024/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3025/// the well-formednes of the destructor declarator @p D with type @p
3026/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003027/// emit diagnostics and set the declarator to invalid. Even if this happens,
3028/// will be updated to reflect a well-formed type for the destructor and
3029/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00003030QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003031 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003032 // C++ [class.dtor]p1:
3033 // [...] A typedef-name that names a class is a class-name
3034 // (7.1.3); however, a typedef-name that names a class shall not
3035 // be used as the identifier in the declarator for a destructor
3036 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003037 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregord92ec472010-07-01 05:10:53 +00003038 if (isa<TypedefType>(DeclaratorType))
Chris Lattner65401802009-04-25 08:28:21 +00003039 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003040 << DeclaratorType;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003041
3042 // C++ [class.dtor]p2:
3043 // A destructor is used to destroy objects of its class type. A
3044 // destructor takes no parameters, and no return type can be
3045 // specified for it (not even void). The address of a destructor
3046 // shall not be taken. A destructor shall not be static. A
3047 // destructor can be invoked for a const, volatile or const
3048 // volatile object. A destructor shall not be declared const,
3049 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00003050 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003051 if (!D.isInvalidType())
3052 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3053 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00003054 << SourceRange(D.getIdentifierLoc())
3055 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3056
John McCalld931b082010-08-26 03:08:43 +00003057 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003058 }
Chris Lattner65401802009-04-25 08:28:21 +00003059 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003060 // Destructors don't have return types, but the parser will
3061 // happily parse something like:
3062 //
3063 // class X {
3064 // float ~X();
3065 // };
3066 //
3067 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003068 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3069 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3070 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003071 }
Mike Stump1eb44332009-09-09 15:08:12 +00003072
Chris Lattner65401802009-04-25 08:28:21 +00003073 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3074 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003075 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003076 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3077 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003078 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003079 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3080 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003081 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003082 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3083 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003084 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003085 }
3086
3087 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003088 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003089 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3090
3091 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003092 FTI.freeArgs();
3093 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003094 }
3095
Mike Stump1eb44332009-09-09 15:08:12 +00003096 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003097 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003098 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003099 D.setInvalidType();
3100 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003101
3102 // Rebuild the function type "R" without any type qualifiers or
3103 // parameters (in case any of the errors above fired) and with
3104 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003105 // types.
3106 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3107 if (!Proto)
3108 return QualType();
3109
Douglas Gregorce056bc2010-02-21 22:15:06 +00003110 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Douglas Gregord92ec472010-07-01 05:10:53 +00003111 Proto->hasExceptionSpec(),
3112 Proto->hasAnyExceptionSpec(),
3113 Proto->getNumExceptions(),
3114 Proto->exception_begin(),
3115 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003116}
3117
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003118/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3119/// well-formednes of the conversion function declarator @p D with
3120/// type @p R. If there are any errors in the declarator, this routine
3121/// will emit diagnostics and return true. Otherwise, it will return
3122/// false. Either way, the type @p R will be updated to reflect a
3123/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003124void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003125 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003126 // C++ [class.conv.fct]p1:
3127 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003128 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003129 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003130 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003131 if (!D.isInvalidType())
3132 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3133 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3134 << SourceRange(D.getIdentifierLoc());
3135 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003136 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003137 }
John McCalla3f81372010-04-13 00:04:31 +00003138
3139 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3140
Chris Lattner6e475012009-04-25 08:35:12 +00003141 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003142 // Conversion functions don't have return types, but the parser will
3143 // happily parse something like:
3144 //
3145 // class X {
3146 // float operator bool();
3147 // };
3148 //
3149 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003150 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3151 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3152 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003153 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003154 }
3155
John McCalla3f81372010-04-13 00:04:31 +00003156 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3157
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003158 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003159 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003160 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3161
3162 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00003163 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003164 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003165 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003166 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003167 D.setInvalidType();
3168 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003169
John McCalla3f81372010-04-13 00:04:31 +00003170 // Diagnose "&operator bool()" and other such nonsense. This
3171 // is actually a gcc extension which we don't support.
3172 if (Proto->getResultType() != ConvType) {
3173 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3174 << Proto->getResultType();
3175 D.setInvalidType();
3176 ConvType = Proto->getResultType();
3177 }
3178
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003179 // C++ [class.conv.fct]p4:
3180 // The conversion-type-id shall not represent a function type nor
3181 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003182 if (ConvType->isArrayType()) {
3183 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3184 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003185 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003186 } else if (ConvType->isFunctionType()) {
3187 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3188 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003189 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003190 }
3191
3192 // Rebuild the function type "R" without any parameters (in case any
3193 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003194 // return type.
John McCalla3f81372010-04-13 00:04:31 +00003195 if (D.isInvalidType()) {
3196 R = Context.getFunctionType(ConvType, 0, 0, false,
3197 Proto->getTypeQuals(),
3198 Proto->hasExceptionSpec(),
3199 Proto->hasAnyExceptionSpec(),
3200 Proto->getNumExceptions(),
3201 Proto->exception_begin(),
3202 Proto->getExtInfo());
3203 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003204
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003205 // C++0x explicit conversion operators.
3206 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003207 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003208 diag::warn_explicit_conversion_functions)
3209 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003210}
3211
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003212/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3213/// the declaration of the given C++ conversion function. This routine
3214/// is responsible for recording the conversion function in the C++
3215/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003216Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003217 assert(Conversion && "Expected to receive a conversion function declaration");
3218
Douglas Gregor9d350972008-12-12 08:25:50 +00003219 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003220
3221 // Make sure we aren't redeclaring the conversion function.
3222 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003223
3224 // C++ [class.conv.fct]p1:
3225 // [...] A conversion function is never used to convert a
3226 // (possibly cv-qualified) object to the (possibly cv-qualified)
3227 // same object type (or a reference to it), to a (possibly
3228 // cv-qualified) base class of that type (or a reference to it),
3229 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003230 // FIXME: Suppress this warning if the conversion function ends up being a
3231 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003232 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003233 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003234 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003235 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003236 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3237 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00003238 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00003239 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003240 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3241 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003242 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003243 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003244 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003245 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003246 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003247 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003248 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003249 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003250 }
3251
Douglas Gregor48026d22010-01-11 18:40:55 +00003252 if (Conversion->getPrimaryTemplate()) {
3253 // ignore specializations
3254 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003255 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor0c551062010-01-11 18:53:25 +00003256 = Conversion->getDescribedFunctionTemplate()) {
3257 if (ClassDecl->replaceConversion(
3258 ConversionTemplate->getPreviousDeclaration(),
3259 ConversionTemplate))
John McCalld226f652010-08-21 09:40:31 +00003260 return ConversionTemplate;
Douglas Gregor0c551062010-01-11 18:53:25 +00003261 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3262 Conversion))
John McCalld226f652010-08-21 09:40:31 +00003263 return Conversion;
Douglas Gregor70316a02008-12-26 15:00:45 +00003264 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00003265 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003266 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00003267 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor48026d22010-01-11 18:40:55 +00003268 else
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00003269 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003270
John McCalld226f652010-08-21 09:40:31 +00003271 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003272}
3273
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003274//===----------------------------------------------------------------------===//
3275// Namespace Handling
3276//===----------------------------------------------------------------------===//
3277
John McCallea318642010-08-26 09:15:37 +00003278
3279
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003280/// ActOnStartNamespaceDef - This is called at the start of a namespace
3281/// definition.
John McCalld226f652010-08-21 09:40:31 +00003282Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003283 SourceLocation InlineLoc,
John McCallea318642010-08-26 09:15:37 +00003284 SourceLocation IdentLoc,
3285 IdentifierInfo *II,
3286 SourceLocation LBrace,
3287 AttributeList *AttrList) {
Douglas Gregor21e09b62010-08-19 20:55:47 +00003288 // anonymous namespace starts at its left brace
3289 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3290 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003291 Namespc->setLBracLoc(LBrace);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003292 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003293
3294 Scope *DeclRegionScope = NamespcScope->getParent();
3295
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003296 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3297
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003298 if (const VisibilityAttr *attr = Namespc->getAttr<VisibilityAttr>())
John McCallea318642010-08-26 09:15:37 +00003299 PushVisibilityAttr(attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003300
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003301 if (II) {
3302 // C++ [namespace.def]p2:
3303 // The identifier in an original-namespace-definition shall not have been
3304 // previously defined in the declarative region in which the
3305 // original-namespace-definition appears. The identifier in an
3306 // original-namespace-definition is the name of the namespace. Subsequently
3307 // in that declarative region, it is treated as an original-namespace-name.
3308
John McCallf36e02d2009-10-09 21:13:30 +00003309 NamedDecl *PrevDecl
Douglas Gregorc83c6872010-04-15 22:33:43 +00003310 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00003311 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00003312
Douglas Gregor44b43212008-12-11 16:49:14 +00003313 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3314 // This is an extended namespace definition.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003315 if (Namespc->isInline() != OrigNS->isInline()) {
3316 // inline-ness must match
3317 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3318 << Namespc->isInline();
3319 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3320 Namespc->setInvalidDecl();
3321 // Recover by ignoring the new namespace's inline status.
3322 Namespc->setInline(OrigNS->isInline());
3323 }
3324
Douglas Gregor44b43212008-12-11 16:49:14 +00003325 // Attach this namespace decl to the chain of extended namespace
3326 // definitions.
3327 OrigNS->setNextNamespace(Namespc);
3328 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003329
Mike Stump1eb44332009-09-09 15:08:12 +00003330 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003331 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003332 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003333 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003334 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003335 } else if (PrevDecl) {
3336 // This is an invalid name redefinition.
3337 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3338 << Namespc->getDeclName();
3339 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3340 Namespc->setInvalidDecl();
3341 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003342 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003343 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003344 // This is the first "real" definition of the namespace "std", so update
3345 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003346 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003347 // We had already defined a dummy namespace "std". Link this new
3348 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003349 StdNS->setNextNamespace(Namespc);
3350 StdNS->setLocation(IdentLoc);
3351 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003352 }
3353
3354 // Make our StdNamespace cache point at the first real definition of the
3355 // "std" namespace.
3356 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003357 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003358
3359 PushOnScopeChains(Namespc, DeclRegionScope);
3360 } else {
John McCall9aeed322009-10-01 00:25:31 +00003361 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003362 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003363
3364 // Link the anonymous namespace into its parent.
3365 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003366 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003367 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3368 PrevDecl = TU->getAnonymousNamespace();
3369 TU->setAnonymousNamespace(Namespc);
3370 } else {
3371 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3372 PrevDecl = ND->getAnonymousNamespace();
3373 ND->setAnonymousNamespace(Namespc);
3374 }
3375
3376 // Link the anonymous namespace with its previous declaration.
3377 if (PrevDecl) {
3378 assert(PrevDecl->isAnonymousNamespace());
3379 assert(!PrevDecl->getNextNamespace());
3380 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3381 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003382
3383 if (Namespc->isInline() != PrevDecl->isInline()) {
3384 // inline-ness must match
3385 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3386 << Namespc->isInline();
3387 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3388 Namespc->setInvalidDecl();
3389 // Recover by ignoring the new namespace's inline status.
3390 Namespc->setInline(PrevDecl->isInline());
3391 }
John McCall5fdd7642009-12-16 02:06:49 +00003392 }
John McCall9aeed322009-10-01 00:25:31 +00003393
Douglas Gregora4181472010-03-24 00:46:35 +00003394 CurContext->addDecl(Namespc);
3395
John McCall9aeed322009-10-01 00:25:31 +00003396 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3397 // behaves as if it were replaced by
3398 // namespace unique { /* empty body */ }
3399 // using namespace unique;
3400 // namespace unique { namespace-body }
3401 // where all occurrences of 'unique' in a translation unit are
3402 // replaced by the same identifier and this identifier differs
3403 // from all other identifiers in the entire program.
3404
3405 // We just create the namespace with an empty name and then add an
3406 // implicit using declaration, just like the standard suggests.
3407 //
3408 // CodeGen enforces the "universally unique" aspect by giving all
3409 // declarations semantically contained within an anonymous
3410 // namespace internal linkage.
3411
John McCall5fdd7642009-12-16 02:06:49 +00003412 if (!PrevDecl) {
3413 UsingDirectiveDecl* UD
3414 = UsingDirectiveDecl::Create(Context, CurContext,
3415 /* 'using' */ LBrace,
3416 /* 'namespace' */ SourceLocation(),
3417 /* qualifier */ SourceRange(),
3418 /* NNS */ NULL,
3419 /* identifier */ SourceLocation(),
3420 Namespc,
3421 /* Ancestor */ CurContext);
3422 UD->setImplicit();
3423 CurContext->addDecl(UD);
3424 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003425 }
3426
3427 // Although we could have an invalid decl (i.e. the namespace name is a
3428 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003429 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3430 // for the namespace has the declarations that showed up in that particular
3431 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003432 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003433 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003434}
3435
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003436/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3437/// is a namespace alias, returns the namespace it points to.
3438static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3439 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3440 return AD->getNamespace();
3441 return dyn_cast_or_null<NamespaceDecl>(D);
3442}
3443
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003444/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3445/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003446void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003447 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3448 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3449 Namespc->setRBracLoc(RBrace);
3450 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003451 if (Namespc->hasAttr<VisibilityAttr>())
3452 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003453}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003454
John McCall384aff82010-08-25 07:42:41 +00003455CXXRecordDecl *Sema::getStdBadAlloc() const {
3456 return cast_or_null<CXXRecordDecl>(
3457 StdBadAlloc.get(Context.getExternalSource()));
3458}
3459
3460NamespaceDecl *Sema::getStdNamespace() const {
3461 return cast_or_null<NamespaceDecl>(
3462 StdNamespace.get(Context.getExternalSource()));
3463}
3464
Douglas Gregor66992202010-06-29 17:53:46 +00003465/// \brief Retrieve the special "std" namespace, which may require us to
3466/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003467NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003468 if (!StdNamespace) {
3469 // The "std" namespace has not yet been defined, so build one implicitly.
3470 StdNamespace = NamespaceDecl::Create(Context,
3471 Context.getTranslationUnitDecl(),
3472 SourceLocation(),
3473 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003474 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003475 }
3476
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003477 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003478}
3479
John McCalld226f652010-08-21 09:40:31 +00003480Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003481 SourceLocation UsingLoc,
3482 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003483 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003484 SourceLocation IdentLoc,
3485 IdentifierInfo *NamespcName,
3486 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003487 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3488 assert(NamespcName && "Invalid NamespcName.");
3489 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003490 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003491
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003492 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003493 NestedNameSpecifier *Qualifier = 0;
3494 if (SS.isSet())
3495 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3496
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003497 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003498 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3499 LookupParsedName(R, S, &SS);
3500 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003501 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003502
Douglas Gregor66992202010-06-29 17:53:46 +00003503 if (R.empty()) {
3504 // Allow "using namespace std;" or "using namespace ::std;" even if
3505 // "std" hasn't been defined yet, for GCC compatibility.
3506 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3507 NamespcName->isStr("std")) {
3508 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003509 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003510 R.resolveKind();
3511 }
3512 // Otherwise, attempt typo correction.
3513 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3514 CTC_NoKeywords, 0)) {
3515 if (R.getAsSingle<NamespaceDecl>() ||
3516 R.getAsSingle<NamespaceAliasDecl>()) {
3517 if (DeclContext *DC = computeDeclContext(SS, false))
3518 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3519 << NamespcName << DC << Corrected << SS.getRange()
3520 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3521 else
3522 Diag(IdentLoc, diag::err_using_directive_suggest)
3523 << NamespcName << Corrected
3524 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3525 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3526 << Corrected;
3527
3528 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003529 } else {
3530 R.clear();
3531 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003532 }
3533 }
3534 }
3535
John McCallf36e02d2009-10-09 21:13:30 +00003536 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003537 NamedDecl *Named = R.getFoundDecl();
3538 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3539 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003540 // C++ [namespace.udir]p1:
3541 // A using-directive specifies that the names in the nominated
3542 // namespace can be used in the scope in which the
3543 // using-directive appears after the using-directive. During
3544 // unqualified name lookup (3.4.1), the names appear as if they
3545 // were declared in the nearest enclosing namespace which
3546 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003547 // namespace. [Note: in this context, "contains" means "contains
3548 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003549
3550 // Find enclosing context containing both using-directive and
3551 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003552 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003553 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3554 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3555 CommonAncestor = CommonAncestor->getParent();
3556
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003557 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003558 SS.getRange(),
3559 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003560 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003561 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003562 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003563 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003564 }
3565
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003566 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003567 delete AttrList;
John McCalld226f652010-08-21 09:40:31 +00003568 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003569}
3570
3571void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3572 // If scope has associated entity, then using directive is at namespace
3573 // or translation unit scope. We add UsingDirectiveDecls, into
3574 // it's lookup structure.
3575 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003576 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003577 else
3578 // Otherwise it is block-sope. using-directives will affect lookup
3579 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00003580 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003581}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003582
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003583
John McCalld226f652010-08-21 09:40:31 +00003584Decl *Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003585 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003586 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003587 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003588 CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003589 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003590 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003591 bool IsTypeName,
3592 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003593 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003594
Douglas Gregor12c118a2009-11-04 16:30:06 +00003595 switch (Name.getKind()) {
3596 case UnqualifiedId::IK_Identifier:
3597 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003598 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003599 case UnqualifiedId::IK_ConversionFunctionId:
3600 break;
3601
3602 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003603 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003604 // C++0x inherited constructors.
3605 if (getLangOptions().CPlusPlus0x) break;
3606
Douglas Gregor12c118a2009-11-04 16:30:06 +00003607 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3608 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003609 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003610
3611 case UnqualifiedId::IK_DestructorName:
3612 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3613 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003614 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003615
3616 case UnqualifiedId::IK_TemplateId:
3617 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3618 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00003619 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003620 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003621
3622 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3623 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00003624 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00003625 return 0;
John McCall604e7f12009-12-08 07:46:18 +00003626
John McCall60fa3cf2009-12-11 02:10:03 +00003627 // Warn about using declarations.
3628 // TODO: store that the declaration was written without 'using' and
3629 // talk about access decls instead of using decls in the
3630 // diagnostics.
3631 if (!HasUsingKeyword) {
3632 UsingLoc = Name.getSourceRange().getBegin();
3633
3634 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003635 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003636 }
3637
John McCall9488ea12009-11-17 05:59:44 +00003638 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003639 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003640 /* IsInstantiation */ false,
3641 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003642 if (UD)
3643 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003644
John McCalld226f652010-08-21 09:40:31 +00003645 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00003646}
3647
Douglas Gregor09acc982010-07-07 23:08:52 +00003648/// \brief Determine whether a using declaration considers the given
3649/// declarations as "equivalent", e.g., if they are redeclarations of
3650/// the same entity or are both typedefs of the same type.
3651static bool
3652IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3653 bool &SuppressRedeclaration) {
3654 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3655 SuppressRedeclaration = false;
3656 return true;
3657 }
3658
3659 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3660 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3661 SuppressRedeclaration = true;
3662 return Context.hasSameType(TD1->getUnderlyingType(),
3663 TD2->getUnderlyingType());
3664 }
3665
3666 return false;
3667}
3668
3669
John McCall9f54ad42009-12-10 09:41:52 +00003670/// Determines whether to create a using shadow decl for a particular
3671/// decl, given the set of decls existing prior to this using lookup.
3672bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3673 const LookupResult &Previous) {
3674 // Diagnose finding a decl which is not from a base class of the
3675 // current class. We do this now because there are cases where this
3676 // function will silently decide not to build a shadow decl, which
3677 // will pre-empt further diagnostics.
3678 //
3679 // We don't need to do this in C++0x because we do the check once on
3680 // the qualifier.
3681 //
3682 // FIXME: diagnose the following if we care enough:
3683 // struct A { int foo; };
3684 // struct B : A { using A::foo; };
3685 // template <class T> struct C : A {};
3686 // template <class T> struct D : C<T> { using B::foo; } // <---
3687 // This is invalid (during instantiation) in C++03 because B::foo
3688 // resolves to the using decl in B, which is not a base class of D<T>.
3689 // We can't diagnose it immediately because C<T> is an unknown
3690 // specialization. The UsingShadowDecl in D<T> then points directly
3691 // to A::foo, which will look well-formed when we instantiate.
3692 // The right solution is to not collapse the shadow-decl chain.
3693 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3694 DeclContext *OrigDC = Orig->getDeclContext();
3695
3696 // Handle enums and anonymous structs.
3697 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3698 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3699 while (OrigRec->isAnonymousStructOrUnion())
3700 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3701
3702 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3703 if (OrigDC == CurContext) {
3704 Diag(Using->getLocation(),
3705 diag::err_using_decl_nested_name_specifier_is_current_class)
3706 << Using->getNestedNameRange();
3707 Diag(Orig->getLocation(), diag::note_using_decl_target);
3708 return true;
3709 }
3710
3711 Diag(Using->getNestedNameRange().getBegin(),
3712 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3713 << Using->getTargetNestedNameDecl()
3714 << cast<CXXRecordDecl>(CurContext)
3715 << Using->getNestedNameRange();
3716 Diag(Orig->getLocation(), diag::note_using_decl_target);
3717 return true;
3718 }
3719 }
3720
3721 if (Previous.empty()) return false;
3722
3723 NamedDecl *Target = Orig;
3724 if (isa<UsingShadowDecl>(Target))
3725 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3726
John McCalld7533ec2009-12-11 02:33:26 +00003727 // If the target happens to be one of the previous declarations, we
3728 // don't have a conflict.
3729 //
3730 // FIXME: but we might be increasing its access, in which case we
3731 // should redeclare it.
3732 NamedDecl *NonTag = 0, *Tag = 0;
3733 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3734 I != E; ++I) {
3735 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00003736 bool Result;
3737 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3738 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00003739
3740 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3741 }
3742
John McCall9f54ad42009-12-10 09:41:52 +00003743 if (Target->isFunctionOrFunctionTemplate()) {
3744 FunctionDecl *FD;
3745 if (isa<FunctionTemplateDecl>(Target))
3746 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3747 else
3748 FD = cast<FunctionDecl>(Target);
3749
3750 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00003751 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00003752 case Ovl_Overload:
3753 return false;
3754
3755 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003756 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003757 break;
3758
3759 // We found a decl with the exact signature.
3760 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00003761 // If we're in a record, we want to hide the target, so we
3762 // return true (without a diagnostic) to tell the caller not to
3763 // build a shadow decl.
3764 if (CurContext->isRecord())
3765 return true;
3766
3767 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003768 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003769 break;
3770 }
3771
3772 Diag(Target->getLocation(), diag::note_using_decl_target);
3773 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3774 return true;
3775 }
3776
3777 // Target is not a function.
3778
John McCall9f54ad42009-12-10 09:41:52 +00003779 if (isa<TagDecl>(Target)) {
3780 // No conflict between a tag and a non-tag.
3781 if (!Tag) return false;
3782
John McCall41ce66f2009-12-10 19:51:03 +00003783 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003784 Diag(Target->getLocation(), diag::note_using_decl_target);
3785 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3786 return true;
3787 }
3788
3789 // No conflict between a tag and a non-tag.
3790 if (!NonTag) return false;
3791
John McCall41ce66f2009-12-10 19:51:03 +00003792 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003793 Diag(Target->getLocation(), diag::note_using_decl_target);
3794 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3795 return true;
3796}
3797
John McCall9488ea12009-11-17 05:59:44 +00003798/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003799UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003800 UsingDecl *UD,
3801 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003802
3803 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003804 NamedDecl *Target = Orig;
3805 if (isa<UsingShadowDecl>(Target)) {
3806 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3807 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003808 }
3809
3810 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003811 = UsingShadowDecl::Create(Context, CurContext,
3812 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003813 UD->addShadowDecl(Shadow);
3814
3815 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003816 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003817 else
John McCall604e7f12009-12-08 07:46:18 +00003818 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003819 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003820
John McCall32daa422010-03-31 01:36:47 +00003821 // Register it as a conversion if appropriate.
3822 if (Shadow->getDeclName().getNameKind()
3823 == DeclarationName::CXXConversionFunctionName)
3824 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3825
John McCall604e7f12009-12-08 07:46:18 +00003826 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3827 Shadow->setInvalidDecl();
3828
John McCall9f54ad42009-12-10 09:41:52 +00003829 return Shadow;
3830}
John McCall604e7f12009-12-08 07:46:18 +00003831
John McCall9f54ad42009-12-10 09:41:52 +00003832/// Hides a using shadow declaration. This is required by the current
3833/// using-decl implementation when a resolvable using declaration in a
3834/// class is followed by a declaration which would hide or override
3835/// one or more of the using decl's targets; for example:
3836///
3837/// struct Base { void foo(int); };
3838/// struct Derived : Base {
3839/// using Base::foo;
3840/// void foo(int);
3841/// };
3842///
3843/// The governing language is C++03 [namespace.udecl]p12:
3844///
3845/// When a using-declaration brings names from a base class into a
3846/// derived class scope, member functions in the derived class
3847/// override and/or hide member functions with the same name and
3848/// parameter types in a base class (rather than conflicting).
3849///
3850/// There are two ways to implement this:
3851/// (1) optimistically create shadow decls when they're not hidden
3852/// by existing declarations, or
3853/// (2) don't create any shadow decls (or at least don't make them
3854/// visible) until we've fully parsed/instantiated the class.
3855/// The problem with (1) is that we might have to retroactively remove
3856/// a shadow decl, which requires several O(n) operations because the
3857/// decl structures are (very reasonably) not designed for removal.
3858/// (2) avoids this but is very fiddly and phase-dependent.
3859void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00003860 if (Shadow->getDeclName().getNameKind() ==
3861 DeclarationName::CXXConversionFunctionName)
3862 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3863
John McCall9f54ad42009-12-10 09:41:52 +00003864 // Remove it from the DeclContext...
3865 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003866
John McCall9f54ad42009-12-10 09:41:52 +00003867 // ...and the scope, if applicable...
3868 if (S) {
John McCalld226f652010-08-21 09:40:31 +00003869 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003870 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003871 }
3872
John McCall9f54ad42009-12-10 09:41:52 +00003873 // ...and the using decl.
3874 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3875
3876 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00003877 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00003878}
3879
John McCall7ba107a2009-11-18 02:36:19 +00003880/// Builds a using declaration.
3881///
3882/// \param IsInstantiation - Whether this call arises from an
3883/// instantiation of an unresolved using declaration. We treat
3884/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003885NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3886 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003887 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003888 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003889 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003890 bool IsInstantiation,
3891 bool IsTypeName,
3892 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003893 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003894 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00003895 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003896
Anders Carlsson550b14b2009-08-28 05:49:21 +00003897 // FIXME: We ignore attributes for now.
3898 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003899
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003900 if (SS.isEmpty()) {
3901 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003902 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003903 }
Mike Stump1eb44332009-09-09 15:08:12 +00003904
John McCall9f54ad42009-12-10 09:41:52 +00003905 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003906 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00003907 ForRedeclaration);
3908 Previous.setHideTags(false);
3909 if (S) {
3910 LookupName(Previous, S);
3911
3912 // It is really dumb that we have to do this.
3913 LookupResult::Filter F = Previous.makeFilter();
3914 while (F.hasNext()) {
3915 NamedDecl *D = F.next();
3916 if (!isDeclInScope(D, CurContext, S))
3917 F.erase();
3918 }
3919 F.done();
3920 } else {
3921 assert(IsInstantiation && "no scope in non-instantiation");
3922 assert(CurContext->isRecord() && "scope not record in instantiation");
3923 LookupQualifiedName(Previous, CurContext);
3924 }
3925
Mike Stump1eb44332009-09-09 15:08:12 +00003926 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003927 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3928
John McCall9f54ad42009-12-10 09:41:52 +00003929 // Check for invalid redeclarations.
3930 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3931 return 0;
3932
3933 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003934 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3935 return 0;
3936
John McCallaf8e6ed2009-11-12 03:15:40 +00003937 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003938 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003939 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003940 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003941 // FIXME: not all declaration name kinds are legal here
3942 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3943 UsingLoc, TypenameLoc,
3944 SS.getRange(), NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003945 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00003946 } else {
3947 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003948 UsingLoc, SS.getRange(),
3949 NNS, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00003950 }
John McCalled976492009-12-04 22:46:56 +00003951 } else {
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003952 D = UsingDecl::Create(Context, CurContext,
3953 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCalled976492009-12-04 22:46:56 +00003954 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003955 }
John McCalled976492009-12-04 22:46:56 +00003956 D->setAccess(AS);
3957 CurContext->addDecl(D);
3958
3959 if (!LookupContext) return D;
3960 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003961
John McCall77bb1aa2010-05-01 00:40:08 +00003962 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00003963 UD->setInvalidDecl();
3964 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003965 }
3966
John McCall604e7f12009-12-08 07:46:18 +00003967 // Look up the target name.
3968
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003969 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003970
John McCall604e7f12009-12-08 07:46:18 +00003971 // Unlike most lookups, we don't always want to hide tag
3972 // declarations: tag names are visible through the using declaration
3973 // even if hidden by ordinary names, *except* in a dependent context
3974 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003975 if (!IsInstantiation)
3976 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003977
John McCalla24dc2e2009-11-17 02:14:36 +00003978 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003979
John McCallf36e02d2009-10-09 21:13:30 +00003980 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003981 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003982 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003983 UD->setInvalidDecl();
3984 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003985 }
3986
John McCalled976492009-12-04 22:46:56 +00003987 if (R.isAmbiguous()) {
3988 UD->setInvalidDecl();
3989 return UD;
3990 }
Mike Stump1eb44332009-09-09 15:08:12 +00003991
John McCall7ba107a2009-11-18 02:36:19 +00003992 if (IsTypeName) {
3993 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003994 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003995 Diag(IdentLoc, diag::err_using_typename_non_type);
3996 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3997 Diag((*I)->getUnderlyingDecl()->getLocation(),
3998 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003999 UD->setInvalidDecl();
4000 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004001 }
4002 } else {
4003 // If we asked for a non-typename and we got a type, error out,
4004 // but only if this is an instantiation of an unresolved using
4005 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00004006 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004007 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4008 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004009 UD->setInvalidDecl();
4010 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004011 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004012 }
4013
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004014 // C++0x N2914 [namespace.udecl]p6:
4015 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00004016 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004017 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4018 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004019 UD->setInvalidDecl();
4020 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004021 }
Mike Stump1eb44332009-09-09 15:08:12 +00004022
John McCall9f54ad42009-12-10 09:41:52 +00004023 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4024 if (!CheckUsingShadowDecl(UD, *I, Previous))
4025 BuildUsingShadowDecl(S, UD, *I);
4026 }
John McCall9488ea12009-11-17 05:59:44 +00004027
4028 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004029}
4030
John McCall9f54ad42009-12-10 09:41:52 +00004031/// Checks that the given using declaration is not an invalid
4032/// redeclaration. Note that this is checking only for the using decl
4033/// itself, not for any ill-formedness among the UsingShadowDecls.
4034bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4035 bool isTypeName,
4036 const CXXScopeSpec &SS,
4037 SourceLocation NameLoc,
4038 const LookupResult &Prev) {
4039 // C++03 [namespace.udecl]p8:
4040 // C++0x [namespace.udecl]p10:
4041 // A using-declaration is a declaration and can therefore be used
4042 // repeatedly where (and only where) multiple declarations are
4043 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00004044 //
4045 // That's in non-member contexts.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004046 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00004047 return false;
4048
4049 NestedNameSpecifier *Qual
4050 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4051
4052 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4053 NamedDecl *D = *I;
4054
4055 bool DTypename;
4056 NestedNameSpecifier *DQual;
4057 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4058 DTypename = UD->isTypeName();
4059 DQual = UD->getTargetNestedNameDecl();
4060 } else if (UnresolvedUsingValueDecl *UD
4061 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4062 DTypename = false;
4063 DQual = UD->getTargetNestedNameSpecifier();
4064 } else if (UnresolvedUsingTypenameDecl *UD
4065 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4066 DTypename = true;
4067 DQual = UD->getTargetNestedNameSpecifier();
4068 } else continue;
4069
4070 // using decls differ if one says 'typename' and the other doesn't.
4071 // FIXME: non-dependent using decls?
4072 if (isTypeName != DTypename) continue;
4073
4074 // using decls differ if they name different scopes (but note that
4075 // template instantiation can cause this check to trigger when it
4076 // didn't before instantiation).
4077 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4078 Context.getCanonicalNestedNameSpecifier(DQual))
4079 continue;
4080
4081 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00004082 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00004083 return true;
4084 }
4085
4086 return false;
4087}
4088
John McCall604e7f12009-12-08 07:46:18 +00004089
John McCalled976492009-12-04 22:46:56 +00004090/// Checks that the given nested-name qualifier used in a using decl
4091/// in the current context is appropriately related to the current
4092/// scope. If an error is found, diagnoses it and returns true.
4093bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4094 const CXXScopeSpec &SS,
4095 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004096 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004097
John McCall604e7f12009-12-08 07:46:18 +00004098 if (!CurContext->isRecord()) {
4099 // C++03 [namespace.udecl]p3:
4100 // C++0x [namespace.udecl]p8:
4101 // A using-declaration for a class member shall be a member-declaration.
4102
4103 // If we weren't able to compute a valid scope, it must be a
4104 // dependent class scope.
4105 if (!NamedContext || NamedContext->isRecord()) {
4106 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4107 << SS.getRange();
4108 return true;
4109 }
4110
4111 // Otherwise, everything is known to be fine.
4112 return false;
4113 }
4114
4115 // The current scope is a record.
4116
4117 // If the named context is dependent, we can't decide much.
4118 if (!NamedContext) {
4119 // FIXME: in C++0x, we can diagnose if we can prove that the
4120 // nested-name-specifier does not refer to a base class, which is
4121 // still possible in some cases.
4122
4123 // Otherwise we have to conservatively report that things might be
4124 // okay.
4125 return false;
4126 }
4127
4128 if (!NamedContext->isRecord()) {
4129 // Ideally this would point at the last name in the specifier,
4130 // but we don't have that level of source info.
4131 Diag(SS.getRange().getBegin(),
4132 diag::err_using_decl_nested_name_specifier_is_not_class)
4133 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4134 return true;
4135 }
4136
4137 if (getLangOptions().CPlusPlus0x) {
4138 // C++0x [namespace.udecl]p3:
4139 // In a using-declaration used as a member-declaration, the
4140 // nested-name-specifier shall name a base class of the class
4141 // being defined.
4142
4143 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4144 cast<CXXRecordDecl>(NamedContext))) {
4145 if (CurContext == NamedContext) {
4146 Diag(NameLoc,
4147 diag::err_using_decl_nested_name_specifier_is_current_class)
4148 << SS.getRange();
4149 return true;
4150 }
4151
4152 Diag(SS.getRange().getBegin(),
4153 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4154 << (NestedNameSpecifier*) SS.getScopeRep()
4155 << cast<CXXRecordDecl>(CurContext)
4156 << SS.getRange();
4157 return true;
4158 }
4159
4160 return false;
4161 }
4162
4163 // C++03 [namespace.udecl]p4:
4164 // A using-declaration used as a member-declaration shall refer
4165 // to a member of a base class of the class being defined [etc.].
4166
4167 // Salient point: SS doesn't have to name a base class as long as
4168 // lookup only finds members from base classes. Therefore we can
4169 // diagnose here only if we can prove that that can't happen,
4170 // i.e. if the class hierarchies provably don't intersect.
4171
4172 // TODO: it would be nice if "definitely valid" results were cached
4173 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4174 // need to be repeated.
4175
4176 struct UserData {
4177 llvm::DenseSet<const CXXRecordDecl*> Bases;
4178
4179 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4180 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4181 Data->Bases.insert(Base);
4182 return true;
4183 }
4184
4185 bool hasDependentBases(const CXXRecordDecl *Class) {
4186 return !Class->forallBases(collect, this);
4187 }
4188
4189 /// Returns true if the base is dependent or is one of the
4190 /// accumulated base classes.
4191 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4192 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4193 return !Data->Bases.count(Base);
4194 }
4195
4196 bool mightShareBases(const CXXRecordDecl *Class) {
4197 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4198 }
4199 };
4200
4201 UserData Data;
4202
4203 // Returns false if we find a dependent base.
4204 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4205 return false;
4206
4207 // Returns false if the class has a dependent base or if it or one
4208 // of its bases is present in the base set of the current context.
4209 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4210 return false;
4211
4212 Diag(SS.getRange().getBegin(),
4213 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4214 << (NestedNameSpecifier*) SS.getScopeRep()
4215 << cast<CXXRecordDecl>(CurContext)
4216 << SS.getRange();
4217
4218 return true;
John McCalled976492009-12-04 22:46:56 +00004219}
4220
John McCalld226f652010-08-21 09:40:31 +00004221Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004222 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004223 SourceLocation AliasLoc,
4224 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004225 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004226 SourceLocation IdentLoc,
4227 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004228
Anders Carlsson81c85c42009-03-28 23:53:49 +00004229 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004230 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4231 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004232
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004233 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004234 NamedDecl *PrevDecl
4235 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4236 ForRedeclaration);
4237 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4238 PrevDecl = 0;
4239
4240 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004241 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004242 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004243 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004244 // FIXME: At some point, we'll want to create the (redundant)
4245 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004246 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004247 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004248 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004249 }
Mike Stump1eb44332009-09-09 15:08:12 +00004250
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004251 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4252 diag::err_redefinition_different_kind;
4253 Diag(AliasLoc, DiagID) << Alias;
4254 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004255 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004256 }
4257
John McCalla24dc2e2009-11-17 02:14:36 +00004258 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004259 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004260
John McCallf36e02d2009-10-09 21:13:30 +00004261 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004262 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4263 CTC_NoKeywords, 0)) {
4264 if (R.getAsSingle<NamespaceDecl>() ||
4265 R.getAsSingle<NamespaceAliasDecl>()) {
4266 if (DeclContext *DC = computeDeclContext(SS, false))
4267 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4268 << Ident << DC << Corrected << SS.getRange()
4269 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4270 else
4271 Diag(IdentLoc, diag::err_using_directive_suggest)
4272 << Ident << Corrected
4273 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4274
4275 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4276 << Corrected;
4277
4278 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004279 } else {
4280 R.clear();
4281 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004282 }
4283 }
4284
4285 if (R.empty()) {
4286 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004287 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004288 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004289 }
Mike Stump1eb44332009-09-09 15:08:12 +00004290
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004291 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004292 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4293 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004294 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004295 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004296
John McCall3dbd3d52010-02-16 06:53:13 +00004297 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004298 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004299}
4300
Douglas Gregor39957dc2010-05-01 15:04:51 +00004301namespace {
4302 /// \brief Scoped object used to handle the state changes required in Sema
4303 /// to implicitly define the body of a C++ member function;
4304 class ImplicitlyDefinedFunctionScope {
4305 Sema &S;
4306 DeclContext *PreviousContext;
4307
4308 public:
4309 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4310 : S(S), PreviousContext(S.CurContext)
4311 {
4312 S.CurContext = Method;
4313 S.PushFunctionScope();
4314 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4315 }
4316
4317 ~ImplicitlyDefinedFunctionScope() {
4318 S.PopExpressionEvaluationContext();
4319 S.PopFunctionOrBlockScope();
4320 S.CurContext = PreviousContext;
4321 }
4322 };
4323}
4324
Sebastian Redl751025d2010-09-13 22:02:47 +00004325static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4326 CXXRecordDecl *D) {
4327 ASTContext &Context = Self.Context;
4328 QualType ClassType = Context.getTypeDeclType(D);
4329 DeclarationName ConstructorName
4330 = Context.DeclarationNames.getCXXConstructorName(
4331 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4332
4333 DeclContext::lookup_const_iterator Con, ConEnd;
4334 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4335 Con != ConEnd; ++Con) {
4336 // FIXME: In C++0x, a constructor template can be a default constructor.
4337 if (isa<FunctionTemplateDecl>(*Con))
4338 continue;
4339
4340 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4341 if (Constructor->isDefaultConstructor())
4342 return Constructor;
4343 }
4344 return 0;
4345}
4346
Douglas Gregor23c94db2010-07-02 17:43:08 +00004347CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4348 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004349 // C++ [class.ctor]p5:
4350 // A default constructor for a class X is a constructor of class X
4351 // that can be called without an argument. If there is no
4352 // user-declared constructor for class X, a default constructor is
4353 // implicitly declared. An implicitly-declared default constructor
4354 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004355 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4356 "Should not build implicit default constructor!");
4357
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004358 // C++ [except.spec]p14:
4359 // An implicitly declared special member function (Clause 12) shall have an
4360 // exception-specification. [...]
4361 ImplicitExceptionSpecification ExceptSpec(Context);
4362
4363 // Direct base-class destructors.
4364 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4365 BEnd = ClassDecl->bases_end();
4366 B != BEnd; ++B) {
4367 if (B->isVirtual()) // Handled below.
4368 continue;
4369
Douglas Gregor18274032010-07-03 00:47:00 +00004370 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4371 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4372 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4373 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redl751025d2010-09-13 22:02:47 +00004374 else if (CXXConstructorDecl *Constructor
4375 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004376 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004377 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004378 }
4379
4380 // Virtual base-class destructors.
4381 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4382 BEnd = ClassDecl->vbases_end();
4383 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004384 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4385 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4386 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4387 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4388 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004389 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004390 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004391 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004392 }
4393
4394 // Field destructors.
4395 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4396 FEnd = ClassDecl->field_end();
4397 F != FEnd; ++F) {
4398 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004399 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4400 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4401 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4402 ExceptSpec.CalledDecl(
4403 DeclareImplicitDefaultConstructor(FieldClassDecl));
4404 else if (CXXConstructorDecl *Constructor
Sebastian Redl751025d2010-09-13 22:02:47 +00004405 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004406 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004407 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004408 }
4409
4410
4411 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004412 CanQualType ClassType
4413 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4414 DeclarationName Name
4415 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004416 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor32df23e2010-07-01 22:02:46 +00004417 CXXConstructorDecl *DefaultCon
Abramo Bagnara25777432010-08-11 22:01:17 +00004418 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004419 Context.getFunctionType(Context.VoidTy,
4420 0, 0, false, 0,
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004421 ExceptSpec.hasExceptionSpecification(),
4422 ExceptSpec.hasAnyExceptionSpecification(),
4423 ExceptSpec.size(),
4424 ExceptSpec.data(),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004425 FunctionType::ExtInfo()),
4426 /*TInfo=*/0,
4427 /*isExplicit=*/false,
4428 /*isInline=*/true,
4429 /*isImplicitlyDeclared=*/true);
4430 DefaultCon->setAccess(AS_public);
4431 DefaultCon->setImplicit();
4432 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004433
4434 // Note that we have declared this constructor.
4435 ClassDecl->setDeclaredDefaultConstructor(true);
4436 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4437
Douglas Gregor23c94db2010-07-02 17:43:08 +00004438 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004439 PushOnScopeChains(DefaultCon, S, false);
4440 ClassDecl->addDecl(DefaultCon);
4441
Douglas Gregor32df23e2010-07-01 22:02:46 +00004442 return DefaultCon;
4443}
4444
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004445void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4446 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004447 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004448 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004449 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004450
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004451 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004452 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004453
Douglas Gregor39957dc2010-05-01 15:04:51 +00004454 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004455 ErrorTrap Trap(*this);
4456 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4457 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004458 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004459 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004460 Constructor->setInvalidDecl();
4461 } else {
4462 Constructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004463 MarkVTableUsed(CurrentLocation, ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004464 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004465}
4466
Douglas Gregor23c94db2010-07-02 17:43:08 +00004467CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004468 // C++ [class.dtor]p2:
4469 // If a class has no user-declared destructor, a destructor is
4470 // declared implicitly. An implicitly-declared destructor is an
4471 // inline public member of its class.
4472
4473 // C++ [except.spec]p14:
4474 // An implicitly declared special member function (Clause 12) shall have
4475 // an exception-specification.
4476 ImplicitExceptionSpecification ExceptSpec(Context);
4477
4478 // Direct base-class destructors.
4479 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4480 BEnd = ClassDecl->bases_end();
4481 B != BEnd; ++B) {
4482 if (B->isVirtual()) // Handled below.
4483 continue;
4484
4485 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4486 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004487 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004488 }
4489
4490 // Virtual base-class destructors.
4491 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4492 BEnd = ClassDecl->vbases_end();
4493 B != BEnd; ++B) {
4494 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4495 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004496 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004497 }
4498
4499 // Field destructors.
4500 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4501 FEnd = ClassDecl->field_end();
4502 F != FEnd; ++F) {
4503 if (const RecordType *RecordTy
4504 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4505 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004506 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004507 }
4508
Douglas Gregor4923aa22010-07-02 20:37:36 +00004509 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004510 QualType Ty = Context.getFunctionType(Context.VoidTy,
4511 0, 0, false, 0,
4512 ExceptSpec.hasExceptionSpecification(),
4513 ExceptSpec.hasAnyExceptionSpecification(),
4514 ExceptSpec.size(),
4515 ExceptSpec.data(),
4516 FunctionType::ExtInfo());
4517
4518 CanQualType ClassType
4519 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4520 DeclarationName Name
4521 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004522 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004523 CXXDestructorDecl *Destructor
Abramo Bagnara25777432010-08-11 22:01:17 +00004524 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty,
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004525 /*isInline=*/true,
4526 /*isImplicitlyDeclared=*/true);
4527 Destructor->setAccess(AS_public);
4528 Destructor->setImplicit();
4529 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00004530
4531 // Note that we have declared this destructor.
4532 ClassDecl->setDeclaredDestructor(true);
4533 ++ASTContext::NumImplicitDestructorsDeclared;
4534
4535 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004536 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00004537 PushOnScopeChains(Destructor, S, false);
4538 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004539
4540 // This could be uniqued if it ever proves significant.
4541 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4542
4543 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00004544
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004545 return Destructor;
4546}
4547
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004548void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004549 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00004550 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004551 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004552 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004553 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004554
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004555 if (Destructor->isInvalidDecl())
4556 return;
4557
Douglas Gregor39957dc2010-05-01 15:04:51 +00004558 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004559
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004560 ErrorTrap Trap(*this);
John McCallef027fe2010-03-16 21:39:52 +00004561 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4562 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004563
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004564 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004565 Diag(CurrentLocation, diag::note_member_synthesized_at)
4566 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4567
4568 Destructor->setInvalidDecl();
4569 return;
4570 }
4571
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004572 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004573 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004574}
4575
Douglas Gregor06a9f362010-05-01 20:49:11 +00004576/// \brief Builds a statement that copies the given entity from \p From to
4577/// \c To.
4578///
4579/// This routine is used to copy the members of a class with an
4580/// implicitly-declared copy assignment operator. When the entities being
4581/// copied are arrays, this routine builds for loops to copy them.
4582///
4583/// \param S The Sema object used for type-checking.
4584///
4585/// \param Loc The location where the implicit copy is being generated.
4586///
4587/// \param T The type of the expressions being copied. Both expressions must
4588/// have this type.
4589///
4590/// \param To The expression we are copying to.
4591///
4592/// \param From The expression we are copying from.
4593///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004594/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4595/// Otherwise, it's a non-static member subobject.
4596///
Douglas Gregor06a9f362010-05-01 20:49:11 +00004597/// \param Depth Internal parameter recording the depth of the recursion.
4598///
4599/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00004600static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00004601BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00004602 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004603 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00004604 // C++0x [class.copy]p30:
4605 // Each subobject is assigned in the manner appropriate to its type:
4606 //
4607 // - if the subobject is of class type, the copy assignment operator
4608 // for the class is used (as if by explicit qualification; that is,
4609 // ignoring any possible virtual overriding functions in more derived
4610 // classes);
4611 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4612 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4613
4614 // Look for operator=.
4615 DeclarationName Name
4616 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4617 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4618 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4619
4620 // Filter out any result that isn't a copy-assignment operator.
4621 LookupResult::Filter F = OpLookup.makeFilter();
4622 while (F.hasNext()) {
4623 NamedDecl *D = F.next();
4624 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4625 if (Method->isCopyAssignmentOperator())
4626 continue;
4627
4628 F.erase();
John McCallb0207482010-03-16 06:11:48 +00004629 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004630 F.done();
4631
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004632 // Suppress the protected check (C++ [class.protected]) for each of the
4633 // assignment operators we found. This strange dance is required when
4634 // we're assigning via a base classes's copy-assignment operator. To
4635 // ensure that we're getting the right base class subobject (without
4636 // ambiguities), we need to cast "this" to that subobject type; to
4637 // ensure that we don't go through the virtual call mechanism, we need
4638 // to qualify the operator= name with the base class (see below). However,
4639 // this means that if the base class has a protected copy assignment
4640 // operator, the protected member access check will fail. So, we
4641 // rewrite "protected" access to "public" access in this case, since we
4642 // know by construction that we're calling from a derived class.
4643 if (CopyingBaseSubobject) {
4644 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4645 L != LEnd; ++L) {
4646 if (L.getAccess() == AS_protected)
4647 L.setAccess(AS_public);
4648 }
4649 }
4650
Douglas Gregor06a9f362010-05-01 20:49:11 +00004651 // Create the nested-name-specifier that will be used to qualify the
4652 // reference to operator=; this is required to suppress the virtual
4653 // call mechanism.
4654 CXXScopeSpec SS;
4655 SS.setRange(Loc);
4656 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4657 T.getTypePtr()));
4658
4659 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00004660 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00004661 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004662 /*FirstQualifierInScope=*/0, OpLookup,
4663 /*TemplateArgs=*/0,
4664 /*SuppressQualifierCheck=*/true);
4665 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004666 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004667
4668 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00004669
John McCall60d7b3a2010-08-24 06:29:42 +00004670 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00004671 OpEqualRef.takeAs<Expr>(),
4672 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004673 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004674 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004675
4676 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004677 }
John McCallb0207482010-03-16 06:11:48 +00004678
Douglas Gregor06a9f362010-05-01 20:49:11 +00004679 // - if the subobject is of scalar type, the built-in assignment
4680 // operator is used.
4681 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4682 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00004683 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004684 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004685 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004686
4687 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004688 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004689
4690 // - if the subobject is an array, each element is assigned, in the
4691 // manner appropriate to the element type;
4692
4693 // Construct a loop over the array bounds, e.g.,
4694 //
4695 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4696 //
4697 // that will copy each of the array elements.
4698 QualType SizeType = S.Context.getSizeType();
4699
4700 // Create the iteration variable.
4701 IdentifierInfo *IterationVarName = 0;
4702 {
4703 llvm::SmallString<8> Str;
4704 llvm::raw_svector_ostream OS(Str);
4705 OS << "__i" << Depth;
4706 IterationVarName = &S.Context.Idents.get(OS.str());
4707 }
4708 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4709 IterationVarName, SizeType,
4710 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00004711 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004712
4713 // Initialize the iteration variable to zero.
4714 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004715 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004716
4717 // Create a reference to the iteration variable; we'll use this several
4718 // times throughout.
4719 Expr *IterationVarRef
4720 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4721 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4722
4723 // Create the DeclStmt that holds the iteration variable.
4724 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4725
4726 // Create the comparison against the array bound.
4727 llvm::APInt Upper = ArrayTy->getSize();
4728 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00004729 Expr *Comparison
4730 = new (S.Context) BinaryOperator(IterationVarRef->Retain(),
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004731 IntegerLiteral::Create(S.Context,
4732 Upper, SizeType, Loc),
4733 BO_NE, S.Context.BoolTy, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004734
4735 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004736 Expr *Increment
4737 = new (S.Context) UnaryOperator(IterationVarRef->Retain(),
John McCall2de56d12010-08-25 11:45:40 +00004738 UO_PreInc,
John McCall9ae2f072010-08-23 23:25:46 +00004739 SizeType, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004740
4741 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004742 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4743 IterationVarRef, Loc));
4744 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4745 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004746
4747 // Build the copy for an individual element of the array.
John McCall60d7b3a2010-08-24 06:29:42 +00004748 StmtResult Copy = BuildSingleCopyAssign(S, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004749 ArrayTy->getElementType(),
John McCall9ae2f072010-08-23 23:25:46 +00004750 To, From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004751 CopyingBaseSubobject, Depth+1);
Douglas Gregorff331c12010-07-25 18:17:45 +00004752 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004753 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004754
4755 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00004756 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004757 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00004758 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00004759 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004760}
4761
Douglas Gregora376d102010-07-02 21:50:04 +00004762/// \brief Determine whether the given class has a copy assignment operator
4763/// that accepts a const-qualified argument.
4764static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4765 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4766
4767 if (!Class->hasDeclaredCopyAssignment())
4768 S.DeclareImplicitCopyAssignment(Class);
4769
4770 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4771 DeclarationName OpName
4772 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4773
4774 DeclContext::lookup_const_iterator Op, OpEnd;
4775 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4776 // C++ [class.copy]p9:
4777 // A user-declared copy assignment operator is a non-static non-template
4778 // member function of class X with exactly one parameter of type X, X&,
4779 // const X&, volatile X& or const volatile X&.
4780 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4781 if (!Method)
4782 continue;
4783
4784 if (Method->isStatic())
4785 continue;
4786 if (Method->getPrimaryTemplate())
4787 continue;
4788 const FunctionProtoType *FnType =
4789 Method->getType()->getAs<FunctionProtoType>();
4790 assert(FnType && "Overloaded operator has no prototype.");
4791 // Don't assert on this; an invalid decl might have been left in the AST.
4792 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4793 continue;
4794 bool AcceptsConst = true;
4795 QualType ArgType = FnType->getArgType(0);
4796 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4797 ArgType = Ref->getPointeeType();
4798 // Is it a non-const lvalue reference?
4799 if (!ArgType.isConstQualified())
4800 AcceptsConst = false;
4801 }
4802 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4803 continue;
4804
4805 // We have a single argument of type cv X or cv X&, i.e. we've found the
4806 // copy assignment operator. Return whether it accepts const arguments.
4807 return AcceptsConst;
4808 }
4809 assert(Class->isInvalidDecl() &&
4810 "No copy assignment operator declared in valid code.");
4811 return false;
4812}
4813
Douglas Gregor23c94db2010-07-02 17:43:08 +00004814CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00004815 // Note: The following rules are largely analoguous to the copy
4816 // constructor rules. Note that virtual bases are not taken into account
4817 // for determining the argument type of the operator. Note also that
4818 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00004819
4820
Douglas Gregord3c35902010-07-01 16:36:15 +00004821 // C++ [class.copy]p10:
4822 // If the class definition does not explicitly declare a copy
4823 // assignment operator, one is declared implicitly.
4824 // The implicitly-defined copy assignment operator for a class X
4825 // will have the form
4826 //
4827 // X& X::operator=(const X&)
4828 //
4829 // if
4830 bool HasConstCopyAssignment = true;
4831
4832 // -- each direct base class B of X has a copy assignment operator
4833 // whose parameter is of type const B&, const volatile B& or B,
4834 // and
4835 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4836 BaseEnd = ClassDecl->bases_end();
4837 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4838 assert(!Base->getType()->isDependentType() &&
4839 "Cannot generate implicit members for class with dependent bases.");
4840 const CXXRecordDecl *BaseClassDecl
4841 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004842 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004843 }
4844
4845 // -- for all the nonstatic data members of X that are of a class
4846 // type M (or array thereof), each such class type has a copy
4847 // assignment operator whose parameter is of type const M&,
4848 // const volatile M& or M.
4849 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4850 FieldEnd = ClassDecl->field_end();
4851 HasConstCopyAssignment && Field != FieldEnd;
4852 ++Field) {
4853 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4854 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4855 const CXXRecordDecl *FieldClassDecl
4856 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004857 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004858 }
4859 }
4860
4861 // Otherwise, the implicitly declared copy assignment operator will
4862 // have the form
4863 //
4864 // X& X::operator=(X&)
4865 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4866 QualType RetType = Context.getLValueReferenceType(ArgType);
4867 if (HasConstCopyAssignment)
4868 ArgType = ArgType.withConst();
4869 ArgType = Context.getLValueReferenceType(ArgType);
4870
Douglas Gregorb87786f2010-07-01 17:48:08 +00004871 // C++ [except.spec]p14:
4872 // An implicitly declared special member function (Clause 12) shall have an
4873 // exception-specification. [...]
4874 ImplicitExceptionSpecification ExceptSpec(Context);
4875 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4876 BaseEnd = ClassDecl->bases_end();
4877 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00004878 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004879 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004880
4881 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4882 DeclareImplicitCopyAssignment(BaseClassDecl);
4883
Douglas Gregorb87786f2010-07-01 17:48:08 +00004884 if (CXXMethodDecl *CopyAssign
4885 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4886 ExceptSpec.CalledDecl(CopyAssign);
4887 }
4888 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4889 FieldEnd = ClassDecl->field_end();
4890 Field != FieldEnd;
4891 ++Field) {
4892 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4893 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00004894 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004895 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004896
4897 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4898 DeclareImplicitCopyAssignment(FieldClassDecl);
4899
Douglas Gregorb87786f2010-07-01 17:48:08 +00004900 if (CXXMethodDecl *CopyAssign
4901 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4902 ExceptSpec.CalledDecl(CopyAssign);
4903 }
4904 }
4905
Douglas Gregord3c35902010-07-01 16:36:15 +00004906 // An implicitly-declared copy assignment operator is an inline public
4907 // member of its class.
4908 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnara25777432010-08-11 22:01:17 +00004909 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00004910 CXXMethodDecl *CopyAssignment
Abramo Bagnara25777432010-08-11 22:01:17 +00004911 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregord3c35902010-07-01 16:36:15 +00004912 Context.getFunctionType(RetType, &ArgType, 1,
4913 false, 0,
Douglas Gregorb87786f2010-07-01 17:48:08 +00004914 ExceptSpec.hasExceptionSpecification(),
4915 ExceptSpec.hasAnyExceptionSpecification(),
4916 ExceptSpec.size(),
4917 ExceptSpec.data(),
Douglas Gregord3c35902010-07-01 16:36:15 +00004918 FunctionType::ExtInfo()),
4919 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00004920 /*StorageClassAsWritten=*/SC_None,
Douglas Gregord3c35902010-07-01 16:36:15 +00004921 /*isInline=*/true);
4922 CopyAssignment->setAccess(AS_public);
4923 CopyAssignment->setImplicit();
4924 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
4925 CopyAssignment->setCopyAssignment(true);
4926
4927 // Add the parameter to the operator.
4928 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4929 ClassDecl->getLocation(),
4930 /*Id=*/0,
4931 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00004932 SC_None,
4933 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00004934 CopyAssignment->setParams(&FromParam, 1);
4935
Douglas Gregora376d102010-07-02 21:50:04 +00004936 // Note that we have added this copy-assignment operator.
4937 ClassDecl->setDeclaredCopyAssignment(true);
4938 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4939
Douglas Gregor23c94db2010-07-02 17:43:08 +00004940 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00004941 PushOnScopeChains(CopyAssignment, S, false);
4942 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00004943
4944 AddOverriddenMethods(ClassDecl, CopyAssignment);
4945 return CopyAssignment;
4946}
4947
Douglas Gregor06a9f362010-05-01 20:49:11 +00004948void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4949 CXXMethodDecl *CopyAssignOperator) {
4950 assert((CopyAssignOperator->isImplicit() &&
4951 CopyAssignOperator->isOverloadedOperator() &&
4952 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004953 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00004954 "DefineImplicitCopyAssignment called for wrong function");
4955
4956 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4957
4958 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4959 CopyAssignOperator->setInvalidDecl();
4960 return;
4961 }
4962
4963 CopyAssignOperator->setUsed();
4964
4965 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004966 ErrorTrap Trap(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004967
4968 // C++0x [class.copy]p30:
4969 // The implicitly-defined or explicitly-defaulted copy assignment operator
4970 // for a non-union class X performs memberwise copy assignment of its
4971 // subobjects. The direct base classes of X are assigned first, in the
4972 // order of their declaration in the base-specifier-list, and then the
4973 // immediate non-static data members of X are assigned, in the order in
4974 // which they were declared in the class definition.
4975
4976 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00004977 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004978
4979 // The parameter for the "other" object, which we are copying from.
4980 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4981 Qualifiers OtherQuals = Other->getType().getQualifiers();
4982 QualType OtherRefType = Other->getType();
4983 if (const LValueReferenceType *OtherRef
4984 = OtherRefType->getAs<LValueReferenceType>()) {
4985 OtherRefType = OtherRef->getPointeeType();
4986 OtherQuals = OtherRefType.getQualifiers();
4987 }
4988
4989 // Our location for everything implicitly-generated.
4990 SourceLocation Loc = CopyAssignOperator->getLocation();
4991
4992 // Construct a reference to the "other" object. We'll be using this
4993 // throughout the generated ASTs.
4994 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4995 assert(OtherRef && "Reference to parameter cannot fail!");
4996
4997 // Construct the "this" pointer. We'll be using this throughout the generated
4998 // ASTs.
4999 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5000 assert(This && "Reference to this cannot fail!");
5001
5002 // Assign base classes.
5003 bool Invalid = false;
5004 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5005 E = ClassDecl->bases_end(); Base != E; ++Base) {
5006 // Form the assignment:
5007 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5008 QualType BaseType = Base->getType().getUnqualifiedType();
5009 CXXRecordDecl *BaseClassDecl = 0;
5010 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
5011 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
5012 else {
5013 Invalid = true;
5014 continue;
5015 }
5016
John McCallf871d0c2010-08-07 06:22:56 +00005017 CXXCastPath BasePath;
5018 BasePath.push_back(Base);
5019
Douglas Gregor06a9f362010-05-01 20:49:11 +00005020 // Construct the "from" expression, which is an implicit cast to the
5021 // appropriately-qualified base type.
5022 Expr *From = OtherRef->Retain();
5023 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall5baba9d2010-08-25 10:28:54 +00005024 CK_UncheckedDerivedToBase,
5025 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005026
5027 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00005028 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005029
5030 // Implicitly cast "this" to the appropriately-qualified base type.
5031 Expr *ToE = To.takeAs<Expr>();
5032 ImpCastExprToType(ToE,
5033 Context.getCVRQualifiedType(BaseType,
5034 CopyAssignOperator->getTypeQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00005035 CK_UncheckedDerivedToBase,
5036 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005037 To = Owned(ToE);
5038
5039 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00005040 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00005041 To.get(), From,
5042 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005043 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005044 Diag(CurrentLocation, diag::note_member_synthesized_at)
5045 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5046 CopyAssignOperator->setInvalidDecl();
5047 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005048 }
5049
5050 // Success! Record the copy.
5051 Statements.push_back(Copy.takeAs<Expr>());
5052 }
5053
5054 // \brief Reference to the __builtin_memcpy function.
5055 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005056 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005057 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005058
5059 // Assign non-static members.
5060 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5061 FieldEnd = ClassDecl->field_end();
5062 Field != FieldEnd; ++Field) {
5063 // Check for members of reference type; we can't copy those.
5064 if (Field->getType()->isReferenceType()) {
5065 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5066 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5067 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005068 Diag(CurrentLocation, diag::note_member_synthesized_at)
5069 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005070 Invalid = true;
5071 continue;
5072 }
5073
5074 // Check for members of const-qualified, non-class type.
5075 QualType BaseType = Context.getBaseElementType(Field->getType());
5076 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5077 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5078 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5079 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005080 Diag(CurrentLocation, diag::note_member_synthesized_at)
5081 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005082 Invalid = true;
5083 continue;
5084 }
5085
5086 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005087 if (FieldType->isIncompleteArrayType()) {
5088 assert(ClassDecl->hasFlexibleArrayMember() &&
5089 "Incomplete array type is not valid");
5090 continue;
5091 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005092
5093 // Build references to the field in the object we're copying from and to.
5094 CXXScopeSpec SS; // Intentionally empty
5095 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5096 LookupMemberName);
5097 MemberLookup.addDecl(*Field);
5098 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005099 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005100 Loc, /*IsArrow=*/false,
5101 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005102 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005103 Loc, /*IsArrow=*/true,
5104 SS, 0, MemberLookup, 0);
5105 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5106 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5107
5108 // If the field should be copied with __builtin_memcpy rather than via
5109 // explicit assignments, do so. This optimization only applies for arrays
5110 // of scalars and arrays of class type with trivial copy-assignment
5111 // operators.
5112 if (FieldType->isArrayType() &&
5113 (!BaseType->isRecordType() ||
5114 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5115 ->hasTrivialCopyAssignment())) {
5116 // Compute the size of the memory buffer to be copied.
5117 QualType SizeType = Context.getSizeType();
5118 llvm::APInt Size(Context.getTypeSize(SizeType),
5119 Context.getTypeSizeInChars(BaseType).getQuantity());
5120 for (const ConstantArrayType *Array
5121 = Context.getAsConstantArrayType(FieldType);
5122 Array;
5123 Array = Context.getAsConstantArrayType(Array->getElementType())) {
5124 llvm::APInt ArraySize = Array->getSize();
5125 ArraySize.zextOrTrunc(Size.getBitWidth());
5126 Size *= ArraySize;
5127 }
5128
5129 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005130 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5131 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005132
5133 bool NeedsCollectableMemCpy =
5134 (BaseType->isRecordType() &&
5135 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5136
5137 if (NeedsCollectableMemCpy) {
5138 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005139 // Create a reference to the __builtin_objc_memmove_collectable function.
5140 LookupResult R(*this,
5141 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005142 Loc, LookupOrdinaryName);
5143 LookupName(R, TUScope, true);
5144
5145 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5146 if (!CollectableMemCpy) {
5147 // Something went horribly wrong earlier, and we will have
5148 // complained about it.
5149 Invalid = true;
5150 continue;
5151 }
5152
5153 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5154 CollectableMemCpy->getType(),
5155 Loc, 0).takeAs<Expr>();
5156 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5157 }
5158 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005159 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005160 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005161 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5162 LookupOrdinaryName);
5163 LookupName(R, TUScope, true);
5164
5165 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5166 if (!BuiltinMemCpy) {
5167 // Something went horribly wrong earlier, and we will have complained
5168 // about it.
5169 Invalid = true;
5170 continue;
5171 }
5172
5173 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5174 BuiltinMemCpy->getType(),
5175 Loc, 0).takeAs<Expr>();
5176 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5177 }
5178
John McCallca0408f2010-08-23 06:44:23 +00005179 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005180 CallArgs.push_back(To.takeAs<Expr>());
5181 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005182 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00005183 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005184 if (NeedsCollectableMemCpy)
5185 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005186 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005187 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005188 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005189 else
5190 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005191 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005192 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00005193 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005194
Douglas Gregor06a9f362010-05-01 20:49:11 +00005195 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5196 Statements.push_back(Call.takeAs<Expr>());
5197 continue;
5198 }
5199
5200 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005201 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005202 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005203 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005204 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005205 Diag(CurrentLocation, diag::note_member_synthesized_at)
5206 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5207 CopyAssignOperator->setInvalidDecl();
5208 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005209 }
5210
5211 // Success! Record the copy.
5212 Statements.push_back(Copy.takeAs<Stmt>());
5213 }
5214
5215 if (!Invalid) {
5216 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005217 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005218
John McCall60d7b3a2010-08-24 06:29:42 +00005219 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005220 if (Return.isInvalid())
5221 Invalid = true;
5222 else {
5223 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005224
5225 if (Trap.hasErrorOccurred()) {
5226 Diag(CurrentLocation, diag::note_member_synthesized_at)
5227 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5228 Invalid = true;
5229 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005230 }
5231 }
5232
5233 if (Invalid) {
5234 CopyAssignOperator->setInvalidDecl();
5235 return;
5236 }
5237
John McCall60d7b3a2010-08-24 06:29:42 +00005238 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005239 /*isStmtExpr=*/false);
5240 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5241 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005242}
5243
Douglas Gregor23c94db2010-07-02 17:43:08 +00005244CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5245 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005246 // C++ [class.copy]p4:
5247 // If the class definition does not explicitly declare a copy
5248 // constructor, one is declared implicitly.
5249
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005250 // C++ [class.copy]p5:
5251 // The implicitly-declared copy constructor for a class X will
5252 // have the form
5253 //
5254 // X::X(const X&)
5255 //
5256 // if
5257 bool HasConstCopyConstructor = true;
5258
5259 // -- each direct or virtual base class B of X has a copy
5260 // constructor whose first parameter is of type const B& or
5261 // const volatile B&, and
5262 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5263 BaseEnd = ClassDecl->bases_end();
5264 HasConstCopyConstructor && Base != BaseEnd;
5265 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005266 // Virtual bases are handled below.
5267 if (Base->isVirtual())
5268 continue;
5269
Douglas Gregor22584312010-07-02 23:41:54 +00005270 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005271 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005272 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5273 DeclareImplicitCopyConstructor(BaseClassDecl);
5274
Douglas Gregor598a8542010-07-01 18:27:03 +00005275 HasConstCopyConstructor
5276 = BaseClassDecl->hasConstCopyConstructor(Context);
5277 }
5278
5279 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5280 BaseEnd = ClassDecl->vbases_end();
5281 HasConstCopyConstructor && Base != BaseEnd;
5282 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005283 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005284 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005285 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5286 DeclareImplicitCopyConstructor(BaseClassDecl);
5287
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005288 HasConstCopyConstructor
5289 = BaseClassDecl->hasConstCopyConstructor(Context);
5290 }
5291
5292 // -- for all the nonstatic data members of X that are of a
5293 // class type M (or array thereof), each such class type
5294 // has a copy constructor whose first parameter is of type
5295 // const M& or const volatile M&.
5296 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5297 FieldEnd = ClassDecl->field_end();
5298 HasConstCopyConstructor && Field != FieldEnd;
5299 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005300 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005301 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005302 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005303 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005304 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5305 DeclareImplicitCopyConstructor(FieldClassDecl);
5306
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005307 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005308 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005309 }
5310 }
5311
5312 // Otherwise, the implicitly declared copy constructor will have
5313 // the form
5314 //
5315 // X::X(X&)
5316 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5317 QualType ArgType = ClassType;
5318 if (HasConstCopyConstructor)
5319 ArgType = ArgType.withConst();
5320 ArgType = Context.getLValueReferenceType(ArgType);
5321
Douglas Gregor0d405db2010-07-01 20:59:04 +00005322 // C++ [except.spec]p14:
5323 // An implicitly declared special member function (Clause 12) shall have an
5324 // exception-specification. [...]
5325 ImplicitExceptionSpecification ExceptSpec(Context);
5326 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5327 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5328 BaseEnd = ClassDecl->bases_end();
5329 Base != BaseEnd;
5330 ++Base) {
5331 // Virtual bases are handled below.
5332 if (Base->isVirtual())
5333 continue;
5334
Douglas Gregor22584312010-07-02 23:41:54 +00005335 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005336 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005337 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5338 DeclareImplicitCopyConstructor(BaseClassDecl);
5339
Douglas Gregor0d405db2010-07-01 20:59:04 +00005340 if (CXXConstructorDecl *CopyConstructor
5341 = BaseClassDecl->getCopyConstructor(Context, Quals))
5342 ExceptSpec.CalledDecl(CopyConstructor);
5343 }
5344 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5345 BaseEnd = ClassDecl->vbases_end();
5346 Base != BaseEnd;
5347 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005348 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005349 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005350 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5351 DeclareImplicitCopyConstructor(BaseClassDecl);
5352
Douglas Gregor0d405db2010-07-01 20:59:04 +00005353 if (CXXConstructorDecl *CopyConstructor
5354 = BaseClassDecl->getCopyConstructor(Context, Quals))
5355 ExceptSpec.CalledDecl(CopyConstructor);
5356 }
5357 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5358 FieldEnd = ClassDecl->field_end();
5359 Field != FieldEnd;
5360 ++Field) {
5361 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5362 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005363 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005364 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005365 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5366 DeclareImplicitCopyConstructor(FieldClassDecl);
5367
Douglas Gregor0d405db2010-07-01 20:59:04 +00005368 if (CXXConstructorDecl *CopyConstructor
5369 = FieldClassDecl->getCopyConstructor(Context, Quals))
5370 ExceptSpec.CalledDecl(CopyConstructor);
5371 }
5372 }
5373
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005374 // An implicitly-declared copy constructor is an inline public
5375 // member of its class.
5376 DeclarationName Name
5377 = Context.DeclarationNames.getCXXConstructorName(
5378 Context.getCanonicalType(ClassType));
Abramo Bagnara25777432010-08-11 22:01:17 +00005379 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005380 CXXConstructorDecl *CopyConstructor
Abramo Bagnara25777432010-08-11 22:01:17 +00005381 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005382 Context.getFunctionType(Context.VoidTy,
5383 &ArgType, 1,
5384 false, 0,
Douglas Gregor0d405db2010-07-01 20:59:04 +00005385 ExceptSpec.hasExceptionSpecification(),
5386 ExceptSpec.hasAnyExceptionSpecification(),
5387 ExceptSpec.size(),
5388 ExceptSpec.data(),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005389 FunctionType::ExtInfo()),
5390 /*TInfo=*/0,
5391 /*isExplicit=*/false,
5392 /*isInline=*/true,
5393 /*isImplicitlyDeclared=*/true);
5394 CopyConstructor->setAccess(AS_public);
5395 CopyConstructor->setImplicit();
5396 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5397
Douglas Gregor22584312010-07-02 23:41:54 +00005398 // Note that we have declared this constructor.
5399 ClassDecl->setDeclaredCopyConstructor(true);
5400 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5401
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005402 // Add the parameter to the constructor.
5403 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5404 ClassDecl->getLocation(),
5405 /*IdentifierInfo=*/0,
5406 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005407 SC_None,
5408 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005409 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00005410 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00005411 PushOnScopeChains(CopyConstructor, S, false);
5412 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005413
5414 return CopyConstructor;
5415}
5416
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005417void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5418 CXXConstructorDecl *CopyConstructor,
5419 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00005420 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00005421 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005422 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005423 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005424
Anders Carlsson63010a72010-04-23 16:24:12 +00005425 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005426 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005427
Douglas Gregor39957dc2010-05-01 15:04:51 +00005428 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005429 ErrorTrap Trap(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005430
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005431 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5432 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00005433 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005434 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00005435 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005436 } else {
5437 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5438 CopyConstructor->getLocation(),
5439 MultiStmtArg(*this, 0, 0),
5440 /*isStmtExpr=*/false)
5441 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00005442 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005443
5444 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005445}
5446
John McCall60d7b3a2010-08-24 06:29:42 +00005447ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005448Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00005449 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00005450 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005451 bool RequiresZeroInit,
John McCall7a1fad32010-08-24 07:32:53 +00005452 unsigned ConstructKind) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005453 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005454
Douglas Gregor2f599792010-04-02 18:24:57 +00005455 // C++0x [class.copy]p34:
5456 // When certain criteria are met, an implementation is allowed to
5457 // omit the copy/move construction of a class object, even if the
5458 // copy/move constructor and/or destructor for the object have
5459 // side effects. [...]
5460 // - when a temporary class object that has not been bound to a
5461 // reference (12.2) would be copied/moved to a class object
5462 // with the same cv-unqualified type, the copy/move operation
5463 // can be omitted by constructing the temporary object
5464 // directly into the target of the omitted copy/move
5465 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
5466 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
5467 Elidable = SubExpr->isTemporaryObject() &&
Douglas Gregorb8f7de92010-08-22 18:27:02 +00005468 ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor2f599792010-04-02 18:24:57 +00005469 Context.hasSameUnqualifiedType(SubExpr->getType(),
5470 Context.getTypeDeclType(Constructor->getParent()));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005471 }
Mike Stump1eb44332009-09-09 15:08:12 +00005472
5473 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005474 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlsson72e96fd2010-05-02 22:54:08 +00005475 ConstructKind);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005476}
5477
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005478/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5479/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005480ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005481Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5482 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00005483 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005484 bool RequiresZeroInit,
John McCall7a1fad32010-08-24 07:32:53 +00005485 unsigned ConstructKind) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00005486 unsigned NumExprs = ExprArgs.size();
5487 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005488
Douglas Gregor7edfb692009-11-23 12:27:39 +00005489 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005490 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00005491 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00005492 RequiresZeroInit,
5493 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind)));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005494}
5495
Mike Stump1eb44332009-09-09 15:08:12 +00005496bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005497 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00005498 MultiExprArg Exprs) {
John McCall60d7b3a2010-08-24 06:29:42 +00005499 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00005500 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00005501 move(Exprs), false, CXXConstructExpr::CK_Complete);
Anders Carlssonfe2de492009-08-25 05:18:00 +00005502 if (TempResult.isInvalid())
5503 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005504
Anders Carlssonda3f4e22009-08-25 05:12:04 +00005505 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005506 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00005507 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00005508 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00005509
Anders Carlssonfe2de492009-08-25 05:18:00 +00005510 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00005511}
5512
John McCall68c6c9a2010-02-02 09:10:11 +00005513void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5514 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00005515 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregorfb2db462010-05-22 17:12:29 +00005516 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00005517 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall4f9506a2010-02-02 08:45:54 +00005518 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00005519 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005520 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00005521 << VD->getDeclName()
5522 << VD->getType());
John McCall626e96e2010-08-01 20:20:59 +00005523
5524 if (!VD->isInvalidDecl() && VD->hasGlobalStorage())
5525 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall4f9506a2010-02-02 08:45:54 +00005526 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005527}
5528
Mike Stump1eb44332009-09-09 15:08:12 +00005529/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005530/// ActOnDeclarator, when a C++ direct initializer is present.
5531/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00005532void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005533 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00005534 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005535 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00005536 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005537
5538 // If there is no declaration, there was an error parsing it. Just ignore
5539 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005540 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005541 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005542
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005543 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5544 if (!VDecl) {
5545 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5546 RealDecl->setInvalidDecl();
5547 return;
5548 }
5549
Douglas Gregor83ddad32009-08-26 21:14:46 +00005550 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005551 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005552 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5553 //
5554 // Clients that want to distinguish between the two forms, can check for
5555 // direct initializer using VarDecl::hasCXXDirectInitializer().
5556 // A major benefit is that clients that don't particularly care about which
5557 // exactly form was it (like the CodeGen) can handle both cases without
5558 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005559
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005560 // C++ 8.5p11:
5561 // The form of initialization (using parentheses or '=') is generally
5562 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005563 // class type.
5564
Douglas Gregor4dffad62010-02-11 22:55:30 +00005565 if (!VDecl->getType()->isDependentType() &&
5566 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00005567 diag::err_typecheck_decl_incomplete_type)) {
5568 VDecl->setInvalidDecl();
5569 return;
5570 }
5571
Douglas Gregor90f93822009-12-22 22:17:25 +00005572 // The variable can not have an abstract class type.
5573 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5574 diag::err_abstract_type_in_decl,
5575 AbstractVariableType))
5576 VDecl->setInvalidDecl();
5577
Sebastian Redl31310a22010-02-01 20:16:42 +00005578 const VarDecl *Def;
5579 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00005580 Diag(VDecl->getLocation(), diag::err_redefinition)
5581 << VDecl->getDeclName();
5582 Diag(Def->getLocation(), diag::note_previous_definition);
5583 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005584 return;
5585 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00005586
Douglas Gregor3a91abf2010-08-24 05:27:49 +00005587 // C++ [class.static.data]p4
5588 // If a static data member is of const integral or const
5589 // enumeration type, its declaration in the class definition can
5590 // specify a constant-initializer which shall be an integral
5591 // constant expression (5.19). In that case, the member can appear
5592 // in integral constant expressions. The member shall still be
5593 // defined in a namespace scope if it is used in the program and the
5594 // namespace scope definition shall not contain an initializer.
5595 //
5596 // We already performed a redefinition check above, but for static
5597 // data members we also need to check whether there was an in-class
5598 // declaration with an initializer.
5599 const VarDecl* PrevInit = 0;
5600 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5601 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5602 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5603 return;
5604 }
5605
Douglas Gregor4dffad62010-02-11 22:55:30 +00005606 // If either the declaration has a dependent type or if any of the
5607 // expressions is type-dependent, we represent the initialization
5608 // via a ParenListExpr for later use during template instantiation.
5609 if (VDecl->getType()->isDependentType() ||
5610 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
5611 // Let clients know that initialization was done with a direct initializer.
5612 VDecl->setCXXDirectInitializer(true);
5613
5614 // Store the initialization expressions as a ParenListExpr.
5615 unsigned NumExprs = Exprs.size();
5616 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5617 (Expr **)Exprs.release(),
5618 NumExprs, RParenLoc));
5619 return;
5620 }
Douglas Gregor90f93822009-12-22 22:17:25 +00005621
5622 // Capture the variable that is being initialized and the style of
5623 // initialization.
5624 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5625
5626 // FIXME: Poor source location information.
5627 InitializationKind Kind
5628 = InitializationKind::CreateDirect(VDecl->getLocation(),
5629 LParenLoc, RParenLoc);
5630
5631 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00005632 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00005633 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00005634 if (Result.isInvalid()) {
5635 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005636 return;
5637 }
Douglas Gregor90f93822009-12-22 22:17:25 +00005638
John McCall9ae2f072010-08-23 23:25:46 +00005639 Result = MaybeCreateCXXExprWithTemporaries(Result.get());
Douglas Gregor838db382010-02-11 01:19:42 +00005640 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005641 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005642
John McCall4204f072010-08-02 21:13:48 +00005643 if (!VDecl->isInvalidDecl() &&
5644 !VDecl->getDeclContext()->isDependentContext() &&
Sebastian Redl36281c62010-09-08 04:46:19 +00005645 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() &&
John McCall4204f072010-08-02 21:13:48 +00005646 !VDecl->getInit()->isConstantInitializer(Context,
5647 VDecl->getType()->isReferenceType()))
5648 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5649 << VDecl->getInit()->getSourceRange();
5650
John McCall68c6c9a2010-02-02 09:10:11 +00005651 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5652 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005653}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00005654
Douglas Gregor39da0b82009-09-09 23:08:42 +00005655/// \brief Given a constructor and the set of arguments provided for the
5656/// constructor, convert the arguments and add any required default arguments
5657/// to form a proper call to this constructor.
5658///
5659/// \returns true if an error occurred, false otherwise.
5660bool
5661Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5662 MultiExprArg ArgsPtr,
5663 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00005664 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00005665 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5666 unsigned NumArgs = ArgsPtr.size();
5667 Expr **Args = (Expr **)ArgsPtr.get();
5668
5669 const FunctionProtoType *Proto
5670 = Constructor->getType()->getAs<FunctionProtoType>();
5671 assert(Proto && "Constructor without a prototype?");
5672 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00005673
5674 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005675 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00005676 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005677 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00005678 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005679
5680 VariadicCallType CallType =
5681 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5682 llvm::SmallVector<Expr *, 8> AllArgs;
5683 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5684 Proto, 0, Args, NumArgs, AllArgs,
5685 CallType);
5686 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5687 ConvertedArgs.push_back(AllArgs[i]);
5688 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00005689}
5690
Anders Carlsson20d45d22009-12-12 00:32:00 +00005691static inline bool
5692CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5693 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00005694 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00005695 if (isa<NamespaceDecl>(DC)) {
5696 return SemaRef.Diag(FnDecl->getLocation(),
5697 diag::err_operator_new_delete_declared_in_namespace)
5698 << FnDecl->getDeclName();
5699 }
5700
5701 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00005702 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005703 return SemaRef.Diag(FnDecl->getLocation(),
5704 diag::err_operator_new_delete_declared_static)
5705 << FnDecl->getDeclName();
5706 }
5707
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00005708 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00005709}
5710
Anders Carlsson156c78e2009-12-13 17:53:43 +00005711static inline bool
5712CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5713 CanQualType ExpectedResultType,
5714 CanQualType ExpectedFirstParamType,
5715 unsigned DependentParamTypeDiag,
5716 unsigned InvalidParamTypeDiag) {
5717 QualType ResultType =
5718 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5719
5720 // Check that the result type is not dependent.
5721 if (ResultType->isDependentType())
5722 return SemaRef.Diag(FnDecl->getLocation(),
5723 diag::err_operator_new_delete_dependent_result_type)
5724 << FnDecl->getDeclName() << ExpectedResultType;
5725
5726 // Check that the result type is what we expect.
5727 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5728 return SemaRef.Diag(FnDecl->getLocation(),
5729 diag::err_operator_new_delete_invalid_result_type)
5730 << FnDecl->getDeclName() << ExpectedResultType;
5731
5732 // A function template must have at least 2 parameters.
5733 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5734 return SemaRef.Diag(FnDecl->getLocation(),
5735 diag::err_operator_new_delete_template_too_few_parameters)
5736 << FnDecl->getDeclName();
5737
5738 // The function decl must have at least 1 parameter.
5739 if (FnDecl->getNumParams() == 0)
5740 return SemaRef.Diag(FnDecl->getLocation(),
5741 diag::err_operator_new_delete_too_few_parameters)
5742 << FnDecl->getDeclName();
5743
5744 // Check the the first parameter type is not dependent.
5745 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5746 if (FirstParamType->isDependentType())
5747 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5748 << FnDecl->getDeclName() << ExpectedFirstParamType;
5749
5750 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00005751 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00005752 ExpectedFirstParamType)
5753 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5754 << FnDecl->getDeclName() << ExpectedFirstParamType;
5755
5756 return false;
5757}
5758
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005759static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00005760CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005761 // C++ [basic.stc.dynamic.allocation]p1:
5762 // A program is ill-formed if an allocation function is declared in a
5763 // namespace scope other than global scope or declared static in global
5764 // scope.
5765 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5766 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00005767
5768 CanQualType SizeTy =
5769 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5770
5771 // C++ [basic.stc.dynamic.allocation]p1:
5772 // The return type shall be void*. The first parameter shall have type
5773 // std::size_t.
5774 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5775 SizeTy,
5776 diag::err_operator_new_dependent_param_type,
5777 diag::err_operator_new_param_type))
5778 return true;
5779
5780 // C++ [basic.stc.dynamic.allocation]p1:
5781 // The first parameter shall not have an associated default argument.
5782 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00005783 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00005784 diag::err_operator_new_default_arg)
5785 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5786
5787 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00005788}
5789
5790static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005791CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5792 // C++ [basic.stc.dynamic.deallocation]p1:
5793 // A program is ill-formed if deallocation functions are declared in a
5794 // namespace scope other than global scope or declared static in global
5795 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00005796 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5797 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005798
5799 // C++ [basic.stc.dynamic.deallocation]p2:
5800 // Each deallocation function shall return void and its first parameter
5801 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00005802 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5803 SemaRef.Context.VoidPtrTy,
5804 diag::err_operator_delete_dependent_param_type,
5805 diag::err_operator_delete_param_type))
5806 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005807
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005808 return false;
5809}
5810
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005811/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5812/// of this overloaded operator is well-formed. If so, returns false;
5813/// otherwise, emits appropriate diagnostics and returns true.
5814bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005815 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005816 "Expected an overloaded operator declaration");
5817
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005818 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5819
Mike Stump1eb44332009-09-09 15:08:12 +00005820 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005821 // The allocation and deallocation functions, operator new,
5822 // operator new[], operator delete and operator delete[], are
5823 // described completely in 3.7.3. The attributes and restrictions
5824 // found in the rest of this subclause do not apply to them unless
5825 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00005826 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005827 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00005828
Anders Carlssona3ccda52009-12-12 00:26:23 +00005829 if (Op == OO_New || Op == OO_Array_New)
5830 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005831
5832 // C++ [over.oper]p6:
5833 // An operator function shall either be a non-static member
5834 // function or be a non-member function and have at least one
5835 // parameter whose type is a class, a reference to a class, an
5836 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005837 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5838 if (MethodDecl->isStatic())
5839 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005840 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005841 } else {
5842 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005843 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5844 ParamEnd = FnDecl->param_end();
5845 Param != ParamEnd; ++Param) {
5846 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00005847 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5848 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005849 ClassOrEnumParam = true;
5850 break;
5851 }
5852 }
5853
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005854 if (!ClassOrEnumParam)
5855 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005856 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005857 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005858 }
5859
5860 // C++ [over.oper]p8:
5861 // An operator function cannot have default arguments (8.3.6),
5862 // except where explicitly stated below.
5863 //
Mike Stump1eb44332009-09-09 15:08:12 +00005864 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005865 // (C++ [over.call]p1).
5866 if (Op != OO_Call) {
5867 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5868 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00005869 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00005870 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00005871 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00005872 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005873 }
5874 }
5875
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005876 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5877 { false, false, false }
5878#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5879 , { Unary, Binary, MemberOnly }
5880#include "clang/Basic/OperatorKinds.def"
5881 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005882
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005883 bool CanBeUnaryOperator = OperatorUses[Op][0];
5884 bool CanBeBinaryOperator = OperatorUses[Op][1];
5885 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005886
5887 // C++ [over.oper]p8:
5888 // [...] Operator functions cannot have more or fewer parameters
5889 // than the number required for the corresponding operator, as
5890 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00005891 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005892 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005893 if (Op != OO_Call &&
5894 ((NumParams == 1 && !CanBeUnaryOperator) ||
5895 (NumParams == 2 && !CanBeBinaryOperator) ||
5896 (NumParams < 1) || (NumParams > 2))) {
5897 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00005898 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005899 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005900 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005901 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005902 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005903 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005904 assert(CanBeBinaryOperator &&
5905 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00005906 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005907 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005908
Chris Lattner416e46f2008-11-21 07:57:12 +00005909 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005910 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005911 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005912
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005913 // Overloaded operators other than operator() cannot be variadic.
5914 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00005915 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005916 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005917 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005918 }
5919
5920 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005921 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5922 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005923 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005924 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005925 }
5926
5927 // C++ [over.inc]p1:
5928 // The user-defined function called operator++ implements the
5929 // prefix and postfix ++ operator. If this function is a member
5930 // function with no parameters, or a non-member function with one
5931 // parameter of class or enumeration type, it defines the prefix
5932 // increment operator ++ for objects of that type. If the function
5933 // is a member function with one parameter (which shall be of type
5934 // int) or a non-member function with two parameters (the second
5935 // of which shall be of type int), it defines the postfix
5936 // increment operator ++ for objects of that type.
5937 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5938 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5939 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005940 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005941 ParamIsInt = BT->getKind() == BuiltinType::Int;
5942
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005943 if (!ParamIsInt)
5944 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005945 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005946 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005947 }
5948
Sebastian Redl64b45f72009-01-05 20:52:13 +00005949 // Notify the class if it got an assignment operator.
5950 if (Op == OO_Equal) {
5951 // Would have returned earlier otherwise.
5952 assert(isa<CXXMethodDecl>(FnDecl) &&
5953 "Overloaded = not member, but not filtered.");
5954 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5955 Method->getParent()->addedAssignmentOperator(Context, Method);
5956 }
5957
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005958 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005959}
Chris Lattner5a003a42008-12-17 07:09:26 +00005960
Sean Hunta6c058d2010-01-13 09:01:02 +00005961/// CheckLiteralOperatorDeclaration - Check whether the declaration
5962/// of this literal operator function is well-formed. If so, returns
5963/// false; otherwise, emits appropriate diagnostics and returns true.
5964bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5965 DeclContext *DC = FnDecl->getDeclContext();
5966 Decl::Kind Kind = DC->getDeclKind();
5967 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5968 Kind != Decl::LinkageSpec) {
5969 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5970 << FnDecl->getDeclName();
5971 return true;
5972 }
5973
5974 bool Valid = false;
5975
Sean Hunt216c2782010-04-07 23:11:06 +00005976 // template <char...> type operator "" name() is the only valid template
5977 // signature, and the only valid signature with no parameters.
5978 if (FnDecl->param_size() == 0) {
5979 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5980 // Must have only one template parameter
5981 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5982 if (Params->size() == 1) {
5983 NonTypeTemplateParmDecl *PmDecl =
5984 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00005985
Sean Hunt216c2782010-04-07 23:11:06 +00005986 // The template parameter must be a char parameter pack.
5987 // FIXME: This test will always fail because non-type parameter packs
5988 // have not been implemented.
5989 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5990 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5991 Valid = true;
5992 }
5993 }
5994 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00005995 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00005996 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5997
Sean Hunta6c058d2010-01-13 09:01:02 +00005998 QualType T = (*Param)->getType();
5999
Sean Hunt30019c02010-04-07 22:57:35 +00006000 // unsigned long long int, long double, and any character type are allowed
6001 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00006002 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6003 Context.hasSameType(T, Context.LongDoubleTy) ||
6004 Context.hasSameType(T, Context.CharTy) ||
6005 Context.hasSameType(T, Context.WCharTy) ||
6006 Context.hasSameType(T, Context.Char16Ty) ||
6007 Context.hasSameType(T, Context.Char32Ty)) {
6008 if (++Param == FnDecl->param_end())
6009 Valid = true;
6010 goto FinishedParams;
6011 }
6012
Sean Hunt30019c02010-04-07 22:57:35 +00006013 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00006014 const PointerType *PT = T->getAs<PointerType>();
6015 if (!PT)
6016 goto FinishedParams;
6017 T = PT->getPointeeType();
6018 if (!T.isConstQualified())
6019 goto FinishedParams;
6020 T = T.getUnqualifiedType();
6021
6022 // Move on to the second parameter;
6023 ++Param;
6024
6025 // If there is no second parameter, the first must be a const char *
6026 if (Param == FnDecl->param_end()) {
6027 if (Context.hasSameType(T, Context.CharTy))
6028 Valid = true;
6029 goto FinishedParams;
6030 }
6031
6032 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6033 // are allowed as the first parameter to a two-parameter function
6034 if (!(Context.hasSameType(T, Context.CharTy) ||
6035 Context.hasSameType(T, Context.WCharTy) ||
6036 Context.hasSameType(T, Context.Char16Ty) ||
6037 Context.hasSameType(T, Context.Char32Ty)))
6038 goto FinishedParams;
6039
6040 // The second and final parameter must be an std::size_t
6041 T = (*Param)->getType().getUnqualifiedType();
6042 if (Context.hasSameType(T, Context.getSizeType()) &&
6043 ++Param == FnDecl->param_end())
6044 Valid = true;
6045 }
6046
6047 // FIXME: This diagnostic is absolutely terrible.
6048FinishedParams:
6049 if (!Valid) {
6050 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6051 << FnDecl->getDeclName();
6052 return true;
6053 }
6054
6055 return false;
6056}
6057
Douglas Gregor074149e2009-01-05 19:45:36 +00006058/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6059/// linkage specification, including the language and (if present)
6060/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6061/// the location of the language string literal, which is provided
6062/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6063/// the '{' brace. Otherwise, this linkage specification does not
6064/// have any braces.
John McCalld226f652010-08-21 09:40:31 +00006065Decl *Sema::ActOnStartLinkageSpecification(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006066 SourceLocation ExternLoc,
6067 SourceLocation LangLoc,
Benjamin Kramerd5663812010-05-03 13:08:54 +00006068 llvm::StringRef Lang,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006069 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00006070 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006071 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006072 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006073 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006074 Language = LinkageSpecDecl::lang_cxx;
6075 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00006076 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00006077 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006078 }
Mike Stump1eb44332009-09-09 15:08:12 +00006079
Chris Lattnercc98eac2008-12-17 07:13:27 +00006080 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00006081
Douglas Gregor074149e2009-01-05 19:45:36 +00006082 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00006083 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00006084 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006085 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00006086 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00006087 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006088}
6089
Abramo Bagnara35f9a192010-07-30 16:47:02 +00006090/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006091/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6092/// valid, it's the position of the closing '}' brace in a linkage
6093/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006094Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6095 Decl *LinkageSpec,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006096 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00006097 if (LinkageSpec)
6098 PopDeclContext();
6099 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006100}
6101
Douglas Gregord308e622009-05-18 20:51:54 +00006102/// \brief Perform semantic analysis for the variable declaration that
6103/// occurs within a C++ catch clause, returning the newly-created
6104/// variable.
Douglas Gregor83cb9422010-09-09 17:09:21 +00006105VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00006106 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006107 IdentifierInfo *Name,
Douglas Gregor83cb9422010-09-09 17:09:21 +00006108 SourceLocation Loc) {
Douglas Gregord308e622009-05-18 20:51:54 +00006109 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00006110 QualType ExDeclType = TInfo->getType();
6111
Sebastian Redl4b07b292008-12-22 19:15:10 +00006112 // Arrays and functions decay.
6113 if (ExDeclType->isArrayType())
6114 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6115 else if (ExDeclType->isFunctionType())
6116 ExDeclType = Context.getPointerType(ExDeclType);
6117
6118 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6119 // The exception-declaration shall not denote a pointer or reference to an
6120 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006121 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006122 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00006123 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006124 Invalid = true;
6125 }
Douglas Gregord308e622009-05-18 20:51:54 +00006126
Douglas Gregora2762912010-03-08 01:47:36 +00006127 // GCC allows catching pointers and references to incomplete types
6128 // as an extension; so do we, but we warn by default.
6129
Sebastian Redl4b07b292008-12-22 19:15:10 +00006130 QualType BaseType = ExDeclType;
6131 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006132 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006133 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006134 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006135 BaseType = Ptr->getPointeeType();
6136 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006137 DK = diag::ext_catch_incomplete_ptr;
6138 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006139 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006140 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006141 BaseType = Ref->getPointeeType();
6142 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006143 DK = diag::ext_catch_incomplete_ref;
6144 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006145 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006146 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006147 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6148 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006149 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006150
Mike Stump1eb44332009-09-09 15:08:12 +00006151 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006152 RequireNonAbstractType(Loc, ExDeclType,
6153 diag::err_abstract_type_in_decl,
6154 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006155 Invalid = true;
6156
John McCall5a180392010-07-24 00:37:23 +00006157 // Only the non-fragile NeXT runtime currently supports C++ catches
6158 // of ObjC types, and no runtime supports catching ObjC types by value.
6159 if (!Invalid && getLangOptions().ObjC1) {
6160 QualType T = ExDeclType;
6161 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6162 T = RT->getPointeeType();
6163
6164 if (T->isObjCObjectType()) {
6165 Diag(Loc, diag::err_objc_object_catch);
6166 Invalid = true;
6167 } else if (T->isObjCObjectPointerType()) {
6168 if (!getLangOptions().NeXTRuntime) {
6169 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6170 Invalid = true;
6171 } else if (!getLangOptions().ObjCNonFragileABI) {
6172 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6173 Invalid = true;
6174 }
6175 }
6176 }
6177
Mike Stump1eb44332009-09-09 15:08:12 +00006178 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalld931b082010-08-26 03:08:43 +00006179 Name, ExDeclType, TInfo, SC_None,
6180 SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006181 ExDecl->setExceptionVariable(true);
6182
Douglas Gregor6d182892010-03-05 23:38:39 +00006183 if (!Invalid) {
6184 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6185 // C++ [except.handle]p16:
6186 // The object declared in an exception-declaration or, if the
6187 // exception-declaration does not specify a name, a temporary (12.2) is
6188 // copy-initialized (8.5) from the exception object. [...]
6189 // The object is destroyed when the handler exits, after the destruction
6190 // of any automatic objects initialized within the handler.
6191 //
6192 // We just pretend to initialize the object with itself, then make sure
6193 // it can be destroyed later.
6194 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6195 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
6196 Loc, ExDeclType, 0);
6197 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6198 SourceLocation());
6199 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00006200 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00006201 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6d182892010-03-05 23:38:39 +00006202 if (Result.isInvalid())
6203 Invalid = true;
6204 else
6205 FinalizeVarWithDestructor(ExDecl, RecordTy);
6206 }
6207 }
6208
Douglas Gregord308e622009-05-18 20:51:54 +00006209 if (Invalid)
6210 ExDecl->setInvalidDecl();
6211
6212 return ExDecl;
6213}
6214
6215/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6216/// handler.
John McCalld226f652010-08-21 09:40:31 +00006217Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006218 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6219 QualType ExDeclType = TInfo->getType();
Douglas Gregord308e622009-05-18 20:51:54 +00006220
6221 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00006222 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006223 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006224 LookupOrdinaryName,
6225 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006226 // The scope should be freshly made just for us. There is just no way
6227 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006228 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006229 if (PrevDecl->isTemplateParameter()) {
6230 // Maybe we will complain about the shadowed template parameter.
6231 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006232 }
6233 }
6234
Chris Lattnereaaebc72009-04-25 08:06:05 +00006235 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006236 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6237 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006238 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006239 }
6240
Douglas Gregor83cb9422010-09-09 17:09:21 +00006241 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006242 D.getIdentifier(),
Douglas Gregor83cb9422010-09-09 17:09:21 +00006243 D.getIdentifierLoc());
Douglas Gregord308e622009-05-18 20:51:54 +00006244
Chris Lattnereaaebc72009-04-25 08:06:05 +00006245 if (Invalid)
6246 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00006247
Sebastian Redl4b07b292008-12-22 19:15:10 +00006248 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006249 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00006250 PushOnScopeChains(ExDecl, S);
6251 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006252 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006253
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006254 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00006255 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006256}
Anders Carlssonfb311762009-03-14 00:25:26 +00006257
John McCalld226f652010-08-21 09:40:31 +00006258Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00006259 Expr *AssertExpr,
6260 Expr *AssertMessageExpr_) {
6261 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00006262
Anders Carlssonc3082412009-03-14 00:33:21 +00006263 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6264 llvm::APSInt Value(32);
6265 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6266 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6267 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006268 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00006269 }
Anders Carlssonfb311762009-03-14 00:25:26 +00006270
Anders Carlssonc3082412009-03-14 00:33:21 +00006271 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00006272 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00006273 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00006274 }
6275 }
Mike Stump1eb44332009-09-09 15:08:12 +00006276
Mike Stump1eb44332009-09-09 15:08:12 +00006277 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00006278 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00006279
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006280 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00006281 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00006282}
Sebastian Redl50de12f2009-03-24 22:27:57 +00006283
Douglas Gregor1d869352010-04-07 16:53:43 +00006284/// \brief Perform semantic analysis of the given friend type declaration.
6285///
6286/// \returns A friend declaration that.
6287FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6288 TypeSourceInfo *TSInfo) {
6289 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6290
6291 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006292 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00006293
Douglas Gregor06245bf2010-04-07 17:57:12 +00006294 if (!getLangOptions().CPlusPlus0x) {
6295 // C++03 [class.friend]p2:
6296 // An elaborated-type-specifier shall be used in a friend declaration
6297 // for a class.*
6298 //
6299 // * The class-key of the elaborated-type-specifier is required.
6300 if (!ActiveTemplateInstantiations.empty()) {
6301 // Do not complain about the form of friend template types during
6302 // template instantiation; we will already have complained when the
6303 // template was declared.
6304 } else if (!T->isElaboratedTypeSpecifier()) {
6305 // If we evaluated the type to a record type, suggest putting
6306 // a tag in front.
6307 if (const RecordType *RT = T->getAs<RecordType>()) {
6308 RecordDecl *RD = RT->getDecl();
6309
6310 std::string InsertionText = std::string(" ") + RD->getKindName();
6311
6312 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6313 << (unsigned) RD->getTagKind()
6314 << T
6315 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6316 InsertionText);
6317 } else {
6318 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6319 << T
6320 << SourceRange(FriendLoc, TypeRange.getEnd());
6321 }
6322 } else if (T->getAs<EnumType>()) {
6323 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00006324 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00006325 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00006326 }
6327 }
6328
Douglas Gregor06245bf2010-04-07 17:57:12 +00006329 // C++0x [class.friend]p3:
6330 // If the type specifier in a friend declaration designates a (possibly
6331 // cv-qualified) class type, that class is declared as a friend; otherwise,
6332 // the friend declaration is ignored.
6333
6334 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6335 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00006336
6337 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6338}
6339
John McCalldd4a3b02009-09-16 22:47:08 +00006340/// Handle a friend type declaration. This works in tandem with
6341/// ActOnTag.
6342///
6343/// Notes on friend class templates:
6344///
6345/// We generally treat friend class declarations as if they were
6346/// declaring a class. So, for example, the elaborated type specifier
6347/// in a friend declaration is required to obey the restrictions of a
6348/// class-head (i.e. no typedefs in the scope chain), template
6349/// parameters are required to match up with simple template-ids, &c.
6350/// However, unlike when declaring a template specialization, it's
6351/// okay to refer to a template specialization without an empty
6352/// template parameter declaration, e.g.
6353/// friend class A<T>::B<unsigned>;
6354/// We permit this as a special case; if there are any template
6355/// parameters present at all, require proper matching, i.e.
6356/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00006357Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00006358 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00006359 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00006360
6361 assert(DS.isFriendSpecified());
6362 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6363
John McCalldd4a3b02009-09-16 22:47:08 +00006364 // Try to convert the decl specifier to a type. This works for
6365 // friend templates because ActOnTag never produces a ClassTemplateDecl
6366 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00006367 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00006368 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6369 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00006370 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00006371 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006372
John McCalldd4a3b02009-09-16 22:47:08 +00006373 // This is definitely an error in C++98. It's probably meant to
6374 // be forbidden in C++0x, too, but the specification is just
6375 // poorly written.
6376 //
6377 // The problem is with declarations like the following:
6378 // template <T> friend A<T>::foo;
6379 // where deciding whether a class C is a friend or not now hinges
6380 // on whether there exists an instantiation of A that causes
6381 // 'foo' to equal C. There are restrictions on class-heads
6382 // (which we declare (by fiat) elaborated friend declarations to
6383 // be) that makes this tractable.
6384 //
6385 // FIXME: handle "template <> friend class A<T>;", which
6386 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00006387 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00006388 Diag(Loc, diag::err_tagless_friend_type_template)
6389 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006390 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00006391 }
Douglas Gregor1d869352010-04-07 16:53:43 +00006392
John McCall02cace72009-08-28 07:59:38 +00006393 // C++98 [class.friend]p1: A friend of a class is a function
6394 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00006395 // This is fixed in DR77, which just barely didn't make the C++03
6396 // deadline. It's also a very silly restriction that seriously
6397 // affects inner classes and which nobody else seems to implement;
6398 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00006399 //
6400 // But note that we could warn about it: it's always useless to
6401 // friend one of your own members (it's not, however, worthless to
6402 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00006403
John McCalldd4a3b02009-09-16 22:47:08 +00006404 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00006405 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00006406 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00006407 NumTempParamLists,
John McCalldd4a3b02009-09-16 22:47:08 +00006408 (TemplateParameterList**) TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00006409 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00006410 DS.getFriendSpecLoc());
6411 else
Douglas Gregor1d869352010-04-07 16:53:43 +00006412 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6413
6414 if (!D)
John McCalld226f652010-08-21 09:40:31 +00006415 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00006416
John McCalldd4a3b02009-09-16 22:47:08 +00006417 D->setAccess(AS_public);
6418 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00006419
John McCalld226f652010-08-21 09:40:31 +00006420 return D;
John McCall02cace72009-08-28 07:59:38 +00006421}
6422
John McCalld226f652010-08-21 09:40:31 +00006423Decl *Sema::ActOnFriendFunctionDecl(Scope *S,
6424 Declarator &D,
6425 bool IsDefinition,
John McCallbbbcdd92009-09-11 21:02:39 +00006426 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00006427 const DeclSpec &DS = D.getDeclSpec();
6428
6429 assert(DS.isFriendSpecified());
6430 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6431
6432 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00006433 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6434 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00006435
6436 // C++ [class.friend]p1
6437 // A friend of a class is a function or class....
6438 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00006439 // It *doesn't* see through dependent types, which is correct
6440 // according to [temp.arg.type]p3:
6441 // If a declaration acquires a function type through a
6442 // type dependent on a template-parameter and this causes
6443 // a declaration that does not use the syntactic form of a
6444 // function declarator to have a function type, the program
6445 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00006446 if (!T->isFunctionType()) {
6447 Diag(Loc, diag::err_unexpected_friend);
6448
6449 // It might be worthwhile to try to recover by creating an
6450 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00006451 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006452 }
6453
6454 // C++ [namespace.memdef]p3
6455 // - If a friend declaration in a non-local class first declares a
6456 // class or function, the friend class or function is a member
6457 // of the innermost enclosing namespace.
6458 // - The name of the friend is not found by simple name lookup
6459 // until a matching declaration is provided in that namespace
6460 // scope (either before or after the class declaration granting
6461 // friendship).
6462 // - If a friend function is called, its name may be found by the
6463 // name lookup that considers functions from namespaces and
6464 // classes associated with the types of the function arguments.
6465 // - When looking for a prior declaration of a class or a function
6466 // declared as a friend, scopes outside the innermost enclosing
6467 // namespace scope are not considered.
6468
John McCall02cace72009-08-28 07:59:38 +00006469 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00006470 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6471 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00006472 assert(Name);
6473
John McCall67d1a672009-08-06 02:15:43 +00006474 // The context we found the declaration in, or in which we should
6475 // create the declaration.
6476 DeclContext *DC;
6477
6478 // FIXME: handle local classes
6479
6480 // Recover from invalid scope qualifiers as if they just weren't there.
Abramo Bagnara25777432010-08-11 22:01:17 +00006481 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00006482 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00006483 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
6484 DC = computeDeclContext(ScopeQual);
6485
6486 // FIXME: handle dependent contexts
John McCalld226f652010-08-21 09:40:31 +00006487 if (!DC) return 0;
6488 if (RequireCompleteDeclContext(ScopeQual, DC)) return 0;
John McCall67d1a672009-08-06 02:15:43 +00006489
John McCall68263142009-11-18 22:49:29 +00006490 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00006491
John McCall9da9cdf2010-05-28 01:41:47 +00006492 // Ignore things found implicitly in the wrong scope.
John McCall67d1a672009-08-06 02:15:43 +00006493 // TODO: better diagnostics for this case. Suggesting the right
6494 // qualified scope would be nice...
John McCall9da9cdf2010-05-28 01:41:47 +00006495 LookupResult::Filter F = Previous.makeFilter();
6496 while (F.hasNext()) {
6497 NamedDecl *D = F.next();
Sebastian Redl7a126a42010-08-31 00:36:30 +00006498 if (!DC->InEnclosingNamespaceSetOf(
6499 D->getDeclContext()->getRedeclContext()))
John McCall9da9cdf2010-05-28 01:41:47 +00006500 F.erase();
6501 }
6502 F.done();
6503
6504 if (Previous.empty()) {
John McCall02cace72009-08-28 07:59:38 +00006505 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00006506 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
John McCalld226f652010-08-21 09:40:31 +00006507 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006508 }
6509
6510 // C++ [class.friend]p1: A friend of a class is a function or
6511 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00006512 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00006513 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6514
John McCall67d1a672009-08-06 02:15:43 +00006515 // Otherwise walk out to the nearest namespace scope looking for matches.
6516 } else {
6517 // TODO: handle local class contexts.
6518
6519 DC = CurContext;
6520 while (true) {
6521 // Skip class contexts. If someone can cite chapter and verse
6522 // for this behavior, that would be nice --- it's what GCC and
6523 // EDG do, and it seems like a reasonable intent, but the spec
6524 // really only says that checks for unqualified existing
6525 // declarations should stop at the nearest enclosing namespace,
6526 // not that they should only consider the nearest enclosing
6527 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00006528 while (DC->isRecord())
6529 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00006530
John McCall68263142009-11-18 22:49:29 +00006531 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00006532
6533 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00006534 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00006535 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00006536
John McCall67d1a672009-08-06 02:15:43 +00006537 if (DC->isFileContext()) break;
6538 DC = DC->getParent();
6539 }
6540
6541 // C++ [class.friend]p1: A friend of a class is a function or
6542 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00006543 // C++0x changes this for both friend types and functions.
6544 // Most C++ 98 compilers do seem to give an error here, so
6545 // we do, too.
John McCall68263142009-11-18 22:49:29 +00006546 if (!Previous.empty() && DC->Equals(CurContext)
6547 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00006548 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6549 }
6550
Douglas Gregor182ddf02009-09-28 00:08:27 +00006551 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00006552 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006553 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6554 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6555 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00006556 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006557 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6558 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00006559 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006560 }
John McCall67d1a672009-08-06 02:15:43 +00006561 }
6562
Douglas Gregor182ddf02009-09-28 00:08:27 +00006563 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00006564 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00006565 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00006566 IsDefinition,
6567 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00006568 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00006569
Douglas Gregor182ddf02009-09-28 00:08:27 +00006570 assert(ND->getDeclContext() == DC);
6571 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00006572
John McCallab88d972009-08-31 22:39:49 +00006573 // Add the function declaration to the appropriate lookup tables,
6574 // adjusting the redeclarations list as necessary. We don't
6575 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00006576 //
John McCallab88d972009-08-31 22:39:49 +00006577 // Also update the scope-based lookup if the target context's
6578 // lookup context is in lexical scope.
6579 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006580 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00006581 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006582 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00006583 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006584 }
John McCall02cace72009-08-28 07:59:38 +00006585
6586 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00006587 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00006588 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00006589 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00006590 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00006591
John McCalld226f652010-08-21 09:40:31 +00006592 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00006593}
6594
John McCalld226f652010-08-21 09:40:31 +00006595void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6596 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00006597
Sebastian Redl50de12f2009-03-24 22:27:57 +00006598 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6599 if (!Fn) {
6600 Diag(DelLoc, diag::err_deleted_non_function);
6601 return;
6602 }
6603 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6604 Diag(DelLoc, diag::err_deleted_decl_not_first);
6605 Diag(Prev->getLocation(), diag::note_previous_declaration);
6606 // If the declaration wasn't the first, we delete the function anyway for
6607 // recovery.
6608 }
6609 Fn->setDeleted();
6610}
Sebastian Redl13e88542009-04-27 21:33:24 +00006611
6612static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6613 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6614 ++CI) {
6615 Stmt *SubStmt = *CI;
6616 if (!SubStmt)
6617 continue;
6618 if (isa<ReturnStmt>(SubStmt))
6619 Self.Diag(SubStmt->getSourceRange().getBegin(),
6620 diag::err_return_in_constructor_handler);
6621 if (!isa<Expr>(SubStmt))
6622 SearchForReturnInStmt(Self, SubStmt);
6623 }
6624}
6625
6626void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6627 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6628 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6629 SearchForReturnInStmt(*this, Handler);
6630 }
6631}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006632
Mike Stump1eb44332009-09-09 15:08:12 +00006633bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006634 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00006635 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6636 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006637
Chandler Carruth73857792010-02-15 11:53:20 +00006638 if (Context.hasSameType(NewTy, OldTy) ||
6639 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006640 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006641
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006642 // Check if the return types are covariant
6643 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00006644
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006645 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006646 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6647 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006648 NewClassTy = NewPT->getPointeeType();
6649 OldClassTy = OldPT->getPointeeType();
6650 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006651 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6652 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6653 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6654 NewClassTy = NewRT->getPointeeType();
6655 OldClassTy = OldRT->getPointeeType();
6656 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006657 }
6658 }
Mike Stump1eb44332009-09-09 15:08:12 +00006659
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006660 // The return types aren't either both pointers or references to a class type.
6661 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006662 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006663 diag::err_different_return_type_for_overriding_virtual_function)
6664 << New->getDeclName() << NewTy << OldTy;
6665 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00006666
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006667 return true;
6668 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006669
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006670 // C++ [class.virtual]p6:
6671 // If the return type of D::f differs from the return type of B::f, the
6672 // class type in the return type of D::f shall be complete at the point of
6673 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00006674 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6675 if (!RT->isBeingDefined() &&
6676 RequireCompleteType(New->getLocation(), NewClassTy,
6677 PDiag(diag::err_covariant_return_incomplete)
6678 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006679 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00006680 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006681
Douglas Gregora4923eb2009-11-16 21:35:15 +00006682 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006683 // Check if the new class derives from the old class.
6684 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6685 Diag(New->getLocation(),
6686 diag::err_covariant_return_not_derived)
6687 << New->getDeclName() << NewTy << OldTy;
6688 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6689 return true;
6690 }
Mike Stump1eb44332009-09-09 15:08:12 +00006691
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006692 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00006693 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00006694 diag::err_covariant_return_inaccessible_base,
6695 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6696 // FIXME: Should this point to the return type?
6697 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006698 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6699 return true;
6700 }
6701 }
Mike Stump1eb44332009-09-09 15:08:12 +00006702
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006703 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006704 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006705 Diag(New->getLocation(),
6706 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006707 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006708 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6709 return true;
6710 };
Mike Stump1eb44332009-09-09 15:08:12 +00006711
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006712
6713 // The new class type must have the same or less qualifiers as the old type.
6714 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6715 Diag(New->getLocation(),
6716 diag::err_covariant_return_type_class_type_more_qualified)
6717 << New->getDeclName() << NewTy << OldTy;
6718 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6719 return true;
6720 };
Mike Stump1eb44332009-09-09 15:08:12 +00006721
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006722 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006723}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006724
Sean Huntbbd37c62009-11-21 08:43:09 +00006725bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6726 const CXXMethodDecl *Old)
6727{
6728 if (Old->hasAttr<FinalAttr>()) {
6729 Diag(New->getLocation(), diag::err_final_function_overridden)
6730 << New->getDeclName();
6731 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6732 return true;
6733 }
6734
6735 return false;
6736}
6737
Douglas Gregor4ba31362009-12-01 17:24:26 +00006738/// \brief Mark the given method pure.
6739///
6740/// \param Method the method to be marked pure.
6741///
6742/// \param InitRange the source range that covers the "0" initializer.
6743bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6744 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6745 Method->setPure();
6746
6747 // A class is abstract if at least one function is pure virtual.
6748 Method->getParent()->setAbstract(true);
6749 return false;
6750 }
6751
6752 if (!Method->isInvalidDecl())
6753 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6754 << Method->getDeclName() << InitRange;
6755 return true;
6756}
6757
John McCall731ad842009-12-19 09:28:58 +00006758/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6759/// an initializer for the out-of-line declaration 'Dcl'. The scope
6760/// is a fresh scope pushed for just this purpose.
6761///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006762/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6763/// static data member of class X, names should be looked up in the scope of
6764/// class X.
John McCalld226f652010-08-21 09:40:31 +00006765void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006766 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006767 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006768
John McCall731ad842009-12-19 09:28:58 +00006769 // We should only get called for declarations with scope specifiers, like:
6770 // int foo::bar;
6771 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006772 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006773}
6774
6775/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00006776/// initializer for the out-of-line declaration 'D'.
6777void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006778 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006779 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006780
John McCall731ad842009-12-19 09:28:58 +00006781 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006782 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006783}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006784
6785/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6786/// C++ if/switch/while/for statement.
6787/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00006788DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006789 // C++ 6.4p2:
6790 // The declarator shall not specify a function or an array.
6791 // The type-specifier-seq shall not contain typedef and shall not declare a
6792 // new class or enumeration.
6793 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6794 "Parser allowed 'typedef' as storage class of condition decl.");
6795
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006796 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00006797 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6798 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006799
6800 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6801 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6802 // would be created and CXXConditionDeclExpr wants a VarDecl.
6803 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6804 << D.getSourceRange();
6805 return DeclResult();
6806 } else if (OwnedTag && OwnedTag->isDefinition()) {
6807 // The type-specifier-seq shall not declare a new class or enumeration.
6808 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6809 }
6810
John McCalld226f652010-08-21 09:40:31 +00006811 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006812 if (!Dcl)
6813 return DeclResult();
6814
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006815 return Dcl;
6816}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006817
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006818void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6819 bool DefinitionRequired) {
6820 // Ignore any vtable uses in unevaluated operands or for classes that do
6821 // not have a vtable.
6822 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6823 CurContext->isDependentContext() ||
6824 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00006825 return;
6826
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006827 // Try to insert this class into the map.
6828 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6829 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6830 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6831 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00006832 // If we already had an entry, check to see if we are promoting this vtable
6833 // to required a definition. If so, we need to reappend to the VTableUses
6834 // list, since we may have already processed the first entry.
6835 if (DefinitionRequired && !Pos.first->second) {
6836 Pos.first->second = true;
6837 } else {
6838 // Otherwise, we can early exit.
6839 return;
6840 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006841 }
6842
6843 // Local classes need to have their virtual members marked
6844 // immediately. For all other classes, we mark their virtual members
6845 // at the end of the translation unit.
6846 if (Class->isLocalClass())
6847 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00006848 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006849 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00006850}
6851
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006852bool Sema::DefineUsedVTables() {
6853 // If any dynamic classes have their key function defined within
6854 // this translation unit, then those vtables are considered "used" and must
6855 // be emitted.
6856 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6857 if (const CXXMethodDecl *KeyFunction
6858 = Context.getKeyFunction(DynamicClasses[I])) {
6859 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006860 if (KeyFunction->hasBody(Definition))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006861 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6862 }
6863 }
6864
6865 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00006866 return false;
6867
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006868 // Note: The VTableUses vector could grow as a result of marking
6869 // the members of a class as "used", so we check the size each
6870 // time through the loop and prefer indices (with are stable) to
6871 // iterators (which are not).
6872 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00006873 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006874 if (!Class)
6875 continue;
6876
6877 SourceLocation Loc = VTableUses[I].second;
6878
6879 // If this class has a key function, but that key function is
6880 // defined in another translation unit, we don't need to emit the
6881 // vtable even though we're using it.
6882 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006883 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006884 switch (KeyFunction->getTemplateSpecializationKind()) {
6885 case TSK_Undeclared:
6886 case TSK_ExplicitSpecialization:
6887 case TSK_ExplicitInstantiationDeclaration:
6888 // The key function is in another translation unit.
6889 continue;
6890
6891 case TSK_ExplicitInstantiationDefinition:
6892 case TSK_ImplicitInstantiation:
6893 // We will be instantiating the key function.
6894 break;
6895 }
6896 } else if (!KeyFunction) {
6897 // If we have a class with no key function that is the subject
6898 // of an explicit instantiation declaration, suppress the
6899 // vtable; it will live with the explicit instantiation
6900 // definition.
6901 bool IsExplicitInstantiationDeclaration
6902 = Class->getTemplateSpecializationKind()
6903 == TSK_ExplicitInstantiationDeclaration;
6904 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6905 REnd = Class->redecls_end();
6906 R != REnd; ++R) {
6907 TemplateSpecializationKind TSK
6908 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6909 if (TSK == TSK_ExplicitInstantiationDeclaration)
6910 IsExplicitInstantiationDeclaration = true;
6911 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6912 IsExplicitInstantiationDeclaration = false;
6913 break;
6914 }
6915 }
6916
6917 if (IsExplicitInstantiationDeclaration)
6918 continue;
6919 }
6920
6921 // Mark all of the virtual members of this class as referenced, so
6922 // that we can build a vtable. Then, tell the AST consumer that a
6923 // vtable for this class is required.
6924 MarkVirtualMembersReferenced(Loc, Class);
6925 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6926 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6927
6928 // Optionally warn if we're emitting a weak vtable.
6929 if (Class->getLinkage() == ExternalLinkage &&
6930 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006931 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006932 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6933 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006934 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006935 VTableUses.clear();
6936
Anders Carlssond6a637f2009-12-07 08:24:59 +00006937 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006938}
Anders Carlssond6a637f2009-12-07 08:24:59 +00006939
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006940void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6941 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00006942 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6943 e = RD->method_end(); i != e; ++i) {
6944 CXXMethodDecl *MD = *i;
6945
6946 // C++ [basic.def.odr]p2:
6947 // [...] A virtual member function is used if it is not pure. [...]
6948 if (MD->isVirtual() && !MD->isPure())
6949 MarkDeclarationReferenced(Loc, MD);
6950 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006951
6952 // Only classes that have virtual bases need a VTT.
6953 if (RD->getNumVBases() == 0)
6954 return;
6955
6956 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6957 e = RD->bases_end(); i != e; ++i) {
6958 const CXXRecordDecl *Base =
6959 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006960 if (Base->getNumVBases() == 0)
6961 continue;
6962 MarkVirtualMembersReferenced(Loc, Base);
6963 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00006964}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006965
6966/// SetIvarInitializers - This routine builds initialization ASTs for the
6967/// Objective-C implementation whose ivars need be initialized.
6968void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6969 if (!getLangOptions().CPlusPlus)
6970 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00006971 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006972 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6973 CollectIvarsToConstructOrDestruct(OID, ivars);
6974 if (ivars.empty())
6975 return;
6976 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6977 for (unsigned i = 0; i < ivars.size(); i++) {
6978 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00006979 if (Field->isInvalidDecl())
6980 continue;
6981
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006982 CXXBaseOrMemberInitializer *Member;
6983 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6984 InitializationKind InitKind =
6985 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6986
6987 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00006988 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00006989 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00006990 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006991 // Note, MemberInit could actually come back empty if no initialization
6992 // is required (e.g., because it would call a trivial default constructor)
6993 if (!MemberInit.get() || MemberInit.isInvalid())
6994 continue;
6995
6996 Member =
6997 new (Context) CXXBaseOrMemberInitializer(Context,
6998 Field, SourceLocation(),
6999 SourceLocation(),
7000 MemberInit.takeAs<Expr>(),
7001 SourceLocation());
7002 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007003
7004 // Be sure that the destructor is accessible and is marked as referenced.
7005 if (const RecordType *RecordTy
7006 = Context.getBaseElementType(Field->getType())
7007 ->getAs<RecordType>()) {
7008 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00007009 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00007010 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7011 CheckDestructorAccess(Field->getLocation(), Destructor,
7012 PDiag(diag::err_access_dtor_ivar)
7013 << Context.getBaseElementType(Field->getType()));
7014 }
7015 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00007016 }
7017 ObjCImplementation->setIvarInitializers(Context,
7018 AllToInit.data(), AllToInit.size());
7019 }
7020}