blob: 20d1177a21e7d7c32f3aa5d399aa9db22f37d59c [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.
Mike Stump1eb44332009-09-09 15:08:12 +0000587Sema::BaseResult
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) {
961 if (BitWidth) DeleteExpr(BitWidth);
John McCalld226f652010-08-21 09:40:31 +0000962 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +0000963 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000964
965 // Non-instance-fields can't have a bitfield.
966 if (BitWidth) {
967 if (Member->isInvalidDecl()) {
968 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000969 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000970 // C++ 9.6p3: A bit-field shall not be a static member.
971 // "static member 'A' cannot be a bit-field"
972 Diag(Loc, diag::err_static_not_bitfield)
973 << Name << BitWidth->getSourceRange();
974 } else if (isa<TypedefDecl>(Member)) {
975 // "typedef member 'x' cannot be a bit-field"
976 Diag(Loc, diag::err_typedef_not_bitfield)
977 << Name << BitWidth->getSourceRange();
978 } else {
979 // A function typedef ("typedef int f(); f a;").
980 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
981 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000982 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000983 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000984 }
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Chris Lattner8b963ef2009-03-05 23:01:03 +0000986 DeleteExpr(BitWidth);
987 BitWidth = 0;
988 Member->setInvalidDecl();
989 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000990
991 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Douglas Gregor37b372b2009-08-20 22:52:58 +0000993 // If we have declared a member function template, set the access of the
994 // templated declaration as well.
995 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
996 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000997 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000998
Douglas Gregor10bd3682008-11-17 22:58:34 +0000999 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001000
Douglas Gregor021c3b32009-03-11 23:00:04 +00001001 if (Init)
John McCall9ae2f072010-08-23 23:25:46 +00001002 AddInitializerToDecl(Member, Init, false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001003 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +00001004 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001005
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001006 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +00001007 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001008 return 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001009 }
John McCalld226f652010-08-21 09:40:31 +00001010 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001011}
1012
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001013/// \brief Find the direct and/or virtual base specifiers that
1014/// correspond to the given base type, for use in base initialization
1015/// within a constructor.
1016static bool FindBaseInitializer(Sema &SemaRef,
1017 CXXRecordDecl *ClassDecl,
1018 QualType BaseType,
1019 const CXXBaseSpecifier *&DirectBaseSpec,
1020 const CXXBaseSpecifier *&VirtualBaseSpec) {
1021 // First, check for a direct base class.
1022 DirectBaseSpec = 0;
1023 for (CXXRecordDecl::base_class_const_iterator Base
1024 = ClassDecl->bases_begin();
1025 Base != ClassDecl->bases_end(); ++Base) {
1026 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1027 // We found a direct base of this type. That's what we're
1028 // initializing.
1029 DirectBaseSpec = &*Base;
1030 break;
1031 }
1032 }
1033
1034 // Check for a virtual base class.
1035 // FIXME: We might be able to short-circuit this if we know in advance that
1036 // there are no virtual bases.
1037 VirtualBaseSpec = 0;
1038 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1039 // We haven't found a base yet; search the class hierarchy for a
1040 // virtual base class.
1041 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1042 /*DetectVirtual=*/false);
1043 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1044 BaseType, Paths)) {
1045 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1046 Path != Paths.end(); ++Path) {
1047 if (Path->back().Base->isVirtual()) {
1048 VirtualBaseSpec = Path->back().Base;
1049 break;
1050 }
1051 }
1052 }
1053 }
1054
1055 return DirectBaseSpec || VirtualBaseSpec;
1056}
1057
Douglas Gregor7ad83902008-11-05 04:29:56 +00001058/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001059Sema::MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001060Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001061 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001062 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001063 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001064 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001065 SourceLocation IdLoc,
1066 SourceLocation LParenLoc,
1067 ExprTy **Args, unsigned NumArgs,
1068 SourceLocation *CommaLocs,
1069 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001070 if (!ConstructorD)
1071 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001073 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001074
1075 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001076 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001077 if (!Constructor) {
1078 // The user wrote a constructor initializer on a function that is
1079 // not a C++ constructor. Ignore the error for now, because we may
1080 // have more member initializers coming; we'll diagnose it just
1081 // once in ActOnMemInitializers.
1082 return true;
1083 }
1084
1085 CXXRecordDecl *ClassDecl = Constructor->getParent();
1086
1087 // C++ [class.base.init]p2:
1088 // Names in a mem-initializer-id are looked up in the scope of the
1089 // constructor’s class and, if not found in that scope, are looked
1090 // up in the scope containing the constructor’s
1091 // definition. [Note: if the constructor’s class contains a member
1092 // with the same name as a direct or virtual base class of the
1093 // class, a mem-initializer-id naming the member or base class and
1094 // composed of a single identifier refers to the class member. A
1095 // mem-initializer-id for the hidden base class may be specified
1096 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001097 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001098 // Look for a member, first.
1099 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001100 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001101 = ClassDecl->lookup(MemberOrBase);
1102 if (Result.first != Result.second)
1103 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001104
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001105 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001106
Eli Friedman59c04372009-07-29 19:44:27 +00001107 if (Member)
1108 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001109 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001110 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001111 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001112 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001113 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001114
1115 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001116 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001117 } else {
1118 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1119 LookupParsedName(R, S, &SS);
1120
1121 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1122 if (!TyD) {
1123 if (R.isAmbiguous()) return true;
1124
John McCallfd225442010-04-09 19:01:14 +00001125 // We don't want access-control diagnostics here.
1126 R.suppressDiagnostics();
1127
Douglas Gregor7a886e12010-01-19 06:46:48 +00001128 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1129 bool NotUnknownSpecialization = false;
1130 DeclContext *DC = computeDeclContext(SS, false);
1131 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1132 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1133
1134 if (!NotUnknownSpecialization) {
1135 // When the scope specifier can refer to a member of an unknown
1136 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001137 BaseType = CheckTypenameType(ETK_None,
1138 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00001139 *MemberOrBase, SourceLocation(),
1140 SS.getRange(), IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001141 if (BaseType.isNull())
1142 return true;
1143
Douglas Gregor7a886e12010-01-19 06:46:48 +00001144 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001145 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001146 }
1147 }
1148
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001149 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001150 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001151 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1152 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001153 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1154 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1155 // We have found a non-static data member with a similar
1156 // name to what was typed; complain and initialize that
1157 // member.
1158 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1159 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001160 << FixItHint::CreateReplacement(R.getNameLoc(),
1161 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001162 Diag(Member->getLocation(), diag::note_previous_decl)
1163 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001164
1165 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1166 LParenLoc, RParenLoc);
1167 }
1168 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1169 const CXXBaseSpecifier *DirectBaseSpec;
1170 const CXXBaseSpecifier *VirtualBaseSpec;
1171 if (FindBaseInitializer(*this, ClassDecl,
1172 Context.getTypeDeclType(Type),
1173 DirectBaseSpec, VirtualBaseSpec)) {
1174 // We have found a direct or virtual base class with a
1175 // similar name to what was typed; complain and initialize
1176 // that base class.
1177 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1178 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001179 << FixItHint::CreateReplacement(R.getNameLoc(),
1180 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001181
1182 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1183 : VirtualBaseSpec;
1184 Diag(BaseSpec->getSourceRange().getBegin(),
1185 diag::note_base_class_specified_here)
1186 << BaseSpec->getType()
1187 << BaseSpec->getSourceRange();
1188
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001189 TyD = Type;
1190 }
1191 }
1192 }
1193
Douglas Gregor7a886e12010-01-19 06:46:48 +00001194 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001195 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1196 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1197 return true;
1198 }
John McCall2b194412009-12-21 10:41:20 +00001199 }
1200
Douglas Gregor7a886e12010-01-19 06:46:48 +00001201 if (BaseType.isNull()) {
1202 BaseType = Context.getTypeDeclType(TyD);
1203 if (SS.isSet()) {
1204 NestedNameSpecifier *Qualifier =
1205 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001206
Douglas Gregor7a886e12010-01-19 06:46:48 +00001207 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001208 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001209 }
John McCall2b194412009-12-21 10:41:20 +00001210 }
1211 }
Mike Stump1eb44332009-09-09 15:08:12 +00001212
John McCalla93c9342009-12-07 02:54:59 +00001213 if (!TInfo)
1214 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001215
John McCalla93c9342009-12-07 02:54:59 +00001216 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001217 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001218}
1219
John McCallb4190042009-11-04 23:02:40 +00001220/// Checks an initializer expression for use of uninitialized fields, such as
1221/// containing the field that is being initialized. Returns true if there is an
1222/// uninitialized field was used an updates the SourceLocation parameter; false
1223/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001224static bool InitExprContainsUninitializedFields(const Stmt *S,
1225 const FieldDecl *LhsField,
1226 SourceLocation *L) {
1227 if (isa<CallExpr>(S)) {
1228 // Do not descend into function calls or constructors, as the use
1229 // of an uninitialized field may be valid. One would have to inspect
1230 // the contents of the function/ctor to determine if it is safe or not.
1231 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1232 // may be safe, depending on what the function/ctor does.
1233 return false;
1234 }
1235 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1236 const NamedDecl *RhsField = ME->getMemberDecl();
John McCallb4190042009-11-04 23:02:40 +00001237 if (RhsField == LhsField) {
1238 // Initializing a field with itself. Throw a warning.
1239 // But wait; there are exceptions!
1240 // Exception #1: The field may not belong to this record.
1241 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001242 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001243 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1244 // Even though the field matches, it does not belong to this record.
1245 return false;
1246 }
1247 // None of the exceptions triggered; return true to indicate an
1248 // uninitialized field was used.
1249 *L = ME->getMemberLoc();
1250 return true;
1251 }
1252 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001253 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1254 it != e; ++it) {
1255 if (!*it) {
1256 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001257 continue;
1258 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001259 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1260 return true;
John McCallb4190042009-11-04 23:02:40 +00001261 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001262 return false;
John McCallb4190042009-11-04 23:02:40 +00001263}
1264
Eli Friedman59c04372009-07-29 19:44:27 +00001265Sema::MemInitResult
1266Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1267 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001268 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001269 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001270 // Diagnose value-uses of fields to initialize themselves, e.g.
1271 // foo(foo)
1272 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001273 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001274 for (unsigned i = 0; i < NumArgs; ++i) {
1275 SourceLocation L;
1276 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1277 // FIXME: Return true in the case when other fields are used before being
1278 // uninitialized. For example, let this field be the i'th field. When
1279 // initializing the i'th field, throw a warning if any of the >= i'th
1280 // fields are used, as they are not yet initialized.
1281 // Right now we are only handling the case where the i'th field uses
1282 // itself in its initializer.
1283 Diag(L, diag::warn_field_is_uninit);
1284 }
1285 }
1286
Eli Friedman59c04372009-07-29 19:44:27 +00001287 bool HasDependentArg = false;
1288 for (unsigned i = 0; i < NumArgs; i++)
1289 HasDependentArg |= Args[i]->isTypeDependent();
1290
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001291 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001292 // Can't check initialization for a member of dependent type or when
1293 // any of the arguments are type-dependent expressions.
John McCall9ae2f072010-08-23 23:25:46 +00001294 Expr *Init
1295 = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1296 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001297
1298 // Erase any temporaries within this evaluation context; we're not
1299 // going to track them in the AST, since we'll be rebuilding the
1300 // ASTs during template instantiation.
1301 ExprTemporaries.erase(
1302 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1303 ExprTemporaries.end());
1304
1305 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1306 LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001307 Init,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001308 RParenLoc);
1309
Douglas Gregor7ad83902008-11-05 04:29:56 +00001310 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001311
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001312 if (Member->isInvalidDecl())
1313 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001314
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001315 // Initialize the member.
1316 InitializedEntity MemberEntity =
1317 InitializedEntity::InitializeMember(Member, 0);
1318 InitializationKind Kind =
1319 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1320
1321 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1322
John McCall60d7b3a2010-08-24 06:29:42 +00001323 ExprResult MemberInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001324 InitSeq.Perform(*this, MemberEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001325 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001326 if (MemberInit.isInvalid())
1327 return true;
1328
1329 // C++0x [class.base.init]p7:
1330 // The initialization of each base and member constitutes a
1331 // full-expression.
John McCall9ae2f072010-08-23 23:25:46 +00001332 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001333 if (MemberInit.isInvalid())
1334 return true;
1335
1336 // If we are in a dependent context, template instantiation will
1337 // perform this type-checking again. Just save the arguments that we
1338 // received in a ParenListExpr.
1339 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1340 // of the information that we have about the member
1341 // initializer. However, deconstructing the ASTs is a dicey process,
1342 // and this approach is far more likely to get the corner cases right.
1343 if (CurContext->isDependentContext()) {
1344 // Bump the reference count of all of the arguments.
1345 for (unsigned I = 0; I != NumArgs; ++I)
1346 Args[I]->Retain();
1347
John McCall9ae2f072010-08-23 23:25:46 +00001348 Expr *Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1349 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001350 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1351 LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001352 Init,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001353 RParenLoc);
1354 }
1355
Douglas Gregor802ab452009-12-02 22:36:29 +00001356 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001357 LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001358 MemberInit.get(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001359 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001360}
1361
1362Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001363Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001364 Expr **Args, unsigned NumArgs,
1365 SourceLocation LParenLoc, SourceLocation RParenLoc,
1366 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001367 bool HasDependentArg = false;
1368 for (unsigned i = 0; i < NumArgs; i++)
1369 HasDependentArg |= Args[i]->isTypeDependent();
1370
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001371 SourceLocation BaseLoc
1372 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1373
1374 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1375 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1376 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1377
1378 // C++ [class.base.init]p2:
1379 // [...] Unless the mem-initializer-id names a nonstatic data
1380 // member of the constructor’s class or a direct or virtual base
1381 // of that class, the mem-initializer is ill-formed. A
1382 // mem-initializer-list can initialize a base class using any
1383 // name that denotes that base class type.
1384 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1385
1386 // Check for direct and virtual base classes.
1387 const CXXBaseSpecifier *DirectBaseSpec = 0;
1388 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1389 if (!Dependent) {
1390 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1391 VirtualBaseSpec);
1392
1393 // C++ [base.class.init]p2:
1394 // Unless the mem-initializer-id names a nonstatic data member of the
1395 // constructor's class or a direct or virtual base of that class, the
1396 // mem-initializer is ill-formed.
1397 if (!DirectBaseSpec && !VirtualBaseSpec) {
1398 // If the class has any dependent bases, then it's possible that
1399 // one of those types will resolve to the same type as
1400 // BaseType. Therefore, just treat this as a dependent base
1401 // class initialization. FIXME: Should we try to check the
1402 // initialization anyway? It seems odd.
1403 if (ClassDecl->hasAnyDependentBases())
1404 Dependent = true;
1405 else
1406 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1407 << BaseType << Context.getTypeDeclType(ClassDecl)
1408 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1409 }
1410 }
1411
1412 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001413 // Can't check initialization for a base of dependent type or when
1414 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001415 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001416 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1417 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001418
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001419 // Erase any temporaries within this evaluation context; we're not
1420 // going to track them in the AST, since we'll be rebuilding the
1421 // ASTs during template instantiation.
1422 ExprTemporaries.erase(
1423 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1424 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001426 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001427 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001428 LParenLoc,
1429 BaseInit.takeAs<Expr>(),
1430 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001431 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001432
1433 // C++ [base.class.init]p2:
1434 // If a mem-initializer-id is ambiguous because it designates both
1435 // a direct non-virtual base class and an inherited virtual base
1436 // class, the mem-initializer is ill-formed.
1437 if (DirectBaseSpec && VirtualBaseSpec)
1438 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001439 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001440
1441 CXXBaseSpecifier *BaseSpec
1442 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1443 if (!BaseSpec)
1444 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1445
1446 // Initialize the base.
1447 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001448 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001449 InitializationKind Kind =
1450 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1451
1452 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1453
John McCall60d7b3a2010-08-24 06:29:42 +00001454 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001455 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001456 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001457 if (BaseInit.isInvalid())
1458 return true;
1459
1460 // C++0x [class.base.init]p7:
1461 // The initialization of each base and member constitutes a
1462 // full-expression.
John McCall9ae2f072010-08-23 23:25:46 +00001463 BaseInit = MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001464 if (BaseInit.isInvalid())
1465 return true;
1466
1467 // If we are in a dependent context, template instantiation will
1468 // perform this type-checking again. Just save the arguments that we
1469 // received in a ParenListExpr.
1470 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1471 // of the information that we have about the base
1472 // initializer. However, deconstructing the ASTs is a dicey process,
1473 // and this approach is far more likely to get the corner cases right.
1474 if (CurContext->isDependentContext()) {
1475 // Bump the reference count of all of the arguments.
1476 for (unsigned I = 0; I != NumArgs; ++I)
1477 Args[I]->Retain();
1478
John McCall60d7b3a2010-08-24 06:29:42 +00001479 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001480 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1481 RParenLoc));
1482 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001483 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001484 LParenLoc,
1485 Init.takeAs<Expr>(),
1486 RParenLoc);
1487 }
1488
1489 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001490 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001491 LParenLoc,
1492 BaseInit.takeAs<Expr>(),
1493 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001494}
1495
Anders Carlssone5ef7402010-04-23 03:10:23 +00001496/// ImplicitInitializerKind - How an implicit base or member initializer should
1497/// initialize its base or member.
1498enum ImplicitInitializerKind {
1499 IIK_Default,
1500 IIK_Copy,
1501 IIK_Move
1502};
1503
Anders Carlssondefefd22010-04-23 02:00:02 +00001504static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001505BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001506 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001507 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001508 bool IsInheritedVirtualBase,
1509 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001510 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001511 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1512 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001513
John McCall60d7b3a2010-08-24 06:29:42 +00001514 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001515
1516 switch (ImplicitInitKind) {
1517 case IIK_Default: {
1518 InitializationKind InitKind
1519 = InitializationKind::CreateDefault(Constructor->getLocation());
1520 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1521 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1522 Sema::MultiExprArg(SemaRef, 0, 0));
1523 break;
1524 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001525
Anders Carlssone5ef7402010-04-23 03:10:23 +00001526 case IIK_Copy: {
1527 ParmVarDecl *Param = Constructor->getParamDecl(0);
1528 QualType ParamType = Param->getType().getNonReferenceType();
1529
1530 Expr *CopyCtorArg =
1531 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregor62b71f42010-05-03 15:43:53 +00001532 Constructor->getLocation(), ParamType, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001533
Anders Carlssonc7957502010-04-24 22:02:54 +00001534 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001535 QualType ArgTy =
1536 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1537 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001538
1539 CXXCastPath BasePath;
1540 BasePath.push_back(BaseSpec);
Sebastian Redl906082e2010-07-20 04:20:21 +00001541 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCall2de56d12010-08-25 11:45:40 +00001542 CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00001543 VK_LValue, &BasePath);
Anders Carlssonc7957502010-04-24 22:02:54 +00001544
Anders Carlssone5ef7402010-04-23 03:10:23 +00001545 InitializationKind InitKind
1546 = InitializationKind::CreateDirect(Constructor->getLocation(),
1547 SourceLocation(), SourceLocation());
1548 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1549 &CopyCtorArg, 1);
1550 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1551 Sema::MultiExprArg(SemaRef,
John McCallca0408f2010-08-23 06:44:23 +00001552 &CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001553 break;
1554 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001555
Anders Carlssone5ef7402010-04-23 03:10:23 +00001556 case IIK_Move:
1557 assert(false && "Unhandled initializer kind!");
1558 }
John McCall9ae2f072010-08-23 23:25:46 +00001559
1560 if (BaseInit.isInvalid())
1561 return true;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001562
John McCall9ae2f072010-08-23 23:25:46 +00001563 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Anders Carlsson84688f22010-04-20 23:11:20 +00001564 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001565 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001566
Anders Carlssondefefd22010-04-23 02:00:02 +00001567 CXXBaseInit =
Anders Carlsson84688f22010-04-20 23:11:20 +00001568 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1569 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1570 SourceLocation()),
1571 BaseSpec->isVirtual(),
1572 SourceLocation(),
1573 BaseInit.takeAs<Expr>(),
1574 SourceLocation());
1575
Anders Carlssondefefd22010-04-23 02:00:02 +00001576 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001577}
1578
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001579static bool
1580BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001581 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001582 FieldDecl *Field,
1583 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001584 if (Field->isInvalidDecl())
1585 return true;
1586
Chandler Carruthf186b542010-06-29 23:50:44 +00001587 SourceLocation Loc = Constructor->getLocation();
1588
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001589 if (ImplicitInitKind == IIK_Copy) {
1590 ParmVarDecl *Param = Constructor->getParamDecl(0);
1591 QualType ParamType = Param->getType().getNonReferenceType();
1592
1593 Expr *MemberExprBase =
1594 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001595 Loc, ParamType, 0);
1596
1597 // Build a reference to this field within the parameter.
1598 CXXScopeSpec SS;
1599 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1600 Sema::LookupMemberName);
1601 MemberLookup.addDecl(Field, AS_public);
1602 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001603 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001604 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001605 ParamType, Loc,
1606 /*IsArrow=*/false,
1607 SS,
1608 /*FirstQualifierInScope=*/0,
1609 MemberLookup,
1610 /*TemplateArgs=*/0);
1611 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001612 return true;
1613
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001614 // When the field we are copying is an array, create index variables for
1615 // each dimension of the array. We use these index variables to subscript
1616 // the source array, and other clients (e.g., CodeGen) will perform the
1617 // necessary iteration with these index variables.
1618 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1619 QualType BaseType = Field->getType();
1620 QualType SizeType = SemaRef.Context.getSizeType();
1621 while (const ConstantArrayType *Array
1622 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1623 // Create the iteration variable for this array index.
1624 IdentifierInfo *IterationVarName = 0;
1625 {
1626 llvm::SmallString<8> Str;
1627 llvm::raw_svector_ostream OS(Str);
1628 OS << "__i" << IndexVariables.size();
1629 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1630 }
1631 VarDecl *IterationVar
1632 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1633 IterationVarName, SizeType,
1634 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001635 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001636 IndexVariables.push_back(IterationVar);
1637
1638 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001639 ExprResult IterationVarRef
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001640 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1641 assert(!IterationVarRef.isInvalid() &&
1642 "Reference to invented variable cannot fail!");
1643
1644 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001645 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001646 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001647 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001648 Loc);
1649 if (CopyCtorArg.isInvalid())
1650 return true;
1651
1652 BaseType = Array->getElementType();
1653 }
1654
1655 // Construct the entity that we will be initializing. For an array, this
1656 // will be first element in the array, which may require several levels
1657 // of array-subscript entities.
1658 llvm::SmallVector<InitializedEntity, 4> Entities;
1659 Entities.reserve(1 + IndexVariables.size());
1660 Entities.push_back(InitializedEntity::InitializeMember(Field));
1661 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1662 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1663 0,
1664 Entities.back()));
1665
1666 // Direct-initialize to use the copy constructor.
1667 InitializationKind InitKind =
1668 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1669
1670 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1671 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1672 &CopyCtorArgE, 1);
1673
John McCall60d7b3a2010-08-24 06:29:42 +00001674 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001675 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallca0408f2010-08-23 06:44:23 +00001676 Sema::MultiExprArg(SemaRef, &CopyCtorArgE, 1));
John McCall9ae2f072010-08-23 23:25:46 +00001677 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001678 if (MemberInit.isInvalid())
1679 return true;
1680
1681 CXXMemberInit
1682 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1683 MemberInit.takeAs<Expr>(), Loc,
1684 IndexVariables.data(),
1685 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001686 return false;
1687 }
1688
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001689 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1690
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001691 QualType FieldBaseElementType =
1692 SemaRef.Context.getBaseElementType(Field->getType());
1693
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001694 if (FieldBaseElementType->isRecordType()) {
1695 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001696 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001697 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001698
1699 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001700 ExprResult MemberInit =
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001701 InitSeq.Perform(SemaRef, InitEntity, InitKind,
1702 Sema::MultiExprArg(SemaRef, 0, 0));
John McCall9ae2f072010-08-23 23:25:46 +00001703 if (MemberInit.isInvalid())
1704 return true;
1705
1706 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001707 if (MemberInit.isInvalid())
1708 return true;
1709
1710 CXXMemberInit =
1711 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001712 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001713 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001714 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001715 return false;
1716 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001717
1718 if (FieldBaseElementType->isReferenceType()) {
1719 SemaRef.Diag(Constructor->getLocation(),
1720 diag::err_uninitialized_member_in_ctor)
1721 << (int)Constructor->isImplicit()
1722 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1723 << 0 << Field->getDeclName();
1724 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1725 return true;
1726 }
1727
1728 if (FieldBaseElementType.isConstQualified()) {
1729 SemaRef.Diag(Constructor->getLocation(),
1730 diag::err_uninitialized_member_in_ctor)
1731 << (int)Constructor->isImplicit()
1732 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1733 << 1 << Field->getDeclName();
1734 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1735 return true;
1736 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001737
1738 // Nothing to initialize.
1739 CXXMemberInit = 0;
1740 return false;
1741}
John McCallf1860e52010-05-20 23:23:51 +00001742
1743namespace {
1744struct BaseAndFieldInfo {
1745 Sema &S;
1746 CXXConstructorDecl *Ctor;
1747 bool AnyErrorsInInits;
1748 ImplicitInitializerKind IIK;
1749 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1750 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1751
1752 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1753 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1754 // FIXME: Handle implicit move constructors.
1755 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1756 IIK = IIK_Copy;
1757 else
1758 IIK = IIK_Default;
1759 }
1760};
1761}
1762
Chandler Carruthe861c602010-06-30 02:59:29 +00001763static void RecordFieldInitializer(BaseAndFieldInfo &Info,
1764 FieldDecl *Top, FieldDecl *Field,
1765 CXXBaseOrMemberInitializer *Init) {
1766 // If the member doesn't need to be initialized, Init will still be null.
1767 if (!Init)
1768 return;
1769
1770 Info.AllToInit.push_back(Init);
1771 if (Field != Top) {
1772 Init->setMember(Top);
1773 Init->setAnonUnionMember(Field);
1774 }
1775}
1776
John McCallf1860e52010-05-20 23:23:51 +00001777static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1778 FieldDecl *Top, FieldDecl *Field) {
1779
Chandler Carruthe861c602010-06-30 02:59:29 +00001780 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallf1860e52010-05-20 23:23:51 +00001781 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Chandler Carruthe861c602010-06-30 02:59:29 +00001782 RecordFieldInitializer(Info, Top, Field, Init);
John McCallf1860e52010-05-20 23:23:51 +00001783 return false;
1784 }
1785
1786 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1787 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1788 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00001789 CXXRecordDecl *FieldClassDecl
1790 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00001791
1792 // Even though union members never have non-trivial default
1793 // constructions in C++03, we still build member initializers for aggregate
1794 // record types which can be union members, and C++0x allows non-trivial
1795 // default constructors for union members, so we ensure that only one
1796 // member is initialized for these.
1797 if (FieldClassDecl->isUnion()) {
1798 // First check for an explicit initializer for one field.
1799 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1800 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1801 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
1802 RecordFieldInitializer(Info, Top, *FA, Init);
1803
1804 // Once we've initialized a field of an anonymous union, the union
1805 // field in the class is also initialized, so exit immediately.
1806 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00001807 } else if ((*FA)->isAnonymousStructOrUnion()) {
1808 if (CollectFieldInitializer(Info, Top, *FA))
1809 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00001810 }
1811 }
1812
1813 // Fallthrough and construct a default initializer for the union as
1814 // a whole, which can call its default constructor if such a thing exists
1815 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1816 // behavior going forward with C++0x, when anonymous unions there are
1817 // finalized, we should revisit this.
1818 } else {
1819 // For structs, we simply descend through to initialize all members where
1820 // necessary.
1821 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1822 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1823 if (CollectFieldInitializer(Info, Top, *FA))
1824 return true;
1825 }
1826 }
John McCallf1860e52010-05-20 23:23:51 +00001827 }
1828
1829 // Don't try to build an implicit initializer if there were semantic
1830 // errors in any of the initializers (and therefore we might be
1831 // missing some that the user actually wrote).
1832 if (Info.AnyErrorsInInits)
1833 return false;
1834
1835 CXXBaseOrMemberInitializer *Init = 0;
1836 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1837 return true;
John McCallf1860e52010-05-20 23:23:51 +00001838
Chandler Carruthe861c602010-06-30 02:59:29 +00001839 RecordFieldInitializer(Info, Top, Field, Init);
John McCallf1860e52010-05-20 23:23:51 +00001840 return false;
1841}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001842
Eli Friedman80c30da2009-11-09 19:20:36 +00001843bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001844Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001845 CXXBaseOrMemberInitializer **Initializers,
1846 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001847 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001848 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001849 // Just store the initializers as written, they will be checked during
1850 // instantiation.
1851 if (NumInitializers > 0) {
1852 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1853 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1854 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1855 memcpy(baseOrMemberInitializers, Initializers,
1856 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1857 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1858 }
1859
1860 return false;
1861 }
1862
John McCallf1860e52010-05-20 23:23:51 +00001863 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001864
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001865 // We need to build the initializer AST according to order of construction
1866 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00001867 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00001868 if (!ClassDecl)
1869 return true;
1870
Eli Friedman80c30da2009-11-09 19:20:36 +00001871 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001873 for (unsigned i = 0; i < NumInitializers; i++) {
1874 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001875
1876 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00001877 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001878 else
John McCallf1860e52010-05-20 23:23:51 +00001879 Info.AllBaseFields[Member->getMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001880 }
1881
Anders Carlsson711f34a2010-04-21 19:52:01 +00001882 // Keep track of the direct virtual bases.
1883 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1884 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1885 E = ClassDecl->bases_end(); I != E; ++I) {
1886 if (I->isVirtual())
1887 DirectVBases.insert(I);
1888 }
1889
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001890 // Push virtual bases before others.
1891 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1892 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1893
1894 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001895 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1896 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001897 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00001898 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlssondefefd22010-04-23 02:00:02 +00001899 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001900 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001901 VBase, IsInheritedVirtualBase,
1902 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001903 HadError = true;
1904 continue;
1905 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001906
John McCallf1860e52010-05-20 23:23:51 +00001907 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001908 }
1909 }
Mike Stump1eb44332009-09-09 15:08:12 +00001910
John McCallf1860e52010-05-20 23:23:51 +00001911 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001912 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1913 E = ClassDecl->bases_end(); Base != E; ++Base) {
1914 // Virtuals are in the virtual base list and already constructed.
1915 if (Base->isVirtual())
1916 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001918 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001919 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1920 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001921 } else if (!AnyErrors) {
Anders Carlssondefefd22010-04-23 02:00:02 +00001922 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001923 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001924 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00001925 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001926 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001927 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001928 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001929
John McCallf1860e52010-05-20 23:23:51 +00001930 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001931 }
1932 }
Mike Stump1eb44332009-09-09 15:08:12 +00001933
John McCallf1860e52010-05-20 23:23:51 +00001934 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001935 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001936 E = ClassDecl->field_end(); Field != E; ++Field) {
1937 if ((*Field)->getType()->isIncompleteArrayType()) {
1938 assert(ClassDecl->hasFlexibleArrayMember() &&
1939 "Incomplete array type is not valid");
1940 continue;
1941 }
John McCallf1860e52010-05-20 23:23:51 +00001942 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001943 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001944 }
Mike Stump1eb44332009-09-09 15:08:12 +00001945
John McCallf1860e52010-05-20 23:23:51 +00001946 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001947 if (NumInitializers > 0) {
1948 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1949 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1950 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00001951 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCallef027fe2010-03-16 21:39:52 +00001952 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001953 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00001954
John McCallef027fe2010-03-16 21:39:52 +00001955 // Constructors implicitly reference the base and member
1956 // destructors.
1957 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1958 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001959 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001960
1961 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001962}
1963
Eli Friedman6347f422009-07-21 19:28:10 +00001964static void *GetKeyForTopLevelField(FieldDecl *Field) {
1965 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001966 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001967 if (RT->getDecl()->isAnonymousStructOrUnion())
1968 return static_cast<void *>(RT->getDecl());
1969 }
1970 return static_cast<void *>(Field);
1971}
1972
Anders Carlssonea356fb2010-04-02 05:42:15 +00001973static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1974 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001975}
1976
Anders Carlssonea356fb2010-04-02 05:42:15 +00001977static void *GetKeyForMember(ASTContext &Context,
1978 CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001979 bool MemberMaybeAnon = false) {
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001980 if (!Member->isMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00001981 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001982
Eli Friedman6347f422009-07-21 19:28:10 +00001983 // For fields injected into the class via declaration of an anonymous union,
1984 // use its anonymous union class declaration as the unique key.
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001985 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001987 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1988 // data member of the class. Data member used in the initializer list is
1989 // in AnonUnionMember field.
1990 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1991 Field = Member->getAnonUnionMember();
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001992
John McCall3c3ccdb2010-04-10 09:28:51 +00001993 // If the field is a member of an anonymous struct or union, our key
1994 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001995 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00001996 if (RD->isAnonymousStructOrUnion()) {
1997 while (true) {
1998 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1999 if (Parent->isAnonymousStructOrUnion())
2000 RD = Parent;
2001 else
2002 break;
2003 }
2004
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002005 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002006 }
Mike Stump1eb44332009-09-09 15:08:12 +00002007
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002008 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002009}
2010
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002011static void
2012DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002013 const CXXConstructorDecl *Constructor,
John McCalld6ca8da2010-04-10 07:37:23 +00002014 CXXBaseOrMemberInitializer **Inits,
2015 unsigned NumInits) {
2016 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002017 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002018
John McCalld6ca8da2010-04-10 07:37:23 +00002019 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
2020 == Diagnostic::Ignored)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002021 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002022
John McCalld6ca8da2010-04-10 07:37:23 +00002023 // Build the list of bases and members in the order that they'll
2024 // actually be initialized. The explicit initializers should be in
2025 // this same order but may be missing things.
2026 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Anders Carlsson071d6102010-04-02 03:38:04 +00002028 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2029
John McCalld6ca8da2010-04-10 07:37:23 +00002030 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002031 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002032 ClassDecl->vbases_begin(),
2033 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002034 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002035
John McCalld6ca8da2010-04-10 07:37:23 +00002036 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002037 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002038 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002039 if (Base->isVirtual())
2040 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002041 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002042 }
Mike Stump1eb44332009-09-09 15:08:12 +00002043
John McCalld6ca8da2010-04-10 07:37:23 +00002044 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002045 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2046 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002047 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002048
John McCalld6ca8da2010-04-10 07:37:23 +00002049 unsigned NumIdealInits = IdealInitKeys.size();
2050 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002051
John McCalld6ca8da2010-04-10 07:37:23 +00002052 CXXBaseOrMemberInitializer *PrevInit = 0;
2053 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2054 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2055 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
2056
2057 // Scan forward to try to find this initializer in the idealized
2058 // initializers list.
2059 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2060 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002061 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002062
2063 // If we didn't find this initializer, it must be because we
2064 // scanned past it on a previous iteration. That can only
2065 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002066 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002067 Sema::SemaDiagnosticBuilder D =
2068 SemaRef.Diag(PrevInit->getSourceLocation(),
2069 diag::warn_initializer_out_of_order);
2070
2071 if (PrevInit->isMemberInitializer())
2072 D << 0 << PrevInit->getMember()->getDeclName();
2073 else
2074 D << 1 << PrevInit->getBaseClassInfo()->getType();
2075
2076 if (Init->isMemberInitializer())
2077 D << 0 << Init->getMember()->getDeclName();
2078 else
2079 D << 1 << Init->getBaseClassInfo()->getType();
2080
2081 // Move back to the initializer's location in the ideal list.
2082 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2083 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002084 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002085
2086 assert(IdealIndex != NumIdealInits &&
2087 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002088 }
John McCalld6ca8da2010-04-10 07:37:23 +00002089
2090 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002091 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002092}
2093
John McCall3c3ccdb2010-04-10 09:28:51 +00002094namespace {
2095bool CheckRedundantInit(Sema &S,
2096 CXXBaseOrMemberInitializer *Init,
2097 CXXBaseOrMemberInitializer *&PrevInit) {
2098 if (!PrevInit) {
2099 PrevInit = Init;
2100 return false;
2101 }
2102
2103 if (FieldDecl *Field = Init->getMember())
2104 S.Diag(Init->getSourceLocation(),
2105 diag::err_multiple_mem_initialization)
2106 << Field->getDeclName()
2107 << Init->getSourceRange();
2108 else {
2109 Type *BaseClass = Init->getBaseClass();
2110 assert(BaseClass && "neither field nor base");
2111 S.Diag(Init->getSourceLocation(),
2112 diag::err_multiple_base_initialization)
2113 << QualType(BaseClass, 0)
2114 << Init->getSourceRange();
2115 }
2116 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2117 << 0 << PrevInit->getSourceRange();
2118
2119 return true;
2120}
2121
2122typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2123typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2124
2125bool CheckRedundantUnionInit(Sema &S,
2126 CXXBaseOrMemberInitializer *Init,
2127 RedundantUnionMap &Unions) {
2128 FieldDecl *Field = Init->getMember();
2129 RecordDecl *Parent = Field->getParent();
2130 if (!Parent->isAnonymousStructOrUnion())
2131 return false;
2132
2133 NamedDecl *Child = Field;
2134 do {
2135 if (Parent->isUnion()) {
2136 UnionEntry &En = Unions[Parent];
2137 if (En.first && En.first != Child) {
2138 S.Diag(Init->getSourceLocation(),
2139 diag::err_multiple_mem_union_initialization)
2140 << Field->getDeclName()
2141 << Init->getSourceRange();
2142 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2143 << 0 << En.second->getSourceRange();
2144 return true;
2145 } else if (!En.first) {
2146 En.first = Child;
2147 En.second = Init;
2148 }
2149 }
2150
2151 Child = Parent;
2152 Parent = cast<RecordDecl>(Parent->getDeclContext());
2153 } while (Parent->isAnonymousStructOrUnion());
2154
2155 return false;
2156}
2157}
2158
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002159/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002160void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002161 SourceLocation ColonLoc,
2162 MemInitTy **meminits, unsigned NumMemInits,
2163 bool AnyErrors) {
2164 if (!ConstructorDecl)
2165 return;
2166
2167 AdjustDeclIfTemplate(ConstructorDecl);
2168
2169 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002170 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002171
2172 if (!Constructor) {
2173 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2174 return;
2175 }
2176
2177 CXXBaseOrMemberInitializer **MemInits =
2178 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002179
2180 // Mapping for the duplicate initializers check.
2181 // For member initializers, this is keyed with a FieldDecl*.
2182 // For base initializers, this is keyed with a Type*.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002183 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002184
2185 // Mapping for the inconsistent anonymous-union initializers check.
2186 RedundantUnionMap MemberUnions;
2187
Anders Carlssonea356fb2010-04-02 05:42:15 +00002188 bool HadError = false;
2189 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002190 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002191
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002192 // Set the source order index.
2193 Init->setSourceOrder(i);
2194
John McCall3c3ccdb2010-04-10 09:28:51 +00002195 if (Init->isMemberInitializer()) {
2196 FieldDecl *Field = Init->getMember();
2197 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2198 CheckRedundantUnionInit(*this, Init, MemberUnions))
2199 HadError = true;
2200 } else {
2201 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2202 if (CheckRedundantInit(*this, Init, Members[Key]))
2203 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002204 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002205 }
2206
Anders Carlssonea356fb2010-04-02 05:42:15 +00002207 if (HadError)
2208 return;
2209
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002210 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002211
2212 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002213}
2214
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002215void
John McCallef027fe2010-03-16 21:39:52 +00002216Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2217 CXXRecordDecl *ClassDecl) {
2218 // Ignore dependent contexts.
2219 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002220 return;
John McCall58e6f342010-03-16 05:22:47 +00002221
2222 // FIXME: all the access-control diagnostics are positioned on the
2223 // field/base declaration. That's probably good; that said, the
2224 // user might reasonably want to know why the destructor is being
2225 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002226
Anders Carlsson9f853df2009-11-17 04:44:12 +00002227 // Non-static data members.
2228 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2229 E = ClassDecl->field_end(); I != E; ++I) {
2230 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002231 if (Field->isInvalidDecl())
2232 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002233 QualType FieldType = Context.getBaseElementType(Field->getType());
2234
2235 const RecordType* RT = FieldType->getAs<RecordType>();
2236 if (!RT)
2237 continue;
2238
2239 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2240 if (FieldClassDecl->hasTrivialDestructor())
2241 continue;
2242
Douglas Gregordb89f282010-07-01 22:47:18 +00002243 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002244 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002245 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002246 << Field->getDeclName()
2247 << FieldType);
2248
John McCallef027fe2010-03-16 21:39:52 +00002249 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002250 }
2251
John McCall58e6f342010-03-16 05:22:47 +00002252 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2253
Anders Carlsson9f853df2009-11-17 04:44:12 +00002254 // Bases.
2255 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2256 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002257 // Bases are always records in a well-formed non-dependent class.
2258 const RecordType *RT = Base->getType()->getAs<RecordType>();
2259
2260 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002261 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002262 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002263
2264 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002265 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002266 if (BaseClassDecl->hasTrivialDestructor())
2267 continue;
John McCall58e6f342010-03-16 05:22:47 +00002268
Douglas Gregordb89f282010-07-01 22:47:18 +00002269 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002270
2271 // FIXME: caret should be on the start of the class name
2272 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002273 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002274 << Base->getType()
2275 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002276
John McCallef027fe2010-03-16 21:39:52 +00002277 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002278 }
2279
2280 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002281 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2282 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002283
2284 // Bases are always records in a well-formed non-dependent class.
2285 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2286
2287 // Ignore direct virtual bases.
2288 if (DirectVirtualBases.count(RT))
2289 continue;
2290
Anders Carlsson9f853df2009-11-17 04:44:12 +00002291 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002292 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002293 if (BaseClassDecl->hasTrivialDestructor())
2294 continue;
John McCall58e6f342010-03-16 05:22:47 +00002295
Douglas Gregordb89f282010-07-01 22:47:18 +00002296 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002297 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002298 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002299 << VBase->getType());
2300
John McCallef027fe2010-03-16 21:39:52 +00002301 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002302 }
2303}
2304
John McCalld226f652010-08-21 09:40:31 +00002305void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002306 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002307 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Mike Stump1eb44332009-09-09 15:08:12 +00002309 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002310 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlssonec3332b2010-04-02 03:43:34 +00002311 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002312}
2313
Mike Stump1eb44332009-09-09 15:08:12 +00002314bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002315 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002316 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002317 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002318 else
John McCall94c3b562010-08-18 09:41:07 +00002319 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002320}
2321
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002322bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002323 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002324 if (!getLangOptions().CPlusPlus)
2325 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002326
Anders Carlsson11f21a02009-03-23 19:10:31 +00002327 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002328 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002329
Ted Kremenek6217b802009-07-29 21:53:49 +00002330 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002331 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002332 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002333 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002335 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002336 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002337 }
Mike Stump1eb44332009-09-09 15:08:12 +00002338
Ted Kremenek6217b802009-07-29 21:53:49 +00002339 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002340 if (!RT)
2341 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002342
John McCall86ff3082010-02-04 22:26:26 +00002343 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002344
John McCall94c3b562010-08-18 09:41:07 +00002345 // We can't answer whether something is abstract until it has a
2346 // definition. If it's currently being defined, we'll walk back
2347 // over all the declarations when we have a full definition.
2348 const CXXRecordDecl *Def = RD->getDefinition();
2349 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002350 return false;
2351
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002352 if (!RD->isAbstract())
2353 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002354
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002355 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002356 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002357
John McCall94c3b562010-08-18 09:41:07 +00002358 return true;
2359}
2360
2361void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2362 // Check if we've already emitted the list of pure virtual functions
2363 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002364 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002365 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002366
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002367 CXXFinalOverriderMap FinalOverriders;
2368 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002369
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002370 // Keep a set of seen pure methods so we won't diagnose the same method
2371 // more than once.
2372 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2373
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002374 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2375 MEnd = FinalOverriders.end();
2376 M != MEnd;
2377 ++M) {
2378 for (OverridingMethods::iterator SO = M->second.begin(),
2379 SOEnd = M->second.end();
2380 SO != SOEnd; ++SO) {
2381 // C++ [class.abstract]p4:
2382 // A class is abstract if it contains or inherits at least one
2383 // pure virtual function for which the final overrider is pure
2384 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002385
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002386 //
2387 if (SO->second.size() != 1)
2388 continue;
2389
2390 if (!SO->second.front().Method->isPure())
2391 continue;
2392
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002393 if (!SeenPureMethods.insert(SO->second.front().Method))
2394 continue;
2395
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002396 Diag(SO->second.front().Method->getLocation(),
2397 diag::note_pure_virtual_function)
2398 << SO->second.front().Method->getDeclName();
2399 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002400 }
2401
2402 if (!PureVirtualClassDiagSet)
2403 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2404 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002405}
2406
Anders Carlsson8211eff2009-03-24 01:19:16 +00002407namespace {
John McCall94c3b562010-08-18 09:41:07 +00002408struct AbstractUsageInfo {
2409 Sema &S;
2410 CXXRecordDecl *Record;
2411 CanQualType AbstractType;
2412 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002413
John McCall94c3b562010-08-18 09:41:07 +00002414 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2415 : S(S), Record(Record),
2416 AbstractType(S.Context.getCanonicalType(
2417 S.Context.getTypeDeclType(Record))),
2418 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002419
John McCall94c3b562010-08-18 09:41:07 +00002420 void DiagnoseAbstractType() {
2421 if (Invalid) return;
2422 S.DiagnoseAbstractType(Record);
2423 Invalid = true;
2424 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002425
John McCall94c3b562010-08-18 09:41:07 +00002426 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2427};
2428
2429struct CheckAbstractUsage {
2430 AbstractUsageInfo &Info;
2431 const NamedDecl *Ctx;
2432
2433 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2434 : Info(Info), Ctx(Ctx) {}
2435
2436 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2437 switch (TL.getTypeLocClass()) {
2438#define ABSTRACT_TYPELOC(CLASS, PARENT)
2439#define TYPELOC(CLASS, PARENT) \
2440 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2441#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002442 }
John McCall94c3b562010-08-18 09:41:07 +00002443 }
Mike Stump1eb44332009-09-09 15:08:12 +00002444
John McCall94c3b562010-08-18 09:41:07 +00002445 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2446 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2447 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2448 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2449 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002450 }
John McCall94c3b562010-08-18 09:41:07 +00002451 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002452
John McCall94c3b562010-08-18 09:41:07 +00002453 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2454 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2455 }
Mike Stump1eb44332009-09-09 15:08:12 +00002456
John McCall94c3b562010-08-18 09:41:07 +00002457 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2458 // Visit the type parameters from a permissive context.
2459 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2460 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2461 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2462 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2463 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2464 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002465 }
John McCall94c3b562010-08-18 09:41:07 +00002466 }
Mike Stump1eb44332009-09-09 15:08:12 +00002467
John McCall94c3b562010-08-18 09:41:07 +00002468 // Visit pointee types from a permissive context.
2469#define CheckPolymorphic(Type) \
2470 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2471 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2472 }
2473 CheckPolymorphic(PointerTypeLoc)
2474 CheckPolymorphic(ReferenceTypeLoc)
2475 CheckPolymorphic(MemberPointerTypeLoc)
2476 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002477
John McCall94c3b562010-08-18 09:41:07 +00002478 /// Handle all the types we haven't given a more specific
2479 /// implementation for above.
2480 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2481 // Every other kind of type that we haven't called out already
2482 // that has an inner type is either (1) sugar or (2) contains that
2483 // inner type in some way as a subobject.
2484 if (TypeLoc Next = TL.getNextTypeLoc())
2485 return Visit(Next, Sel);
2486
2487 // If there's no inner type and we're in a permissive context,
2488 // don't diagnose.
2489 if (Sel == Sema::AbstractNone) return;
2490
2491 // Check whether the type matches the abstract type.
2492 QualType T = TL.getType();
2493 if (T->isArrayType()) {
2494 Sel = Sema::AbstractArrayType;
2495 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002496 }
John McCall94c3b562010-08-18 09:41:07 +00002497 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2498 if (CT != Info.AbstractType) return;
2499
2500 // It matched; do some magic.
2501 if (Sel == Sema::AbstractArrayType) {
2502 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2503 << T << TL.getSourceRange();
2504 } else {
2505 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2506 << Sel << T << TL.getSourceRange();
2507 }
2508 Info.DiagnoseAbstractType();
2509 }
2510};
2511
2512void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2513 Sema::AbstractDiagSelID Sel) {
2514 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2515}
2516
2517}
2518
2519/// Check for invalid uses of an abstract type in a method declaration.
2520static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2521 CXXMethodDecl *MD) {
2522 // No need to do the check on definitions, which require that
2523 // the return/param types be complete.
2524 if (MD->isThisDeclarationADefinition())
2525 return;
2526
2527 // For safety's sake, just ignore it if we don't have type source
2528 // information. This should never happen for non-implicit methods,
2529 // but...
2530 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2531 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2532}
2533
2534/// Check for invalid uses of an abstract type within a class definition.
2535static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2536 CXXRecordDecl *RD) {
2537 for (CXXRecordDecl::decl_iterator
2538 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2539 Decl *D = *I;
2540 if (D->isImplicit()) continue;
2541
2542 // Methods and method templates.
2543 if (isa<CXXMethodDecl>(D)) {
2544 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2545 } else if (isa<FunctionTemplateDecl>(D)) {
2546 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2547 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2548
2549 // Fields and static variables.
2550 } else if (isa<FieldDecl>(D)) {
2551 FieldDecl *FD = cast<FieldDecl>(D);
2552 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2553 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2554 } else if (isa<VarDecl>(D)) {
2555 VarDecl *VD = cast<VarDecl>(D);
2556 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2557 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2558
2559 // Nested classes and class templates.
2560 } else if (isa<CXXRecordDecl>(D)) {
2561 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2562 } else if (isa<ClassTemplateDecl>(D)) {
2563 CheckAbstractClassUsage(Info,
2564 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2565 }
2566 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002567}
2568
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002569/// \brief Perform semantic checks on a class definition that has been
2570/// completing, introducing implicitly-declared members, checking for
2571/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002572void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002573 if (!Record || Record->isInvalidDecl())
2574 return;
2575
Eli Friedmanff2d8782009-12-16 20:00:27 +00002576 if (!Record->isDependentType())
Douglas Gregor23c94db2010-07-02 17:43:08 +00002577 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002578
Eli Friedmanff2d8782009-12-16 20:00:27 +00002579 if (Record->isInvalidDecl())
2580 return;
2581
John McCall233a6412010-01-28 07:38:46 +00002582 // Set access bits correctly on the directly-declared conversions.
2583 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2584 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2585 Convs->setAccess(I, (*I)->getAccess());
2586
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002587 // Determine whether we need to check for final overriders. We do
2588 // this either when there are virtual base classes (in which case we
2589 // may end up finding multiple final overriders for a given virtual
2590 // function) or any of the base classes is abstract (in which case
2591 // we might detect that this class is abstract).
2592 bool CheckFinalOverriders = false;
2593 if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2594 !Record->isDependentType()) {
2595 if (Record->getNumVBases())
2596 CheckFinalOverriders = true;
2597 else if (!Record->isAbstract()) {
2598 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2599 BEnd = Record->bases_end();
2600 B != BEnd; ++B) {
2601 CXXRecordDecl *BaseDecl
2602 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2603 if (BaseDecl->isAbstract()) {
2604 CheckFinalOverriders = true;
2605 break;
2606 }
2607 }
2608 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002609 }
2610
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002611 if (CheckFinalOverriders) {
2612 CXXFinalOverriderMap FinalOverriders;
2613 Record->getFinalOverriders(FinalOverriders);
2614
2615 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2616 MEnd = FinalOverriders.end();
2617 M != MEnd; ++M) {
2618 for (OverridingMethods::iterator SO = M->second.begin(),
2619 SOEnd = M->second.end();
2620 SO != SOEnd; ++SO) {
2621 assert(SO->second.size() > 0 &&
2622 "All virtual functions have overridding virtual functions");
2623 if (SO->second.size() == 1) {
2624 // C++ [class.abstract]p4:
2625 // A class is abstract if it contains or inherits at least one
2626 // pure virtual function for which the final overrider is pure
2627 // virtual.
2628 if (SO->second.front().Method->isPure())
2629 Record->setAbstract(true);
2630 continue;
2631 }
2632
2633 // C++ [class.virtual]p2:
2634 // In a derived class, if a virtual member function of a base
2635 // class subobject has more than one final overrider the
2636 // program is ill-formed.
2637 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2638 << (NamedDecl *)M->first << Record;
2639 Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2640 for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2641 OMEnd = SO->second.end();
2642 OM != OMEnd; ++OM)
2643 Diag(OM->Method->getLocation(), diag::note_final_overrider)
2644 << (NamedDecl *)M->first << OM->Method->getParent();
2645
2646 Record->setInvalidDecl();
2647 }
2648 }
2649 }
2650
John McCall94c3b562010-08-18 09:41:07 +00002651 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2652 AbstractUsageInfo Info(*this, Record);
2653 CheckAbstractClassUsage(Info, Record);
2654 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002655
2656 // If this is not an aggregate type and has no user-declared constructor,
2657 // complain about any non-static data members of reference or const scalar
2658 // type, since they will never get initializers.
2659 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2660 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2661 bool Complained = false;
2662 for (RecordDecl::field_iterator F = Record->field_begin(),
2663 FEnd = Record->field_end();
2664 F != FEnd; ++F) {
2665 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002666 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002667 if (!Complained) {
2668 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2669 << Record->getTagKind() << Record;
2670 Complained = true;
2671 }
2672
2673 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2674 << F->getType()->isReferenceType()
2675 << F->getDeclName();
2676 }
2677 }
2678 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002679
2680 if (Record->isDynamicClass())
2681 DynamicClasses.push_back(Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002682}
2683
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002684void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00002685 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002686 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002687 SourceLocation RBrac,
2688 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002689 if (!TagDecl)
2690 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002691
Douglas Gregor42af25f2009-05-11 19:58:34 +00002692 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002693
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002694 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00002695 // strict aliasing violation!
2696 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002697 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002698
Douglas Gregor23c94db2010-07-02 17:43:08 +00002699 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00002700 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002701}
2702
Douglas Gregord92ec472010-07-01 05:10:53 +00002703namespace {
2704 /// \brief Helper class that collects exception specifications for
2705 /// implicitly-declared special member functions.
2706 class ImplicitExceptionSpecification {
2707 ASTContext &Context;
2708 bool AllowsAllExceptions;
2709 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2710 llvm::SmallVector<QualType, 4> Exceptions;
2711
2712 public:
2713 explicit ImplicitExceptionSpecification(ASTContext &Context)
2714 : Context(Context), AllowsAllExceptions(false) { }
2715
2716 /// \brief Whether the special member function should have any
2717 /// exception specification at all.
2718 bool hasExceptionSpecification() const {
2719 return !AllowsAllExceptions;
2720 }
2721
2722 /// \brief Whether the special member function should have a
2723 /// throw(...) exception specification (a Microsoft extension).
2724 bool hasAnyExceptionSpecification() const {
2725 return false;
2726 }
2727
2728 /// \brief The number of exceptions in the exception specification.
2729 unsigned size() const { return Exceptions.size(); }
2730
2731 /// \brief The set of exceptions in the exception specification.
2732 const QualType *data() const { return Exceptions.data(); }
2733
2734 /// \brief Note that
2735 void CalledDecl(CXXMethodDecl *Method) {
2736 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor4681ca82010-07-01 15:29:53 +00002737 if (AllowsAllExceptions || !Method)
Douglas Gregord92ec472010-07-01 05:10:53 +00002738 return;
2739
2740 const FunctionProtoType *Proto
2741 = Method->getType()->getAs<FunctionProtoType>();
2742
2743 // If this function can throw any exceptions, make a note of that.
2744 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2745 AllowsAllExceptions = true;
2746 ExceptionsSeen.clear();
2747 Exceptions.clear();
2748 return;
2749 }
2750
2751 // Record the exceptions in this function's exception specification.
2752 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2753 EEnd = Proto->exception_end();
2754 E != EEnd; ++E)
2755 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2756 Exceptions.push_back(*E);
2757 }
2758 };
2759}
2760
2761
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002762/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2763/// special functions, such as the default constructor, copy
2764/// constructor, or destructor, to the given C++ class (C++
2765/// [special]p1). This routine can only be executed just before the
2766/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002767void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00002768 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002769 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002770
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00002771 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00002772 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002773
Douglas Gregora376d102010-07-02 21:50:04 +00002774 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2775 ++ASTContext::NumImplicitCopyAssignmentOperators;
2776
2777 // If we have a dynamic class, then the copy assignment operator may be
2778 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2779 // it shows up in the right place in the vtable and that we diagnose
2780 // problems with the implicit exception specification.
2781 if (ClassDecl->isDynamicClass())
2782 DeclareImplicitCopyAssignment(ClassDecl);
2783 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002784
Douglas Gregor4923aa22010-07-02 20:37:36 +00002785 if (!ClassDecl->hasUserDeclaredDestructor()) {
2786 ++ASTContext::NumImplicitDestructors;
2787
2788 // If we have a dynamic class, then the destructor may be virtual, so we
2789 // have to declare the destructor immediately. This ensures that, e.g., it
2790 // shows up in the right place in the vtable and that we diagnose problems
2791 // with the implicit exception specification.
2792 if (ClassDecl->isDynamicClass())
2793 DeclareImplicitDestructor(ClassDecl);
2794 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002795}
2796
John McCalld226f652010-08-21 09:40:31 +00002797void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002798 if (!D)
2799 return;
2800
2801 TemplateParameterList *Params = 0;
2802 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2803 Params = Template->getTemplateParameters();
2804 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2805 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2806 Params = PartialSpec->getTemplateParameters();
2807 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002808 return;
2809
Douglas Gregor6569d682009-05-27 23:11:45 +00002810 for (TemplateParameterList::iterator Param = Params->begin(),
2811 ParamEnd = Params->end();
2812 Param != ParamEnd; ++Param) {
2813 NamedDecl *Named = cast<NamedDecl>(*Param);
2814 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00002815 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00002816 IdResolver.AddDecl(Named);
2817 }
2818 }
2819}
2820
John McCalld226f652010-08-21 09:40:31 +00002821void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002822 if (!RecordD) return;
2823 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00002824 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00002825 PushDeclContext(S, Record);
2826}
2827
John McCalld226f652010-08-21 09:40:31 +00002828void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002829 if (!RecordD) return;
2830 PopDeclContext();
2831}
2832
Douglas Gregor72b505b2008-12-16 21:30:33 +00002833/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2834/// parsing a top-level (non-nested) C++ class, and we are now
2835/// parsing those parts of the given Method declaration that could
2836/// not be parsed earlier (C++ [class.mem]p2), such as default
2837/// arguments. This action should enter the scope of the given
2838/// Method declaration as if we had just parsed the qualified method
2839/// name. However, it should not bring the parameters into scope;
2840/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00002841void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002842}
2843
2844/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2845/// C++ method declaration. We're (re-)introducing the given
2846/// function parameter into scope for use in parsing later parts of
2847/// the method declaration. For example, we could see an
2848/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00002849void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002850 if (!ParamD)
2851 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002852
John McCalld226f652010-08-21 09:40:31 +00002853 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00002854
2855 // If this parameter has an unparsed default argument, clear it out
2856 // to make way for the parsed default argument.
2857 if (Param->hasUnparsedDefaultArg())
2858 Param->setDefaultArg(0);
2859
John McCalld226f652010-08-21 09:40:31 +00002860 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002861 if (Param->getDeclName())
2862 IdResolver.AddDecl(Param);
2863}
2864
2865/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2866/// processing the delayed method declaration for Method. The method
2867/// declaration is now considered finished. There may be a separate
2868/// ActOnStartOfFunctionDef action later (not necessarily
2869/// immediately!) for this method, if it was also defined inside the
2870/// class body.
John McCalld226f652010-08-21 09:40:31 +00002871void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002872 if (!MethodD)
2873 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002874
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002875 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002876
John McCalld226f652010-08-21 09:40:31 +00002877 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002878
2879 // Now that we have our default arguments, check the constructor
2880 // again. It could produce additional diagnostics or affect whether
2881 // the class has implicitly-declared destructors, among other
2882 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002883 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2884 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002885
2886 // Check the default arguments, which we may have added.
2887 if (!Method->isInvalidDecl())
2888 CheckCXXDefaultArguments(Method);
2889}
2890
Douglas Gregor42a552f2008-11-05 20:51:48 +00002891/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002892/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002893/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002894/// emit diagnostics and set the invalid bit to true. In any case, the type
2895/// will be updated to reflect a well-formed type for the constructor and
2896/// returned.
2897QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00002898 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002899 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002900
2901 // C++ [class.ctor]p3:
2902 // A constructor shall not be virtual (10.3) or static (9.4). A
2903 // constructor can be invoked for a const, volatile or const
2904 // volatile object. A constructor shall not be declared const,
2905 // volatile, or const volatile (9.3.2).
2906 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002907 if (!D.isInvalidType())
2908 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2909 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2910 << SourceRange(D.getIdentifierLoc());
2911 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002912 }
John McCalld931b082010-08-26 03:08:43 +00002913 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002914 if (!D.isInvalidType())
2915 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2916 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2917 << SourceRange(D.getIdentifierLoc());
2918 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00002919 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002920 }
Mike Stump1eb44332009-09-09 15:08:12 +00002921
Chris Lattner65401802009-04-25 08:28:21 +00002922 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2923 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002924 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002925 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2926 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002927 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002928 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2929 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002930 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002931 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2932 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002933 }
Mike Stump1eb44332009-09-09 15:08:12 +00002934
Douglas Gregor42a552f2008-11-05 20:51:48 +00002935 // Rebuild the function type "R" without any type qualifiers (in
2936 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00002937 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00002938 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002939 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2940 Proto->getNumArgs(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002941 Proto->isVariadic(), 0,
2942 Proto->hasExceptionSpec(),
2943 Proto->hasAnyExceptionSpec(),
2944 Proto->getNumExceptions(),
2945 Proto->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00002946 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002947}
2948
Douglas Gregor72b505b2008-12-16 21:30:33 +00002949/// CheckConstructor - Checks a fully-formed constructor for
2950/// well-formedness, issuing any diagnostics required. Returns true if
2951/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002952void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002953 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002954 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2955 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002956 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002957
2958 // C++ [class.copy]p3:
2959 // A declaration of a constructor for a class X is ill-formed if
2960 // its first parameter is of type (optionally cv-qualified) X and
2961 // either there are no other parameters or else all other
2962 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002963 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002964 ((Constructor->getNumParams() == 1) ||
2965 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002966 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2967 Constructor->getTemplateSpecializationKind()
2968 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002969 QualType ParamType = Constructor->getParamDecl(0)->getType();
2970 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2971 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002972 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002973 const char *ConstRef
2974 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2975 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00002976 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002977 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002978
2979 // FIXME: Rather that making the constructor invalid, we should endeavor
2980 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002981 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002982 }
2983 }
Mike Stump1eb44332009-09-09 15:08:12 +00002984
John McCall3d043362010-04-13 07:45:41 +00002985 // Notify the class that we've added a constructor. In principle we
2986 // don't need to do this for out-of-line declarations; in practice
2987 // we only instantiate the most recent declaration of a method, so
2988 // we have to call this for everything but friends.
2989 if (!Constructor->getFriendObjectKind())
2990 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002991}
2992
John McCall15442822010-08-04 01:04:25 +00002993/// CheckDestructor - Checks a fully-formed destructor definition for
2994/// well-formedness, issuing any diagnostics required. Returns true
2995/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002996bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002997 CXXRecordDecl *RD = Destructor->getParent();
2998
2999 if (Destructor->isVirtual()) {
3000 SourceLocation Loc;
3001
3002 if (!Destructor->isImplicit())
3003 Loc = Destructor->getLocation();
3004 else
3005 Loc = RD->getLocation();
3006
3007 // If we have a virtual destructor, look up the deallocation function
3008 FunctionDecl *OperatorDelete = 0;
3009 DeclarationName Name =
3010 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003011 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00003012 return true;
John McCall5efd91a2010-07-03 18:33:00 +00003013
3014 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00003015
3016 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00003017 }
Anders Carlsson37909802009-11-30 21:24:50 +00003018
3019 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00003020}
3021
Mike Stump1eb44332009-09-09 15:08:12 +00003022static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003023FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3024 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3025 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00003026 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003027}
3028
Douglas Gregor42a552f2008-11-05 20:51:48 +00003029/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3030/// the well-formednes of the destructor declarator @p D with type @p
3031/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003032/// emit diagnostics and set the declarator to invalid. Even if this happens,
3033/// will be updated to reflect a well-formed type for the destructor and
3034/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00003035QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003036 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003037 // C++ [class.dtor]p1:
3038 // [...] A typedef-name that names a class is a class-name
3039 // (7.1.3); however, a typedef-name that names a class shall not
3040 // be used as the identifier in the declarator for a destructor
3041 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003042 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregord92ec472010-07-01 05:10:53 +00003043 if (isa<TypedefType>(DeclaratorType))
Chris Lattner65401802009-04-25 08:28:21 +00003044 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003045 << DeclaratorType;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003046
3047 // C++ [class.dtor]p2:
3048 // A destructor is used to destroy objects of its class type. A
3049 // destructor takes no parameters, and no return type can be
3050 // specified for it (not even void). The address of a destructor
3051 // shall not be taken. A destructor shall not be static. A
3052 // destructor can be invoked for a const, volatile or const
3053 // volatile object. A destructor shall not be declared const,
3054 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00003055 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003056 if (!D.isInvalidType())
3057 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3058 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00003059 << SourceRange(D.getIdentifierLoc())
3060 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3061
John McCalld931b082010-08-26 03:08:43 +00003062 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003063 }
Chris Lattner65401802009-04-25 08:28:21 +00003064 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003065 // Destructors don't have return types, but the parser will
3066 // happily parse something like:
3067 //
3068 // class X {
3069 // float ~X();
3070 // };
3071 //
3072 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003073 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3074 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3075 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003076 }
Mike Stump1eb44332009-09-09 15:08:12 +00003077
Chris Lattner65401802009-04-25 08:28:21 +00003078 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3079 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003080 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003081 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3082 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003083 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003084 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3085 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003086 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003087 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3088 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003089 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003090 }
3091
3092 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003093 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003094 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3095
3096 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003097 FTI.freeArgs();
3098 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003099 }
3100
Mike Stump1eb44332009-09-09 15:08:12 +00003101 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003102 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003103 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003104 D.setInvalidType();
3105 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003106
3107 // Rebuild the function type "R" without any type qualifiers or
3108 // parameters (in case any of the errors above fired) and with
3109 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003110 // types.
3111 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3112 if (!Proto)
3113 return QualType();
3114
Douglas Gregorce056bc2010-02-21 22:15:06 +00003115 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Douglas Gregord92ec472010-07-01 05:10:53 +00003116 Proto->hasExceptionSpec(),
3117 Proto->hasAnyExceptionSpec(),
3118 Proto->getNumExceptions(),
3119 Proto->exception_begin(),
3120 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003121}
3122
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003123/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3124/// well-formednes of the conversion function declarator @p D with
3125/// type @p R. If there are any errors in the declarator, this routine
3126/// will emit diagnostics and return true. Otherwise, it will return
3127/// false. Either way, the type @p R will be updated to reflect a
3128/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003129void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003130 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003131 // C++ [class.conv.fct]p1:
3132 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003133 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003134 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003135 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003136 if (!D.isInvalidType())
3137 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3138 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3139 << SourceRange(D.getIdentifierLoc());
3140 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003141 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003142 }
John McCalla3f81372010-04-13 00:04:31 +00003143
3144 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3145
Chris Lattner6e475012009-04-25 08:35:12 +00003146 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003147 // Conversion functions don't have return types, but the parser will
3148 // happily parse something like:
3149 //
3150 // class X {
3151 // float operator bool();
3152 // };
3153 //
3154 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003155 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3156 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3157 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003158 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003159 }
3160
John McCalla3f81372010-04-13 00:04:31 +00003161 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3162
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003163 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003164 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003165 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3166
3167 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00003168 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003169 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003170 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003171 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003172 D.setInvalidType();
3173 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003174
John McCalla3f81372010-04-13 00:04:31 +00003175 // Diagnose "&operator bool()" and other such nonsense. This
3176 // is actually a gcc extension which we don't support.
3177 if (Proto->getResultType() != ConvType) {
3178 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3179 << Proto->getResultType();
3180 D.setInvalidType();
3181 ConvType = Proto->getResultType();
3182 }
3183
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003184 // C++ [class.conv.fct]p4:
3185 // The conversion-type-id shall not represent a function type nor
3186 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003187 if (ConvType->isArrayType()) {
3188 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3189 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003190 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003191 } else if (ConvType->isFunctionType()) {
3192 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3193 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003194 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003195 }
3196
3197 // Rebuild the function type "R" without any parameters (in case any
3198 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003199 // return type.
John McCalla3f81372010-04-13 00:04:31 +00003200 if (D.isInvalidType()) {
3201 R = Context.getFunctionType(ConvType, 0, 0, false,
3202 Proto->getTypeQuals(),
3203 Proto->hasExceptionSpec(),
3204 Proto->hasAnyExceptionSpec(),
3205 Proto->getNumExceptions(),
3206 Proto->exception_begin(),
3207 Proto->getExtInfo());
3208 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003209
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003210 // C++0x explicit conversion operators.
3211 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003212 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003213 diag::warn_explicit_conversion_functions)
3214 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003215}
3216
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003217/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3218/// the declaration of the given C++ conversion function. This routine
3219/// is responsible for recording the conversion function in the C++
3220/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003221Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003222 assert(Conversion && "Expected to receive a conversion function declaration");
3223
Douglas Gregor9d350972008-12-12 08:25:50 +00003224 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003225
3226 // Make sure we aren't redeclaring the conversion function.
3227 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003228
3229 // C++ [class.conv.fct]p1:
3230 // [...] A conversion function is never used to convert a
3231 // (possibly cv-qualified) object to the (possibly cv-qualified)
3232 // same object type (or a reference to it), to a (possibly
3233 // cv-qualified) base class of that type (or a reference to it),
3234 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003235 // FIXME: Suppress this warning if the conversion function ends up being a
3236 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003237 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003238 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003239 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003240 ConvType = ConvTypeRef->getPointeeType();
3241 if (ConvType->isRecordType()) {
3242 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3243 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003244 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003245 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003246 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003247 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003248 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003249 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003250 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003251 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003252 }
3253
Douglas Gregor48026d22010-01-11 18:40:55 +00003254 if (Conversion->getPrimaryTemplate()) {
3255 // ignore specializations
3256 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003257 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor0c551062010-01-11 18:53:25 +00003258 = Conversion->getDescribedFunctionTemplate()) {
3259 if (ClassDecl->replaceConversion(
3260 ConversionTemplate->getPreviousDeclaration(),
3261 ConversionTemplate))
John McCalld226f652010-08-21 09:40:31 +00003262 return ConversionTemplate;
Douglas Gregor0c551062010-01-11 18:53:25 +00003263 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3264 Conversion))
John McCalld226f652010-08-21 09:40:31 +00003265 return Conversion;
Douglas Gregor70316a02008-12-26 15:00:45 +00003266 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00003267 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003268 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00003269 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor48026d22010-01-11 18:40:55 +00003270 else
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00003271 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003272
John McCalld226f652010-08-21 09:40:31 +00003273 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003274}
3275
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003276//===----------------------------------------------------------------------===//
3277// Namespace Handling
3278//===----------------------------------------------------------------------===//
3279
3280/// ActOnStartNamespaceDef - This is called at the start of a namespace
3281/// definition.
John McCalld226f652010-08-21 09:40:31 +00003282Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003283 SourceLocation IdentLoc,
3284 IdentifierInfo *II,
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003285 SourceLocation LBrace,
3286 AttributeList *AttrList) {
Douglas Gregor21e09b62010-08-19 20:55:47 +00003287 // anonymous namespace starts at its left brace
3288 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3289 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003290 Namespc->setLBracLoc(LBrace);
3291
3292 Scope *DeclRegionScope = NamespcScope->getParent();
3293
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003294 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3295
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003296 if (const VisibilityAttr *attr = Namespc->getAttr<VisibilityAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00003297 PushPragmaVisibility(attr->getVisibility(), attr->getLocation());
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003298
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003299 if (II) {
3300 // C++ [namespace.def]p2:
3301 // The identifier in an original-namespace-definition shall not have been
3302 // previously defined in the declarative region in which the
3303 // original-namespace-definition appears. The identifier in an
3304 // original-namespace-definition is the name of the namespace. Subsequently
3305 // in that declarative region, it is treated as an original-namespace-name.
3306
John McCallf36e02d2009-10-09 21:13:30 +00003307 NamedDecl *PrevDecl
Douglas Gregorc83c6872010-04-15 22:33:43 +00003308 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00003309 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00003310
Douglas Gregor44b43212008-12-11 16:49:14 +00003311 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3312 // This is an extended namespace definition.
3313 // Attach this namespace decl to the chain of extended namespace
3314 // definitions.
3315 OrigNS->setNextNamespace(Namespc);
3316 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003317
Mike Stump1eb44332009-09-09 15:08:12 +00003318 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003319 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003320 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003321 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003322 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003323 } else if (PrevDecl) {
3324 // This is an invalid name redefinition.
3325 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3326 << Namespc->getDeclName();
3327 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3328 Namespc->setInvalidDecl();
3329 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003330 } else if (II->isStr("std") &&
3331 CurContext->getLookupContext()->isTranslationUnit()) {
3332 // This is the first "real" definition of the namespace "std", so update
3333 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003334 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003335 // We had already defined a dummy namespace "std". Link this new
3336 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003337 StdNS->setNextNamespace(Namespc);
3338 StdNS->setLocation(IdentLoc);
3339 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003340 }
3341
3342 // Make our StdNamespace cache point at the first real definition of the
3343 // "std" namespace.
3344 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003345 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003346
3347 PushOnScopeChains(Namespc, DeclRegionScope);
3348 } else {
John McCall9aeed322009-10-01 00:25:31 +00003349 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003350 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003351
3352 // Link the anonymous namespace into its parent.
3353 NamespaceDecl *PrevDecl;
3354 DeclContext *Parent = CurContext->getLookupContext();
3355 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3356 PrevDecl = TU->getAnonymousNamespace();
3357 TU->setAnonymousNamespace(Namespc);
3358 } else {
3359 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3360 PrevDecl = ND->getAnonymousNamespace();
3361 ND->setAnonymousNamespace(Namespc);
3362 }
3363
3364 // Link the anonymous namespace with its previous declaration.
3365 if (PrevDecl) {
3366 assert(PrevDecl->isAnonymousNamespace());
3367 assert(!PrevDecl->getNextNamespace());
3368 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3369 PrevDecl->setNextNamespace(Namespc);
3370 }
John McCall9aeed322009-10-01 00:25:31 +00003371
Douglas Gregora4181472010-03-24 00:46:35 +00003372 CurContext->addDecl(Namespc);
3373
John McCall9aeed322009-10-01 00:25:31 +00003374 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3375 // behaves as if it were replaced by
3376 // namespace unique { /* empty body */ }
3377 // using namespace unique;
3378 // namespace unique { namespace-body }
3379 // where all occurrences of 'unique' in a translation unit are
3380 // replaced by the same identifier and this identifier differs
3381 // from all other identifiers in the entire program.
3382
3383 // We just create the namespace with an empty name and then add an
3384 // implicit using declaration, just like the standard suggests.
3385 //
3386 // CodeGen enforces the "universally unique" aspect by giving all
3387 // declarations semantically contained within an anonymous
3388 // namespace internal linkage.
3389
John McCall5fdd7642009-12-16 02:06:49 +00003390 if (!PrevDecl) {
3391 UsingDirectiveDecl* UD
3392 = UsingDirectiveDecl::Create(Context, CurContext,
3393 /* 'using' */ LBrace,
3394 /* 'namespace' */ SourceLocation(),
3395 /* qualifier */ SourceRange(),
3396 /* NNS */ NULL,
3397 /* identifier */ SourceLocation(),
3398 Namespc,
3399 /* Ancestor */ CurContext);
3400 UD->setImplicit();
3401 CurContext->addDecl(UD);
3402 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003403 }
3404
3405 // Although we could have an invalid decl (i.e. the namespace name is a
3406 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003407 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3408 // for the namespace has the declarations that showed up in that particular
3409 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003410 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003411 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003412}
3413
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003414/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3415/// is a namespace alias, returns the namespace it points to.
3416static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3417 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3418 return AD->getNamespace();
3419 return dyn_cast_or_null<NamespaceDecl>(D);
3420}
3421
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003422/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3423/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003424void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003425 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3426 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3427 Namespc->setRBracLoc(RBrace);
3428 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003429 if (Namespc->hasAttr<VisibilityAttr>())
3430 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003431}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003432
John McCall384aff82010-08-25 07:42:41 +00003433CXXRecordDecl *Sema::getStdBadAlloc() const {
3434 return cast_or_null<CXXRecordDecl>(
3435 StdBadAlloc.get(Context.getExternalSource()));
3436}
3437
3438NamespaceDecl *Sema::getStdNamespace() const {
3439 return cast_or_null<NamespaceDecl>(
3440 StdNamespace.get(Context.getExternalSource()));
3441}
3442
Douglas Gregor66992202010-06-29 17:53:46 +00003443/// \brief Retrieve the special "std" namespace, which may require us to
3444/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003445NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003446 if (!StdNamespace) {
3447 // The "std" namespace has not yet been defined, so build one implicitly.
3448 StdNamespace = NamespaceDecl::Create(Context,
3449 Context.getTranslationUnitDecl(),
3450 SourceLocation(),
3451 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003452 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003453 }
3454
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003455 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003456}
3457
John McCalld226f652010-08-21 09:40:31 +00003458Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003459 SourceLocation UsingLoc,
3460 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003461 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003462 SourceLocation IdentLoc,
3463 IdentifierInfo *NamespcName,
3464 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003465 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3466 assert(NamespcName && "Invalid NamespcName.");
3467 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003468 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003469
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003470 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003471 NestedNameSpecifier *Qualifier = 0;
3472 if (SS.isSet())
3473 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3474
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003475 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003476 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3477 LookupParsedName(R, S, &SS);
3478 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003479 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003480
Douglas Gregor66992202010-06-29 17:53:46 +00003481 if (R.empty()) {
3482 // Allow "using namespace std;" or "using namespace ::std;" even if
3483 // "std" hasn't been defined yet, for GCC compatibility.
3484 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3485 NamespcName->isStr("std")) {
3486 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003487 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003488 R.resolveKind();
3489 }
3490 // Otherwise, attempt typo correction.
3491 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3492 CTC_NoKeywords, 0)) {
3493 if (R.getAsSingle<NamespaceDecl>() ||
3494 R.getAsSingle<NamespaceAliasDecl>()) {
3495 if (DeclContext *DC = computeDeclContext(SS, false))
3496 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3497 << NamespcName << DC << Corrected << SS.getRange()
3498 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3499 else
3500 Diag(IdentLoc, diag::err_using_directive_suggest)
3501 << NamespcName << Corrected
3502 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3503 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3504 << Corrected;
3505
3506 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003507 } else {
3508 R.clear();
3509 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003510 }
3511 }
3512 }
3513
John McCallf36e02d2009-10-09 21:13:30 +00003514 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003515 NamedDecl *Named = R.getFoundDecl();
3516 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3517 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003518 // C++ [namespace.udir]p1:
3519 // A using-directive specifies that the names in the nominated
3520 // namespace can be used in the scope in which the
3521 // using-directive appears after the using-directive. During
3522 // unqualified name lookup (3.4.1), the names appear as if they
3523 // were declared in the nearest enclosing namespace which
3524 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003525 // namespace. [Note: in this context, "contains" means "contains
3526 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003527
3528 // Find enclosing context containing both using-directive and
3529 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003530 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003531 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3532 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3533 CommonAncestor = CommonAncestor->getParent();
3534
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003535 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003536 SS.getRange(),
3537 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003538 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003539 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003540 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003541 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003542 }
3543
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003544 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003545 delete AttrList;
John McCalld226f652010-08-21 09:40:31 +00003546 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003547}
3548
3549void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3550 // If scope has associated entity, then using directive is at namespace
3551 // or translation unit scope. We add UsingDirectiveDecls, into
3552 // it's lookup structure.
3553 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003554 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003555 else
3556 // Otherwise it is block-sope. using-directives will affect lookup
3557 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00003558 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003559}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003560
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003561
John McCalld226f652010-08-21 09:40:31 +00003562Decl *Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003563 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003564 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003565 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003566 CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003567 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003568 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003569 bool IsTypeName,
3570 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003571 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003572
Douglas Gregor12c118a2009-11-04 16:30:06 +00003573 switch (Name.getKind()) {
3574 case UnqualifiedId::IK_Identifier:
3575 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003576 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003577 case UnqualifiedId::IK_ConversionFunctionId:
3578 break;
3579
3580 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003581 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003582 // C++0x inherited constructors.
3583 if (getLangOptions().CPlusPlus0x) break;
3584
Douglas Gregor12c118a2009-11-04 16:30:06 +00003585 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3586 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003587 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003588
3589 case UnqualifiedId::IK_DestructorName:
3590 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3591 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003592 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003593
3594 case UnqualifiedId::IK_TemplateId:
3595 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3596 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00003597 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003598 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003599
3600 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3601 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00003602 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00003603 return 0;
John McCall604e7f12009-12-08 07:46:18 +00003604
John McCall60fa3cf2009-12-11 02:10:03 +00003605 // Warn about using declarations.
3606 // TODO: store that the declaration was written without 'using' and
3607 // talk about access decls instead of using decls in the
3608 // diagnostics.
3609 if (!HasUsingKeyword) {
3610 UsingLoc = Name.getSourceRange().getBegin();
3611
3612 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003613 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003614 }
3615
John McCall9488ea12009-11-17 05:59:44 +00003616 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003617 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003618 /* IsInstantiation */ false,
3619 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003620 if (UD)
3621 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003622
John McCalld226f652010-08-21 09:40:31 +00003623 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00003624}
3625
Douglas Gregor09acc982010-07-07 23:08:52 +00003626/// \brief Determine whether a using declaration considers the given
3627/// declarations as "equivalent", e.g., if they are redeclarations of
3628/// the same entity or are both typedefs of the same type.
3629static bool
3630IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3631 bool &SuppressRedeclaration) {
3632 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3633 SuppressRedeclaration = false;
3634 return true;
3635 }
3636
3637 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3638 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3639 SuppressRedeclaration = true;
3640 return Context.hasSameType(TD1->getUnderlyingType(),
3641 TD2->getUnderlyingType());
3642 }
3643
3644 return false;
3645}
3646
3647
John McCall9f54ad42009-12-10 09:41:52 +00003648/// Determines whether to create a using shadow decl for a particular
3649/// decl, given the set of decls existing prior to this using lookup.
3650bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3651 const LookupResult &Previous) {
3652 // Diagnose finding a decl which is not from a base class of the
3653 // current class. We do this now because there are cases where this
3654 // function will silently decide not to build a shadow decl, which
3655 // will pre-empt further diagnostics.
3656 //
3657 // We don't need to do this in C++0x because we do the check once on
3658 // the qualifier.
3659 //
3660 // FIXME: diagnose the following if we care enough:
3661 // struct A { int foo; };
3662 // struct B : A { using A::foo; };
3663 // template <class T> struct C : A {};
3664 // template <class T> struct D : C<T> { using B::foo; } // <---
3665 // This is invalid (during instantiation) in C++03 because B::foo
3666 // resolves to the using decl in B, which is not a base class of D<T>.
3667 // We can't diagnose it immediately because C<T> is an unknown
3668 // specialization. The UsingShadowDecl in D<T> then points directly
3669 // to A::foo, which will look well-formed when we instantiate.
3670 // The right solution is to not collapse the shadow-decl chain.
3671 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3672 DeclContext *OrigDC = Orig->getDeclContext();
3673
3674 // Handle enums and anonymous structs.
3675 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3676 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3677 while (OrigRec->isAnonymousStructOrUnion())
3678 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3679
3680 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3681 if (OrigDC == CurContext) {
3682 Diag(Using->getLocation(),
3683 diag::err_using_decl_nested_name_specifier_is_current_class)
3684 << Using->getNestedNameRange();
3685 Diag(Orig->getLocation(), diag::note_using_decl_target);
3686 return true;
3687 }
3688
3689 Diag(Using->getNestedNameRange().getBegin(),
3690 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3691 << Using->getTargetNestedNameDecl()
3692 << cast<CXXRecordDecl>(CurContext)
3693 << Using->getNestedNameRange();
3694 Diag(Orig->getLocation(), diag::note_using_decl_target);
3695 return true;
3696 }
3697 }
3698
3699 if (Previous.empty()) return false;
3700
3701 NamedDecl *Target = Orig;
3702 if (isa<UsingShadowDecl>(Target))
3703 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3704
John McCalld7533ec2009-12-11 02:33:26 +00003705 // If the target happens to be one of the previous declarations, we
3706 // don't have a conflict.
3707 //
3708 // FIXME: but we might be increasing its access, in which case we
3709 // should redeclare it.
3710 NamedDecl *NonTag = 0, *Tag = 0;
3711 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3712 I != E; ++I) {
3713 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00003714 bool Result;
3715 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3716 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00003717
3718 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3719 }
3720
John McCall9f54ad42009-12-10 09:41:52 +00003721 if (Target->isFunctionOrFunctionTemplate()) {
3722 FunctionDecl *FD;
3723 if (isa<FunctionTemplateDecl>(Target))
3724 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3725 else
3726 FD = cast<FunctionDecl>(Target);
3727
3728 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00003729 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00003730 case Ovl_Overload:
3731 return false;
3732
3733 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003734 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003735 break;
3736
3737 // We found a decl with the exact signature.
3738 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00003739 // If we're in a record, we want to hide the target, so we
3740 // return true (without a diagnostic) to tell the caller not to
3741 // build a shadow decl.
3742 if (CurContext->isRecord())
3743 return true;
3744
3745 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003746 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003747 break;
3748 }
3749
3750 Diag(Target->getLocation(), diag::note_using_decl_target);
3751 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3752 return true;
3753 }
3754
3755 // Target is not a function.
3756
John McCall9f54ad42009-12-10 09:41:52 +00003757 if (isa<TagDecl>(Target)) {
3758 // No conflict between a tag and a non-tag.
3759 if (!Tag) return false;
3760
John McCall41ce66f2009-12-10 19:51:03 +00003761 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003762 Diag(Target->getLocation(), diag::note_using_decl_target);
3763 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3764 return true;
3765 }
3766
3767 // No conflict between a tag and a non-tag.
3768 if (!NonTag) return false;
3769
John McCall41ce66f2009-12-10 19:51:03 +00003770 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003771 Diag(Target->getLocation(), diag::note_using_decl_target);
3772 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3773 return true;
3774}
3775
John McCall9488ea12009-11-17 05:59:44 +00003776/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003777UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003778 UsingDecl *UD,
3779 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003780
3781 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003782 NamedDecl *Target = Orig;
3783 if (isa<UsingShadowDecl>(Target)) {
3784 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3785 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003786 }
3787
3788 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003789 = UsingShadowDecl::Create(Context, CurContext,
3790 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003791 UD->addShadowDecl(Shadow);
3792
3793 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003794 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003795 else
John McCall604e7f12009-12-08 07:46:18 +00003796 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003797 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003798
John McCall32daa422010-03-31 01:36:47 +00003799 // Register it as a conversion if appropriate.
3800 if (Shadow->getDeclName().getNameKind()
3801 == DeclarationName::CXXConversionFunctionName)
3802 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3803
John McCall604e7f12009-12-08 07:46:18 +00003804 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3805 Shadow->setInvalidDecl();
3806
John McCall9f54ad42009-12-10 09:41:52 +00003807 return Shadow;
3808}
John McCall604e7f12009-12-08 07:46:18 +00003809
John McCall9f54ad42009-12-10 09:41:52 +00003810/// Hides a using shadow declaration. This is required by the current
3811/// using-decl implementation when a resolvable using declaration in a
3812/// class is followed by a declaration which would hide or override
3813/// one or more of the using decl's targets; for example:
3814///
3815/// struct Base { void foo(int); };
3816/// struct Derived : Base {
3817/// using Base::foo;
3818/// void foo(int);
3819/// };
3820///
3821/// The governing language is C++03 [namespace.udecl]p12:
3822///
3823/// When a using-declaration brings names from a base class into a
3824/// derived class scope, member functions in the derived class
3825/// override and/or hide member functions with the same name and
3826/// parameter types in a base class (rather than conflicting).
3827///
3828/// There are two ways to implement this:
3829/// (1) optimistically create shadow decls when they're not hidden
3830/// by existing declarations, or
3831/// (2) don't create any shadow decls (or at least don't make them
3832/// visible) until we've fully parsed/instantiated the class.
3833/// The problem with (1) is that we might have to retroactively remove
3834/// a shadow decl, which requires several O(n) operations because the
3835/// decl structures are (very reasonably) not designed for removal.
3836/// (2) avoids this but is very fiddly and phase-dependent.
3837void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00003838 if (Shadow->getDeclName().getNameKind() ==
3839 DeclarationName::CXXConversionFunctionName)
3840 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3841
John McCall9f54ad42009-12-10 09:41:52 +00003842 // Remove it from the DeclContext...
3843 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003844
John McCall9f54ad42009-12-10 09:41:52 +00003845 // ...and the scope, if applicable...
3846 if (S) {
John McCalld226f652010-08-21 09:40:31 +00003847 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003848 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003849 }
3850
John McCall9f54ad42009-12-10 09:41:52 +00003851 // ...and the using decl.
3852 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3853
3854 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00003855 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00003856}
3857
John McCall7ba107a2009-11-18 02:36:19 +00003858/// Builds a using declaration.
3859///
3860/// \param IsInstantiation - Whether this call arises from an
3861/// instantiation of an unresolved using declaration. We treat
3862/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003863NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3864 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003865 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003866 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003867 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003868 bool IsInstantiation,
3869 bool IsTypeName,
3870 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003871 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003872 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00003873 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003874
Anders Carlsson550b14b2009-08-28 05:49:21 +00003875 // FIXME: We ignore attributes for now.
3876 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003877
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003878 if (SS.isEmpty()) {
3879 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003880 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003881 }
Mike Stump1eb44332009-09-09 15:08:12 +00003882
John McCall9f54ad42009-12-10 09:41:52 +00003883 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003884 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00003885 ForRedeclaration);
3886 Previous.setHideTags(false);
3887 if (S) {
3888 LookupName(Previous, S);
3889
3890 // It is really dumb that we have to do this.
3891 LookupResult::Filter F = Previous.makeFilter();
3892 while (F.hasNext()) {
3893 NamedDecl *D = F.next();
3894 if (!isDeclInScope(D, CurContext, S))
3895 F.erase();
3896 }
3897 F.done();
3898 } else {
3899 assert(IsInstantiation && "no scope in non-instantiation");
3900 assert(CurContext->isRecord() && "scope not record in instantiation");
3901 LookupQualifiedName(Previous, CurContext);
3902 }
3903
Mike Stump1eb44332009-09-09 15:08:12 +00003904 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003905 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3906
John McCall9f54ad42009-12-10 09:41:52 +00003907 // Check for invalid redeclarations.
3908 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3909 return 0;
3910
3911 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003912 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3913 return 0;
3914
John McCallaf8e6ed2009-11-12 03:15:40 +00003915 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003916 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003917 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003918 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003919 // FIXME: not all declaration name kinds are legal here
3920 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3921 UsingLoc, TypenameLoc,
3922 SS.getRange(), NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003923 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00003924 } else {
3925 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003926 UsingLoc, SS.getRange(),
3927 NNS, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00003928 }
John McCalled976492009-12-04 22:46:56 +00003929 } else {
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003930 D = UsingDecl::Create(Context, CurContext,
3931 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCalled976492009-12-04 22:46:56 +00003932 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003933 }
John McCalled976492009-12-04 22:46:56 +00003934 D->setAccess(AS);
3935 CurContext->addDecl(D);
3936
3937 if (!LookupContext) return D;
3938 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003939
John McCall77bb1aa2010-05-01 00:40:08 +00003940 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00003941 UD->setInvalidDecl();
3942 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003943 }
3944
John McCall604e7f12009-12-08 07:46:18 +00003945 // Look up the target name.
3946
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003947 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003948
John McCall604e7f12009-12-08 07:46:18 +00003949 // Unlike most lookups, we don't always want to hide tag
3950 // declarations: tag names are visible through the using declaration
3951 // even if hidden by ordinary names, *except* in a dependent context
3952 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003953 if (!IsInstantiation)
3954 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003955
John McCalla24dc2e2009-11-17 02:14:36 +00003956 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003957
John McCallf36e02d2009-10-09 21:13:30 +00003958 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003959 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003960 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003961 UD->setInvalidDecl();
3962 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003963 }
3964
John McCalled976492009-12-04 22:46:56 +00003965 if (R.isAmbiguous()) {
3966 UD->setInvalidDecl();
3967 return UD;
3968 }
Mike Stump1eb44332009-09-09 15:08:12 +00003969
John McCall7ba107a2009-11-18 02:36:19 +00003970 if (IsTypeName) {
3971 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003972 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003973 Diag(IdentLoc, diag::err_using_typename_non_type);
3974 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3975 Diag((*I)->getUnderlyingDecl()->getLocation(),
3976 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003977 UD->setInvalidDecl();
3978 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003979 }
3980 } else {
3981 // If we asked for a non-typename and we got a type, error out,
3982 // but only if this is an instantiation of an unresolved using
3983 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003984 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003985 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3986 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003987 UD->setInvalidDecl();
3988 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003989 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003990 }
3991
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003992 // C++0x N2914 [namespace.udecl]p6:
3993 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003994 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003995 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3996 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003997 UD->setInvalidDecl();
3998 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003999 }
Mike Stump1eb44332009-09-09 15:08:12 +00004000
John McCall9f54ad42009-12-10 09:41:52 +00004001 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4002 if (!CheckUsingShadowDecl(UD, *I, Previous))
4003 BuildUsingShadowDecl(S, UD, *I);
4004 }
John McCall9488ea12009-11-17 05:59:44 +00004005
4006 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004007}
4008
John McCall9f54ad42009-12-10 09:41:52 +00004009/// Checks that the given using declaration is not an invalid
4010/// redeclaration. Note that this is checking only for the using decl
4011/// itself, not for any ill-formedness among the UsingShadowDecls.
4012bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4013 bool isTypeName,
4014 const CXXScopeSpec &SS,
4015 SourceLocation NameLoc,
4016 const LookupResult &Prev) {
4017 // C++03 [namespace.udecl]p8:
4018 // C++0x [namespace.udecl]p10:
4019 // A using-declaration is a declaration and can therefore be used
4020 // repeatedly where (and only where) multiple declarations are
4021 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00004022 //
4023 // That's in non-member contexts.
4024 if (!CurContext->getLookupContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00004025 return false;
4026
4027 NestedNameSpecifier *Qual
4028 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4029
4030 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4031 NamedDecl *D = *I;
4032
4033 bool DTypename;
4034 NestedNameSpecifier *DQual;
4035 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4036 DTypename = UD->isTypeName();
4037 DQual = UD->getTargetNestedNameDecl();
4038 } else if (UnresolvedUsingValueDecl *UD
4039 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4040 DTypename = false;
4041 DQual = UD->getTargetNestedNameSpecifier();
4042 } else if (UnresolvedUsingTypenameDecl *UD
4043 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4044 DTypename = true;
4045 DQual = UD->getTargetNestedNameSpecifier();
4046 } else continue;
4047
4048 // using decls differ if one says 'typename' and the other doesn't.
4049 // FIXME: non-dependent using decls?
4050 if (isTypeName != DTypename) continue;
4051
4052 // using decls differ if they name different scopes (but note that
4053 // template instantiation can cause this check to trigger when it
4054 // didn't before instantiation).
4055 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4056 Context.getCanonicalNestedNameSpecifier(DQual))
4057 continue;
4058
4059 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00004060 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00004061 return true;
4062 }
4063
4064 return false;
4065}
4066
John McCall604e7f12009-12-08 07:46:18 +00004067
John McCalled976492009-12-04 22:46:56 +00004068/// Checks that the given nested-name qualifier used in a using decl
4069/// in the current context is appropriately related to the current
4070/// scope. If an error is found, diagnoses it and returns true.
4071bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4072 const CXXScopeSpec &SS,
4073 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004074 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004075
John McCall604e7f12009-12-08 07:46:18 +00004076 if (!CurContext->isRecord()) {
4077 // C++03 [namespace.udecl]p3:
4078 // C++0x [namespace.udecl]p8:
4079 // A using-declaration for a class member shall be a member-declaration.
4080
4081 // If we weren't able to compute a valid scope, it must be a
4082 // dependent class scope.
4083 if (!NamedContext || NamedContext->isRecord()) {
4084 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4085 << SS.getRange();
4086 return true;
4087 }
4088
4089 // Otherwise, everything is known to be fine.
4090 return false;
4091 }
4092
4093 // The current scope is a record.
4094
4095 // If the named context is dependent, we can't decide much.
4096 if (!NamedContext) {
4097 // FIXME: in C++0x, we can diagnose if we can prove that the
4098 // nested-name-specifier does not refer to a base class, which is
4099 // still possible in some cases.
4100
4101 // Otherwise we have to conservatively report that things might be
4102 // okay.
4103 return false;
4104 }
4105
4106 if (!NamedContext->isRecord()) {
4107 // Ideally this would point at the last name in the specifier,
4108 // but we don't have that level of source info.
4109 Diag(SS.getRange().getBegin(),
4110 diag::err_using_decl_nested_name_specifier_is_not_class)
4111 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4112 return true;
4113 }
4114
4115 if (getLangOptions().CPlusPlus0x) {
4116 // C++0x [namespace.udecl]p3:
4117 // In a using-declaration used as a member-declaration, the
4118 // nested-name-specifier shall name a base class of the class
4119 // being defined.
4120
4121 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4122 cast<CXXRecordDecl>(NamedContext))) {
4123 if (CurContext == NamedContext) {
4124 Diag(NameLoc,
4125 diag::err_using_decl_nested_name_specifier_is_current_class)
4126 << SS.getRange();
4127 return true;
4128 }
4129
4130 Diag(SS.getRange().getBegin(),
4131 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4132 << (NestedNameSpecifier*) SS.getScopeRep()
4133 << cast<CXXRecordDecl>(CurContext)
4134 << SS.getRange();
4135 return true;
4136 }
4137
4138 return false;
4139 }
4140
4141 // C++03 [namespace.udecl]p4:
4142 // A using-declaration used as a member-declaration shall refer
4143 // to a member of a base class of the class being defined [etc.].
4144
4145 // Salient point: SS doesn't have to name a base class as long as
4146 // lookup only finds members from base classes. Therefore we can
4147 // diagnose here only if we can prove that that can't happen,
4148 // i.e. if the class hierarchies provably don't intersect.
4149
4150 // TODO: it would be nice if "definitely valid" results were cached
4151 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4152 // need to be repeated.
4153
4154 struct UserData {
4155 llvm::DenseSet<const CXXRecordDecl*> Bases;
4156
4157 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4158 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4159 Data->Bases.insert(Base);
4160 return true;
4161 }
4162
4163 bool hasDependentBases(const CXXRecordDecl *Class) {
4164 return !Class->forallBases(collect, this);
4165 }
4166
4167 /// Returns true if the base is dependent or is one of the
4168 /// accumulated base classes.
4169 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4170 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4171 return !Data->Bases.count(Base);
4172 }
4173
4174 bool mightShareBases(const CXXRecordDecl *Class) {
4175 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4176 }
4177 };
4178
4179 UserData Data;
4180
4181 // Returns false if we find a dependent base.
4182 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4183 return false;
4184
4185 // Returns false if the class has a dependent base or if it or one
4186 // of its bases is present in the base set of the current context.
4187 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4188 return false;
4189
4190 Diag(SS.getRange().getBegin(),
4191 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4192 << (NestedNameSpecifier*) SS.getScopeRep()
4193 << cast<CXXRecordDecl>(CurContext)
4194 << SS.getRange();
4195
4196 return true;
John McCalled976492009-12-04 22:46:56 +00004197}
4198
John McCalld226f652010-08-21 09:40:31 +00004199Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004200 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004201 SourceLocation AliasLoc,
4202 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004203 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004204 SourceLocation IdentLoc,
4205 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004206
Anders Carlsson81c85c42009-03-28 23:53:49 +00004207 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004208 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4209 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004210
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004211 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004212 NamedDecl *PrevDecl
4213 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4214 ForRedeclaration);
4215 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4216 PrevDecl = 0;
4217
4218 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004219 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004220 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004221 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004222 // FIXME: At some point, we'll want to create the (redundant)
4223 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004224 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004225 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004226 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004227 }
Mike Stump1eb44332009-09-09 15:08:12 +00004228
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004229 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4230 diag::err_redefinition_different_kind;
4231 Diag(AliasLoc, DiagID) << Alias;
4232 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004233 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004234 }
4235
John McCalla24dc2e2009-11-17 02:14:36 +00004236 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004237 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004238
John McCallf36e02d2009-10-09 21:13:30 +00004239 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004240 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4241 CTC_NoKeywords, 0)) {
4242 if (R.getAsSingle<NamespaceDecl>() ||
4243 R.getAsSingle<NamespaceAliasDecl>()) {
4244 if (DeclContext *DC = computeDeclContext(SS, false))
4245 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4246 << Ident << DC << Corrected << SS.getRange()
4247 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4248 else
4249 Diag(IdentLoc, diag::err_using_directive_suggest)
4250 << Ident << Corrected
4251 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4252
4253 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4254 << Corrected;
4255
4256 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004257 } else {
4258 R.clear();
4259 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004260 }
4261 }
4262
4263 if (R.empty()) {
4264 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004265 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004266 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004267 }
Mike Stump1eb44332009-09-09 15:08:12 +00004268
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004269 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004270 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4271 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004272 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004273 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004274
John McCall3dbd3d52010-02-16 06:53:13 +00004275 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004276 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004277}
4278
Douglas Gregor39957dc2010-05-01 15:04:51 +00004279namespace {
4280 /// \brief Scoped object used to handle the state changes required in Sema
4281 /// to implicitly define the body of a C++ member function;
4282 class ImplicitlyDefinedFunctionScope {
4283 Sema &S;
4284 DeclContext *PreviousContext;
4285
4286 public:
4287 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4288 : S(S), PreviousContext(S.CurContext)
4289 {
4290 S.CurContext = Method;
4291 S.PushFunctionScope();
4292 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4293 }
4294
4295 ~ImplicitlyDefinedFunctionScope() {
4296 S.PopExpressionEvaluationContext();
4297 S.PopFunctionOrBlockScope();
4298 S.CurContext = PreviousContext;
4299 }
4300 };
4301}
4302
Douglas Gregor23c94db2010-07-02 17:43:08 +00004303CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4304 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004305 // C++ [class.ctor]p5:
4306 // A default constructor for a class X is a constructor of class X
4307 // that can be called without an argument. If there is no
4308 // user-declared constructor for class X, a default constructor is
4309 // implicitly declared. An implicitly-declared default constructor
4310 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004311 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4312 "Should not build implicit default constructor!");
4313
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004314 // C++ [except.spec]p14:
4315 // An implicitly declared special member function (Clause 12) shall have an
4316 // exception-specification. [...]
4317 ImplicitExceptionSpecification ExceptSpec(Context);
4318
4319 // Direct base-class destructors.
4320 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4321 BEnd = ClassDecl->bases_end();
4322 B != BEnd; ++B) {
4323 if (B->isVirtual()) // Handled below.
4324 continue;
4325
Douglas Gregor18274032010-07-03 00:47:00 +00004326 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4327 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4328 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4329 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4330 else if (CXXConstructorDecl *Constructor
4331 = BaseClassDecl->getDefaultConstructor())
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004332 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004333 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004334 }
4335
4336 // Virtual base-class destructors.
4337 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4338 BEnd = ClassDecl->vbases_end();
4339 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004340 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4341 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4342 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4343 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4344 else if (CXXConstructorDecl *Constructor
4345 = BaseClassDecl->getDefaultConstructor())
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004346 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004347 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004348 }
4349
4350 // Field destructors.
4351 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4352 FEnd = ClassDecl->field_end();
4353 F != FEnd; ++F) {
4354 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004355 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4356 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4357 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4358 ExceptSpec.CalledDecl(
4359 DeclareImplicitDefaultConstructor(FieldClassDecl));
4360 else if (CXXConstructorDecl *Constructor
4361 = FieldClassDecl->getDefaultConstructor())
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004362 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004363 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004364 }
4365
4366
4367 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004368 CanQualType ClassType
4369 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4370 DeclarationName Name
4371 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004372 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor32df23e2010-07-01 22:02:46 +00004373 CXXConstructorDecl *DefaultCon
Abramo Bagnara25777432010-08-11 22:01:17 +00004374 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004375 Context.getFunctionType(Context.VoidTy,
4376 0, 0, false, 0,
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004377 ExceptSpec.hasExceptionSpecification(),
4378 ExceptSpec.hasAnyExceptionSpecification(),
4379 ExceptSpec.size(),
4380 ExceptSpec.data(),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004381 FunctionType::ExtInfo()),
4382 /*TInfo=*/0,
4383 /*isExplicit=*/false,
4384 /*isInline=*/true,
4385 /*isImplicitlyDeclared=*/true);
4386 DefaultCon->setAccess(AS_public);
4387 DefaultCon->setImplicit();
4388 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004389
4390 // Note that we have declared this constructor.
4391 ClassDecl->setDeclaredDefaultConstructor(true);
4392 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4393
Douglas Gregor23c94db2010-07-02 17:43:08 +00004394 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004395 PushOnScopeChains(DefaultCon, S, false);
4396 ClassDecl->addDecl(DefaultCon);
4397
Douglas Gregor32df23e2010-07-01 22:02:46 +00004398 return DefaultCon;
4399}
4400
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004401void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4402 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004403 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004404 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004405 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004406
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004407 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004408 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004409
Douglas Gregor39957dc2010-05-01 15:04:51 +00004410 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004411 ErrorTrap Trap(*this);
4412 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4413 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004414 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004415 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004416 Constructor->setInvalidDecl();
4417 } else {
4418 Constructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004419 MarkVTableUsed(CurrentLocation, ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004420 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004421}
4422
Douglas Gregor23c94db2010-07-02 17:43:08 +00004423CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004424 // C++ [class.dtor]p2:
4425 // If a class has no user-declared destructor, a destructor is
4426 // declared implicitly. An implicitly-declared destructor is an
4427 // inline public member of its class.
4428
4429 // C++ [except.spec]p14:
4430 // An implicitly declared special member function (Clause 12) shall have
4431 // an exception-specification.
4432 ImplicitExceptionSpecification ExceptSpec(Context);
4433
4434 // Direct base-class destructors.
4435 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4436 BEnd = ClassDecl->bases_end();
4437 B != BEnd; ++B) {
4438 if (B->isVirtual()) // Handled below.
4439 continue;
4440
4441 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4442 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004443 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004444 }
4445
4446 // Virtual base-class destructors.
4447 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4448 BEnd = ClassDecl->vbases_end();
4449 B != BEnd; ++B) {
4450 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4451 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004452 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004453 }
4454
4455 // Field destructors.
4456 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4457 FEnd = ClassDecl->field_end();
4458 F != FEnd; ++F) {
4459 if (const RecordType *RecordTy
4460 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4461 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004462 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004463 }
4464
Douglas Gregor4923aa22010-07-02 20:37:36 +00004465 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004466 QualType Ty = Context.getFunctionType(Context.VoidTy,
4467 0, 0, false, 0,
4468 ExceptSpec.hasExceptionSpecification(),
4469 ExceptSpec.hasAnyExceptionSpecification(),
4470 ExceptSpec.size(),
4471 ExceptSpec.data(),
4472 FunctionType::ExtInfo());
4473
4474 CanQualType ClassType
4475 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4476 DeclarationName Name
4477 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004478 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004479 CXXDestructorDecl *Destructor
Abramo Bagnara25777432010-08-11 22:01:17 +00004480 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty,
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004481 /*isInline=*/true,
4482 /*isImplicitlyDeclared=*/true);
4483 Destructor->setAccess(AS_public);
4484 Destructor->setImplicit();
4485 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00004486
4487 // Note that we have declared this destructor.
4488 ClassDecl->setDeclaredDestructor(true);
4489 ++ASTContext::NumImplicitDestructorsDeclared;
4490
4491 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004492 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00004493 PushOnScopeChains(Destructor, S, false);
4494 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004495
4496 // This could be uniqued if it ever proves significant.
4497 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4498
4499 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00004500
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004501 return Destructor;
4502}
4503
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004504void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004505 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00004506 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004507 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004508 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004509 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004510
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004511 if (Destructor->isInvalidDecl())
4512 return;
4513
Douglas Gregor39957dc2010-05-01 15:04:51 +00004514 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004515
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004516 ErrorTrap Trap(*this);
John McCallef027fe2010-03-16 21:39:52 +00004517 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4518 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004519
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004520 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004521 Diag(CurrentLocation, diag::note_member_synthesized_at)
4522 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4523
4524 Destructor->setInvalidDecl();
4525 return;
4526 }
4527
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004528 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004529 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004530}
4531
Douglas Gregor06a9f362010-05-01 20:49:11 +00004532/// \brief Builds a statement that copies the given entity from \p From to
4533/// \c To.
4534///
4535/// This routine is used to copy the members of a class with an
4536/// implicitly-declared copy assignment operator. When the entities being
4537/// copied are arrays, this routine builds for loops to copy them.
4538///
4539/// \param S The Sema object used for type-checking.
4540///
4541/// \param Loc The location where the implicit copy is being generated.
4542///
4543/// \param T The type of the expressions being copied. Both expressions must
4544/// have this type.
4545///
4546/// \param To The expression we are copying to.
4547///
4548/// \param From The expression we are copying from.
4549///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004550/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4551/// Otherwise, it's a non-static member subobject.
4552///
Douglas Gregor06a9f362010-05-01 20:49:11 +00004553/// \param Depth Internal parameter recording the depth of the recursion.
4554///
4555/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00004556static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00004557BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00004558 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004559 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00004560 // C++0x [class.copy]p30:
4561 // Each subobject is assigned in the manner appropriate to its type:
4562 //
4563 // - if the subobject is of class type, the copy assignment operator
4564 // for the class is used (as if by explicit qualification; that is,
4565 // ignoring any possible virtual overriding functions in more derived
4566 // classes);
4567 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4568 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4569
4570 // Look for operator=.
4571 DeclarationName Name
4572 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4573 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4574 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4575
4576 // Filter out any result that isn't a copy-assignment operator.
4577 LookupResult::Filter F = OpLookup.makeFilter();
4578 while (F.hasNext()) {
4579 NamedDecl *D = F.next();
4580 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4581 if (Method->isCopyAssignmentOperator())
4582 continue;
4583
4584 F.erase();
John McCallb0207482010-03-16 06:11:48 +00004585 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004586 F.done();
4587
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004588 // Suppress the protected check (C++ [class.protected]) for each of the
4589 // assignment operators we found. This strange dance is required when
4590 // we're assigning via a base classes's copy-assignment operator. To
4591 // ensure that we're getting the right base class subobject (without
4592 // ambiguities), we need to cast "this" to that subobject type; to
4593 // ensure that we don't go through the virtual call mechanism, we need
4594 // to qualify the operator= name with the base class (see below). However,
4595 // this means that if the base class has a protected copy assignment
4596 // operator, the protected member access check will fail. So, we
4597 // rewrite "protected" access to "public" access in this case, since we
4598 // know by construction that we're calling from a derived class.
4599 if (CopyingBaseSubobject) {
4600 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4601 L != LEnd; ++L) {
4602 if (L.getAccess() == AS_protected)
4603 L.setAccess(AS_public);
4604 }
4605 }
4606
Douglas Gregor06a9f362010-05-01 20:49:11 +00004607 // Create the nested-name-specifier that will be used to qualify the
4608 // reference to operator=; this is required to suppress the virtual
4609 // call mechanism.
4610 CXXScopeSpec SS;
4611 SS.setRange(Loc);
4612 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4613 T.getTypePtr()));
4614
4615 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00004616 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00004617 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004618 /*FirstQualifierInScope=*/0, OpLookup,
4619 /*TemplateArgs=*/0,
4620 /*SuppressQualifierCheck=*/true);
4621 if (OpEqualRef.isInvalid())
4622 return S.StmtError();
4623
4624 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00004625
John McCall60d7b3a2010-08-24 06:29:42 +00004626 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004627 OpEqualRef.takeAs<Expr>(),
John McCall9ae2f072010-08-23 23:25:46 +00004628 Loc, &From, 1, 0, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004629 if (Call.isInvalid())
4630 return S.StmtError();
4631
4632 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004633 }
John McCallb0207482010-03-16 06:11:48 +00004634
Douglas Gregor06a9f362010-05-01 20:49:11 +00004635 // - if the subobject is of scalar type, the built-in assignment
4636 // operator is used.
4637 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4638 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00004639 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004640 if (Assignment.isInvalid())
4641 return S.StmtError();
4642
4643 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004644 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004645
4646 // - if the subobject is an array, each element is assigned, in the
4647 // manner appropriate to the element type;
4648
4649 // Construct a loop over the array bounds, e.g.,
4650 //
4651 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4652 //
4653 // that will copy each of the array elements.
4654 QualType SizeType = S.Context.getSizeType();
4655
4656 // Create the iteration variable.
4657 IdentifierInfo *IterationVarName = 0;
4658 {
4659 llvm::SmallString<8> Str;
4660 llvm::raw_svector_ostream OS(Str);
4661 OS << "__i" << Depth;
4662 IterationVarName = &S.Context.Idents.get(OS.str());
4663 }
4664 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4665 IterationVarName, SizeType,
4666 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00004667 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004668
4669 // Initialize the iteration variable to zero.
4670 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
4671 IterationVar->setInit(new (S.Context) IntegerLiteral(Zero, SizeType, Loc));
4672
4673 // Create a reference to the iteration variable; we'll use this several
4674 // times throughout.
4675 Expr *IterationVarRef
4676 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4677 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4678
4679 // Create the DeclStmt that holds the iteration variable.
4680 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4681
4682 // Create the comparison against the array bound.
4683 llvm::APInt Upper = ArrayTy->getSize();
4684 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00004685 Expr *Comparison
4686 = new (S.Context) BinaryOperator(IterationVarRef->Retain(),
Douglas Gregor06a9f362010-05-01 20:49:11 +00004687 new (S.Context) IntegerLiteral(Upper, SizeType, Loc),
John McCall2de56d12010-08-25 11:45:40 +00004688 BO_NE, S.Context.BoolTy, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004689
4690 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004691 Expr *Increment
4692 = new (S.Context) UnaryOperator(IterationVarRef->Retain(),
John McCall2de56d12010-08-25 11:45:40 +00004693 UO_PreInc,
John McCall9ae2f072010-08-23 23:25:46 +00004694 SizeType, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004695
4696 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004697 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4698 IterationVarRef, Loc));
4699 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4700 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004701
4702 // Build the copy for an individual element of the array.
John McCall60d7b3a2010-08-24 06:29:42 +00004703 StmtResult Copy = BuildSingleCopyAssign(S, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004704 ArrayTy->getElementType(),
John McCall9ae2f072010-08-23 23:25:46 +00004705 To, From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004706 CopyingBaseSubobject, Depth+1);
Douglas Gregorff331c12010-07-25 18:17:45 +00004707 if (Copy.isInvalid())
Douglas Gregor06a9f362010-05-01 20:49:11 +00004708 return S.StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004709
4710 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00004711 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004712 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00004713 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00004714 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004715}
4716
Douglas Gregora376d102010-07-02 21:50:04 +00004717/// \brief Determine whether the given class has a copy assignment operator
4718/// that accepts a const-qualified argument.
4719static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4720 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4721
4722 if (!Class->hasDeclaredCopyAssignment())
4723 S.DeclareImplicitCopyAssignment(Class);
4724
4725 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4726 DeclarationName OpName
4727 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4728
4729 DeclContext::lookup_const_iterator Op, OpEnd;
4730 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4731 // C++ [class.copy]p9:
4732 // A user-declared copy assignment operator is a non-static non-template
4733 // member function of class X with exactly one parameter of type X, X&,
4734 // const X&, volatile X& or const volatile X&.
4735 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4736 if (!Method)
4737 continue;
4738
4739 if (Method->isStatic())
4740 continue;
4741 if (Method->getPrimaryTemplate())
4742 continue;
4743 const FunctionProtoType *FnType =
4744 Method->getType()->getAs<FunctionProtoType>();
4745 assert(FnType && "Overloaded operator has no prototype.");
4746 // Don't assert on this; an invalid decl might have been left in the AST.
4747 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4748 continue;
4749 bool AcceptsConst = true;
4750 QualType ArgType = FnType->getArgType(0);
4751 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4752 ArgType = Ref->getPointeeType();
4753 // Is it a non-const lvalue reference?
4754 if (!ArgType.isConstQualified())
4755 AcceptsConst = false;
4756 }
4757 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4758 continue;
4759
4760 // We have a single argument of type cv X or cv X&, i.e. we've found the
4761 // copy assignment operator. Return whether it accepts const arguments.
4762 return AcceptsConst;
4763 }
4764 assert(Class->isInvalidDecl() &&
4765 "No copy assignment operator declared in valid code.");
4766 return false;
4767}
4768
Douglas Gregor23c94db2010-07-02 17:43:08 +00004769CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00004770 // Note: The following rules are largely analoguous to the copy
4771 // constructor rules. Note that virtual bases are not taken into account
4772 // for determining the argument type of the operator. Note also that
4773 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00004774
4775
Douglas Gregord3c35902010-07-01 16:36:15 +00004776 // C++ [class.copy]p10:
4777 // If the class definition does not explicitly declare a copy
4778 // assignment operator, one is declared implicitly.
4779 // The implicitly-defined copy assignment operator for a class X
4780 // will have the form
4781 //
4782 // X& X::operator=(const X&)
4783 //
4784 // if
4785 bool HasConstCopyAssignment = true;
4786
4787 // -- each direct base class B of X has a copy assignment operator
4788 // whose parameter is of type const B&, const volatile B& or B,
4789 // and
4790 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4791 BaseEnd = ClassDecl->bases_end();
4792 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4793 assert(!Base->getType()->isDependentType() &&
4794 "Cannot generate implicit members for class with dependent bases.");
4795 const CXXRecordDecl *BaseClassDecl
4796 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004797 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004798 }
4799
4800 // -- for all the nonstatic data members of X that are of a class
4801 // type M (or array thereof), each such class type has a copy
4802 // assignment operator whose parameter is of type const M&,
4803 // const volatile M& or M.
4804 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4805 FieldEnd = ClassDecl->field_end();
4806 HasConstCopyAssignment && Field != FieldEnd;
4807 ++Field) {
4808 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4809 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4810 const CXXRecordDecl *FieldClassDecl
4811 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004812 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004813 }
4814 }
4815
4816 // Otherwise, the implicitly declared copy assignment operator will
4817 // have the form
4818 //
4819 // X& X::operator=(X&)
4820 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4821 QualType RetType = Context.getLValueReferenceType(ArgType);
4822 if (HasConstCopyAssignment)
4823 ArgType = ArgType.withConst();
4824 ArgType = Context.getLValueReferenceType(ArgType);
4825
Douglas Gregorb87786f2010-07-01 17:48:08 +00004826 // C++ [except.spec]p14:
4827 // An implicitly declared special member function (Clause 12) shall have an
4828 // exception-specification. [...]
4829 ImplicitExceptionSpecification ExceptSpec(Context);
4830 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4831 BaseEnd = ClassDecl->bases_end();
4832 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00004833 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004834 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004835
4836 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4837 DeclareImplicitCopyAssignment(BaseClassDecl);
4838
Douglas Gregorb87786f2010-07-01 17:48:08 +00004839 if (CXXMethodDecl *CopyAssign
4840 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4841 ExceptSpec.CalledDecl(CopyAssign);
4842 }
4843 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4844 FieldEnd = ClassDecl->field_end();
4845 Field != FieldEnd;
4846 ++Field) {
4847 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4848 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00004849 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004850 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004851
4852 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4853 DeclareImplicitCopyAssignment(FieldClassDecl);
4854
Douglas Gregorb87786f2010-07-01 17:48:08 +00004855 if (CXXMethodDecl *CopyAssign
4856 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4857 ExceptSpec.CalledDecl(CopyAssign);
4858 }
4859 }
4860
Douglas Gregord3c35902010-07-01 16:36:15 +00004861 // An implicitly-declared copy assignment operator is an inline public
4862 // member of its class.
4863 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnara25777432010-08-11 22:01:17 +00004864 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00004865 CXXMethodDecl *CopyAssignment
Abramo Bagnara25777432010-08-11 22:01:17 +00004866 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregord3c35902010-07-01 16:36:15 +00004867 Context.getFunctionType(RetType, &ArgType, 1,
4868 false, 0,
Douglas Gregorb87786f2010-07-01 17:48:08 +00004869 ExceptSpec.hasExceptionSpecification(),
4870 ExceptSpec.hasAnyExceptionSpecification(),
4871 ExceptSpec.size(),
4872 ExceptSpec.data(),
Douglas Gregord3c35902010-07-01 16:36:15 +00004873 FunctionType::ExtInfo()),
4874 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00004875 /*StorageClassAsWritten=*/SC_None,
Douglas Gregord3c35902010-07-01 16:36:15 +00004876 /*isInline=*/true);
4877 CopyAssignment->setAccess(AS_public);
4878 CopyAssignment->setImplicit();
4879 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
4880 CopyAssignment->setCopyAssignment(true);
4881
4882 // Add the parameter to the operator.
4883 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4884 ClassDecl->getLocation(),
4885 /*Id=*/0,
4886 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00004887 SC_None,
4888 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00004889 CopyAssignment->setParams(&FromParam, 1);
4890
Douglas Gregora376d102010-07-02 21:50:04 +00004891 // Note that we have added this copy-assignment operator.
4892 ClassDecl->setDeclaredCopyAssignment(true);
4893 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4894
Douglas Gregor23c94db2010-07-02 17:43:08 +00004895 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00004896 PushOnScopeChains(CopyAssignment, S, false);
4897 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00004898
4899 AddOverriddenMethods(ClassDecl, CopyAssignment);
4900 return CopyAssignment;
4901}
4902
Douglas Gregor06a9f362010-05-01 20:49:11 +00004903void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4904 CXXMethodDecl *CopyAssignOperator) {
4905 assert((CopyAssignOperator->isImplicit() &&
4906 CopyAssignOperator->isOverloadedOperator() &&
4907 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004908 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00004909 "DefineImplicitCopyAssignment called for wrong function");
4910
4911 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4912
4913 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4914 CopyAssignOperator->setInvalidDecl();
4915 return;
4916 }
4917
4918 CopyAssignOperator->setUsed();
4919
4920 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004921 ErrorTrap Trap(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004922
4923 // C++0x [class.copy]p30:
4924 // The implicitly-defined or explicitly-defaulted copy assignment operator
4925 // for a non-union class X performs memberwise copy assignment of its
4926 // subobjects. The direct base classes of X are assigned first, in the
4927 // order of their declaration in the base-specifier-list, and then the
4928 // immediate non-static data members of X are assigned, in the order in
4929 // which they were declared in the class definition.
4930
4931 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00004932 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004933
4934 // The parameter for the "other" object, which we are copying from.
4935 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4936 Qualifiers OtherQuals = Other->getType().getQualifiers();
4937 QualType OtherRefType = Other->getType();
4938 if (const LValueReferenceType *OtherRef
4939 = OtherRefType->getAs<LValueReferenceType>()) {
4940 OtherRefType = OtherRef->getPointeeType();
4941 OtherQuals = OtherRefType.getQualifiers();
4942 }
4943
4944 // Our location for everything implicitly-generated.
4945 SourceLocation Loc = CopyAssignOperator->getLocation();
4946
4947 // Construct a reference to the "other" object. We'll be using this
4948 // throughout the generated ASTs.
4949 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4950 assert(OtherRef && "Reference to parameter cannot fail!");
4951
4952 // Construct the "this" pointer. We'll be using this throughout the generated
4953 // ASTs.
4954 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4955 assert(This && "Reference to this cannot fail!");
4956
4957 // Assign base classes.
4958 bool Invalid = false;
4959 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4960 E = ClassDecl->bases_end(); Base != E; ++Base) {
4961 // Form the assignment:
4962 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4963 QualType BaseType = Base->getType().getUnqualifiedType();
4964 CXXRecordDecl *BaseClassDecl = 0;
4965 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4966 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4967 else {
4968 Invalid = true;
4969 continue;
4970 }
4971
John McCallf871d0c2010-08-07 06:22:56 +00004972 CXXCastPath BasePath;
4973 BasePath.push_back(Base);
4974
Douglas Gregor06a9f362010-05-01 20:49:11 +00004975 // Construct the "from" expression, which is an implicit cast to the
4976 // appropriately-qualified base type.
4977 Expr *From = OtherRef->Retain();
4978 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall5baba9d2010-08-25 10:28:54 +00004979 CK_UncheckedDerivedToBase,
4980 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004981
4982 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00004983 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004984
4985 // Implicitly cast "this" to the appropriately-qualified base type.
4986 Expr *ToE = To.takeAs<Expr>();
4987 ImpCastExprToType(ToE,
4988 Context.getCVRQualifiedType(BaseType,
4989 CopyAssignOperator->getTypeQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00004990 CK_UncheckedDerivedToBase,
4991 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004992 To = Owned(ToE);
4993
4994 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00004995 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00004996 To.get(), From,
4997 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004998 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004999 Diag(CurrentLocation, diag::note_member_synthesized_at)
5000 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5001 CopyAssignOperator->setInvalidDecl();
5002 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005003 }
5004
5005 // Success! Record the copy.
5006 Statements.push_back(Copy.takeAs<Expr>());
5007 }
5008
5009 // \brief Reference to the __builtin_memcpy function.
5010 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005011 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005012 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005013
5014 // Assign non-static members.
5015 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5016 FieldEnd = ClassDecl->field_end();
5017 Field != FieldEnd; ++Field) {
5018 // Check for members of reference type; we can't copy those.
5019 if (Field->getType()->isReferenceType()) {
5020 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5021 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5022 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005023 Diag(CurrentLocation, diag::note_member_synthesized_at)
5024 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005025 Invalid = true;
5026 continue;
5027 }
5028
5029 // Check for members of const-qualified, non-class type.
5030 QualType BaseType = Context.getBaseElementType(Field->getType());
5031 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5032 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5033 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5034 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005035 Diag(CurrentLocation, diag::note_member_synthesized_at)
5036 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005037 Invalid = true;
5038 continue;
5039 }
5040
5041 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005042 if (FieldType->isIncompleteArrayType()) {
5043 assert(ClassDecl->hasFlexibleArrayMember() &&
5044 "Incomplete array type is not valid");
5045 continue;
5046 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005047
5048 // Build references to the field in the object we're copying from and to.
5049 CXXScopeSpec SS; // Intentionally empty
5050 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5051 LookupMemberName);
5052 MemberLookup.addDecl(*Field);
5053 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005054 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005055 Loc, /*IsArrow=*/false,
5056 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005057 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005058 Loc, /*IsArrow=*/true,
5059 SS, 0, MemberLookup, 0);
5060 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5061 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5062
5063 // If the field should be copied with __builtin_memcpy rather than via
5064 // explicit assignments, do so. This optimization only applies for arrays
5065 // of scalars and arrays of class type with trivial copy-assignment
5066 // operators.
5067 if (FieldType->isArrayType() &&
5068 (!BaseType->isRecordType() ||
5069 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5070 ->hasTrivialCopyAssignment())) {
5071 // Compute the size of the memory buffer to be copied.
5072 QualType SizeType = Context.getSizeType();
5073 llvm::APInt Size(Context.getTypeSize(SizeType),
5074 Context.getTypeSizeInChars(BaseType).getQuantity());
5075 for (const ConstantArrayType *Array
5076 = Context.getAsConstantArrayType(FieldType);
5077 Array;
5078 Array = Context.getAsConstantArrayType(Array->getElementType())) {
5079 llvm::APInt ArraySize = Array->getSize();
5080 ArraySize.zextOrTrunc(Size.getBitWidth());
5081 Size *= ArraySize;
5082 }
5083
5084 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005085 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5086 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005087
5088 bool NeedsCollectableMemCpy =
5089 (BaseType->isRecordType() &&
5090 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5091
5092 if (NeedsCollectableMemCpy) {
5093 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005094 // Create a reference to the __builtin_objc_memmove_collectable function.
5095 LookupResult R(*this,
5096 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005097 Loc, LookupOrdinaryName);
5098 LookupName(R, TUScope, true);
5099
5100 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5101 if (!CollectableMemCpy) {
5102 // Something went horribly wrong earlier, and we will have
5103 // complained about it.
5104 Invalid = true;
5105 continue;
5106 }
5107
5108 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5109 CollectableMemCpy->getType(),
5110 Loc, 0).takeAs<Expr>();
5111 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5112 }
5113 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005114 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005115 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005116 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5117 LookupOrdinaryName);
5118 LookupName(R, TUScope, true);
5119
5120 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5121 if (!BuiltinMemCpy) {
5122 // Something went horribly wrong earlier, and we will have complained
5123 // about it.
5124 Invalid = true;
5125 continue;
5126 }
5127
5128 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5129 BuiltinMemCpy->getType(),
5130 Loc, 0).takeAs<Expr>();
5131 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5132 }
5133
John McCallca0408f2010-08-23 06:44:23 +00005134 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005135 CallArgs.push_back(To.takeAs<Expr>());
5136 CallArgs.push_back(From.takeAs<Expr>());
5137 CallArgs.push_back(new (Context) IntegerLiteral(Size, SizeType, Loc));
5138 llvm::SmallVector<SourceLocation, 4> Commas; // FIXME: Silly
5139 Commas.push_back(Loc);
5140 Commas.push_back(Loc);
John McCall60d7b3a2010-08-24 06:29:42 +00005141 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005142 if (NeedsCollectableMemCpy)
5143 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005144 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005145 Loc, move_arg(CallArgs),
5146 Commas.data(), Loc);
5147 else
5148 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005149 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005150 Loc, move_arg(CallArgs),
5151 Commas.data(), Loc);
5152
Douglas Gregor06a9f362010-05-01 20:49:11 +00005153 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5154 Statements.push_back(Call.takeAs<Expr>());
5155 continue;
5156 }
5157
5158 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005159 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005160 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005161 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005162 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005163 Diag(CurrentLocation, diag::note_member_synthesized_at)
5164 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5165 CopyAssignOperator->setInvalidDecl();
5166 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005167 }
5168
5169 // Success! Record the copy.
5170 Statements.push_back(Copy.takeAs<Stmt>());
5171 }
5172
5173 if (!Invalid) {
5174 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005175 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005176
John McCall60d7b3a2010-08-24 06:29:42 +00005177 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005178 if (Return.isInvalid())
5179 Invalid = true;
5180 else {
5181 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005182
5183 if (Trap.hasErrorOccurred()) {
5184 Diag(CurrentLocation, diag::note_member_synthesized_at)
5185 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5186 Invalid = true;
5187 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005188 }
5189 }
5190
5191 if (Invalid) {
5192 CopyAssignOperator->setInvalidDecl();
5193 return;
5194 }
5195
John McCall60d7b3a2010-08-24 06:29:42 +00005196 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005197 /*isStmtExpr=*/false);
5198 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5199 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005200}
5201
Douglas Gregor23c94db2010-07-02 17:43:08 +00005202CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5203 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005204 // C++ [class.copy]p4:
5205 // If the class definition does not explicitly declare a copy
5206 // constructor, one is declared implicitly.
5207
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005208 // C++ [class.copy]p5:
5209 // The implicitly-declared copy constructor for a class X will
5210 // have the form
5211 //
5212 // X::X(const X&)
5213 //
5214 // if
5215 bool HasConstCopyConstructor = true;
5216
5217 // -- each direct or virtual base class B of X has a copy
5218 // constructor whose first parameter is of type const B& or
5219 // const volatile B&, and
5220 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5221 BaseEnd = ClassDecl->bases_end();
5222 HasConstCopyConstructor && Base != BaseEnd;
5223 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005224 // Virtual bases are handled below.
5225 if (Base->isVirtual())
5226 continue;
5227
Douglas Gregor22584312010-07-02 23:41:54 +00005228 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005229 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005230 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5231 DeclareImplicitCopyConstructor(BaseClassDecl);
5232
Douglas Gregor598a8542010-07-01 18:27:03 +00005233 HasConstCopyConstructor
5234 = BaseClassDecl->hasConstCopyConstructor(Context);
5235 }
5236
5237 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5238 BaseEnd = ClassDecl->vbases_end();
5239 HasConstCopyConstructor && Base != BaseEnd;
5240 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005241 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005242 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005243 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5244 DeclareImplicitCopyConstructor(BaseClassDecl);
5245
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005246 HasConstCopyConstructor
5247 = BaseClassDecl->hasConstCopyConstructor(Context);
5248 }
5249
5250 // -- for all the nonstatic data members of X that are of a
5251 // class type M (or array thereof), each such class type
5252 // has a copy constructor whose first parameter is of type
5253 // const M& or const volatile M&.
5254 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5255 FieldEnd = ClassDecl->field_end();
5256 HasConstCopyConstructor && Field != FieldEnd;
5257 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005258 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005259 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005260 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005261 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005262 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5263 DeclareImplicitCopyConstructor(FieldClassDecl);
5264
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005265 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005266 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005267 }
5268 }
5269
5270 // Otherwise, the implicitly declared copy constructor will have
5271 // the form
5272 //
5273 // X::X(X&)
5274 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5275 QualType ArgType = ClassType;
5276 if (HasConstCopyConstructor)
5277 ArgType = ArgType.withConst();
5278 ArgType = Context.getLValueReferenceType(ArgType);
5279
Douglas Gregor0d405db2010-07-01 20:59:04 +00005280 // C++ [except.spec]p14:
5281 // An implicitly declared special member function (Clause 12) shall have an
5282 // exception-specification. [...]
5283 ImplicitExceptionSpecification ExceptSpec(Context);
5284 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5285 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5286 BaseEnd = ClassDecl->bases_end();
5287 Base != BaseEnd;
5288 ++Base) {
5289 // Virtual bases are handled below.
5290 if (Base->isVirtual())
5291 continue;
5292
Douglas Gregor22584312010-07-02 23:41:54 +00005293 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005294 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005295 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5296 DeclareImplicitCopyConstructor(BaseClassDecl);
5297
Douglas Gregor0d405db2010-07-01 20:59:04 +00005298 if (CXXConstructorDecl *CopyConstructor
5299 = BaseClassDecl->getCopyConstructor(Context, Quals))
5300 ExceptSpec.CalledDecl(CopyConstructor);
5301 }
5302 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5303 BaseEnd = ClassDecl->vbases_end();
5304 Base != BaseEnd;
5305 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005306 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005307 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005308 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5309 DeclareImplicitCopyConstructor(BaseClassDecl);
5310
Douglas Gregor0d405db2010-07-01 20:59:04 +00005311 if (CXXConstructorDecl *CopyConstructor
5312 = BaseClassDecl->getCopyConstructor(Context, Quals))
5313 ExceptSpec.CalledDecl(CopyConstructor);
5314 }
5315 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5316 FieldEnd = ClassDecl->field_end();
5317 Field != FieldEnd;
5318 ++Field) {
5319 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5320 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005321 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005322 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005323 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5324 DeclareImplicitCopyConstructor(FieldClassDecl);
5325
Douglas Gregor0d405db2010-07-01 20:59:04 +00005326 if (CXXConstructorDecl *CopyConstructor
5327 = FieldClassDecl->getCopyConstructor(Context, Quals))
5328 ExceptSpec.CalledDecl(CopyConstructor);
5329 }
5330 }
5331
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005332 // An implicitly-declared copy constructor is an inline public
5333 // member of its class.
5334 DeclarationName Name
5335 = Context.DeclarationNames.getCXXConstructorName(
5336 Context.getCanonicalType(ClassType));
Abramo Bagnara25777432010-08-11 22:01:17 +00005337 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005338 CXXConstructorDecl *CopyConstructor
Abramo Bagnara25777432010-08-11 22:01:17 +00005339 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005340 Context.getFunctionType(Context.VoidTy,
5341 &ArgType, 1,
5342 false, 0,
Douglas Gregor0d405db2010-07-01 20:59:04 +00005343 ExceptSpec.hasExceptionSpecification(),
5344 ExceptSpec.hasAnyExceptionSpecification(),
5345 ExceptSpec.size(),
5346 ExceptSpec.data(),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005347 FunctionType::ExtInfo()),
5348 /*TInfo=*/0,
5349 /*isExplicit=*/false,
5350 /*isInline=*/true,
5351 /*isImplicitlyDeclared=*/true);
5352 CopyConstructor->setAccess(AS_public);
5353 CopyConstructor->setImplicit();
5354 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5355
Douglas Gregor22584312010-07-02 23:41:54 +00005356 // Note that we have declared this constructor.
5357 ClassDecl->setDeclaredCopyConstructor(true);
5358 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5359
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005360 // Add the parameter to the constructor.
5361 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5362 ClassDecl->getLocation(),
5363 /*IdentifierInfo=*/0,
5364 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005365 SC_None,
5366 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005367 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00005368 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00005369 PushOnScopeChains(CopyConstructor, S, false);
5370 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005371
5372 return CopyConstructor;
5373}
5374
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005375void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5376 CXXConstructorDecl *CopyConstructor,
5377 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00005378 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00005379 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005380 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005381 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005382
Anders Carlsson63010a72010-04-23 16:24:12 +00005383 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005384 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005385
Douglas Gregor39957dc2010-05-01 15:04:51 +00005386 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005387 ErrorTrap Trap(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005388
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005389 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5390 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00005391 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005392 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00005393 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005394 } else {
5395 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5396 CopyConstructor->getLocation(),
5397 MultiStmtArg(*this, 0, 0),
5398 /*isStmtExpr=*/false)
5399 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00005400 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005401
5402 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005403}
5404
John McCall60d7b3a2010-08-24 06:29:42 +00005405ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005406Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00005407 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00005408 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005409 bool RequiresZeroInit,
John McCall7a1fad32010-08-24 07:32:53 +00005410 unsigned ConstructKind) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005411 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005412
Douglas Gregor2f599792010-04-02 18:24:57 +00005413 // C++0x [class.copy]p34:
5414 // When certain criteria are met, an implementation is allowed to
5415 // omit the copy/move construction of a class object, even if the
5416 // copy/move constructor and/or destructor for the object have
5417 // side effects. [...]
5418 // - when a temporary class object that has not been bound to a
5419 // reference (12.2) would be copied/moved to a class object
5420 // with the same cv-unqualified type, the copy/move operation
5421 // can be omitted by constructing the temporary object
5422 // directly into the target of the omitted copy/move
5423 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
5424 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
5425 Elidable = SubExpr->isTemporaryObject() &&
Douglas Gregorb8f7de92010-08-22 18:27:02 +00005426 ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor2f599792010-04-02 18:24:57 +00005427 Context.hasSameUnqualifiedType(SubExpr->getType(),
5428 Context.getTypeDeclType(Constructor->getParent()));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005429 }
Mike Stump1eb44332009-09-09 15:08:12 +00005430
5431 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005432 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlsson72e96fd2010-05-02 22:54:08 +00005433 ConstructKind);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005434}
5435
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005436/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5437/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005438ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005439Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5440 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00005441 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005442 bool RequiresZeroInit,
John McCall7a1fad32010-08-24 07:32:53 +00005443 unsigned ConstructKind) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00005444 unsigned NumExprs = ExprArgs.size();
5445 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005446
Douglas Gregor7edfb692009-11-23 12:27:39 +00005447 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005448 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00005449 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00005450 RequiresZeroInit,
5451 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind)));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005452}
5453
Mike Stump1eb44332009-09-09 15:08:12 +00005454bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005455 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00005456 MultiExprArg Exprs) {
John McCall60d7b3a2010-08-24 06:29:42 +00005457 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00005458 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00005459 move(Exprs), false, CXXConstructExpr::CK_Complete);
Anders Carlssonfe2de492009-08-25 05:18:00 +00005460 if (TempResult.isInvalid())
5461 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005462
Anders Carlssonda3f4e22009-08-25 05:12:04 +00005463 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005464 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00005465 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00005466 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00005467
Anders Carlssonfe2de492009-08-25 05:18:00 +00005468 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00005469}
5470
John McCall68c6c9a2010-02-02 09:10:11 +00005471void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5472 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00005473 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregorfb2db462010-05-22 17:12:29 +00005474 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00005475 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall4f9506a2010-02-02 08:45:54 +00005476 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00005477 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005478 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00005479 << VD->getDeclName()
5480 << VD->getType());
John McCall626e96e2010-08-01 20:20:59 +00005481
5482 if (!VD->isInvalidDecl() && VD->hasGlobalStorage())
5483 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall4f9506a2010-02-02 08:45:54 +00005484 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005485}
5486
Mike Stump1eb44332009-09-09 15:08:12 +00005487/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005488/// ActOnDeclarator, when a C++ direct initializer is present.
5489/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00005490void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005491 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00005492 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005493 SourceLocation *CommaLocs,
5494 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00005495 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005496
5497 // If there is no declaration, there was an error parsing it. Just ignore
5498 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005499 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005500 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005501
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005502 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5503 if (!VDecl) {
5504 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5505 RealDecl->setInvalidDecl();
5506 return;
5507 }
5508
Douglas Gregor83ddad32009-08-26 21:14:46 +00005509 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005510 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005511 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5512 //
5513 // Clients that want to distinguish between the two forms, can check for
5514 // direct initializer using VarDecl::hasCXXDirectInitializer().
5515 // A major benefit is that clients that don't particularly care about which
5516 // exactly form was it (like the CodeGen) can handle both cases without
5517 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005518
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005519 // C++ 8.5p11:
5520 // The form of initialization (using parentheses or '=') is generally
5521 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005522 // class type.
5523
Douglas Gregor4dffad62010-02-11 22:55:30 +00005524 if (!VDecl->getType()->isDependentType() &&
5525 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00005526 diag::err_typecheck_decl_incomplete_type)) {
5527 VDecl->setInvalidDecl();
5528 return;
5529 }
5530
Douglas Gregor90f93822009-12-22 22:17:25 +00005531 // The variable can not have an abstract class type.
5532 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5533 diag::err_abstract_type_in_decl,
5534 AbstractVariableType))
5535 VDecl->setInvalidDecl();
5536
Sebastian Redl31310a22010-02-01 20:16:42 +00005537 const VarDecl *Def;
5538 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00005539 Diag(VDecl->getLocation(), diag::err_redefinition)
5540 << VDecl->getDeclName();
5541 Diag(Def->getLocation(), diag::note_previous_definition);
5542 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005543 return;
5544 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00005545
Douglas Gregor3a91abf2010-08-24 05:27:49 +00005546 // C++ [class.static.data]p4
5547 // If a static data member is of const integral or const
5548 // enumeration type, its declaration in the class definition can
5549 // specify a constant-initializer which shall be an integral
5550 // constant expression (5.19). In that case, the member can appear
5551 // in integral constant expressions. The member shall still be
5552 // defined in a namespace scope if it is used in the program and the
5553 // namespace scope definition shall not contain an initializer.
5554 //
5555 // We already performed a redefinition check above, but for static
5556 // data members we also need to check whether there was an in-class
5557 // declaration with an initializer.
5558 const VarDecl* PrevInit = 0;
5559 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5560 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5561 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5562 return;
5563 }
5564
Douglas Gregor4dffad62010-02-11 22:55:30 +00005565 // If either the declaration has a dependent type or if any of the
5566 // expressions is type-dependent, we represent the initialization
5567 // via a ParenListExpr for later use during template instantiation.
5568 if (VDecl->getType()->isDependentType() ||
5569 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
5570 // Let clients know that initialization was done with a direct initializer.
5571 VDecl->setCXXDirectInitializer(true);
5572
5573 // Store the initialization expressions as a ParenListExpr.
5574 unsigned NumExprs = Exprs.size();
5575 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5576 (Expr **)Exprs.release(),
5577 NumExprs, RParenLoc));
5578 return;
5579 }
Douglas Gregor90f93822009-12-22 22:17:25 +00005580
5581 // Capture the variable that is being initialized and the style of
5582 // initialization.
5583 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5584
5585 // FIXME: Poor source location information.
5586 InitializationKind Kind
5587 = InitializationKind::CreateDirect(VDecl->getLocation(),
5588 LParenLoc, RParenLoc);
5589
5590 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00005591 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00005592 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00005593 if (Result.isInvalid()) {
5594 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005595 return;
5596 }
Douglas Gregor90f93822009-12-22 22:17:25 +00005597
John McCall9ae2f072010-08-23 23:25:46 +00005598 Result = MaybeCreateCXXExprWithTemporaries(Result.get());
Douglas Gregor838db382010-02-11 01:19:42 +00005599 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005600 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005601
John McCall4204f072010-08-02 21:13:48 +00005602 if (!VDecl->isInvalidDecl() &&
5603 !VDecl->getDeclContext()->isDependentContext() &&
5604 VDecl->hasGlobalStorage() &&
5605 !VDecl->getInit()->isConstantInitializer(Context,
5606 VDecl->getType()->isReferenceType()))
5607 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5608 << VDecl->getInit()->getSourceRange();
5609
John McCall68c6c9a2010-02-02 09:10:11 +00005610 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5611 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005612}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00005613
Douglas Gregor39da0b82009-09-09 23:08:42 +00005614/// \brief Given a constructor and the set of arguments provided for the
5615/// constructor, convert the arguments and add any required default arguments
5616/// to form a proper call to this constructor.
5617///
5618/// \returns true if an error occurred, false otherwise.
5619bool
5620Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5621 MultiExprArg ArgsPtr,
5622 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00005623 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00005624 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5625 unsigned NumArgs = ArgsPtr.size();
5626 Expr **Args = (Expr **)ArgsPtr.get();
5627
5628 const FunctionProtoType *Proto
5629 = Constructor->getType()->getAs<FunctionProtoType>();
5630 assert(Proto && "Constructor without a prototype?");
5631 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00005632
5633 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005634 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00005635 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005636 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00005637 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005638
5639 VariadicCallType CallType =
5640 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5641 llvm::SmallVector<Expr *, 8> AllArgs;
5642 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5643 Proto, 0, Args, NumArgs, AllArgs,
5644 CallType);
5645 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5646 ConvertedArgs.push_back(AllArgs[i]);
5647 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00005648}
5649
Anders Carlsson20d45d22009-12-12 00:32:00 +00005650static inline bool
5651CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5652 const FunctionDecl *FnDecl) {
5653 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
5654 if (isa<NamespaceDecl>(DC)) {
5655 return SemaRef.Diag(FnDecl->getLocation(),
5656 diag::err_operator_new_delete_declared_in_namespace)
5657 << FnDecl->getDeclName();
5658 }
5659
5660 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00005661 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005662 return SemaRef.Diag(FnDecl->getLocation(),
5663 diag::err_operator_new_delete_declared_static)
5664 << FnDecl->getDeclName();
5665 }
5666
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00005667 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00005668}
5669
Anders Carlsson156c78e2009-12-13 17:53:43 +00005670static inline bool
5671CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5672 CanQualType ExpectedResultType,
5673 CanQualType ExpectedFirstParamType,
5674 unsigned DependentParamTypeDiag,
5675 unsigned InvalidParamTypeDiag) {
5676 QualType ResultType =
5677 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5678
5679 // Check that the result type is not dependent.
5680 if (ResultType->isDependentType())
5681 return SemaRef.Diag(FnDecl->getLocation(),
5682 diag::err_operator_new_delete_dependent_result_type)
5683 << FnDecl->getDeclName() << ExpectedResultType;
5684
5685 // Check that the result type is what we expect.
5686 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5687 return SemaRef.Diag(FnDecl->getLocation(),
5688 diag::err_operator_new_delete_invalid_result_type)
5689 << FnDecl->getDeclName() << ExpectedResultType;
5690
5691 // A function template must have at least 2 parameters.
5692 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5693 return SemaRef.Diag(FnDecl->getLocation(),
5694 diag::err_operator_new_delete_template_too_few_parameters)
5695 << FnDecl->getDeclName();
5696
5697 // The function decl must have at least 1 parameter.
5698 if (FnDecl->getNumParams() == 0)
5699 return SemaRef.Diag(FnDecl->getLocation(),
5700 diag::err_operator_new_delete_too_few_parameters)
5701 << FnDecl->getDeclName();
5702
5703 // Check the the first parameter type is not dependent.
5704 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5705 if (FirstParamType->isDependentType())
5706 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5707 << FnDecl->getDeclName() << ExpectedFirstParamType;
5708
5709 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00005710 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00005711 ExpectedFirstParamType)
5712 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5713 << FnDecl->getDeclName() << ExpectedFirstParamType;
5714
5715 return false;
5716}
5717
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005718static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00005719CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005720 // C++ [basic.stc.dynamic.allocation]p1:
5721 // A program is ill-formed if an allocation function is declared in a
5722 // namespace scope other than global scope or declared static in global
5723 // scope.
5724 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5725 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00005726
5727 CanQualType SizeTy =
5728 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5729
5730 // C++ [basic.stc.dynamic.allocation]p1:
5731 // The return type shall be void*. The first parameter shall have type
5732 // std::size_t.
5733 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5734 SizeTy,
5735 diag::err_operator_new_dependent_param_type,
5736 diag::err_operator_new_param_type))
5737 return true;
5738
5739 // C++ [basic.stc.dynamic.allocation]p1:
5740 // The first parameter shall not have an associated default argument.
5741 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00005742 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00005743 diag::err_operator_new_default_arg)
5744 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5745
5746 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00005747}
5748
5749static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005750CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5751 // C++ [basic.stc.dynamic.deallocation]p1:
5752 // A program is ill-formed if deallocation functions are declared in a
5753 // namespace scope other than global scope or declared static in global
5754 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00005755 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5756 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005757
5758 // C++ [basic.stc.dynamic.deallocation]p2:
5759 // Each deallocation function shall return void and its first parameter
5760 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00005761 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5762 SemaRef.Context.VoidPtrTy,
5763 diag::err_operator_delete_dependent_param_type,
5764 diag::err_operator_delete_param_type))
5765 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005766
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005767 return false;
5768}
5769
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005770/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5771/// of this overloaded operator is well-formed. If so, returns false;
5772/// otherwise, emits appropriate diagnostics and returns true.
5773bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005774 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005775 "Expected an overloaded operator declaration");
5776
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005777 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5778
Mike Stump1eb44332009-09-09 15:08:12 +00005779 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005780 // The allocation and deallocation functions, operator new,
5781 // operator new[], operator delete and operator delete[], are
5782 // described completely in 3.7.3. The attributes and restrictions
5783 // found in the rest of this subclause do not apply to them unless
5784 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00005785 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005786 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00005787
Anders Carlssona3ccda52009-12-12 00:26:23 +00005788 if (Op == OO_New || Op == OO_Array_New)
5789 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005790
5791 // C++ [over.oper]p6:
5792 // An operator function shall either be a non-static member
5793 // function or be a non-member function and have at least one
5794 // parameter whose type is a class, a reference to a class, an
5795 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005796 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5797 if (MethodDecl->isStatic())
5798 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005799 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005800 } else {
5801 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005802 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5803 ParamEnd = FnDecl->param_end();
5804 Param != ParamEnd; ++Param) {
5805 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00005806 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5807 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005808 ClassOrEnumParam = true;
5809 break;
5810 }
5811 }
5812
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005813 if (!ClassOrEnumParam)
5814 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005815 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005816 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005817 }
5818
5819 // C++ [over.oper]p8:
5820 // An operator function cannot have default arguments (8.3.6),
5821 // except where explicitly stated below.
5822 //
Mike Stump1eb44332009-09-09 15:08:12 +00005823 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005824 // (C++ [over.call]p1).
5825 if (Op != OO_Call) {
5826 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5827 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00005828 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00005829 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00005830 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00005831 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005832 }
5833 }
5834
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005835 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5836 { false, false, false }
5837#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5838 , { Unary, Binary, MemberOnly }
5839#include "clang/Basic/OperatorKinds.def"
5840 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005841
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005842 bool CanBeUnaryOperator = OperatorUses[Op][0];
5843 bool CanBeBinaryOperator = OperatorUses[Op][1];
5844 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005845
5846 // C++ [over.oper]p8:
5847 // [...] Operator functions cannot have more or fewer parameters
5848 // than the number required for the corresponding operator, as
5849 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00005850 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005851 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005852 if (Op != OO_Call &&
5853 ((NumParams == 1 && !CanBeUnaryOperator) ||
5854 (NumParams == 2 && !CanBeBinaryOperator) ||
5855 (NumParams < 1) || (NumParams > 2))) {
5856 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00005857 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005858 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005859 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005860 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005861 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005862 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005863 assert(CanBeBinaryOperator &&
5864 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00005865 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005866 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005867
Chris Lattner416e46f2008-11-21 07:57:12 +00005868 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005869 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005870 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005871
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005872 // Overloaded operators other than operator() cannot be variadic.
5873 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00005874 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005875 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005876 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005877 }
5878
5879 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005880 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5881 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005882 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005883 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005884 }
5885
5886 // C++ [over.inc]p1:
5887 // The user-defined function called operator++ implements the
5888 // prefix and postfix ++ operator. If this function is a member
5889 // function with no parameters, or a non-member function with one
5890 // parameter of class or enumeration type, it defines the prefix
5891 // increment operator ++ for objects of that type. If the function
5892 // is a member function with one parameter (which shall be of type
5893 // int) or a non-member function with two parameters (the second
5894 // of which shall be of type int), it defines the postfix
5895 // increment operator ++ for objects of that type.
5896 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5897 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5898 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005899 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005900 ParamIsInt = BT->getKind() == BuiltinType::Int;
5901
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005902 if (!ParamIsInt)
5903 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005904 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005905 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005906 }
5907
Sebastian Redl64b45f72009-01-05 20:52:13 +00005908 // Notify the class if it got an assignment operator.
5909 if (Op == OO_Equal) {
5910 // Would have returned earlier otherwise.
5911 assert(isa<CXXMethodDecl>(FnDecl) &&
5912 "Overloaded = not member, but not filtered.");
5913 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5914 Method->getParent()->addedAssignmentOperator(Context, Method);
5915 }
5916
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005917 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005918}
Chris Lattner5a003a42008-12-17 07:09:26 +00005919
Sean Hunta6c058d2010-01-13 09:01:02 +00005920/// CheckLiteralOperatorDeclaration - Check whether the declaration
5921/// of this literal operator function is well-formed. If so, returns
5922/// false; otherwise, emits appropriate diagnostics and returns true.
5923bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5924 DeclContext *DC = FnDecl->getDeclContext();
5925 Decl::Kind Kind = DC->getDeclKind();
5926 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5927 Kind != Decl::LinkageSpec) {
5928 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5929 << FnDecl->getDeclName();
5930 return true;
5931 }
5932
5933 bool Valid = false;
5934
Sean Hunt216c2782010-04-07 23:11:06 +00005935 // template <char...> type operator "" name() is the only valid template
5936 // signature, and the only valid signature with no parameters.
5937 if (FnDecl->param_size() == 0) {
5938 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5939 // Must have only one template parameter
5940 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5941 if (Params->size() == 1) {
5942 NonTypeTemplateParmDecl *PmDecl =
5943 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00005944
Sean Hunt216c2782010-04-07 23:11:06 +00005945 // The template parameter must be a char parameter pack.
5946 // FIXME: This test will always fail because non-type parameter packs
5947 // have not been implemented.
5948 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5949 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5950 Valid = true;
5951 }
5952 }
5953 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00005954 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00005955 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5956
Sean Hunta6c058d2010-01-13 09:01:02 +00005957 QualType T = (*Param)->getType();
5958
Sean Hunt30019c02010-04-07 22:57:35 +00005959 // unsigned long long int, long double, and any character type are allowed
5960 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00005961 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5962 Context.hasSameType(T, Context.LongDoubleTy) ||
5963 Context.hasSameType(T, Context.CharTy) ||
5964 Context.hasSameType(T, Context.WCharTy) ||
5965 Context.hasSameType(T, Context.Char16Ty) ||
5966 Context.hasSameType(T, Context.Char32Ty)) {
5967 if (++Param == FnDecl->param_end())
5968 Valid = true;
5969 goto FinishedParams;
5970 }
5971
Sean Hunt30019c02010-04-07 22:57:35 +00005972 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00005973 const PointerType *PT = T->getAs<PointerType>();
5974 if (!PT)
5975 goto FinishedParams;
5976 T = PT->getPointeeType();
5977 if (!T.isConstQualified())
5978 goto FinishedParams;
5979 T = T.getUnqualifiedType();
5980
5981 // Move on to the second parameter;
5982 ++Param;
5983
5984 // If there is no second parameter, the first must be a const char *
5985 if (Param == FnDecl->param_end()) {
5986 if (Context.hasSameType(T, Context.CharTy))
5987 Valid = true;
5988 goto FinishedParams;
5989 }
5990
5991 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5992 // are allowed as the first parameter to a two-parameter function
5993 if (!(Context.hasSameType(T, Context.CharTy) ||
5994 Context.hasSameType(T, Context.WCharTy) ||
5995 Context.hasSameType(T, Context.Char16Ty) ||
5996 Context.hasSameType(T, Context.Char32Ty)))
5997 goto FinishedParams;
5998
5999 // The second and final parameter must be an std::size_t
6000 T = (*Param)->getType().getUnqualifiedType();
6001 if (Context.hasSameType(T, Context.getSizeType()) &&
6002 ++Param == FnDecl->param_end())
6003 Valid = true;
6004 }
6005
6006 // FIXME: This diagnostic is absolutely terrible.
6007FinishedParams:
6008 if (!Valid) {
6009 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6010 << FnDecl->getDeclName();
6011 return true;
6012 }
6013
6014 return false;
6015}
6016
Douglas Gregor074149e2009-01-05 19:45:36 +00006017/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6018/// linkage specification, including the language and (if present)
6019/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6020/// the location of the language string literal, which is provided
6021/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6022/// the '{' brace. Otherwise, this linkage specification does not
6023/// have any braces.
John McCalld226f652010-08-21 09:40:31 +00006024Decl *Sema::ActOnStartLinkageSpecification(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006025 SourceLocation ExternLoc,
6026 SourceLocation LangLoc,
Benjamin Kramerd5663812010-05-03 13:08:54 +00006027 llvm::StringRef Lang,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006028 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00006029 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006030 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006031 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006032 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006033 Language = LinkageSpecDecl::lang_cxx;
6034 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00006035 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00006036 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006037 }
Mike Stump1eb44332009-09-09 15:08:12 +00006038
Chris Lattnercc98eac2008-12-17 07:13:27 +00006039 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00006040
Douglas Gregor074149e2009-01-05 19:45:36 +00006041 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00006042 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00006043 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006044 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00006045 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00006046 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006047}
6048
Abramo Bagnara35f9a192010-07-30 16:47:02 +00006049/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006050/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6051/// valid, it's the position of the closing '}' brace in a linkage
6052/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006053Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6054 Decl *LinkageSpec,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006055 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00006056 if (LinkageSpec)
6057 PopDeclContext();
6058 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006059}
6060
Douglas Gregord308e622009-05-18 20:51:54 +00006061/// \brief Perform semantic analysis for the variable declaration that
6062/// occurs within a C++ catch clause, returning the newly-created
6063/// variable.
6064VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00006065 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006066 IdentifierInfo *Name,
6067 SourceLocation Loc,
6068 SourceRange Range) {
6069 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006070
6071 // Arrays and functions decay.
6072 if (ExDeclType->isArrayType())
6073 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6074 else if (ExDeclType->isFunctionType())
6075 ExDeclType = Context.getPointerType(ExDeclType);
6076
6077 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6078 // The exception-declaration shall not denote a pointer or reference to an
6079 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006080 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006081 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00006082 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006083 Invalid = true;
6084 }
Douglas Gregord308e622009-05-18 20:51:54 +00006085
Douglas Gregora2762912010-03-08 01:47:36 +00006086 // GCC allows catching pointers and references to incomplete types
6087 // as an extension; so do we, but we warn by default.
6088
Sebastian Redl4b07b292008-12-22 19:15:10 +00006089 QualType BaseType = ExDeclType;
6090 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006091 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006092 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006093 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006094 BaseType = Ptr->getPointeeType();
6095 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006096 DK = diag::ext_catch_incomplete_ptr;
6097 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006098 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006099 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006100 BaseType = Ref->getPointeeType();
6101 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006102 DK = diag::ext_catch_incomplete_ref;
6103 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006104 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006105 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006106 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6107 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006108 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006109
Mike Stump1eb44332009-09-09 15:08:12 +00006110 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006111 RequireNonAbstractType(Loc, ExDeclType,
6112 diag::err_abstract_type_in_decl,
6113 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006114 Invalid = true;
6115
John McCall5a180392010-07-24 00:37:23 +00006116 // Only the non-fragile NeXT runtime currently supports C++ catches
6117 // of ObjC types, and no runtime supports catching ObjC types by value.
6118 if (!Invalid && getLangOptions().ObjC1) {
6119 QualType T = ExDeclType;
6120 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6121 T = RT->getPointeeType();
6122
6123 if (T->isObjCObjectType()) {
6124 Diag(Loc, diag::err_objc_object_catch);
6125 Invalid = true;
6126 } else if (T->isObjCObjectPointerType()) {
6127 if (!getLangOptions().NeXTRuntime) {
6128 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6129 Invalid = true;
6130 } else if (!getLangOptions().ObjCNonFragileABI) {
6131 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6132 Invalid = true;
6133 }
6134 }
6135 }
6136
Mike Stump1eb44332009-09-09 15:08:12 +00006137 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalld931b082010-08-26 03:08:43 +00006138 Name, ExDeclType, TInfo, SC_None,
6139 SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006140 ExDecl->setExceptionVariable(true);
6141
Douglas Gregor6d182892010-03-05 23:38:39 +00006142 if (!Invalid) {
6143 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6144 // C++ [except.handle]p16:
6145 // The object declared in an exception-declaration or, if the
6146 // exception-declaration does not specify a name, a temporary (12.2) is
6147 // copy-initialized (8.5) from the exception object. [...]
6148 // The object is destroyed when the handler exits, after the destruction
6149 // of any automatic objects initialized within the handler.
6150 //
6151 // We just pretend to initialize the object with itself, then make sure
6152 // it can be destroyed later.
6153 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6154 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
6155 Loc, ExDeclType, 0);
6156 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6157 SourceLocation());
6158 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00006159 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00006160 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6d182892010-03-05 23:38:39 +00006161 if (Result.isInvalid())
6162 Invalid = true;
6163 else
6164 FinalizeVarWithDestructor(ExDecl, RecordTy);
6165 }
6166 }
6167
Douglas Gregord308e622009-05-18 20:51:54 +00006168 if (Invalid)
6169 ExDecl->setInvalidDecl();
6170
6171 return ExDecl;
6172}
6173
6174/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6175/// handler.
John McCalld226f652010-08-21 09:40:31 +00006176Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006177 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6178 QualType ExDeclType = TInfo->getType();
Douglas Gregord308e622009-05-18 20:51:54 +00006179
6180 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00006181 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006182 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006183 LookupOrdinaryName,
6184 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006185 // The scope should be freshly made just for us. There is just no way
6186 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006187 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006188 if (PrevDecl->isTemplateParameter()) {
6189 // Maybe we will complain about the shadowed template parameter.
6190 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006191 }
6192 }
6193
Chris Lattnereaaebc72009-04-25 08:06:05 +00006194 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006195 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6196 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006197 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006198 }
6199
John McCalla93c9342009-12-07 02:54:59 +00006200 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006201 D.getIdentifier(),
6202 D.getIdentifierLoc(),
6203 D.getDeclSpec().getSourceRange());
6204
Chris Lattnereaaebc72009-04-25 08:06:05 +00006205 if (Invalid)
6206 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00006207
Sebastian Redl4b07b292008-12-22 19:15:10 +00006208 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006209 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00006210 PushOnScopeChains(ExDecl, S);
6211 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006212 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006213
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006214 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00006215 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006216}
Anders Carlssonfb311762009-03-14 00:25:26 +00006217
John McCalld226f652010-08-21 09:40:31 +00006218Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00006219 Expr *AssertExpr,
6220 Expr *AssertMessageExpr_) {
6221 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00006222
Anders Carlssonc3082412009-03-14 00:33:21 +00006223 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6224 llvm::APSInt Value(32);
6225 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6226 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6227 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006228 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00006229 }
Anders Carlssonfb311762009-03-14 00:25:26 +00006230
Anders Carlssonc3082412009-03-14 00:33:21 +00006231 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00006232 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00006233 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00006234 }
6235 }
Mike Stump1eb44332009-09-09 15:08:12 +00006236
Mike Stump1eb44332009-09-09 15:08:12 +00006237 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00006238 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00006239
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006240 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00006241 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00006242}
Sebastian Redl50de12f2009-03-24 22:27:57 +00006243
Douglas Gregor1d869352010-04-07 16:53:43 +00006244/// \brief Perform semantic analysis of the given friend type declaration.
6245///
6246/// \returns A friend declaration that.
6247FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6248 TypeSourceInfo *TSInfo) {
6249 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6250
6251 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006252 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00006253
Douglas Gregor06245bf2010-04-07 17:57:12 +00006254 if (!getLangOptions().CPlusPlus0x) {
6255 // C++03 [class.friend]p2:
6256 // An elaborated-type-specifier shall be used in a friend declaration
6257 // for a class.*
6258 //
6259 // * The class-key of the elaborated-type-specifier is required.
6260 if (!ActiveTemplateInstantiations.empty()) {
6261 // Do not complain about the form of friend template types during
6262 // template instantiation; we will already have complained when the
6263 // template was declared.
6264 } else if (!T->isElaboratedTypeSpecifier()) {
6265 // If we evaluated the type to a record type, suggest putting
6266 // a tag in front.
6267 if (const RecordType *RT = T->getAs<RecordType>()) {
6268 RecordDecl *RD = RT->getDecl();
6269
6270 std::string InsertionText = std::string(" ") + RD->getKindName();
6271
6272 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6273 << (unsigned) RD->getTagKind()
6274 << T
6275 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6276 InsertionText);
6277 } else {
6278 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6279 << T
6280 << SourceRange(FriendLoc, TypeRange.getEnd());
6281 }
6282 } else if (T->getAs<EnumType>()) {
6283 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00006284 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00006285 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00006286 }
6287 }
6288
Douglas Gregor06245bf2010-04-07 17:57:12 +00006289 // C++0x [class.friend]p3:
6290 // If the type specifier in a friend declaration designates a (possibly
6291 // cv-qualified) class type, that class is declared as a friend; otherwise,
6292 // the friend declaration is ignored.
6293
6294 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6295 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00006296
6297 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6298}
6299
John McCalldd4a3b02009-09-16 22:47:08 +00006300/// Handle a friend type declaration. This works in tandem with
6301/// ActOnTag.
6302///
6303/// Notes on friend class templates:
6304///
6305/// We generally treat friend class declarations as if they were
6306/// declaring a class. So, for example, the elaborated type specifier
6307/// in a friend declaration is required to obey the restrictions of a
6308/// class-head (i.e. no typedefs in the scope chain), template
6309/// parameters are required to match up with simple template-ids, &c.
6310/// However, unlike when declaring a template specialization, it's
6311/// okay to refer to a template specialization without an empty
6312/// template parameter declaration, e.g.
6313/// friend class A<T>::B<unsigned>;
6314/// We permit this as a special case; if there are any template
6315/// parameters present at all, require proper matching, i.e.
6316/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00006317Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00006318 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00006319 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00006320
6321 assert(DS.isFriendSpecified());
6322 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6323
John McCalldd4a3b02009-09-16 22:47:08 +00006324 // Try to convert the decl specifier to a type. This works for
6325 // friend templates because ActOnTag never produces a ClassTemplateDecl
6326 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00006327 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00006328 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6329 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00006330 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00006331 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006332
John McCalldd4a3b02009-09-16 22:47:08 +00006333 // This is definitely an error in C++98. It's probably meant to
6334 // be forbidden in C++0x, too, but the specification is just
6335 // poorly written.
6336 //
6337 // The problem is with declarations like the following:
6338 // template <T> friend A<T>::foo;
6339 // where deciding whether a class C is a friend or not now hinges
6340 // on whether there exists an instantiation of A that causes
6341 // 'foo' to equal C. There are restrictions on class-heads
6342 // (which we declare (by fiat) elaborated friend declarations to
6343 // be) that makes this tractable.
6344 //
6345 // FIXME: handle "template <> friend class A<T>;", which
6346 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00006347 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00006348 Diag(Loc, diag::err_tagless_friend_type_template)
6349 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006350 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00006351 }
Douglas Gregor1d869352010-04-07 16:53:43 +00006352
John McCall02cace72009-08-28 07:59:38 +00006353 // C++98 [class.friend]p1: A friend of a class is a function
6354 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00006355 // This is fixed in DR77, which just barely didn't make the C++03
6356 // deadline. It's also a very silly restriction that seriously
6357 // affects inner classes and which nobody else seems to implement;
6358 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00006359 //
6360 // But note that we could warn about it: it's always useless to
6361 // friend one of your own members (it's not, however, worthless to
6362 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00006363
John McCalldd4a3b02009-09-16 22:47:08 +00006364 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00006365 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00006366 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00006367 NumTempParamLists,
John McCalldd4a3b02009-09-16 22:47:08 +00006368 (TemplateParameterList**) TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00006369 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00006370 DS.getFriendSpecLoc());
6371 else
Douglas Gregor1d869352010-04-07 16:53:43 +00006372 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6373
6374 if (!D)
John McCalld226f652010-08-21 09:40:31 +00006375 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00006376
John McCalldd4a3b02009-09-16 22:47:08 +00006377 D->setAccess(AS_public);
6378 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00006379
John McCalld226f652010-08-21 09:40:31 +00006380 return D;
John McCall02cace72009-08-28 07:59:38 +00006381}
6382
John McCalld226f652010-08-21 09:40:31 +00006383Decl *Sema::ActOnFriendFunctionDecl(Scope *S,
6384 Declarator &D,
6385 bool IsDefinition,
John McCallbbbcdd92009-09-11 21:02:39 +00006386 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00006387 const DeclSpec &DS = D.getDeclSpec();
6388
6389 assert(DS.isFriendSpecified());
6390 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6391
6392 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00006393 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6394 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00006395
6396 // C++ [class.friend]p1
6397 // A friend of a class is a function or class....
6398 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00006399 // It *doesn't* see through dependent types, which is correct
6400 // according to [temp.arg.type]p3:
6401 // If a declaration acquires a function type through a
6402 // type dependent on a template-parameter and this causes
6403 // a declaration that does not use the syntactic form of a
6404 // function declarator to have a function type, the program
6405 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00006406 if (!T->isFunctionType()) {
6407 Diag(Loc, diag::err_unexpected_friend);
6408
6409 // It might be worthwhile to try to recover by creating an
6410 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00006411 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006412 }
6413
6414 // C++ [namespace.memdef]p3
6415 // - If a friend declaration in a non-local class first declares a
6416 // class or function, the friend class or function is a member
6417 // of the innermost enclosing namespace.
6418 // - The name of the friend is not found by simple name lookup
6419 // until a matching declaration is provided in that namespace
6420 // scope (either before or after the class declaration granting
6421 // friendship).
6422 // - If a friend function is called, its name may be found by the
6423 // name lookup that considers functions from namespaces and
6424 // classes associated with the types of the function arguments.
6425 // - When looking for a prior declaration of a class or a function
6426 // declared as a friend, scopes outside the innermost enclosing
6427 // namespace scope are not considered.
6428
John McCall02cace72009-08-28 07:59:38 +00006429 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00006430 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6431 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00006432 assert(Name);
6433
John McCall67d1a672009-08-06 02:15:43 +00006434 // The context we found the declaration in, or in which we should
6435 // create the declaration.
6436 DeclContext *DC;
6437
6438 // FIXME: handle local classes
6439
6440 // Recover from invalid scope qualifiers as if they just weren't there.
Abramo Bagnara25777432010-08-11 22:01:17 +00006441 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00006442 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00006443 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
6444 DC = computeDeclContext(ScopeQual);
6445
6446 // FIXME: handle dependent contexts
John McCalld226f652010-08-21 09:40:31 +00006447 if (!DC) return 0;
6448 if (RequireCompleteDeclContext(ScopeQual, DC)) return 0;
John McCall67d1a672009-08-06 02:15:43 +00006449
John McCall68263142009-11-18 22:49:29 +00006450 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00006451
John McCall9da9cdf2010-05-28 01:41:47 +00006452 // Ignore things found implicitly in the wrong scope.
John McCall67d1a672009-08-06 02:15:43 +00006453 // TODO: better diagnostics for this case. Suggesting the right
6454 // qualified scope would be nice...
John McCall9da9cdf2010-05-28 01:41:47 +00006455 LookupResult::Filter F = Previous.makeFilter();
6456 while (F.hasNext()) {
6457 NamedDecl *D = F.next();
6458 if (!D->getDeclContext()->getLookupContext()->Equals(DC))
6459 F.erase();
6460 }
6461 F.done();
6462
6463 if (Previous.empty()) {
John McCall02cace72009-08-28 07:59:38 +00006464 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00006465 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
John McCalld226f652010-08-21 09:40:31 +00006466 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006467 }
6468
6469 // C++ [class.friend]p1: A friend of a class is a function or
6470 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00006471 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00006472 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6473
John McCall67d1a672009-08-06 02:15:43 +00006474 // Otherwise walk out to the nearest namespace scope looking for matches.
6475 } else {
6476 // TODO: handle local class contexts.
6477
6478 DC = CurContext;
6479 while (true) {
6480 // Skip class contexts. If someone can cite chapter and verse
6481 // for this behavior, that would be nice --- it's what GCC and
6482 // EDG do, and it seems like a reasonable intent, but the spec
6483 // really only says that checks for unqualified existing
6484 // declarations should stop at the nearest enclosing namespace,
6485 // not that they should only consider the nearest enclosing
6486 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00006487 while (DC->isRecord())
6488 DC = DC->getParent();
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
6492 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00006493 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00006494 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00006495
John McCall67d1a672009-08-06 02:15:43 +00006496 if (DC->isFileContext()) break;
6497 DC = DC->getParent();
6498 }
6499
6500 // C++ [class.friend]p1: A friend of a class is a function or
6501 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00006502 // C++0x changes this for both friend types and functions.
6503 // Most C++ 98 compilers do seem to give an error here, so
6504 // we do, too.
John McCall68263142009-11-18 22:49:29 +00006505 if (!Previous.empty() && DC->Equals(CurContext)
6506 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00006507 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6508 }
6509
Douglas Gregor182ddf02009-09-28 00:08:27 +00006510 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00006511 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006512 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6513 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6514 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00006515 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006516 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6517 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00006518 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006519 }
John McCall67d1a672009-08-06 02:15:43 +00006520 }
6521
Douglas Gregor182ddf02009-09-28 00:08:27 +00006522 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00006523 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00006524 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00006525 IsDefinition,
6526 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00006527 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00006528
Douglas Gregor182ddf02009-09-28 00:08:27 +00006529 assert(ND->getDeclContext() == DC);
6530 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00006531
John McCallab88d972009-08-31 22:39:49 +00006532 // Add the function declaration to the appropriate lookup tables,
6533 // adjusting the redeclarations list as necessary. We don't
6534 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00006535 //
John McCallab88d972009-08-31 22:39:49 +00006536 // Also update the scope-based lookup if the target context's
6537 // lookup context is in lexical scope.
6538 if (!CurContext->isDependentContext()) {
6539 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00006540 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006541 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00006542 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006543 }
John McCall02cace72009-08-28 07:59:38 +00006544
6545 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00006546 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00006547 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00006548 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00006549 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00006550
John McCalld226f652010-08-21 09:40:31 +00006551 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00006552}
6553
John McCalld226f652010-08-21 09:40:31 +00006554void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6555 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00006556
Sebastian Redl50de12f2009-03-24 22:27:57 +00006557 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6558 if (!Fn) {
6559 Diag(DelLoc, diag::err_deleted_non_function);
6560 return;
6561 }
6562 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6563 Diag(DelLoc, diag::err_deleted_decl_not_first);
6564 Diag(Prev->getLocation(), diag::note_previous_declaration);
6565 // If the declaration wasn't the first, we delete the function anyway for
6566 // recovery.
6567 }
6568 Fn->setDeleted();
6569}
Sebastian Redl13e88542009-04-27 21:33:24 +00006570
6571static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6572 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6573 ++CI) {
6574 Stmt *SubStmt = *CI;
6575 if (!SubStmt)
6576 continue;
6577 if (isa<ReturnStmt>(SubStmt))
6578 Self.Diag(SubStmt->getSourceRange().getBegin(),
6579 diag::err_return_in_constructor_handler);
6580 if (!isa<Expr>(SubStmt))
6581 SearchForReturnInStmt(Self, SubStmt);
6582 }
6583}
6584
6585void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6586 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6587 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6588 SearchForReturnInStmt(*this, Handler);
6589 }
6590}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006591
Mike Stump1eb44332009-09-09 15:08:12 +00006592bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006593 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00006594 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6595 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006596
Chandler Carruth73857792010-02-15 11:53:20 +00006597 if (Context.hasSameType(NewTy, OldTy) ||
6598 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006599 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006600
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006601 // Check if the return types are covariant
6602 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00006603
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006604 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006605 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6606 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006607 NewClassTy = NewPT->getPointeeType();
6608 OldClassTy = OldPT->getPointeeType();
6609 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006610 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6611 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6612 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6613 NewClassTy = NewRT->getPointeeType();
6614 OldClassTy = OldRT->getPointeeType();
6615 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006616 }
6617 }
Mike Stump1eb44332009-09-09 15:08:12 +00006618
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006619 // The return types aren't either both pointers or references to a class type.
6620 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006621 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006622 diag::err_different_return_type_for_overriding_virtual_function)
6623 << New->getDeclName() << NewTy << OldTy;
6624 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00006625
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006626 return true;
6627 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006628
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006629 // C++ [class.virtual]p6:
6630 // If the return type of D::f differs from the return type of B::f, the
6631 // class type in the return type of D::f shall be complete at the point of
6632 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00006633 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6634 if (!RT->isBeingDefined() &&
6635 RequireCompleteType(New->getLocation(), NewClassTy,
6636 PDiag(diag::err_covariant_return_incomplete)
6637 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006638 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00006639 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006640
Douglas Gregora4923eb2009-11-16 21:35:15 +00006641 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006642 // Check if the new class derives from the old class.
6643 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6644 Diag(New->getLocation(),
6645 diag::err_covariant_return_not_derived)
6646 << New->getDeclName() << NewTy << OldTy;
6647 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6648 return true;
6649 }
Mike Stump1eb44332009-09-09 15:08:12 +00006650
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006651 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00006652 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00006653 diag::err_covariant_return_inaccessible_base,
6654 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6655 // FIXME: Should this point to the return type?
6656 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006657 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6658 return true;
6659 }
6660 }
Mike Stump1eb44332009-09-09 15:08:12 +00006661
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006662 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006663 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006664 Diag(New->getLocation(),
6665 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006666 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006667 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6668 return true;
6669 };
Mike Stump1eb44332009-09-09 15:08:12 +00006670
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006671
6672 // The new class type must have the same or less qualifiers as the old type.
6673 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6674 Diag(New->getLocation(),
6675 diag::err_covariant_return_type_class_type_more_qualified)
6676 << New->getDeclName() << NewTy << OldTy;
6677 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6678 return true;
6679 };
Mike Stump1eb44332009-09-09 15:08:12 +00006680
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006681 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006682}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006683
Sean Huntbbd37c62009-11-21 08:43:09 +00006684bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6685 const CXXMethodDecl *Old)
6686{
6687 if (Old->hasAttr<FinalAttr>()) {
6688 Diag(New->getLocation(), diag::err_final_function_overridden)
6689 << New->getDeclName();
6690 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6691 return true;
6692 }
6693
6694 return false;
6695}
6696
Douglas Gregor4ba31362009-12-01 17:24:26 +00006697/// \brief Mark the given method pure.
6698///
6699/// \param Method the method to be marked pure.
6700///
6701/// \param InitRange the source range that covers the "0" initializer.
6702bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6703 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6704 Method->setPure();
6705
6706 // A class is abstract if at least one function is pure virtual.
6707 Method->getParent()->setAbstract(true);
6708 return false;
6709 }
6710
6711 if (!Method->isInvalidDecl())
6712 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6713 << Method->getDeclName() << InitRange;
6714 return true;
6715}
6716
John McCall731ad842009-12-19 09:28:58 +00006717/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6718/// an initializer for the out-of-line declaration 'Dcl'. The scope
6719/// is a fresh scope pushed for just this purpose.
6720///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006721/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6722/// static data member of class X, names should be looked up in the scope of
6723/// class X.
John McCalld226f652010-08-21 09:40:31 +00006724void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006725 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006726 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006727
John McCall731ad842009-12-19 09:28:58 +00006728 // We should only get called for declarations with scope specifiers, like:
6729 // int foo::bar;
6730 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006731 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006732}
6733
6734/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00006735/// initializer for the out-of-line declaration 'D'.
6736void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006737 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006738 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006739
John McCall731ad842009-12-19 09:28:58 +00006740 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006741 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006742}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006743
6744/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6745/// C++ if/switch/while/for statement.
6746/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00006747DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006748 // C++ 6.4p2:
6749 // The declarator shall not specify a function or an array.
6750 // The type-specifier-seq shall not contain typedef and shall not declare a
6751 // new class or enumeration.
6752 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6753 "Parser allowed 'typedef' as storage class of condition decl.");
6754
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006755 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00006756 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6757 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006758
6759 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6760 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6761 // would be created and CXXConditionDeclExpr wants a VarDecl.
6762 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6763 << D.getSourceRange();
6764 return DeclResult();
6765 } else if (OwnedTag && OwnedTag->isDefinition()) {
6766 // The type-specifier-seq shall not declare a new class or enumeration.
6767 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6768 }
6769
John McCalld226f652010-08-21 09:40:31 +00006770 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006771 if (!Dcl)
6772 return DeclResult();
6773
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006774 return Dcl;
6775}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006776
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006777void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6778 bool DefinitionRequired) {
6779 // Ignore any vtable uses in unevaluated operands or for classes that do
6780 // not have a vtable.
6781 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6782 CurContext->isDependentContext() ||
6783 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00006784 return;
6785
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006786 // Try to insert this class into the map.
6787 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6788 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6789 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6790 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00006791 // If we already had an entry, check to see if we are promoting this vtable
6792 // to required a definition. If so, we need to reappend to the VTableUses
6793 // list, since we may have already processed the first entry.
6794 if (DefinitionRequired && !Pos.first->second) {
6795 Pos.first->second = true;
6796 } else {
6797 // Otherwise, we can early exit.
6798 return;
6799 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006800 }
6801
6802 // Local classes need to have their virtual members marked
6803 // immediately. For all other classes, we mark their virtual members
6804 // at the end of the translation unit.
6805 if (Class->isLocalClass())
6806 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00006807 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006808 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00006809}
6810
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006811bool Sema::DefineUsedVTables() {
6812 // If any dynamic classes have their key function defined within
6813 // this translation unit, then those vtables are considered "used" and must
6814 // be emitted.
6815 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6816 if (const CXXMethodDecl *KeyFunction
6817 = Context.getKeyFunction(DynamicClasses[I])) {
6818 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006819 if (KeyFunction->hasBody(Definition))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006820 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6821 }
6822 }
6823
6824 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00006825 return false;
6826
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006827 // Note: The VTableUses vector could grow as a result of marking
6828 // the members of a class as "used", so we check the size each
6829 // time through the loop and prefer indices (with are stable) to
6830 // iterators (which are not).
6831 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00006832 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006833 if (!Class)
6834 continue;
6835
6836 SourceLocation Loc = VTableUses[I].second;
6837
6838 // If this class has a key function, but that key function is
6839 // defined in another translation unit, we don't need to emit the
6840 // vtable even though we're using it.
6841 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006842 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006843 switch (KeyFunction->getTemplateSpecializationKind()) {
6844 case TSK_Undeclared:
6845 case TSK_ExplicitSpecialization:
6846 case TSK_ExplicitInstantiationDeclaration:
6847 // The key function is in another translation unit.
6848 continue;
6849
6850 case TSK_ExplicitInstantiationDefinition:
6851 case TSK_ImplicitInstantiation:
6852 // We will be instantiating the key function.
6853 break;
6854 }
6855 } else if (!KeyFunction) {
6856 // If we have a class with no key function that is the subject
6857 // of an explicit instantiation declaration, suppress the
6858 // vtable; it will live with the explicit instantiation
6859 // definition.
6860 bool IsExplicitInstantiationDeclaration
6861 = Class->getTemplateSpecializationKind()
6862 == TSK_ExplicitInstantiationDeclaration;
6863 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6864 REnd = Class->redecls_end();
6865 R != REnd; ++R) {
6866 TemplateSpecializationKind TSK
6867 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6868 if (TSK == TSK_ExplicitInstantiationDeclaration)
6869 IsExplicitInstantiationDeclaration = true;
6870 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6871 IsExplicitInstantiationDeclaration = false;
6872 break;
6873 }
6874 }
6875
6876 if (IsExplicitInstantiationDeclaration)
6877 continue;
6878 }
6879
6880 // Mark all of the virtual members of this class as referenced, so
6881 // that we can build a vtable. Then, tell the AST consumer that a
6882 // vtable for this class is required.
6883 MarkVirtualMembersReferenced(Loc, Class);
6884 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6885 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6886
6887 // Optionally warn if we're emitting a weak vtable.
6888 if (Class->getLinkage() == ExternalLinkage &&
6889 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006890 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006891 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6892 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006893 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006894 VTableUses.clear();
6895
Anders Carlssond6a637f2009-12-07 08:24:59 +00006896 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006897}
Anders Carlssond6a637f2009-12-07 08:24:59 +00006898
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006899void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6900 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00006901 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6902 e = RD->method_end(); i != e; ++i) {
6903 CXXMethodDecl *MD = *i;
6904
6905 // C++ [basic.def.odr]p2:
6906 // [...] A virtual member function is used if it is not pure. [...]
6907 if (MD->isVirtual() && !MD->isPure())
6908 MarkDeclarationReferenced(Loc, MD);
6909 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006910
6911 // Only classes that have virtual bases need a VTT.
6912 if (RD->getNumVBases() == 0)
6913 return;
6914
6915 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6916 e = RD->bases_end(); i != e; ++i) {
6917 const CXXRecordDecl *Base =
6918 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006919 if (Base->getNumVBases() == 0)
6920 continue;
6921 MarkVirtualMembersReferenced(Loc, Base);
6922 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00006923}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006924
6925/// SetIvarInitializers - This routine builds initialization ASTs for the
6926/// Objective-C implementation whose ivars need be initialized.
6927void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6928 if (!getLangOptions().CPlusPlus)
6929 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00006930 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006931 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6932 CollectIvarsToConstructOrDestruct(OID, ivars);
6933 if (ivars.empty())
6934 return;
6935 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6936 for (unsigned i = 0; i < ivars.size(); i++) {
6937 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00006938 if (Field->isInvalidDecl())
6939 continue;
6940
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006941 CXXBaseOrMemberInitializer *Member;
6942 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6943 InitializationKind InitKind =
6944 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6945
6946 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00006947 ExprResult MemberInit =
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006948 InitSeq.Perform(*this, InitEntity, InitKind,
6949 Sema::MultiExprArg(*this, 0, 0));
John McCall9ae2f072010-08-23 23:25:46 +00006950 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006951 // Note, MemberInit could actually come back empty if no initialization
6952 // is required (e.g., because it would call a trivial default constructor)
6953 if (!MemberInit.get() || MemberInit.isInvalid())
6954 continue;
6955
6956 Member =
6957 new (Context) CXXBaseOrMemberInitializer(Context,
6958 Field, SourceLocation(),
6959 SourceLocation(),
6960 MemberInit.takeAs<Expr>(),
6961 SourceLocation());
6962 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00006963
6964 // Be sure that the destructor is accessible and is marked as referenced.
6965 if (const RecordType *RecordTy
6966 = Context.getBaseElementType(Field->getType())
6967 ->getAs<RecordType>()) {
6968 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00006969 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00006970 MarkDeclarationReferenced(Field->getLocation(), Destructor);
6971 CheckDestructorAccess(Field->getLocation(), Destructor,
6972 PDiag(diag::err_access_dtor_ivar)
6973 << Context.getBaseElementType(Field->getType()));
6974 }
6975 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006976 }
6977 ObjCImplementation->setIvarInitializers(Context,
6978 AllToInit.data(), AllToInit.size());
6979 }
6980}