blob: 7205abdbc21b7432b8ec49bb6ba5f4f7f49cc135 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000034#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000035#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner8123a952008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattner9e979552008-04-12 23:52:44 +000043namespace {
44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
45 /// the default argument of a parameter to determine whether it
46 /// contains any ill-formed subexpressions. For example, this will
47 /// diagnose the use of local variables or parameters within the
48 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 public:
Mike Stump1eb44332009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000057
Chris Lattner9e979552008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000061 };
Chris Lattner8123a952008-04-10 02:22:51 +000062
Chris Lattner9e979552008-04-12 23:52:44 +000063 /// VisitExpr - Visit all of the children of this expression.
64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
65 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000066 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000067 E = Node->child_end(); I != E; ++I)
68 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000070 }
71
Chris Lattner9e979552008-04-12 23:52:44 +000072 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000077 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000093 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000097 }
Chris Lattner8123a952008-04-10 02:22:51 +000098
Douglas Gregor3996f232008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattner9e979552008-04-12 23:52:44 +0000101
Douglas Gregor796da182008-11-04 14:32:21 +0000102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
106 // member function.
107 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000110 }
Chris Lattner8123a952008-04-10 02:22:51 +0000111}
112
Anders Carlssoned961f92009-08-25 02:29:20 +0000113bool
John McCall9ae2f072010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000116 if (RequireCompleteType(Param->getLocation(), Param->getType(),
117 diag::err_typecheck_decl_incomplete_type)) {
118 Param->setInvalidDecl();
119 return true;
120 }
121
Anders Carlssoned961f92009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Douglas Gregor99a2e602009-12-16 01:38:02 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
129 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
130 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000131 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000132 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +0000133 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000134 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000135 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000136 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000137
Anders Carlsson0ece4912009-12-15 20:51:39 +0000138 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Anders Carlssoned961f92009-08-25 02:29:20 +0000140 // Okay: add the default argument to the parameter
141 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Anders Carlsson9351c172009-08-25 03:18:48 +0000143 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000144}
145
Chris Lattner8123a952008-04-10 02:22:51 +0000146/// ActOnParamDefaultArgument - Check whether the default argument
147/// provided for a function parameter is well-formed. If so, attach it
148/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000149void
John McCalld226f652010-08-21 09:40:31 +0000150Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000151 Expr *DefaultArg) {
152 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000153 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000154
John McCalld226f652010-08-21 09:40:31 +0000155 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000156 UnparsedDefaultArgLocs.erase(Param);
157
Chris Lattner3d1cee32008-04-08 05:04:30 +0000158 // Default arguments are only permitted in C++
159 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000160 Diag(EqualLoc, diag::err_param_default_argument)
161 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000162 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000163 return;
164 }
165
Anders Carlsson66e30672009-08-25 01:02:06 +0000166 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000167 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
168 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000169 Param->setInvalidDecl();
170 return;
171 }
Mike Stump1eb44332009-09-09 15:08:12 +0000172
John McCall9ae2f072010-08-23 23:25:46 +0000173 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000174}
175
Douglas Gregor61366e92008-12-24 00:01:03 +0000176/// ActOnParamUnparsedDefaultArgument - We've seen a default
177/// argument for a function parameter, but we can't parse it yet
178/// because we're inside a class definition. Note that this default
179/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000180void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000181 SourceLocation EqualLoc,
182 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000183 if (!param)
184 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000185
John McCalld226f652010-08-21 09:40:31 +0000186 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000187 if (Param)
188 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Anders Carlsson5e300d12009-06-12 16:51:40 +0000190 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000191}
192
Douglas Gregor72b505b2008-12-16 21:30:33 +0000193/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
194/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000195void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000196 if (!param)
197 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000198
John McCalld226f652010-08-21 09:40:31 +0000199 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Anders Carlsson5e300d12009-06-12 16:51:40 +0000201 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Anders Carlsson5e300d12009-06-12 16:51:40 +0000203 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000204}
205
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000206/// CheckExtraCXXDefaultArguments - Check for any extra default
207/// arguments in the declarator, which is not a function declaration
208/// or definition and therefore is not permitted to have default
209/// arguments. This routine should be invoked for every declarator
210/// that is not a function declaration or definition.
211void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
212 // C++ [dcl.fct.default]p3
213 // A default argument expression shall be specified only in the
214 // parameter-declaration-clause of a function declaration or in a
215 // template-parameter (14.1). It shall not be specified for a
216 // parameter pack. If it is specified in a
217 // parameter-declaration-clause, it shall not occur within a
218 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000219 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000220 DeclaratorChunk &chunk = D.getTypeObject(i);
221 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000222 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
223 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000224 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000225 if (Param->hasUnparsedDefaultArg()) {
226 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000227 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
228 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
229 delete Toks;
230 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000231 } else if (Param->getDefaultArg()) {
232 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
233 << Param->getDefaultArg()->getSourceRange();
234 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000235 }
236 }
237 }
238 }
239}
240
Chris Lattner3d1cee32008-04-08 05:04:30 +0000241// MergeCXXFunctionDecl - Merge two declarations of the same C++
242// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000243// type. Subroutine of MergeFunctionDecl. Returns true if there was an
244// error, false otherwise.
245bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
246 bool Invalid = false;
247
Chris Lattner3d1cee32008-04-08 05:04:30 +0000248 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000249 // For non-template functions, default arguments can be added in
250 // later declarations of a function in the same
251 // scope. Declarations in different scopes have completely
252 // distinct sets of default arguments. That is, declarations in
253 // inner scopes do not acquire default arguments from
254 // declarations in outer scopes, and vice versa. In a given
255 // function declaration, all parameters subsequent to a
256 // parameter with a default argument shall have default
257 // arguments supplied in this or previous declarations. A
258 // default argument shall not be redefined by a later
259 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000260 //
261 // C++ [dcl.fct.default]p6:
262 // Except for member functions of class templates, the default arguments
263 // in a member function definition that appears outside of the class
264 // definition are added to the set of default arguments provided by the
265 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000266 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
267 ParmVarDecl *OldParam = Old->getParamDecl(p);
268 ParmVarDecl *NewParam = New->getParamDecl(p);
269
Douglas Gregor6cc15182009-09-11 18:44:32 +0000270 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000271 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
272 // hint here. Alternatively, we could walk the type-source information
273 // for NewParam to find the last source location in the type... but it
274 // isn't worth the effort right now. This is the kind of test case that
275 // is hard to get right:
276
277 // int f(int);
278 // void g(int (*fp)(int) = f);
279 // void g(int (*fp)(int) = &f);
Mike Stump1eb44332009-09-09 15:08:12 +0000280 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000281 diag::err_param_default_argument_redefinition)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000282 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000283
284 // Look for the function declaration where the default argument was
285 // actually written, which may be a declaration prior to Old.
286 for (FunctionDecl *Older = Old->getPreviousDeclaration();
287 Older; Older = Older->getPreviousDeclaration()) {
288 if (!Older->getParamDecl(p)->hasDefaultArg())
289 break;
290
291 OldParam = Older->getParamDecl(p);
292 }
293
294 Diag(OldParam->getLocation(), diag::note_previous_definition)
295 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000296 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000297 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000298 // Merge the old default argument into the new parameter.
299 // It's important to use getInit() here; getDefaultArg()
300 // strips off any top-level CXXExprWithTemporaries.
John McCallbf73b352010-03-12 18:31:32 +0000301 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000302 if (OldParam->hasUninstantiatedDefaultArg())
303 NewParam->setUninstantiatedDefaultArg(
304 OldParam->getUninstantiatedDefaultArg());
305 else
John McCall3d6c1782010-05-04 01:53:42 +0000306 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000307 } else if (NewParam->hasDefaultArg()) {
308 if (New->getDescribedFunctionTemplate()) {
309 // Paragraph 4, quoted above, only applies to non-template functions.
310 Diag(NewParam->getLocation(),
311 diag::err_param_default_argument_template_redecl)
312 << NewParam->getDefaultArgRange();
313 Diag(Old->getLocation(), diag::note_template_prev_declaration)
314 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000315 } else if (New->getTemplateSpecializationKind()
316 != TSK_ImplicitInstantiation &&
317 New->getTemplateSpecializationKind() != TSK_Undeclared) {
318 // C++ [temp.expr.spec]p21:
319 // Default function arguments shall not be specified in a declaration
320 // or a definition for one of the following explicit specializations:
321 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000322 // - the explicit specialization of a member function template;
323 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000324 // template where the class template specialization to which the
325 // member function specialization belongs is implicitly
326 // instantiated.
327 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
328 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
329 << New->getDeclName()
330 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000331 } else if (New->getDeclContext()->isDependentContext()) {
332 // C++ [dcl.fct.default]p6 (DR217):
333 // Default arguments for a member function of a class template shall
334 // be specified on the initial declaration of the member function
335 // within the class template.
336 //
337 // Reading the tea leaves a bit in DR217 and its reference to DR205
338 // leads me to the conclusion that one cannot add default function
339 // arguments for an out-of-line definition of a member function of a
340 // dependent type.
341 int WhichKind = 2;
342 if (CXXRecordDecl *Record
343 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
344 if (Record->getDescribedClassTemplate())
345 WhichKind = 0;
346 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
347 WhichKind = 1;
348 else
349 WhichKind = 2;
350 }
351
352 Diag(NewParam->getLocation(),
353 diag::err_param_default_argument_member_template_redecl)
354 << WhichKind
355 << NewParam->getDefaultArgRange();
356 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000357 }
358 }
359
Douglas Gregore13ad832010-02-12 07:32:17 +0000360 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000361 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000362
Douglas Gregorcda9c672009-02-16 17:45:42 +0000363 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000364}
365
366/// CheckCXXDefaultArguments - Verify that the default arguments for a
367/// function declaration are well-formed according to C++
368/// [dcl.fct.default].
369void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
370 unsigned NumParams = FD->getNumParams();
371 unsigned p;
372
373 // Find first parameter with a default argument
374 for (p = 0; p < NumParams; ++p) {
375 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000376 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000377 break;
378 }
379
380 // C++ [dcl.fct.default]p4:
381 // In a given function declaration, all parameters
382 // subsequent to a parameter with a default argument shall
383 // have default arguments supplied in this or previous
384 // declarations. A default argument shall not be redefined
385 // by a later declaration (not even to the same value).
386 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000387 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000388 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000389 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000390 if (Param->isInvalidDecl())
391 /* We already complained about this parameter. */;
392 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000393 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000394 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000395 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000396 else
Mike Stump1eb44332009-09-09 15:08:12 +0000397 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000398 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Chris Lattner3d1cee32008-04-08 05:04:30 +0000400 LastMissingDefaultArg = p;
401 }
402 }
403
404 if (LastMissingDefaultArg > 0) {
405 // Some default arguments were missing. Clear out all of the
406 // default arguments up to (and including) the last missing
407 // default argument, so that we leave the function parameters
408 // in a semantically valid state.
409 for (p = 0; p <= LastMissingDefaultArg; ++p) {
410 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000411 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000412 Param->setDefaultArg(0);
413 }
414 }
415 }
416}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000417
Douglas Gregorb48fe382008-10-31 09:07:45 +0000418/// isCurrentClassName - Determine whether the identifier II is the
419/// name of the class type currently being defined. In the case of
420/// nested classes, this will only return true if II is the name of
421/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000422bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
423 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000424 assert(getLangOptions().CPlusPlus && "No class names in C!");
425
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000426 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000427 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000428 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000429 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
430 } else
431 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
432
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000433 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000434 return &II == CurDecl->getIdentifier();
435 else
436 return false;
437}
438
Mike Stump1eb44332009-09-09 15:08:12 +0000439/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000440///
441/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
442/// and returns NULL otherwise.
443CXXBaseSpecifier *
444Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
445 SourceRange SpecifierRange,
446 bool Virtual, AccessSpecifier Access,
Nick Lewycky56062202010-07-26 16:56:01 +0000447 TypeSourceInfo *TInfo) {
448 QualType BaseType = TInfo->getType();
449
Douglas Gregor2943aed2009-03-03 04:44:36 +0000450 // C++ [class.union]p1:
451 // A union shall not have base classes.
452 if (Class->isUnion()) {
453 Diag(Class->getLocation(), diag::err_base_clause_on_union)
454 << SpecifierRange;
455 return 0;
456 }
457
458 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000459 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000460 Class->getTagKind() == TTK_Class,
461 Access, TInfo);
462
463 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000464
465 // Base specifiers must be record types.
466 if (!BaseType->isRecordType()) {
467 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
468 return 0;
469 }
470
471 // C++ [class.union]p1:
472 // A union shall not be used as a base class.
473 if (BaseType->isUnionType()) {
474 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
475 return 0;
476 }
477
478 // C++ [class.derived]p2:
479 // The class-name in a base-specifier shall not be an incompletely
480 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000481 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000482 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000483 << SpecifierRange)) {
484 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000485 return 0;
John McCall572fc622010-08-17 07:23:57 +0000486 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000487
Eli Friedman1d954f62009-08-15 21:55:26 +0000488 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000489 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000490 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000491 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000492 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000493 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
494 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000495
Sean Huntbbd37c62009-11-21 08:43:09 +0000496 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
497 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
498 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000499 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
500 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000501 return 0;
502 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000503
Eli Friedmand0137332009-12-05 23:03:49 +0000504 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
John McCall572fc622010-08-17 07:23:57 +0000505
506 if (BaseDecl->isInvalidDecl())
507 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000508
509 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000510 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000511 Class->getTagKind() == TTK_Class,
512 Access, TInfo);
Anders Carlsson51f94042009-12-03 17:49:57 +0000513}
514
515void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
516 const CXXRecordDecl *BaseClass,
517 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000518 // A class with a non-empty base class is not empty.
519 // FIXME: Standard ref?
520 if (!BaseClass->isEmpty())
521 Class->setEmpty(false);
522
523 // C++ [class.virtual]p1:
524 // A class that [...] inherits a virtual function is called a polymorphic
525 // class.
526 if (BaseClass->isPolymorphic())
527 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000528
Douglas Gregor2943aed2009-03-03 04:44:36 +0000529 // C++ [dcl.init.aggr]p1:
530 // An aggregate is [...] a class with [...] no base classes [...].
531 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000532
533 // C++ [class]p4:
534 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000535 Class->setPOD(false);
536
Anders Carlsson51f94042009-12-03 17:49:57 +0000537 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000538 // C++ [class.ctor]p5:
539 // A constructor is trivial if its class has no virtual base classes.
540 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000541
542 // C++ [class.copy]p6:
543 // A copy constructor is trivial if its class has no virtual base classes.
544 Class->setHasTrivialCopyConstructor(false);
545
546 // C++ [class.copy]p11:
547 // A copy assignment operator is trivial if its class has no virtual
548 // base classes.
549 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000550
551 // C++0x [meta.unary.prop] is_empty:
552 // T is a class type, but not a union type, with ... no virtual base
553 // classes
554 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000555 } else {
556 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000557 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000558 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000559 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000560 Class->setHasTrivialConstructor(false);
561
562 // C++ [class.copy]p6:
563 // A copy constructor is trivial if all the direct base classes of its
564 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000565 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000566 Class->setHasTrivialCopyConstructor(false);
567
568 // C++ [class.copy]p11:
569 // A copy assignment operator is trivial if all the direct base classes
570 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000571 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000572 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000573 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000574
575 // C++ [class.ctor]p3:
576 // A destructor is trivial if all the direct base classes of its class
577 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000578 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000579 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000580}
581
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000582/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
583/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000584/// example:
585/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000586/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +0000587BaseResult
John McCalld226f652010-08-21 09:40:31 +0000588Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000589 bool Virtual, AccessSpecifier Access,
John McCallb3d87482010-08-24 05:47:05 +0000590 ParsedType basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000591 if (!classdecl)
592 return true;
593
Douglas Gregor40808ce2009-03-09 23:48:35 +0000594 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000595 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000596 if (!Class)
597 return true;
598
Nick Lewycky56062202010-07-26 16:56:01 +0000599 TypeSourceInfo *TInfo = 0;
600 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000601 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Nick Lewycky56062202010-07-26 16:56:01 +0000602 Virtual, Access, TInfo))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000603 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Douglas Gregor2943aed2009-03-03 04:44:36 +0000605 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000606}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000607
Douglas Gregor2943aed2009-03-03 04:44:36 +0000608/// \brief Performs the actual work of attaching the given base class
609/// specifiers to a C++ class.
610bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
611 unsigned NumBases) {
612 if (NumBases == 0)
613 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000614
615 // Used to keep track of which base types we have already seen, so
616 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000617 // that the key is always the unqualified canonical type of the base
618 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000619 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
620
621 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000622 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000623 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000624 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000625 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000626 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000627 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-05-20 23:34:56 +0000628 if (!Class->hasObjectMember()) {
629 if (const RecordType *FDTTy =
630 NewBaseType.getTypePtr()->getAs<RecordType>())
631 if (FDTTy->getDecl()->hasObjectMember())
632 Class->setHasObjectMember(true);
633 }
634
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000635 if (KnownBaseTypes[NewBaseType]) {
636 // C++ [class.mi]p3:
637 // A class shall not be specified as a direct base class of a
638 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000639 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000640 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000641 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000642 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000643
644 // Delete the duplicate base class specifier; we're going to
645 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000646 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000647
648 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000649 } else {
650 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000651 KnownBaseTypes[NewBaseType] = Bases[idx];
652 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000653 }
654 }
655
656 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000657 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000658
659 // Delete the remaining (good) base class specifiers, since their
660 // data has been copied into the CXXRecordDecl.
661 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000662 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000663
664 return Invalid;
665}
666
667/// ActOnBaseSpecifiers - Attach the given base specifiers to the
668/// class, after checking whether there are any duplicate base
669/// classes.
John McCalld226f652010-08-21 09:40:31 +0000670void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000671 unsigned NumBases) {
672 if (!ClassDecl || !Bases || !NumBases)
673 return;
674
675 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000676 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000677 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000678}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000679
John McCall3cb0ebd2010-03-10 03:28:59 +0000680static CXXRecordDecl *GetClassForType(QualType T) {
681 if (const RecordType *RT = T->getAs<RecordType>())
682 return cast<CXXRecordDecl>(RT->getDecl());
683 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
684 return ICT->getDecl();
685 else
686 return 0;
687}
688
Douglas Gregora8f32e02009-10-06 17:59:45 +0000689/// \brief Determine whether the type \p Derived is a C++ class that is
690/// derived from the type \p Base.
691bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
692 if (!getLangOptions().CPlusPlus)
693 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000694
695 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
696 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000697 return false;
698
John McCall3cb0ebd2010-03-10 03:28:59 +0000699 CXXRecordDecl *BaseRD = GetClassForType(Base);
700 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000701 return false;
702
John McCall86ff3082010-02-04 22:26:26 +0000703 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
704 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000705}
706
707/// \brief Determine whether the type \p Derived is a C++ class that is
708/// derived from the type \p Base.
709bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
710 if (!getLangOptions().CPlusPlus)
711 return false;
712
John McCall3cb0ebd2010-03-10 03:28:59 +0000713 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
714 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000715 return false;
716
John McCall3cb0ebd2010-03-10 03:28:59 +0000717 CXXRecordDecl *BaseRD = GetClassForType(Base);
718 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000719 return false;
720
Douglas Gregora8f32e02009-10-06 17:59:45 +0000721 return DerivedRD->isDerivedFrom(BaseRD, Paths);
722}
723
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000724void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000725 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000726 assert(BasePathArray.empty() && "Base path array must be empty!");
727 assert(Paths.isRecordingPaths() && "Must record paths!");
728
729 const CXXBasePath &Path = Paths.front();
730
731 // We first go backward and check if we have a virtual base.
732 // FIXME: It would be better if CXXBasePath had the base specifier for
733 // the nearest virtual base.
734 unsigned Start = 0;
735 for (unsigned I = Path.size(); I != 0; --I) {
736 if (Path[I - 1].Base->isVirtual()) {
737 Start = I - 1;
738 break;
739 }
740 }
741
742 // Now add all bases.
743 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000744 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000745}
746
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000747/// \brief Determine whether the given base path includes a virtual
748/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000749bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
750 for (CXXCastPath::const_iterator B = BasePath.begin(),
751 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000752 B != BEnd; ++B)
753 if ((*B)->isVirtual())
754 return true;
755
756 return false;
757}
758
Douglas Gregora8f32e02009-10-06 17:59:45 +0000759/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
760/// conversion (where Derived and Base are class types) is
761/// well-formed, meaning that the conversion is unambiguous (and
762/// that all of the base classes are accessible). Returns true
763/// and emits a diagnostic if the code is ill-formed, returns false
764/// otherwise. Loc is the location where this routine should point to
765/// if there is an error, and Range is the source range to highlight
766/// if there is an error.
767bool
768Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000769 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000770 unsigned AmbigiousBaseConvID,
771 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000772 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000773 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000774 // First, determine whether the path from Derived to Base is
775 // ambiguous. This is slightly more expensive than checking whether
776 // the Derived to Base conversion exists, because here we need to
777 // explore multiple paths to determine if there is an ambiguity.
778 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
779 /*DetectVirtual=*/false);
780 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
781 assert(DerivationOkay &&
782 "Can only be used with a derived-to-base conversion");
783 (void)DerivationOkay;
784
785 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000786 if (InaccessibleBaseID) {
787 // Check that the base class can be accessed.
788 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
789 InaccessibleBaseID)) {
790 case AR_inaccessible:
791 return true;
792 case AR_accessible:
793 case AR_dependent:
794 case AR_delayed:
795 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000796 }
John McCall6b2accb2010-02-10 09:31:12 +0000797 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000798
799 // Build a base path if necessary.
800 if (BasePath)
801 BuildBasePathArray(Paths, *BasePath);
802 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000803 }
804
805 // We know that the derived-to-base conversion is ambiguous, and
806 // we're going to produce a diagnostic. Perform the derived-to-base
807 // search just one more time to compute all of the possible paths so
808 // that we can print them out. This is more expensive than any of
809 // the previous derived-to-base checks we've done, but at this point
810 // performance isn't as much of an issue.
811 Paths.clear();
812 Paths.setRecordingPaths(true);
813 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
814 assert(StillOkay && "Can only be used with a derived-to-base conversion");
815 (void)StillOkay;
816
817 // Build up a textual representation of the ambiguous paths, e.g.,
818 // D -> B -> A, that will be used to illustrate the ambiguous
819 // conversions in the diagnostic. We only print one of the paths
820 // to each base class subobject.
821 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
822
823 Diag(Loc, AmbigiousBaseConvID)
824 << Derived << Base << PathDisplayStr << Range << Name;
825 return true;
826}
827
828bool
829Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000830 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000831 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000832 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000833 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000834 IgnoreAccess ? 0
835 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000836 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000837 Loc, Range, DeclarationName(),
838 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000839}
840
841
842/// @brief Builds a string representing ambiguous paths from a
843/// specific derived class to different subobjects of the same base
844/// class.
845///
846/// This function builds a string that can be used in error messages
847/// to show the different paths that one can take through the
848/// inheritance hierarchy to go from the derived class to different
849/// subobjects of a base class. The result looks something like this:
850/// @code
851/// struct D -> struct B -> struct A
852/// struct D -> struct C -> struct A
853/// @endcode
854std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
855 std::string PathDisplayStr;
856 std::set<unsigned> DisplayedPaths;
857 for (CXXBasePaths::paths_iterator Path = Paths.begin();
858 Path != Paths.end(); ++Path) {
859 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
860 // We haven't displayed a path to this particular base
861 // class subobject yet.
862 PathDisplayStr += "\n ";
863 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
864 for (CXXBasePath::const_iterator Element = Path->begin();
865 Element != Path->end(); ++Element)
866 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
867 }
868 }
869
870 return PathDisplayStr;
871}
872
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000873//===----------------------------------------------------------------------===//
874// C++ class member Handling
875//===----------------------------------------------------------------------===//
876
Abramo Bagnara6206d532010-06-05 05:09:32 +0000877/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000878Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
879 SourceLocation ASLoc,
880 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000881 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000882 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000883 ASLoc, ColonLoc);
884 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000885 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000886}
887
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000888/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
889/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
890/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000891/// any.
John McCalld226f652010-08-21 09:40:31 +0000892Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000893Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000894 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000895 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
896 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000897 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +0000898 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
899 DeclarationName Name = NameInfo.getName();
900 SourceLocation Loc = NameInfo.getLoc();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000901 Expr *BitWidth = static_cast<Expr*>(BW);
902 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000903
John McCall4bde1e12010-06-04 08:34:12 +0000904 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +0000905 assert(!DS.isFriendSpecified());
906
John McCall4bde1e12010-06-04 08:34:12 +0000907 bool isFunc = false;
908 if (D.isFunctionDeclarator())
909 isFunc = true;
910 else if (D.getNumTypeObjects() == 0 &&
911 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallb3d87482010-08-24 05:47:05 +0000912 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCall4bde1e12010-06-04 08:34:12 +0000913 isFunc = TDType->isFunctionType();
914 }
915
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000916 // C++ 9.2p6: A member shall not be declared to have automatic storage
917 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000918 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
919 // data members and cannot be applied to names declared const or static,
920 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000921 switch (DS.getStorageClassSpec()) {
922 case DeclSpec::SCS_unspecified:
923 case DeclSpec::SCS_typedef:
924 case DeclSpec::SCS_static:
925 // FALL THROUGH.
926 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000927 case DeclSpec::SCS_mutable:
928 if (isFunc) {
929 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000930 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000931 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000932 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000933
Sebastian Redla11f42f2008-11-17 23:24:37 +0000934 // FIXME: It would be nicer if the keyword was ignored only for this
935 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000936 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +0000937 }
938 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000939 default:
940 if (DS.getStorageClassSpecLoc().isValid())
941 Diag(DS.getStorageClassSpecLoc(),
942 diag::err_storageclass_invalid_for_member);
943 else
944 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
945 D.getMutableDeclSpec().ClearStorageClassSpecs();
946 }
947
Sebastian Redl669d5d72008-11-14 23:42:31 +0000948 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
949 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000950 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000951
952 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000953 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000954 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000955 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
956 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000957 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000958 } else {
John McCalld226f652010-08-21 09:40:31 +0000959 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000960 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +0000961 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +0000962 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000963
964 // Non-instance-fields can't have a bitfield.
965 if (BitWidth) {
966 if (Member->isInvalidDecl()) {
967 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000968 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000969 // C++ 9.6p3: A bit-field shall not be a static member.
970 // "static member 'A' cannot be a bit-field"
971 Diag(Loc, diag::err_static_not_bitfield)
972 << Name << BitWidth->getSourceRange();
973 } else if (isa<TypedefDecl>(Member)) {
974 // "typedef member 'x' cannot be a bit-field"
975 Diag(Loc, diag::err_typedef_not_bitfield)
976 << Name << BitWidth->getSourceRange();
977 } else {
978 // A function typedef ("typedef int f(); f a;").
979 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
980 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000981 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000982 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000983 }
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Chris Lattner8b963ef2009-03-05 23:01:03 +0000985 BitWidth = 0;
986 Member->setInvalidDecl();
987 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000988
989 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Douglas Gregor37b372b2009-08-20 22:52:58 +0000991 // If we have declared a member function template, set the access of the
992 // templated declaration as well.
993 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
994 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000995 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000996
Douglas Gregor10bd3682008-11-17 22:58:34 +0000997 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000998
Douglas Gregor021c3b32009-03-11 23:00:04 +0000999 if (Init)
John McCall9ae2f072010-08-23 23:25:46 +00001000 AddInitializerToDecl(Member, Init, false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001001 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +00001002 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001003
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001004 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +00001005 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001006 return 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001007 }
John McCalld226f652010-08-21 09:40:31 +00001008 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001009}
1010
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001011/// \brief Find the direct and/or virtual base specifiers that
1012/// correspond to the given base type, for use in base initialization
1013/// within a constructor.
1014static bool FindBaseInitializer(Sema &SemaRef,
1015 CXXRecordDecl *ClassDecl,
1016 QualType BaseType,
1017 const CXXBaseSpecifier *&DirectBaseSpec,
1018 const CXXBaseSpecifier *&VirtualBaseSpec) {
1019 // First, check for a direct base class.
1020 DirectBaseSpec = 0;
1021 for (CXXRecordDecl::base_class_const_iterator Base
1022 = ClassDecl->bases_begin();
1023 Base != ClassDecl->bases_end(); ++Base) {
1024 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1025 // We found a direct base of this type. That's what we're
1026 // initializing.
1027 DirectBaseSpec = &*Base;
1028 break;
1029 }
1030 }
1031
1032 // Check for a virtual base class.
1033 // FIXME: We might be able to short-circuit this if we know in advance that
1034 // there are no virtual bases.
1035 VirtualBaseSpec = 0;
1036 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1037 // We haven't found a base yet; search the class hierarchy for a
1038 // virtual base class.
1039 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1040 /*DetectVirtual=*/false);
1041 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1042 BaseType, Paths)) {
1043 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1044 Path != Paths.end(); ++Path) {
1045 if (Path->back().Base->isVirtual()) {
1046 VirtualBaseSpec = Path->back().Base;
1047 break;
1048 }
1049 }
1050 }
1051 }
1052
1053 return DirectBaseSpec || VirtualBaseSpec;
1054}
1055
Douglas Gregor7ad83902008-11-05 04:29:56 +00001056/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallf312b1e2010-08-26 23:41:50 +00001057MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001058Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001059 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001060 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001061 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001062 ParsedType TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001063 SourceLocation IdLoc,
1064 SourceLocation LParenLoc,
1065 ExprTy **Args, unsigned NumArgs,
1066 SourceLocation *CommaLocs,
1067 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001068 if (!ConstructorD)
1069 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001071 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001072
1073 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001074 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001075 if (!Constructor) {
1076 // The user wrote a constructor initializer on a function that is
1077 // not a C++ constructor. Ignore the error for now, because we may
1078 // have more member initializers coming; we'll diagnose it just
1079 // once in ActOnMemInitializers.
1080 return true;
1081 }
1082
1083 CXXRecordDecl *ClassDecl = Constructor->getParent();
1084
1085 // C++ [class.base.init]p2:
1086 // Names in a mem-initializer-id are looked up in the scope of the
1087 // constructor’s class and, if not found in that scope, are looked
1088 // up in the scope containing the constructor’s
1089 // definition. [Note: if the constructor’s class contains a member
1090 // with the same name as a direct or virtual base class of the
1091 // class, a mem-initializer-id naming the member or base class and
1092 // composed of a single identifier refers to the class member. A
1093 // mem-initializer-id for the hidden base class may be specified
1094 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001095 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001096 // Look for a member, first.
1097 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001098 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001099 = ClassDecl->lookup(MemberOrBase);
1100 if (Result.first != Result.second)
1101 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001102
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001103 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001104
Eli Friedman59c04372009-07-29 19:44:27 +00001105 if (Member)
1106 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001107 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001108 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001109 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001110 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001111 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001112
1113 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001114 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001115 } else {
1116 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1117 LookupParsedName(R, S, &SS);
1118
1119 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1120 if (!TyD) {
1121 if (R.isAmbiguous()) return true;
1122
John McCallfd225442010-04-09 19:01:14 +00001123 // We don't want access-control diagnostics here.
1124 R.suppressDiagnostics();
1125
Douglas Gregor7a886e12010-01-19 06:46:48 +00001126 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1127 bool NotUnknownSpecialization = false;
1128 DeclContext *DC = computeDeclContext(SS, false);
1129 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1130 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1131
1132 if (!NotUnknownSpecialization) {
1133 // When the scope specifier can refer to a member of an unknown
1134 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001135 BaseType = CheckTypenameType(ETK_None,
1136 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00001137 *MemberOrBase, SourceLocation(),
1138 SS.getRange(), IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001139 if (BaseType.isNull())
1140 return true;
1141
Douglas Gregor7a886e12010-01-19 06:46:48 +00001142 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001143 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001144 }
1145 }
1146
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001147 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001148 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001149 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1150 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001151 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00001152 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001153 // We have found a non-static data member with a similar
1154 // name to what was typed; complain and initialize that
1155 // member.
1156 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1157 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001158 << FixItHint::CreateReplacement(R.getNameLoc(),
1159 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001160 Diag(Member->getLocation(), diag::note_previous_decl)
1161 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001162
1163 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1164 LParenLoc, RParenLoc);
1165 }
1166 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1167 const CXXBaseSpecifier *DirectBaseSpec;
1168 const CXXBaseSpecifier *VirtualBaseSpec;
1169 if (FindBaseInitializer(*this, ClassDecl,
1170 Context.getTypeDeclType(Type),
1171 DirectBaseSpec, VirtualBaseSpec)) {
1172 // We have found a direct or virtual base class with a
1173 // similar name to what was typed; complain and initialize
1174 // that base class.
1175 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1176 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001177 << FixItHint::CreateReplacement(R.getNameLoc(),
1178 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001179
1180 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1181 : VirtualBaseSpec;
1182 Diag(BaseSpec->getSourceRange().getBegin(),
1183 diag::note_base_class_specified_here)
1184 << BaseSpec->getType()
1185 << BaseSpec->getSourceRange();
1186
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001187 TyD = Type;
1188 }
1189 }
1190 }
1191
Douglas Gregor7a886e12010-01-19 06:46:48 +00001192 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001193 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1194 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1195 return true;
1196 }
John McCall2b194412009-12-21 10:41:20 +00001197 }
1198
Douglas Gregor7a886e12010-01-19 06:46:48 +00001199 if (BaseType.isNull()) {
1200 BaseType = Context.getTypeDeclType(TyD);
1201 if (SS.isSet()) {
1202 NestedNameSpecifier *Qualifier =
1203 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001204
Douglas Gregor7a886e12010-01-19 06:46:48 +00001205 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001206 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001207 }
John McCall2b194412009-12-21 10:41:20 +00001208 }
1209 }
Mike Stump1eb44332009-09-09 15:08:12 +00001210
John McCalla93c9342009-12-07 02:54:59 +00001211 if (!TInfo)
1212 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001213
John McCalla93c9342009-12-07 02:54:59 +00001214 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001215 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001216}
1217
John McCallb4190042009-11-04 23:02:40 +00001218/// Checks an initializer expression for use of uninitialized fields, such as
1219/// containing the field that is being initialized. Returns true if there is an
1220/// uninitialized field was used an updates the SourceLocation parameter; false
1221/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001222static bool InitExprContainsUninitializedFields(const Stmt *S,
1223 const FieldDecl *LhsField,
1224 SourceLocation *L) {
1225 if (isa<CallExpr>(S)) {
1226 // Do not descend into function calls or constructors, as the use
1227 // of an uninitialized field may be valid. One would have to inspect
1228 // the contents of the function/ctor to determine if it is safe or not.
1229 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1230 // may be safe, depending on what the function/ctor does.
1231 return false;
1232 }
1233 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1234 const NamedDecl *RhsField = ME->getMemberDecl();
John McCallb4190042009-11-04 23:02:40 +00001235 if (RhsField == LhsField) {
1236 // Initializing a field with itself. Throw a warning.
1237 // But wait; there are exceptions!
1238 // Exception #1: The field may not belong to this record.
1239 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001240 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001241 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1242 // Even though the field matches, it does not belong to this record.
1243 return false;
1244 }
1245 // None of the exceptions triggered; return true to indicate an
1246 // uninitialized field was used.
1247 *L = ME->getMemberLoc();
1248 return true;
1249 }
1250 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001251 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1252 it != e; ++it) {
1253 if (!*it) {
1254 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001255 continue;
1256 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001257 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1258 return true;
John McCallb4190042009-11-04 23:02:40 +00001259 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001260 return false;
John McCallb4190042009-11-04 23:02:40 +00001261}
1262
John McCallf312b1e2010-08-26 23:41:50 +00001263MemInitResult
Eli Friedman59c04372009-07-29 19:44:27 +00001264Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1265 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001266 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001267 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001268 // Diagnose value-uses of fields to initialize themselves, e.g.
1269 // foo(foo)
1270 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001271 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001272 for (unsigned i = 0; i < NumArgs; ++i) {
1273 SourceLocation L;
1274 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1275 // FIXME: Return true in the case when other fields are used before being
1276 // uninitialized. For example, let this field be the i'th field. When
1277 // initializing the i'th field, throw a warning if any of the >= i'th
1278 // fields are used, as they are not yet initialized.
1279 // Right now we are only handling the case where the i'th field uses
1280 // itself in its initializer.
1281 Diag(L, diag::warn_field_is_uninit);
1282 }
1283 }
1284
Eli Friedman59c04372009-07-29 19:44:27 +00001285 bool HasDependentArg = false;
1286 for (unsigned i = 0; i < NumArgs; i++)
1287 HasDependentArg |= Args[i]->isTypeDependent();
1288
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001289 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001290 // Can't check initialization for a member of dependent type or when
1291 // any of the arguments are type-dependent expressions.
John McCall9ae2f072010-08-23 23:25:46 +00001292 Expr *Init
1293 = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1294 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001295
1296 // Erase any temporaries within this evaluation context; we're not
1297 // going to track them in the AST, since we'll be rebuilding the
1298 // ASTs during template instantiation.
1299 ExprTemporaries.erase(
1300 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1301 ExprTemporaries.end());
1302
1303 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1304 LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001305 Init,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001306 RParenLoc);
1307
Douglas Gregor7ad83902008-11-05 04:29:56 +00001308 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001309
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001310 if (Member->isInvalidDecl())
1311 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001312
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001313 // Initialize the member.
1314 InitializedEntity MemberEntity =
1315 InitializedEntity::InitializeMember(Member, 0);
1316 InitializationKind Kind =
1317 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1318
1319 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1320
John McCall60d7b3a2010-08-24 06:29:42 +00001321 ExprResult MemberInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001322 InitSeq.Perform(*this, MemberEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001323 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001324 if (MemberInit.isInvalid())
1325 return true;
1326
1327 // C++0x [class.base.init]p7:
1328 // The initialization of each base and member constitutes a
1329 // full-expression.
John McCall9ae2f072010-08-23 23:25:46 +00001330 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001331 if (MemberInit.isInvalid())
1332 return true;
1333
1334 // If we are in a dependent context, template instantiation will
1335 // perform this type-checking again. Just save the arguments that we
1336 // received in a ParenListExpr.
1337 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1338 // of the information that we have about the member
1339 // initializer. However, deconstructing the ASTs is a dicey process,
1340 // and this approach is far more likely to get the corner cases right.
1341 if (CurContext->isDependentContext()) {
1342 // Bump the reference count of all of the arguments.
1343 for (unsigned I = 0; I != NumArgs; ++I)
1344 Args[I]->Retain();
1345
John McCall9ae2f072010-08-23 23:25:46 +00001346 Expr *Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1347 RParenLoc);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001348 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1349 LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001350 Init,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001351 RParenLoc);
1352 }
1353
Douglas Gregor802ab452009-12-02 22:36:29 +00001354 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001355 LParenLoc,
John McCall9ae2f072010-08-23 23:25:46 +00001356 MemberInit.get(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001357 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001358}
1359
John McCallf312b1e2010-08-26 23:41:50 +00001360MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001361Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001362 Expr **Args, unsigned NumArgs,
1363 SourceLocation LParenLoc, SourceLocation RParenLoc,
1364 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001365 bool HasDependentArg = false;
1366 for (unsigned i = 0; i < NumArgs; i++)
1367 HasDependentArg |= Args[i]->isTypeDependent();
1368
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001369 SourceLocation BaseLoc
1370 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1371
1372 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1373 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1374 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1375
1376 // C++ [class.base.init]p2:
1377 // [...] Unless the mem-initializer-id names a nonstatic data
1378 // member of the constructor’s class or a direct or virtual base
1379 // of that class, the mem-initializer is ill-formed. A
1380 // mem-initializer-list can initialize a base class using any
1381 // name that denotes that base class type.
1382 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1383
1384 // Check for direct and virtual base classes.
1385 const CXXBaseSpecifier *DirectBaseSpec = 0;
1386 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1387 if (!Dependent) {
1388 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1389 VirtualBaseSpec);
1390
1391 // C++ [base.class.init]p2:
1392 // Unless the mem-initializer-id names a nonstatic data member of the
1393 // constructor's class or a direct or virtual base of that class, the
1394 // mem-initializer is ill-formed.
1395 if (!DirectBaseSpec && !VirtualBaseSpec) {
1396 // If the class has any dependent bases, then it's possible that
1397 // one of those types will resolve to the same type as
1398 // BaseType. Therefore, just treat this as a dependent base
1399 // class initialization. FIXME: Should we try to check the
1400 // initialization anyway? It seems odd.
1401 if (ClassDecl->hasAnyDependentBases())
1402 Dependent = true;
1403 else
1404 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1405 << BaseType << Context.getTypeDeclType(ClassDecl)
1406 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1407 }
1408 }
1409
1410 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001411 // Can't check initialization for a base of dependent type or when
1412 // any of the arguments are type-dependent expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00001413 ExprResult BaseInit
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001414 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1415 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001416
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001417 // Erase any temporaries within this evaluation context; we're not
1418 // going to track them in the AST, since we'll be rebuilding the
1419 // ASTs during template instantiation.
1420 ExprTemporaries.erase(
1421 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1422 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001424 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001425 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001426 LParenLoc,
1427 BaseInit.takeAs<Expr>(),
1428 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001429 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001430
1431 // C++ [base.class.init]p2:
1432 // If a mem-initializer-id is ambiguous because it designates both
1433 // a direct non-virtual base class and an inherited virtual base
1434 // class, the mem-initializer is ill-formed.
1435 if (DirectBaseSpec && VirtualBaseSpec)
1436 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001437 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001438
1439 CXXBaseSpecifier *BaseSpec
1440 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1441 if (!BaseSpec)
1442 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1443
1444 // Initialize the base.
1445 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001446 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001447 InitializationKind Kind =
1448 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1449
1450 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1451
John McCall60d7b3a2010-08-24 06:29:42 +00001452 ExprResult BaseInit =
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001453 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001454 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001455 if (BaseInit.isInvalid())
1456 return true;
1457
1458 // C++0x [class.base.init]p7:
1459 // The initialization of each base and member constitutes a
1460 // full-expression.
John McCall9ae2f072010-08-23 23:25:46 +00001461 BaseInit = MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001462 if (BaseInit.isInvalid())
1463 return true;
1464
1465 // If we are in a dependent context, template instantiation will
1466 // perform this type-checking again. Just save the arguments that we
1467 // received in a ParenListExpr.
1468 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1469 // of the information that we have about the base
1470 // initializer. However, deconstructing the ASTs is a dicey process,
1471 // and this approach is far more likely to get the corner cases right.
1472 if (CurContext->isDependentContext()) {
1473 // Bump the reference count of all of the arguments.
1474 for (unsigned I = 0; I != NumArgs; ++I)
1475 Args[I]->Retain();
1476
John McCall60d7b3a2010-08-24 06:29:42 +00001477 ExprResult Init
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001478 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1479 RParenLoc));
1480 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001481 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001482 LParenLoc,
1483 Init.takeAs<Expr>(),
1484 RParenLoc);
1485 }
1486
1487 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001488 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001489 LParenLoc,
1490 BaseInit.takeAs<Expr>(),
1491 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001492}
1493
Anders Carlssone5ef7402010-04-23 03:10:23 +00001494/// ImplicitInitializerKind - How an implicit base or member initializer should
1495/// initialize its base or member.
1496enum ImplicitInitializerKind {
1497 IIK_Default,
1498 IIK_Copy,
1499 IIK_Move
1500};
1501
Anders Carlssondefefd22010-04-23 02:00:02 +00001502static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001503BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001504 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001505 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001506 bool IsInheritedVirtualBase,
1507 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001508 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001509 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1510 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001511
John McCall60d7b3a2010-08-24 06:29:42 +00001512 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001513
1514 switch (ImplicitInitKind) {
1515 case IIK_Default: {
1516 InitializationKind InitKind
1517 = InitializationKind::CreateDefault(Constructor->getLocation());
1518 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1519 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001520 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001521 break;
1522 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001523
Anders Carlssone5ef7402010-04-23 03:10:23 +00001524 case IIK_Copy: {
1525 ParmVarDecl *Param = Constructor->getParamDecl(0);
1526 QualType ParamType = Param->getType().getNonReferenceType();
1527
1528 Expr *CopyCtorArg =
1529 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregor62b71f42010-05-03 15:43:53 +00001530 Constructor->getLocation(), ParamType, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001531
Anders Carlssonc7957502010-04-24 22:02:54 +00001532 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001533 QualType ArgTy =
1534 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1535 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001536
1537 CXXCastPath BasePath;
1538 BasePath.push_back(BaseSpec);
Sebastian Redl906082e2010-07-20 04:20:21 +00001539 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCall2de56d12010-08-25 11:45:40 +00001540 CK_UncheckedDerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00001541 VK_LValue, &BasePath);
Anders Carlssonc7957502010-04-24 22:02:54 +00001542
Anders Carlssone5ef7402010-04-23 03:10:23 +00001543 InitializationKind InitKind
1544 = InitializationKind::CreateDirect(Constructor->getLocation(),
1545 SourceLocation(), SourceLocation());
1546 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1547 &CopyCtorArg, 1);
1548 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001549 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001550 break;
1551 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001552
Anders Carlssone5ef7402010-04-23 03:10:23 +00001553 case IIK_Move:
1554 assert(false && "Unhandled initializer kind!");
1555 }
John McCall9ae2f072010-08-23 23:25:46 +00001556
1557 if (BaseInit.isInvalid())
1558 return true;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001559
John McCall9ae2f072010-08-23 23:25:46 +00001560 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Anders Carlsson84688f22010-04-20 23:11:20 +00001561 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001562 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001563
Anders Carlssondefefd22010-04-23 02:00:02 +00001564 CXXBaseInit =
Anders Carlsson84688f22010-04-20 23:11:20 +00001565 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1566 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1567 SourceLocation()),
1568 BaseSpec->isVirtual(),
1569 SourceLocation(),
1570 BaseInit.takeAs<Expr>(),
1571 SourceLocation());
1572
Anders Carlssondefefd22010-04-23 02:00:02 +00001573 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001574}
1575
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001576static bool
1577BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001578 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001579 FieldDecl *Field,
1580 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001581 if (Field->isInvalidDecl())
1582 return true;
1583
Chandler Carruthf186b542010-06-29 23:50:44 +00001584 SourceLocation Loc = Constructor->getLocation();
1585
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001586 if (ImplicitInitKind == IIK_Copy) {
1587 ParmVarDecl *Param = Constructor->getParamDecl(0);
1588 QualType ParamType = Param->getType().getNonReferenceType();
1589
1590 Expr *MemberExprBase =
1591 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001592 Loc, ParamType, 0);
1593
1594 // Build a reference to this field within the parameter.
1595 CXXScopeSpec SS;
1596 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1597 Sema::LookupMemberName);
1598 MemberLookup.addDecl(Field, AS_public);
1599 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00001600 ExprResult CopyCtorArg
John McCall9ae2f072010-08-23 23:25:46 +00001601 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001602 ParamType, Loc,
1603 /*IsArrow=*/false,
1604 SS,
1605 /*FirstQualifierInScope=*/0,
1606 MemberLookup,
1607 /*TemplateArgs=*/0);
1608 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001609 return true;
1610
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001611 // When the field we are copying is an array, create index variables for
1612 // each dimension of the array. We use these index variables to subscript
1613 // the source array, and other clients (e.g., CodeGen) will perform the
1614 // necessary iteration with these index variables.
1615 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1616 QualType BaseType = Field->getType();
1617 QualType SizeType = SemaRef.Context.getSizeType();
1618 while (const ConstantArrayType *Array
1619 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1620 // Create the iteration variable for this array index.
1621 IdentifierInfo *IterationVarName = 0;
1622 {
1623 llvm::SmallString<8> Str;
1624 llvm::raw_svector_ostream OS(Str);
1625 OS << "__i" << IndexVariables.size();
1626 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1627 }
1628 VarDecl *IterationVar
1629 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1630 IterationVarName, SizeType,
1631 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00001632 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001633 IndexVariables.push_back(IterationVar);
1634
1635 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00001636 ExprResult IterationVarRef
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001637 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1638 assert(!IterationVarRef.isInvalid() &&
1639 "Reference to invented variable cannot fail!");
1640
1641 // Subscript the array with this iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00001642 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001643 Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001644 IterationVarRef.take(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001645 Loc);
1646 if (CopyCtorArg.isInvalid())
1647 return true;
1648
1649 BaseType = Array->getElementType();
1650 }
1651
1652 // Construct the entity that we will be initializing. For an array, this
1653 // will be first element in the array, which may require several levels
1654 // of array-subscript entities.
1655 llvm::SmallVector<InitializedEntity, 4> Entities;
1656 Entities.reserve(1 + IndexVariables.size());
1657 Entities.push_back(InitializedEntity::InitializeMember(Field));
1658 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1659 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1660 0,
1661 Entities.back()));
1662
1663 // Direct-initialize to use the copy constructor.
1664 InitializationKind InitKind =
1665 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1666
1667 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1668 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1669 &CopyCtorArgE, 1);
1670
John McCall60d7b3a2010-08-24 06:29:42 +00001671 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001672 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00001673 MultiExprArg(&CopyCtorArgE, 1));
John McCall9ae2f072010-08-23 23:25:46 +00001674 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001675 if (MemberInit.isInvalid())
1676 return true;
1677
1678 CXXMemberInit
1679 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1680 MemberInit.takeAs<Expr>(), Loc,
1681 IndexVariables.data(),
1682 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001683 return false;
1684 }
1685
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001686 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1687
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001688 QualType FieldBaseElementType =
1689 SemaRef.Context.getBaseElementType(Field->getType());
1690
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001691 if (FieldBaseElementType->isRecordType()) {
1692 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001693 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001694 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001695
1696 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00001697 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00001698 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00001699 if (MemberInit.isInvalid())
1700 return true;
1701
1702 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001703 if (MemberInit.isInvalid())
1704 return true;
1705
1706 CXXMemberInit =
1707 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001708 Field, Loc, Loc,
John McCall9ae2f072010-08-23 23:25:46 +00001709 MemberInit.get(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001710 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001711 return false;
1712 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001713
1714 if (FieldBaseElementType->isReferenceType()) {
1715 SemaRef.Diag(Constructor->getLocation(),
1716 diag::err_uninitialized_member_in_ctor)
1717 << (int)Constructor->isImplicit()
1718 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1719 << 0 << Field->getDeclName();
1720 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1721 return true;
1722 }
1723
1724 if (FieldBaseElementType.isConstQualified()) {
1725 SemaRef.Diag(Constructor->getLocation(),
1726 diag::err_uninitialized_member_in_ctor)
1727 << (int)Constructor->isImplicit()
1728 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1729 << 1 << Field->getDeclName();
1730 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1731 return true;
1732 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001733
1734 // Nothing to initialize.
1735 CXXMemberInit = 0;
1736 return false;
1737}
John McCallf1860e52010-05-20 23:23:51 +00001738
1739namespace {
1740struct BaseAndFieldInfo {
1741 Sema &S;
1742 CXXConstructorDecl *Ctor;
1743 bool AnyErrorsInInits;
1744 ImplicitInitializerKind IIK;
1745 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1746 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1747
1748 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1749 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1750 // FIXME: Handle implicit move constructors.
1751 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1752 IIK = IIK_Copy;
1753 else
1754 IIK = IIK_Default;
1755 }
1756};
1757}
1758
Chandler Carruthe861c602010-06-30 02:59:29 +00001759static void RecordFieldInitializer(BaseAndFieldInfo &Info,
1760 FieldDecl *Top, FieldDecl *Field,
1761 CXXBaseOrMemberInitializer *Init) {
1762 // If the member doesn't need to be initialized, Init will still be null.
1763 if (!Init)
1764 return;
1765
1766 Info.AllToInit.push_back(Init);
1767 if (Field != Top) {
1768 Init->setMember(Top);
1769 Init->setAnonUnionMember(Field);
1770 }
1771}
1772
John McCallf1860e52010-05-20 23:23:51 +00001773static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1774 FieldDecl *Top, FieldDecl *Field) {
1775
Chandler Carruthe861c602010-06-30 02:59:29 +00001776 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallf1860e52010-05-20 23:23:51 +00001777 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Chandler Carruthe861c602010-06-30 02:59:29 +00001778 RecordFieldInitializer(Info, Top, Field, Init);
John McCallf1860e52010-05-20 23:23:51 +00001779 return false;
1780 }
1781
1782 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1783 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1784 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00001785 CXXRecordDecl *FieldClassDecl
1786 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00001787
1788 // Even though union members never have non-trivial default
1789 // constructions in C++03, we still build member initializers for aggregate
1790 // record types which can be union members, and C++0x allows non-trivial
1791 // default constructors for union members, so we ensure that only one
1792 // member is initialized for these.
1793 if (FieldClassDecl->isUnion()) {
1794 // First check for an explicit initializer for one field.
1795 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1796 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1797 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
1798 RecordFieldInitializer(Info, Top, *FA, Init);
1799
1800 // Once we've initialized a field of an anonymous union, the union
1801 // field in the class is also initialized, so exit immediately.
1802 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00001803 } else if ((*FA)->isAnonymousStructOrUnion()) {
1804 if (CollectFieldInitializer(Info, Top, *FA))
1805 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00001806 }
1807 }
1808
1809 // Fallthrough and construct a default initializer for the union as
1810 // a whole, which can call its default constructor if such a thing exists
1811 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1812 // behavior going forward with C++0x, when anonymous unions there are
1813 // finalized, we should revisit this.
1814 } else {
1815 // For structs, we simply descend through to initialize all members where
1816 // necessary.
1817 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1818 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1819 if (CollectFieldInitializer(Info, Top, *FA))
1820 return true;
1821 }
1822 }
John McCallf1860e52010-05-20 23:23:51 +00001823 }
1824
1825 // Don't try to build an implicit initializer if there were semantic
1826 // errors in any of the initializers (and therefore we might be
1827 // missing some that the user actually wrote).
1828 if (Info.AnyErrorsInInits)
1829 return false;
1830
1831 CXXBaseOrMemberInitializer *Init = 0;
1832 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1833 return true;
John McCallf1860e52010-05-20 23:23:51 +00001834
Chandler Carruthe861c602010-06-30 02:59:29 +00001835 RecordFieldInitializer(Info, Top, Field, Init);
John McCallf1860e52010-05-20 23:23:51 +00001836 return false;
1837}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001838
Eli Friedman80c30da2009-11-09 19:20:36 +00001839bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001840Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001841 CXXBaseOrMemberInitializer **Initializers,
1842 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001843 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001844 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001845 // Just store the initializers as written, they will be checked during
1846 // instantiation.
1847 if (NumInitializers > 0) {
1848 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1849 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1850 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1851 memcpy(baseOrMemberInitializers, Initializers,
1852 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1853 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1854 }
1855
1856 return false;
1857 }
1858
John McCallf1860e52010-05-20 23:23:51 +00001859 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001860
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001861 // We need to build the initializer AST according to order of construction
1862 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00001863 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00001864 if (!ClassDecl)
1865 return true;
1866
Eli Friedman80c30da2009-11-09 19:20:36 +00001867 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001869 for (unsigned i = 0; i < NumInitializers; i++) {
1870 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001871
1872 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00001873 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001874 else
John McCallf1860e52010-05-20 23:23:51 +00001875 Info.AllBaseFields[Member->getMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001876 }
1877
Anders Carlsson711f34a2010-04-21 19:52:01 +00001878 // Keep track of the direct virtual bases.
1879 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1880 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1881 E = ClassDecl->bases_end(); I != E; ++I) {
1882 if (I->isVirtual())
1883 DirectVBases.insert(I);
1884 }
1885
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001886 // Push virtual bases before others.
1887 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1888 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1889
1890 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001891 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1892 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001893 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00001894 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlssondefefd22010-04-23 02:00:02 +00001895 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001896 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001897 VBase, IsInheritedVirtualBase,
1898 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001899 HadError = true;
1900 continue;
1901 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001902
John McCallf1860e52010-05-20 23:23:51 +00001903 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001904 }
1905 }
Mike Stump1eb44332009-09-09 15:08:12 +00001906
John McCallf1860e52010-05-20 23:23:51 +00001907 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001908 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1909 E = ClassDecl->bases_end(); Base != E; ++Base) {
1910 // Virtuals are in the virtual base list and already constructed.
1911 if (Base->isVirtual())
1912 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001914 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001915 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1916 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001917 } else if (!AnyErrors) {
Anders Carlssondefefd22010-04-23 02:00:02 +00001918 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001919 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001920 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00001921 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001922 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001923 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001924 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001925
John McCallf1860e52010-05-20 23:23:51 +00001926 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001927 }
1928 }
Mike Stump1eb44332009-09-09 15:08:12 +00001929
John McCallf1860e52010-05-20 23:23:51 +00001930 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001931 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001932 E = ClassDecl->field_end(); Field != E; ++Field) {
1933 if ((*Field)->getType()->isIncompleteArrayType()) {
1934 assert(ClassDecl->hasFlexibleArrayMember() &&
1935 "Incomplete array type is not valid");
1936 continue;
1937 }
John McCallf1860e52010-05-20 23:23:51 +00001938 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001939 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001940 }
Mike Stump1eb44332009-09-09 15:08:12 +00001941
John McCallf1860e52010-05-20 23:23:51 +00001942 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001943 if (NumInitializers > 0) {
1944 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1945 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1946 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00001947 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCallef027fe2010-03-16 21:39:52 +00001948 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001949 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00001950
John McCallef027fe2010-03-16 21:39:52 +00001951 // Constructors implicitly reference the base and member
1952 // destructors.
1953 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1954 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001955 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001956
1957 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001958}
1959
Eli Friedman6347f422009-07-21 19:28:10 +00001960static void *GetKeyForTopLevelField(FieldDecl *Field) {
1961 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001962 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001963 if (RT->getDecl()->isAnonymousStructOrUnion())
1964 return static_cast<void *>(RT->getDecl());
1965 }
1966 return static_cast<void *>(Field);
1967}
1968
Anders Carlssonea356fb2010-04-02 05:42:15 +00001969static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1970 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001971}
1972
Anders Carlssonea356fb2010-04-02 05:42:15 +00001973static void *GetKeyForMember(ASTContext &Context,
1974 CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001975 bool MemberMaybeAnon = false) {
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001976 if (!Member->isMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00001977 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001978
Eli Friedman6347f422009-07-21 19:28:10 +00001979 // For fields injected into the class via declaration of an anonymous union,
1980 // use its anonymous union class declaration as the unique key.
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001981 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001983 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1984 // data member of the class. Data member used in the initializer list is
1985 // in AnonUnionMember field.
1986 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1987 Field = Member->getAnonUnionMember();
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001988
John McCall3c3ccdb2010-04-10 09:28:51 +00001989 // If the field is a member of an anonymous struct or union, our key
1990 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001991 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00001992 if (RD->isAnonymousStructOrUnion()) {
1993 while (true) {
1994 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1995 if (Parent->isAnonymousStructOrUnion())
1996 RD = Parent;
1997 else
1998 break;
1999 }
2000
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002001 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002002 }
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002004 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002005}
2006
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002007static void
2008DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002009 const CXXConstructorDecl *Constructor,
John McCalld6ca8da2010-04-10 07:37:23 +00002010 CXXBaseOrMemberInitializer **Inits,
2011 unsigned NumInits) {
2012 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002013 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002014
John McCalld6ca8da2010-04-10 07:37:23 +00002015 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
2016 == Diagnostic::Ignored)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002017 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002018
John McCalld6ca8da2010-04-10 07:37:23 +00002019 // Build the list of bases and members in the order that they'll
2020 // actually be initialized. The explicit initializers should be in
2021 // this same order but may be missing things.
2022 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Anders Carlsson071d6102010-04-02 03:38:04 +00002024 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2025
John McCalld6ca8da2010-04-10 07:37:23 +00002026 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002027 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002028 ClassDecl->vbases_begin(),
2029 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002030 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002031
John McCalld6ca8da2010-04-10 07:37:23 +00002032 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002033 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002034 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002035 if (Base->isVirtual())
2036 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002037 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002038 }
Mike Stump1eb44332009-09-09 15:08:12 +00002039
John McCalld6ca8da2010-04-10 07:37:23 +00002040 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002041 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2042 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002043 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002044
John McCalld6ca8da2010-04-10 07:37:23 +00002045 unsigned NumIdealInits = IdealInitKeys.size();
2046 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002047
John McCalld6ca8da2010-04-10 07:37:23 +00002048 CXXBaseOrMemberInitializer *PrevInit = 0;
2049 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2050 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2051 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
2052
2053 // Scan forward to try to find this initializer in the idealized
2054 // initializers list.
2055 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2056 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002057 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002058
2059 // If we didn't find this initializer, it must be because we
2060 // scanned past it on a previous iteration. That can only
2061 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002062 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002063 Sema::SemaDiagnosticBuilder D =
2064 SemaRef.Diag(PrevInit->getSourceLocation(),
2065 diag::warn_initializer_out_of_order);
2066
2067 if (PrevInit->isMemberInitializer())
2068 D << 0 << PrevInit->getMember()->getDeclName();
2069 else
2070 D << 1 << PrevInit->getBaseClassInfo()->getType();
2071
2072 if (Init->isMemberInitializer())
2073 D << 0 << Init->getMember()->getDeclName();
2074 else
2075 D << 1 << Init->getBaseClassInfo()->getType();
2076
2077 // Move back to the initializer's location in the ideal list.
2078 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2079 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002080 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002081
2082 assert(IdealIndex != NumIdealInits &&
2083 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002084 }
John McCalld6ca8da2010-04-10 07:37:23 +00002085
2086 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002087 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002088}
2089
John McCall3c3ccdb2010-04-10 09:28:51 +00002090namespace {
2091bool CheckRedundantInit(Sema &S,
2092 CXXBaseOrMemberInitializer *Init,
2093 CXXBaseOrMemberInitializer *&PrevInit) {
2094 if (!PrevInit) {
2095 PrevInit = Init;
2096 return false;
2097 }
2098
2099 if (FieldDecl *Field = Init->getMember())
2100 S.Diag(Init->getSourceLocation(),
2101 diag::err_multiple_mem_initialization)
2102 << Field->getDeclName()
2103 << Init->getSourceRange();
2104 else {
2105 Type *BaseClass = Init->getBaseClass();
2106 assert(BaseClass && "neither field nor base");
2107 S.Diag(Init->getSourceLocation(),
2108 diag::err_multiple_base_initialization)
2109 << QualType(BaseClass, 0)
2110 << Init->getSourceRange();
2111 }
2112 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2113 << 0 << PrevInit->getSourceRange();
2114
2115 return true;
2116}
2117
2118typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2119typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2120
2121bool CheckRedundantUnionInit(Sema &S,
2122 CXXBaseOrMemberInitializer *Init,
2123 RedundantUnionMap &Unions) {
2124 FieldDecl *Field = Init->getMember();
2125 RecordDecl *Parent = Field->getParent();
2126 if (!Parent->isAnonymousStructOrUnion())
2127 return false;
2128
2129 NamedDecl *Child = Field;
2130 do {
2131 if (Parent->isUnion()) {
2132 UnionEntry &En = Unions[Parent];
2133 if (En.first && En.first != Child) {
2134 S.Diag(Init->getSourceLocation(),
2135 diag::err_multiple_mem_union_initialization)
2136 << Field->getDeclName()
2137 << Init->getSourceRange();
2138 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2139 << 0 << En.second->getSourceRange();
2140 return true;
2141 } else if (!En.first) {
2142 En.first = Child;
2143 En.second = Init;
2144 }
2145 }
2146
2147 Child = Parent;
2148 Parent = cast<RecordDecl>(Parent->getDeclContext());
2149 } while (Parent->isAnonymousStructOrUnion());
2150
2151 return false;
2152}
2153}
2154
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002155/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002156void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002157 SourceLocation ColonLoc,
2158 MemInitTy **meminits, unsigned NumMemInits,
2159 bool AnyErrors) {
2160 if (!ConstructorDecl)
2161 return;
2162
2163 AdjustDeclIfTemplate(ConstructorDecl);
2164
2165 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002166 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002167
2168 if (!Constructor) {
2169 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2170 return;
2171 }
2172
2173 CXXBaseOrMemberInitializer **MemInits =
2174 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002175
2176 // Mapping for the duplicate initializers check.
2177 // For member initializers, this is keyed with a FieldDecl*.
2178 // For base initializers, this is keyed with a Type*.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002179 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002180
2181 // Mapping for the inconsistent anonymous-union initializers check.
2182 RedundantUnionMap MemberUnions;
2183
Anders Carlssonea356fb2010-04-02 05:42:15 +00002184 bool HadError = false;
2185 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002186 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002187
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002188 // Set the source order index.
2189 Init->setSourceOrder(i);
2190
John McCall3c3ccdb2010-04-10 09:28:51 +00002191 if (Init->isMemberInitializer()) {
2192 FieldDecl *Field = Init->getMember();
2193 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2194 CheckRedundantUnionInit(*this, Init, MemberUnions))
2195 HadError = true;
2196 } else {
2197 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2198 if (CheckRedundantInit(*this, Init, Members[Key]))
2199 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002200 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002201 }
2202
Anders Carlssonea356fb2010-04-02 05:42:15 +00002203 if (HadError)
2204 return;
2205
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002206 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002207
2208 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002209}
2210
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002211void
John McCallef027fe2010-03-16 21:39:52 +00002212Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2213 CXXRecordDecl *ClassDecl) {
2214 // Ignore dependent contexts.
2215 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002216 return;
John McCall58e6f342010-03-16 05:22:47 +00002217
2218 // FIXME: all the access-control diagnostics are positioned on the
2219 // field/base declaration. That's probably good; that said, the
2220 // user might reasonably want to know why the destructor is being
2221 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002222
Anders Carlsson9f853df2009-11-17 04:44:12 +00002223 // Non-static data members.
2224 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2225 E = ClassDecl->field_end(); I != E; ++I) {
2226 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002227 if (Field->isInvalidDecl())
2228 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002229 QualType FieldType = Context.getBaseElementType(Field->getType());
2230
2231 const RecordType* RT = FieldType->getAs<RecordType>();
2232 if (!RT)
2233 continue;
2234
2235 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2236 if (FieldClassDecl->hasTrivialDestructor())
2237 continue;
2238
Douglas Gregordb89f282010-07-01 22:47:18 +00002239 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002240 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002241 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002242 << Field->getDeclName()
2243 << FieldType);
2244
John McCallef027fe2010-03-16 21:39:52 +00002245 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002246 }
2247
John McCall58e6f342010-03-16 05:22:47 +00002248 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2249
Anders Carlsson9f853df2009-11-17 04:44:12 +00002250 // Bases.
2251 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2252 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002253 // Bases are always records in a well-formed non-dependent class.
2254 const RecordType *RT = Base->getType()->getAs<RecordType>();
2255
2256 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002257 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002258 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002259
2260 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002261 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002262 if (BaseClassDecl->hasTrivialDestructor())
2263 continue;
John McCall58e6f342010-03-16 05:22:47 +00002264
Douglas Gregordb89f282010-07-01 22:47:18 +00002265 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002266
2267 // FIXME: caret should be on the start of the class name
2268 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002269 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002270 << Base->getType()
2271 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002272
John McCallef027fe2010-03-16 21:39:52 +00002273 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002274 }
2275
2276 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002277 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2278 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002279
2280 // Bases are always records in a well-formed non-dependent class.
2281 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2282
2283 // Ignore direct virtual bases.
2284 if (DirectVirtualBases.count(RT))
2285 continue;
2286
Anders Carlsson9f853df2009-11-17 04:44:12 +00002287 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002288 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002289 if (BaseClassDecl->hasTrivialDestructor())
2290 continue;
John McCall58e6f342010-03-16 05:22:47 +00002291
Douglas Gregordb89f282010-07-01 22:47:18 +00002292 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002293 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002294 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002295 << VBase->getType());
2296
John McCallef027fe2010-03-16 21:39:52 +00002297 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002298 }
2299}
2300
John McCalld226f652010-08-21 09:40:31 +00002301void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002302 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002303 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Mike Stump1eb44332009-09-09 15:08:12 +00002305 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002306 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlssonec3332b2010-04-02 03:43:34 +00002307 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002308}
2309
Mike Stump1eb44332009-09-09 15:08:12 +00002310bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002311 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002312 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002313 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002314 else
John McCall94c3b562010-08-18 09:41:07 +00002315 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002316}
2317
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002318bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002319 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002320 if (!getLangOptions().CPlusPlus)
2321 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002322
Anders Carlsson11f21a02009-03-23 19:10:31 +00002323 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002324 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002325
Ted Kremenek6217b802009-07-29 21:53:49 +00002326 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002327 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002328 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002329 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002330
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002331 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002332 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002333 }
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Ted Kremenek6217b802009-07-29 21:53:49 +00002335 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002336 if (!RT)
2337 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002338
John McCall86ff3082010-02-04 22:26:26 +00002339 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002340
John McCall94c3b562010-08-18 09:41:07 +00002341 // We can't answer whether something is abstract until it has a
2342 // definition. If it's currently being defined, we'll walk back
2343 // over all the declarations when we have a full definition.
2344 const CXXRecordDecl *Def = RD->getDefinition();
2345 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002346 return false;
2347
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002348 if (!RD->isAbstract())
2349 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002350
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002351 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002352 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002353
John McCall94c3b562010-08-18 09:41:07 +00002354 return true;
2355}
2356
2357void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2358 // Check if we've already emitted the list of pure virtual functions
2359 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002360 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002361 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002362
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002363 CXXFinalOverriderMap FinalOverriders;
2364 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002366 // Keep a set of seen pure methods so we won't diagnose the same method
2367 // more than once.
2368 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2369
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002370 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2371 MEnd = FinalOverriders.end();
2372 M != MEnd;
2373 ++M) {
2374 for (OverridingMethods::iterator SO = M->second.begin(),
2375 SOEnd = M->second.end();
2376 SO != SOEnd; ++SO) {
2377 // C++ [class.abstract]p4:
2378 // A class is abstract if it contains or inherits at least one
2379 // pure virtual function for which the final overrider is pure
2380 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002381
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002382 //
2383 if (SO->second.size() != 1)
2384 continue;
2385
2386 if (!SO->second.front().Method->isPure())
2387 continue;
2388
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002389 if (!SeenPureMethods.insert(SO->second.front().Method))
2390 continue;
2391
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002392 Diag(SO->second.front().Method->getLocation(),
2393 diag::note_pure_virtual_function)
2394 << SO->second.front().Method->getDeclName();
2395 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002396 }
2397
2398 if (!PureVirtualClassDiagSet)
2399 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2400 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002401}
2402
Anders Carlsson8211eff2009-03-24 01:19:16 +00002403namespace {
John McCall94c3b562010-08-18 09:41:07 +00002404struct AbstractUsageInfo {
2405 Sema &S;
2406 CXXRecordDecl *Record;
2407 CanQualType AbstractType;
2408 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002409
John McCall94c3b562010-08-18 09:41:07 +00002410 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2411 : S(S), Record(Record),
2412 AbstractType(S.Context.getCanonicalType(
2413 S.Context.getTypeDeclType(Record))),
2414 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002415
John McCall94c3b562010-08-18 09:41:07 +00002416 void DiagnoseAbstractType() {
2417 if (Invalid) return;
2418 S.DiagnoseAbstractType(Record);
2419 Invalid = true;
2420 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002421
John McCall94c3b562010-08-18 09:41:07 +00002422 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2423};
2424
2425struct CheckAbstractUsage {
2426 AbstractUsageInfo &Info;
2427 const NamedDecl *Ctx;
2428
2429 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2430 : Info(Info), Ctx(Ctx) {}
2431
2432 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2433 switch (TL.getTypeLocClass()) {
2434#define ABSTRACT_TYPELOC(CLASS, PARENT)
2435#define TYPELOC(CLASS, PARENT) \
2436 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2437#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002438 }
John McCall94c3b562010-08-18 09:41:07 +00002439 }
Mike Stump1eb44332009-09-09 15:08:12 +00002440
John McCall94c3b562010-08-18 09:41:07 +00002441 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2442 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2443 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2444 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2445 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002446 }
John McCall94c3b562010-08-18 09:41:07 +00002447 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002448
John McCall94c3b562010-08-18 09:41:07 +00002449 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2450 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2451 }
Mike Stump1eb44332009-09-09 15:08:12 +00002452
John McCall94c3b562010-08-18 09:41:07 +00002453 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2454 // Visit the type parameters from a permissive context.
2455 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2456 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2457 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2458 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2459 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2460 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002461 }
John McCall94c3b562010-08-18 09:41:07 +00002462 }
Mike Stump1eb44332009-09-09 15:08:12 +00002463
John McCall94c3b562010-08-18 09:41:07 +00002464 // Visit pointee types from a permissive context.
2465#define CheckPolymorphic(Type) \
2466 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2467 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2468 }
2469 CheckPolymorphic(PointerTypeLoc)
2470 CheckPolymorphic(ReferenceTypeLoc)
2471 CheckPolymorphic(MemberPointerTypeLoc)
2472 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002473
John McCall94c3b562010-08-18 09:41:07 +00002474 /// Handle all the types we haven't given a more specific
2475 /// implementation for above.
2476 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2477 // Every other kind of type that we haven't called out already
2478 // that has an inner type is either (1) sugar or (2) contains that
2479 // inner type in some way as a subobject.
2480 if (TypeLoc Next = TL.getNextTypeLoc())
2481 return Visit(Next, Sel);
2482
2483 // If there's no inner type and we're in a permissive context,
2484 // don't diagnose.
2485 if (Sel == Sema::AbstractNone) return;
2486
2487 // Check whether the type matches the abstract type.
2488 QualType T = TL.getType();
2489 if (T->isArrayType()) {
2490 Sel = Sema::AbstractArrayType;
2491 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002492 }
John McCall94c3b562010-08-18 09:41:07 +00002493 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2494 if (CT != Info.AbstractType) return;
2495
2496 // It matched; do some magic.
2497 if (Sel == Sema::AbstractArrayType) {
2498 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2499 << T << TL.getSourceRange();
2500 } else {
2501 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2502 << Sel << T << TL.getSourceRange();
2503 }
2504 Info.DiagnoseAbstractType();
2505 }
2506};
2507
2508void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2509 Sema::AbstractDiagSelID Sel) {
2510 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2511}
2512
2513}
2514
2515/// Check for invalid uses of an abstract type in a method declaration.
2516static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2517 CXXMethodDecl *MD) {
2518 // No need to do the check on definitions, which require that
2519 // the return/param types be complete.
2520 if (MD->isThisDeclarationADefinition())
2521 return;
2522
2523 // For safety's sake, just ignore it if we don't have type source
2524 // information. This should never happen for non-implicit methods,
2525 // but...
2526 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2527 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2528}
2529
2530/// Check for invalid uses of an abstract type within a class definition.
2531static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2532 CXXRecordDecl *RD) {
2533 for (CXXRecordDecl::decl_iterator
2534 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2535 Decl *D = *I;
2536 if (D->isImplicit()) continue;
2537
2538 // Methods and method templates.
2539 if (isa<CXXMethodDecl>(D)) {
2540 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2541 } else if (isa<FunctionTemplateDecl>(D)) {
2542 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2543 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2544
2545 // Fields and static variables.
2546 } else if (isa<FieldDecl>(D)) {
2547 FieldDecl *FD = cast<FieldDecl>(D);
2548 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2549 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2550 } else if (isa<VarDecl>(D)) {
2551 VarDecl *VD = cast<VarDecl>(D);
2552 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2553 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2554
2555 // Nested classes and class templates.
2556 } else if (isa<CXXRecordDecl>(D)) {
2557 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2558 } else if (isa<ClassTemplateDecl>(D)) {
2559 CheckAbstractClassUsage(Info,
2560 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2561 }
2562 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002563}
2564
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002565/// \brief Perform semantic checks on a class definition that has been
2566/// completing, introducing implicitly-declared members, checking for
2567/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002568void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002569 if (!Record || Record->isInvalidDecl())
2570 return;
2571
Eli Friedmanff2d8782009-12-16 20:00:27 +00002572 if (!Record->isDependentType())
Douglas Gregor23c94db2010-07-02 17:43:08 +00002573 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002574
Eli Friedmanff2d8782009-12-16 20:00:27 +00002575 if (Record->isInvalidDecl())
2576 return;
2577
John McCall233a6412010-01-28 07:38:46 +00002578 // Set access bits correctly on the directly-declared conversions.
2579 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2580 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2581 Convs->setAccess(I, (*I)->getAccess());
2582
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002583 // Determine whether we need to check for final overriders. We do
2584 // this either when there are virtual base classes (in which case we
2585 // may end up finding multiple final overriders for a given virtual
2586 // function) or any of the base classes is abstract (in which case
2587 // we might detect that this class is abstract).
2588 bool CheckFinalOverriders = false;
2589 if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2590 !Record->isDependentType()) {
2591 if (Record->getNumVBases())
2592 CheckFinalOverriders = true;
2593 else if (!Record->isAbstract()) {
2594 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2595 BEnd = Record->bases_end();
2596 B != BEnd; ++B) {
2597 CXXRecordDecl *BaseDecl
2598 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2599 if (BaseDecl->isAbstract()) {
2600 CheckFinalOverriders = true;
2601 break;
2602 }
2603 }
2604 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002605 }
2606
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002607 if (CheckFinalOverriders) {
2608 CXXFinalOverriderMap FinalOverriders;
2609 Record->getFinalOverriders(FinalOverriders);
2610
2611 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2612 MEnd = FinalOverriders.end();
2613 M != MEnd; ++M) {
2614 for (OverridingMethods::iterator SO = M->second.begin(),
2615 SOEnd = M->second.end();
2616 SO != SOEnd; ++SO) {
2617 assert(SO->second.size() > 0 &&
2618 "All virtual functions have overridding virtual functions");
2619 if (SO->second.size() == 1) {
2620 // C++ [class.abstract]p4:
2621 // A class is abstract if it contains or inherits at least one
2622 // pure virtual function for which the final overrider is pure
2623 // virtual.
2624 if (SO->second.front().Method->isPure())
2625 Record->setAbstract(true);
2626 continue;
2627 }
2628
2629 // C++ [class.virtual]p2:
2630 // In a derived class, if a virtual member function of a base
2631 // class subobject has more than one final overrider the
2632 // program is ill-formed.
2633 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2634 << (NamedDecl *)M->first << Record;
2635 Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2636 for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2637 OMEnd = SO->second.end();
2638 OM != OMEnd; ++OM)
2639 Diag(OM->Method->getLocation(), diag::note_final_overrider)
2640 << (NamedDecl *)M->first << OM->Method->getParent();
2641
2642 Record->setInvalidDecl();
2643 }
2644 }
2645 }
2646
John McCall94c3b562010-08-18 09:41:07 +00002647 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2648 AbstractUsageInfo Info(*this, Record);
2649 CheckAbstractClassUsage(Info, Record);
2650 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002651
2652 // If this is not an aggregate type and has no user-declared constructor,
2653 // complain about any non-static data members of reference or const scalar
2654 // type, since they will never get initializers.
2655 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2656 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2657 bool Complained = false;
2658 for (RecordDecl::field_iterator F = Record->field_begin(),
2659 FEnd = Record->field_end();
2660 F != FEnd; ++F) {
2661 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002662 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002663 if (!Complained) {
2664 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2665 << Record->getTagKind() << Record;
2666 Complained = true;
2667 }
2668
2669 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2670 << F->getType()->isReferenceType()
2671 << F->getDeclName();
2672 }
2673 }
2674 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002675
2676 if (Record->isDynamicClass())
2677 DynamicClasses.push_back(Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002678}
2679
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002680void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00002681 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002682 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002683 SourceLocation RBrac,
2684 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002685 if (!TagDecl)
2686 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002687
Douglas Gregor42af25f2009-05-11 19:58:34 +00002688 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002689
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002690 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00002691 // strict aliasing violation!
2692 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002693 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002694
Douglas Gregor23c94db2010-07-02 17:43:08 +00002695 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00002696 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002697}
2698
Douglas Gregord92ec472010-07-01 05:10:53 +00002699namespace {
2700 /// \brief Helper class that collects exception specifications for
2701 /// implicitly-declared special member functions.
2702 class ImplicitExceptionSpecification {
2703 ASTContext &Context;
2704 bool AllowsAllExceptions;
2705 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2706 llvm::SmallVector<QualType, 4> Exceptions;
2707
2708 public:
2709 explicit ImplicitExceptionSpecification(ASTContext &Context)
2710 : Context(Context), AllowsAllExceptions(false) { }
2711
2712 /// \brief Whether the special member function should have any
2713 /// exception specification at all.
2714 bool hasExceptionSpecification() const {
2715 return !AllowsAllExceptions;
2716 }
2717
2718 /// \brief Whether the special member function should have a
2719 /// throw(...) exception specification (a Microsoft extension).
2720 bool hasAnyExceptionSpecification() const {
2721 return false;
2722 }
2723
2724 /// \brief The number of exceptions in the exception specification.
2725 unsigned size() const { return Exceptions.size(); }
2726
2727 /// \brief The set of exceptions in the exception specification.
2728 const QualType *data() const { return Exceptions.data(); }
2729
2730 /// \brief Note that
2731 void CalledDecl(CXXMethodDecl *Method) {
2732 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor4681ca82010-07-01 15:29:53 +00002733 if (AllowsAllExceptions || !Method)
Douglas Gregord92ec472010-07-01 05:10:53 +00002734 return;
2735
2736 const FunctionProtoType *Proto
2737 = Method->getType()->getAs<FunctionProtoType>();
2738
2739 // If this function can throw any exceptions, make a note of that.
2740 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2741 AllowsAllExceptions = true;
2742 ExceptionsSeen.clear();
2743 Exceptions.clear();
2744 return;
2745 }
2746
2747 // Record the exceptions in this function's exception specification.
2748 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2749 EEnd = Proto->exception_end();
2750 E != EEnd; ++E)
2751 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2752 Exceptions.push_back(*E);
2753 }
2754 };
2755}
2756
2757
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002758/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2759/// special functions, such as the default constructor, copy
2760/// constructor, or destructor, to the given C++ class (C++
2761/// [special]p1). This routine can only be executed just before the
2762/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002763void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00002764 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002765 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002766
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00002767 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00002768 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002769
Douglas Gregora376d102010-07-02 21:50:04 +00002770 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2771 ++ASTContext::NumImplicitCopyAssignmentOperators;
2772
2773 // If we have a dynamic class, then the copy assignment operator may be
2774 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2775 // it shows up in the right place in the vtable and that we diagnose
2776 // problems with the implicit exception specification.
2777 if (ClassDecl->isDynamicClass())
2778 DeclareImplicitCopyAssignment(ClassDecl);
2779 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002780
Douglas Gregor4923aa22010-07-02 20:37:36 +00002781 if (!ClassDecl->hasUserDeclaredDestructor()) {
2782 ++ASTContext::NumImplicitDestructors;
2783
2784 // If we have a dynamic class, then the destructor may be virtual, so we
2785 // have to declare the destructor immediately. This ensures that, e.g., it
2786 // shows up in the right place in the vtable and that we diagnose problems
2787 // with the implicit exception specification.
2788 if (ClassDecl->isDynamicClass())
2789 DeclareImplicitDestructor(ClassDecl);
2790 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002791}
2792
John McCalld226f652010-08-21 09:40:31 +00002793void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002794 if (!D)
2795 return;
2796
2797 TemplateParameterList *Params = 0;
2798 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2799 Params = Template->getTemplateParameters();
2800 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2801 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2802 Params = PartialSpec->getTemplateParameters();
2803 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002804 return;
2805
Douglas Gregor6569d682009-05-27 23:11:45 +00002806 for (TemplateParameterList::iterator Param = Params->begin(),
2807 ParamEnd = Params->end();
2808 Param != ParamEnd; ++Param) {
2809 NamedDecl *Named = cast<NamedDecl>(*Param);
2810 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00002811 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00002812 IdResolver.AddDecl(Named);
2813 }
2814 }
2815}
2816
John McCalld226f652010-08-21 09:40:31 +00002817void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002818 if (!RecordD) return;
2819 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00002820 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00002821 PushDeclContext(S, Record);
2822}
2823
John McCalld226f652010-08-21 09:40:31 +00002824void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002825 if (!RecordD) return;
2826 PopDeclContext();
2827}
2828
Douglas Gregor72b505b2008-12-16 21:30:33 +00002829/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2830/// parsing a top-level (non-nested) C++ class, and we are now
2831/// parsing those parts of the given Method declaration that could
2832/// not be parsed earlier (C++ [class.mem]p2), such as default
2833/// arguments. This action should enter the scope of the given
2834/// Method declaration as if we had just parsed the qualified method
2835/// name. However, it should not bring the parameters into scope;
2836/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00002837void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002838}
2839
2840/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2841/// C++ method declaration. We're (re-)introducing the given
2842/// function parameter into scope for use in parsing later parts of
2843/// the method declaration. For example, we could see an
2844/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00002845void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002846 if (!ParamD)
2847 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002848
John McCalld226f652010-08-21 09:40:31 +00002849 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00002850
2851 // If this parameter has an unparsed default argument, clear it out
2852 // to make way for the parsed default argument.
2853 if (Param->hasUnparsedDefaultArg())
2854 Param->setDefaultArg(0);
2855
John McCalld226f652010-08-21 09:40:31 +00002856 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002857 if (Param->getDeclName())
2858 IdResolver.AddDecl(Param);
2859}
2860
2861/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2862/// processing the delayed method declaration for Method. The method
2863/// declaration is now considered finished. There may be a separate
2864/// ActOnStartOfFunctionDef action later (not necessarily
2865/// immediately!) for this method, if it was also defined inside the
2866/// class body.
John McCalld226f652010-08-21 09:40:31 +00002867void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002868 if (!MethodD)
2869 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002870
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002871 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002872
John McCalld226f652010-08-21 09:40:31 +00002873 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002874
2875 // Now that we have our default arguments, check the constructor
2876 // again. It could produce additional diagnostics or affect whether
2877 // the class has implicitly-declared destructors, among other
2878 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002879 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2880 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002881
2882 // Check the default arguments, which we may have added.
2883 if (!Method->isInvalidDecl())
2884 CheckCXXDefaultArguments(Method);
2885}
2886
Douglas Gregor42a552f2008-11-05 20:51:48 +00002887/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002888/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002889/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002890/// emit diagnostics and set the invalid bit to true. In any case, the type
2891/// will be updated to reflect a well-formed type for the constructor and
2892/// returned.
2893QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00002894 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002895 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002896
2897 // C++ [class.ctor]p3:
2898 // A constructor shall not be virtual (10.3) or static (9.4). A
2899 // constructor can be invoked for a const, volatile or const
2900 // volatile object. A constructor shall not be declared const,
2901 // volatile, or const volatile (9.3.2).
2902 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002903 if (!D.isInvalidType())
2904 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2905 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2906 << SourceRange(D.getIdentifierLoc());
2907 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002908 }
John McCalld931b082010-08-26 03:08:43 +00002909 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002910 if (!D.isInvalidType())
2911 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2912 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2913 << SourceRange(D.getIdentifierLoc());
2914 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00002915 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00002916 }
Mike Stump1eb44332009-09-09 15:08:12 +00002917
Chris Lattner65401802009-04-25 08:28:21 +00002918 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2919 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002920 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002921 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2922 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002923 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002924 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2925 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002926 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002927 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2928 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002929 }
Mike Stump1eb44332009-09-09 15:08:12 +00002930
Douglas Gregor42a552f2008-11-05 20:51:48 +00002931 // Rebuild the function type "R" without any type qualifiers (in
2932 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00002933 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00002934 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002935 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2936 Proto->getNumArgs(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002937 Proto->isVariadic(), 0,
2938 Proto->hasExceptionSpec(),
2939 Proto->hasAnyExceptionSpec(),
2940 Proto->getNumExceptions(),
2941 Proto->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00002942 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002943}
2944
Douglas Gregor72b505b2008-12-16 21:30:33 +00002945/// CheckConstructor - Checks a fully-formed constructor for
2946/// well-formedness, issuing any diagnostics required. Returns true if
2947/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002948void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002949 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002950 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2951 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002952 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002953
2954 // C++ [class.copy]p3:
2955 // A declaration of a constructor for a class X is ill-formed if
2956 // its first parameter is of type (optionally cv-qualified) X and
2957 // either there are no other parameters or else all other
2958 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002959 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002960 ((Constructor->getNumParams() == 1) ||
2961 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002962 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2963 Constructor->getTemplateSpecializationKind()
2964 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002965 QualType ParamType = Constructor->getParamDecl(0)->getType();
2966 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2967 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002968 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002969 const char *ConstRef
2970 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2971 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00002972 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002973 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002974
2975 // FIXME: Rather that making the constructor invalid, we should endeavor
2976 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002977 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002978 }
2979 }
Mike Stump1eb44332009-09-09 15:08:12 +00002980
John McCall3d043362010-04-13 07:45:41 +00002981 // Notify the class that we've added a constructor. In principle we
2982 // don't need to do this for out-of-line declarations; in practice
2983 // we only instantiate the most recent declaration of a method, so
2984 // we have to call this for everything but friends.
2985 if (!Constructor->getFriendObjectKind())
2986 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002987}
2988
John McCall15442822010-08-04 01:04:25 +00002989/// CheckDestructor - Checks a fully-formed destructor definition for
2990/// well-formedness, issuing any diagnostics required. Returns true
2991/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002992bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002993 CXXRecordDecl *RD = Destructor->getParent();
2994
2995 if (Destructor->isVirtual()) {
2996 SourceLocation Loc;
2997
2998 if (!Destructor->isImplicit())
2999 Loc = Destructor->getLocation();
3000 else
3001 Loc = RD->getLocation();
3002
3003 // If we have a virtual destructor, look up the deallocation function
3004 FunctionDecl *OperatorDelete = 0;
3005 DeclarationName Name =
3006 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003007 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00003008 return true;
John McCall5efd91a2010-07-03 18:33:00 +00003009
3010 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00003011
3012 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00003013 }
Anders Carlsson37909802009-11-30 21:24:50 +00003014
3015 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00003016}
3017
Mike Stump1eb44332009-09-09 15:08:12 +00003018static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003019FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3020 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3021 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00003022 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003023}
3024
Douglas Gregor42a552f2008-11-05 20:51:48 +00003025/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3026/// the well-formednes of the destructor declarator @p D with type @p
3027/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003028/// emit diagnostics and set the declarator to invalid. Even if this happens,
3029/// will be updated to reflect a well-formed type for the destructor and
3030/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00003031QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00003032 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003033 // C++ [class.dtor]p1:
3034 // [...] A typedef-name that names a class is a class-name
3035 // (7.1.3); however, a typedef-name that names a class shall not
3036 // be used as the identifier in the declarator for a destructor
3037 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003038 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregord92ec472010-07-01 05:10:53 +00003039 if (isa<TypedefType>(DeclaratorType))
Chris Lattner65401802009-04-25 08:28:21 +00003040 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003041 << DeclaratorType;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003042
3043 // C++ [class.dtor]p2:
3044 // A destructor is used to destroy objects of its class type. A
3045 // destructor takes no parameters, and no return type can be
3046 // specified for it (not even void). The address of a destructor
3047 // shall not be taken. A destructor shall not be static. A
3048 // destructor can be invoked for a const, volatile or const
3049 // volatile object. A destructor shall not be declared const,
3050 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00003051 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003052 if (!D.isInvalidType())
3053 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3054 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00003055 << SourceRange(D.getIdentifierLoc())
3056 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3057
John McCalld931b082010-08-26 03:08:43 +00003058 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003059 }
Chris Lattner65401802009-04-25 08:28:21 +00003060 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003061 // Destructors don't have return types, but the parser will
3062 // happily parse something like:
3063 //
3064 // class X {
3065 // float ~X();
3066 // };
3067 //
3068 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003069 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3070 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3071 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003072 }
Mike Stump1eb44332009-09-09 15:08:12 +00003073
Chris Lattner65401802009-04-25 08:28:21 +00003074 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3075 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003076 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003077 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3078 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003079 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003080 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3081 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003082 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003083 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3084 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003085 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003086 }
3087
3088 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003089 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003090 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3091
3092 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003093 FTI.freeArgs();
3094 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003095 }
3096
Mike Stump1eb44332009-09-09 15:08:12 +00003097 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003098 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003099 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003100 D.setInvalidType();
3101 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003102
3103 // Rebuild the function type "R" without any type qualifiers or
3104 // parameters (in case any of the errors above fired) and with
3105 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003106 // types.
3107 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3108 if (!Proto)
3109 return QualType();
3110
Douglas Gregorce056bc2010-02-21 22:15:06 +00003111 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Douglas Gregord92ec472010-07-01 05:10:53 +00003112 Proto->hasExceptionSpec(),
3113 Proto->hasAnyExceptionSpec(),
3114 Proto->getNumExceptions(),
3115 Proto->exception_begin(),
3116 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003117}
3118
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003119/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3120/// well-formednes of the conversion function declarator @p D with
3121/// type @p R. If there are any errors in the declarator, this routine
3122/// will emit diagnostics and return true. Otherwise, it will return
3123/// false. Either way, the type @p R will be updated to reflect a
3124/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003125void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00003126 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003127 // C++ [class.conv.fct]p1:
3128 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003129 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003130 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00003131 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003132 if (!D.isInvalidType())
3133 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3134 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3135 << SourceRange(D.getIdentifierLoc());
3136 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00003137 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003138 }
John McCalla3f81372010-04-13 00:04:31 +00003139
3140 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3141
Chris Lattner6e475012009-04-25 08:35:12 +00003142 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003143 // Conversion functions don't have return types, but the parser will
3144 // happily parse something like:
3145 //
3146 // class X {
3147 // float operator bool();
3148 // };
3149 //
3150 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003151 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3152 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3153 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003154 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003155 }
3156
John McCalla3f81372010-04-13 00:04:31 +00003157 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3158
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003159 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003160 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003161 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3162
3163 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00003164 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003165 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003166 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003167 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003168 D.setInvalidType();
3169 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003170
John McCalla3f81372010-04-13 00:04:31 +00003171 // Diagnose "&operator bool()" and other such nonsense. This
3172 // is actually a gcc extension which we don't support.
3173 if (Proto->getResultType() != ConvType) {
3174 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3175 << Proto->getResultType();
3176 D.setInvalidType();
3177 ConvType = Proto->getResultType();
3178 }
3179
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003180 // C++ [class.conv.fct]p4:
3181 // The conversion-type-id shall not represent a function type nor
3182 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003183 if (ConvType->isArrayType()) {
3184 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3185 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003186 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003187 } else if (ConvType->isFunctionType()) {
3188 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3189 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003190 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003191 }
3192
3193 // Rebuild the function type "R" without any parameters (in case any
3194 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003195 // return type.
John McCalla3f81372010-04-13 00:04:31 +00003196 if (D.isInvalidType()) {
3197 R = Context.getFunctionType(ConvType, 0, 0, false,
3198 Proto->getTypeQuals(),
3199 Proto->hasExceptionSpec(),
3200 Proto->hasAnyExceptionSpec(),
3201 Proto->getNumExceptions(),
3202 Proto->exception_begin(),
3203 Proto->getExtInfo());
3204 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003205
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003206 // C++0x explicit conversion operators.
3207 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003208 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003209 diag::warn_explicit_conversion_functions)
3210 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003211}
3212
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003213/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3214/// the declaration of the given C++ conversion function. This routine
3215/// is responsible for recording the conversion function in the C++
3216/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003217Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003218 assert(Conversion && "Expected to receive a conversion function declaration");
3219
Douglas Gregor9d350972008-12-12 08:25:50 +00003220 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003221
3222 // Make sure we aren't redeclaring the conversion function.
3223 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003224
3225 // C++ [class.conv.fct]p1:
3226 // [...] A conversion function is never used to convert a
3227 // (possibly cv-qualified) object to the (possibly cv-qualified)
3228 // same object type (or a reference to it), to a (possibly
3229 // cv-qualified) base class of that type (or a reference to it),
3230 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003231 // FIXME: Suppress this warning if the conversion function ends up being a
3232 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003233 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003234 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003235 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003236 ConvType = ConvTypeRef->getPointeeType();
3237 if (ConvType->isRecordType()) {
3238 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3239 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003240 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003241 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003242 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003243 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003244 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003245 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003246 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003247 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003248 }
3249
Douglas Gregor48026d22010-01-11 18:40:55 +00003250 if (Conversion->getPrimaryTemplate()) {
3251 // ignore specializations
3252 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003253 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor0c551062010-01-11 18:53:25 +00003254 = Conversion->getDescribedFunctionTemplate()) {
3255 if (ClassDecl->replaceConversion(
3256 ConversionTemplate->getPreviousDeclaration(),
3257 ConversionTemplate))
John McCalld226f652010-08-21 09:40:31 +00003258 return ConversionTemplate;
Douglas Gregor0c551062010-01-11 18:53:25 +00003259 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3260 Conversion))
John McCalld226f652010-08-21 09:40:31 +00003261 return Conversion;
Douglas Gregor70316a02008-12-26 15:00:45 +00003262 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00003263 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003264 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00003265 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor48026d22010-01-11 18:40:55 +00003266 else
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00003267 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003268
John McCalld226f652010-08-21 09:40:31 +00003269 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003270}
3271
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003272//===----------------------------------------------------------------------===//
3273// Namespace Handling
3274//===----------------------------------------------------------------------===//
3275
John McCallea318642010-08-26 09:15:37 +00003276
3277
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003278/// ActOnStartNamespaceDef - This is called at the start of a namespace
3279/// definition.
John McCalld226f652010-08-21 09:40:31 +00003280Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00003281 SourceLocation InlineLoc,
John McCallea318642010-08-26 09:15:37 +00003282 SourceLocation IdentLoc,
3283 IdentifierInfo *II,
3284 SourceLocation LBrace,
3285 AttributeList *AttrList) {
Douglas Gregor21e09b62010-08-19 20:55:47 +00003286 // anonymous namespace starts at its left brace
3287 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3288 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003289 Namespc->setLBracLoc(LBrace);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003290 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003291
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>())
John McCallea318642010-08-26 09:15:37 +00003297 PushVisibilityAttr(attr);
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.
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003313 if (Namespc->isInline() != OrigNS->isInline()) {
3314 // inline-ness must match
3315 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3316 << Namespc->isInline();
3317 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3318 Namespc->setInvalidDecl();
3319 // Recover by ignoring the new namespace's inline status.
3320 Namespc->setInline(OrigNS->isInline());
3321 }
3322
Douglas Gregor44b43212008-12-11 16:49:14 +00003323 // Attach this namespace decl to the chain of extended namespace
3324 // definitions.
3325 OrigNS->setNextNamespace(Namespc);
3326 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003327
Mike Stump1eb44332009-09-09 15:08:12 +00003328 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003329 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003330 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003331 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003332 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003333 } else if (PrevDecl) {
3334 // This is an invalid name redefinition.
3335 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3336 << Namespc->getDeclName();
3337 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3338 Namespc->setInvalidDecl();
3339 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003340 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00003341 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003342 // This is the first "real" definition of the namespace "std", so update
3343 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003344 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003345 // We had already defined a dummy namespace "std". Link this new
3346 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003347 StdNS->setNextNamespace(Namespc);
3348 StdNS->setLocation(IdentLoc);
3349 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003350 }
3351
3352 // Make our StdNamespace cache point at the first real definition of the
3353 // "std" namespace.
3354 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003355 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003356
3357 PushOnScopeChains(Namespc, DeclRegionScope);
3358 } else {
John McCall9aeed322009-10-01 00:25:31 +00003359 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003360 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003361
3362 // Link the anonymous namespace into its parent.
3363 NamespaceDecl *PrevDecl;
Sebastian Redl7a126a42010-08-31 00:36:30 +00003364 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00003365 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3366 PrevDecl = TU->getAnonymousNamespace();
3367 TU->setAnonymousNamespace(Namespc);
3368 } else {
3369 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3370 PrevDecl = ND->getAnonymousNamespace();
3371 ND->setAnonymousNamespace(Namespc);
3372 }
3373
3374 // Link the anonymous namespace with its previous declaration.
3375 if (PrevDecl) {
3376 assert(PrevDecl->isAnonymousNamespace());
3377 assert(!PrevDecl->getNextNamespace());
3378 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3379 PrevDecl->setNextNamespace(Namespc);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00003380
3381 if (Namespc->isInline() != PrevDecl->isInline()) {
3382 // inline-ness must match
3383 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3384 << Namespc->isInline();
3385 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3386 Namespc->setInvalidDecl();
3387 // Recover by ignoring the new namespace's inline status.
3388 Namespc->setInline(PrevDecl->isInline());
3389 }
John McCall5fdd7642009-12-16 02:06:49 +00003390 }
John McCall9aeed322009-10-01 00:25:31 +00003391
Douglas Gregora4181472010-03-24 00:46:35 +00003392 CurContext->addDecl(Namespc);
3393
John McCall9aeed322009-10-01 00:25:31 +00003394 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3395 // behaves as if it were replaced by
3396 // namespace unique { /* empty body */ }
3397 // using namespace unique;
3398 // namespace unique { namespace-body }
3399 // where all occurrences of 'unique' in a translation unit are
3400 // replaced by the same identifier and this identifier differs
3401 // from all other identifiers in the entire program.
3402
3403 // We just create the namespace with an empty name and then add an
3404 // implicit using declaration, just like the standard suggests.
3405 //
3406 // CodeGen enforces the "universally unique" aspect by giving all
3407 // declarations semantically contained within an anonymous
3408 // namespace internal linkage.
3409
John McCall5fdd7642009-12-16 02:06:49 +00003410 if (!PrevDecl) {
3411 UsingDirectiveDecl* UD
3412 = UsingDirectiveDecl::Create(Context, CurContext,
3413 /* 'using' */ LBrace,
3414 /* 'namespace' */ SourceLocation(),
3415 /* qualifier */ SourceRange(),
3416 /* NNS */ NULL,
3417 /* identifier */ SourceLocation(),
3418 Namespc,
3419 /* Ancestor */ CurContext);
3420 UD->setImplicit();
3421 CurContext->addDecl(UD);
3422 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003423 }
3424
3425 // Although we could have an invalid decl (i.e. the namespace name is a
3426 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003427 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3428 // for the namespace has the declarations that showed up in that particular
3429 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003430 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003431 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003432}
3433
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003434/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3435/// is a namespace alias, returns the namespace it points to.
3436static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3437 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3438 return AD->getNamespace();
3439 return dyn_cast_or_null<NamespaceDecl>(D);
3440}
3441
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003442/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3443/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003444void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003445 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3446 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3447 Namespc->setRBracLoc(RBrace);
3448 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003449 if (Namespc->hasAttr<VisibilityAttr>())
3450 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003451}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003452
John McCall384aff82010-08-25 07:42:41 +00003453CXXRecordDecl *Sema::getStdBadAlloc() const {
3454 return cast_or_null<CXXRecordDecl>(
3455 StdBadAlloc.get(Context.getExternalSource()));
3456}
3457
3458NamespaceDecl *Sema::getStdNamespace() const {
3459 return cast_or_null<NamespaceDecl>(
3460 StdNamespace.get(Context.getExternalSource()));
3461}
3462
Douglas Gregor66992202010-06-29 17:53:46 +00003463/// \brief Retrieve the special "std" namespace, which may require us to
3464/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003465NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003466 if (!StdNamespace) {
3467 // The "std" namespace has not yet been defined, so build one implicitly.
3468 StdNamespace = NamespaceDecl::Create(Context,
3469 Context.getTranslationUnitDecl(),
3470 SourceLocation(),
3471 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003472 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003473 }
3474
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003475 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003476}
3477
John McCalld226f652010-08-21 09:40:31 +00003478Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003479 SourceLocation UsingLoc,
3480 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003481 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003482 SourceLocation IdentLoc,
3483 IdentifierInfo *NamespcName,
3484 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003485 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3486 assert(NamespcName && "Invalid NamespcName.");
3487 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003488 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003489
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003490 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003491 NestedNameSpecifier *Qualifier = 0;
3492 if (SS.isSet())
3493 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3494
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003495 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003496 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3497 LookupParsedName(R, S, &SS);
3498 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003499 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003500
Douglas Gregor66992202010-06-29 17:53:46 +00003501 if (R.empty()) {
3502 // Allow "using namespace std;" or "using namespace ::std;" even if
3503 // "std" hasn't been defined yet, for GCC compatibility.
3504 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3505 NamespcName->isStr("std")) {
3506 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003507 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003508 R.resolveKind();
3509 }
3510 // Otherwise, attempt typo correction.
3511 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3512 CTC_NoKeywords, 0)) {
3513 if (R.getAsSingle<NamespaceDecl>() ||
3514 R.getAsSingle<NamespaceAliasDecl>()) {
3515 if (DeclContext *DC = computeDeclContext(SS, false))
3516 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3517 << NamespcName << DC << Corrected << SS.getRange()
3518 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3519 else
3520 Diag(IdentLoc, diag::err_using_directive_suggest)
3521 << NamespcName << Corrected
3522 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3523 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3524 << Corrected;
3525
3526 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003527 } else {
3528 R.clear();
3529 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003530 }
3531 }
3532 }
3533
John McCallf36e02d2009-10-09 21:13:30 +00003534 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003535 NamedDecl *Named = R.getFoundDecl();
3536 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3537 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003538 // C++ [namespace.udir]p1:
3539 // A using-directive specifies that the names in the nominated
3540 // namespace can be used in the scope in which the
3541 // using-directive appears after the using-directive. During
3542 // unqualified name lookup (3.4.1), the names appear as if they
3543 // were declared in the nearest enclosing namespace which
3544 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003545 // namespace. [Note: in this context, "contains" means "contains
3546 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003547
3548 // Find enclosing context containing both using-directive and
3549 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003550 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003551 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3552 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3553 CommonAncestor = CommonAncestor->getParent();
3554
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003555 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003556 SS.getRange(),
3557 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003558 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003559 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003560 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003561 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003562 }
3563
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003564 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003565 delete AttrList;
John McCalld226f652010-08-21 09:40:31 +00003566 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003567}
3568
3569void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3570 // If scope has associated entity, then using directive is at namespace
3571 // or translation unit scope. We add UsingDirectiveDecls, into
3572 // it's lookup structure.
3573 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003574 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003575 else
3576 // Otherwise it is block-sope. using-directives will affect lookup
3577 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00003578 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003579}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003580
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003581
John McCalld226f652010-08-21 09:40:31 +00003582Decl *Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003583 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003584 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003585 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003586 CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003587 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003588 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003589 bool IsTypeName,
3590 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003591 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003592
Douglas Gregor12c118a2009-11-04 16:30:06 +00003593 switch (Name.getKind()) {
3594 case UnqualifiedId::IK_Identifier:
3595 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003596 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003597 case UnqualifiedId::IK_ConversionFunctionId:
3598 break;
3599
3600 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003601 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003602 // C++0x inherited constructors.
3603 if (getLangOptions().CPlusPlus0x) break;
3604
Douglas Gregor12c118a2009-11-04 16:30:06 +00003605 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3606 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003607 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003608
3609 case UnqualifiedId::IK_DestructorName:
3610 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3611 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003612 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003613
3614 case UnqualifiedId::IK_TemplateId:
3615 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3616 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00003617 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003618 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003619
3620 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3621 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00003622 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00003623 return 0;
John McCall604e7f12009-12-08 07:46:18 +00003624
John McCall60fa3cf2009-12-11 02:10:03 +00003625 // Warn about using declarations.
3626 // TODO: store that the declaration was written without 'using' and
3627 // talk about access decls instead of using decls in the
3628 // diagnostics.
3629 if (!HasUsingKeyword) {
3630 UsingLoc = Name.getSourceRange().getBegin();
3631
3632 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003633 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003634 }
3635
John McCall9488ea12009-11-17 05:59:44 +00003636 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003637 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003638 /* IsInstantiation */ false,
3639 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003640 if (UD)
3641 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003642
John McCalld226f652010-08-21 09:40:31 +00003643 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00003644}
3645
Douglas Gregor09acc982010-07-07 23:08:52 +00003646/// \brief Determine whether a using declaration considers the given
3647/// declarations as "equivalent", e.g., if they are redeclarations of
3648/// the same entity or are both typedefs of the same type.
3649static bool
3650IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3651 bool &SuppressRedeclaration) {
3652 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3653 SuppressRedeclaration = false;
3654 return true;
3655 }
3656
3657 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3658 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3659 SuppressRedeclaration = true;
3660 return Context.hasSameType(TD1->getUnderlyingType(),
3661 TD2->getUnderlyingType());
3662 }
3663
3664 return false;
3665}
3666
3667
John McCall9f54ad42009-12-10 09:41:52 +00003668/// Determines whether to create a using shadow decl for a particular
3669/// decl, given the set of decls existing prior to this using lookup.
3670bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3671 const LookupResult &Previous) {
3672 // Diagnose finding a decl which is not from a base class of the
3673 // current class. We do this now because there are cases where this
3674 // function will silently decide not to build a shadow decl, which
3675 // will pre-empt further diagnostics.
3676 //
3677 // We don't need to do this in C++0x because we do the check once on
3678 // the qualifier.
3679 //
3680 // FIXME: diagnose the following if we care enough:
3681 // struct A { int foo; };
3682 // struct B : A { using A::foo; };
3683 // template <class T> struct C : A {};
3684 // template <class T> struct D : C<T> { using B::foo; } // <---
3685 // This is invalid (during instantiation) in C++03 because B::foo
3686 // resolves to the using decl in B, which is not a base class of D<T>.
3687 // We can't diagnose it immediately because C<T> is an unknown
3688 // specialization. The UsingShadowDecl in D<T> then points directly
3689 // to A::foo, which will look well-formed when we instantiate.
3690 // The right solution is to not collapse the shadow-decl chain.
3691 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3692 DeclContext *OrigDC = Orig->getDeclContext();
3693
3694 // Handle enums and anonymous structs.
3695 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3696 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3697 while (OrigRec->isAnonymousStructOrUnion())
3698 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3699
3700 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3701 if (OrigDC == CurContext) {
3702 Diag(Using->getLocation(),
3703 diag::err_using_decl_nested_name_specifier_is_current_class)
3704 << Using->getNestedNameRange();
3705 Diag(Orig->getLocation(), diag::note_using_decl_target);
3706 return true;
3707 }
3708
3709 Diag(Using->getNestedNameRange().getBegin(),
3710 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3711 << Using->getTargetNestedNameDecl()
3712 << cast<CXXRecordDecl>(CurContext)
3713 << Using->getNestedNameRange();
3714 Diag(Orig->getLocation(), diag::note_using_decl_target);
3715 return true;
3716 }
3717 }
3718
3719 if (Previous.empty()) return false;
3720
3721 NamedDecl *Target = Orig;
3722 if (isa<UsingShadowDecl>(Target))
3723 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3724
John McCalld7533ec2009-12-11 02:33:26 +00003725 // If the target happens to be one of the previous declarations, we
3726 // don't have a conflict.
3727 //
3728 // FIXME: but we might be increasing its access, in which case we
3729 // should redeclare it.
3730 NamedDecl *NonTag = 0, *Tag = 0;
3731 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3732 I != E; ++I) {
3733 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00003734 bool Result;
3735 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3736 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00003737
3738 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3739 }
3740
John McCall9f54ad42009-12-10 09:41:52 +00003741 if (Target->isFunctionOrFunctionTemplate()) {
3742 FunctionDecl *FD;
3743 if (isa<FunctionTemplateDecl>(Target))
3744 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3745 else
3746 FD = cast<FunctionDecl>(Target);
3747
3748 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00003749 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00003750 case Ovl_Overload:
3751 return false;
3752
3753 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003754 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003755 break;
3756
3757 // We found a decl with the exact signature.
3758 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00003759 // If we're in a record, we want to hide the target, so we
3760 // return true (without a diagnostic) to tell the caller not to
3761 // build a shadow decl.
3762 if (CurContext->isRecord())
3763 return true;
3764
3765 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003766 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003767 break;
3768 }
3769
3770 Diag(Target->getLocation(), diag::note_using_decl_target);
3771 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3772 return true;
3773 }
3774
3775 // Target is not a function.
3776
John McCall9f54ad42009-12-10 09:41:52 +00003777 if (isa<TagDecl>(Target)) {
3778 // No conflict between a tag and a non-tag.
3779 if (!Tag) return false;
3780
John McCall41ce66f2009-12-10 19:51:03 +00003781 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003782 Diag(Target->getLocation(), diag::note_using_decl_target);
3783 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3784 return true;
3785 }
3786
3787 // No conflict between a tag and a non-tag.
3788 if (!NonTag) return false;
3789
John McCall41ce66f2009-12-10 19:51:03 +00003790 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003791 Diag(Target->getLocation(), diag::note_using_decl_target);
3792 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3793 return true;
3794}
3795
John McCall9488ea12009-11-17 05:59:44 +00003796/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003797UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003798 UsingDecl *UD,
3799 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003800
3801 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003802 NamedDecl *Target = Orig;
3803 if (isa<UsingShadowDecl>(Target)) {
3804 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3805 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003806 }
3807
3808 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003809 = UsingShadowDecl::Create(Context, CurContext,
3810 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003811 UD->addShadowDecl(Shadow);
3812
3813 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003814 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003815 else
John McCall604e7f12009-12-08 07:46:18 +00003816 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003817 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003818
John McCall32daa422010-03-31 01:36:47 +00003819 // Register it as a conversion if appropriate.
3820 if (Shadow->getDeclName().getNameKind()
3821 == DeclarationName::CXXConversionFunctionName)
3822 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3823
John McCall604e7f12009-12-08 07:46:18 +00003824 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3825 Shadow->setInvalidDecl();
3826
John McCall9f54ad42009-12-10 09:41:52 +00003827 return Shadow;
3828}
John McCall604e7f12009-12-08 07:46:18 +00003829
John McCall9f54ad42009-12-10 09:41:52 +00003830/// Hides a using shadow declaration. This is required by the current
3831/// using-decl implementation when a resolvable using declaration in a
3832/// class is followed by a declaration which would hide or override
3833/// one or more of the using decl's targets; for example:
3834///
3835/// struct Base { void foo(int); };
3836/// struct Derived : Base {
3837/// using Base::foo;
3838/// void foo(int);
3839/// };
3840///
3841/// The governing language is C++03 [namespace.udecl]p12:
3842///
3843/// When a using-declaration brings names from a base class into a
3844/// derived class scope, member functions in the derived class
3845/// override and/or hide member functions with the same name and
3846/// parameter types in a base class (rather than conflicting).
3847///
3848/// There are two ways to implement this:
3849/// (1) optimistically create shadow decls when they're not hidden
3850/// by existing declarations, or
3851/// (2) don't create any shadow decls (or at least don't make them
3852/// visible) until we've fully parsed/instantiated the class.
3853/// The problem with (1) is that we might have to retroactively remove
3854/// a shadow decl, which requires several O(n) operations because the
3855/// decl structures are (very reasonably) not designed for removal.
3856/// (2) avoids this but is very fiddly and phase-dependent.
3857void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00003858 if (Shadow->getDeclName().getNameKind() ==
3859 DeclarationName::CXXConversionFunctionName)
3860 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3861
John McCall9f54ad42009-12-10 09:41:52 +00003862 // Remove it from the DeclContext...
3863 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003864
John McCall9f54ad42009-12-10 09:41:52 +00003865 // ...and the scope, if applicable...
3866 if (S) {
John McCalld226f652010-08-21 09:40:31 +00003867 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003868 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003869 }
3870
John McCall9f54ad42009-12-10 09:41:52 +00003871 // ...and the using decl.
3872 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3873
3874 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00003875 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00003876}
3877
John McCall7ba107a2009-11-18 02:36:19 +00003878/// Builds a using declaration.
3879///
3880/// \param IsInstantiation - Whether this call arises from an
3881/// instantiation of an unresolved using declaration. We treat
3882/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003883NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3884 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003885 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003886 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003887 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003888 bool IsInstantiation,
3889 bool IsTypeName,
3890 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003891 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003892 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00003893 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003894
Anders Carlsson550b14b2009-08-28 05:49:21 +00003895 // FIXME: We ignore attributes for now.
3896 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003897
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003898 if (SS.isEmpty()) {
3899 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003900 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003901 }
Mike Stump1eb44332009-09-09 15:08:12 +00003902
John McCall9f54ad42009-12-10 09:41:52 +00003903 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003904 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00003905 ForRedeclaration);
3906 Previous.setHideTags(false);
3907 if (S) {
3908 LookupName(Previous, S);
3909
3910 // It is really dumb that we have to do this.
3911 LookupResult::Filter F = Previous.makeFilter();
3912 while (F.hasNext()) {
3913 NamedDecl *D = F.next();
3914 if (!isDeclInScope(D, CurContext, S))
3915 F.erase();
3916 }
3917 F.done();
3918 } else {
3919 assert(IsInstantiation && "no scope in non-instantiation");
3920 assert(CurContext->isRecord() && "scope not record in instantiation");
3921 LookupQualifiedName(Previous, CurContext);
3922 }
3923
Mike Stump1eb44332009-09-09 15:08:12 +00003924 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003925 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3926
John McCall9f54ad42009-12-10 09:41:52 +00003927 // Check for invalid redeclarations.
3928 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3929 return 0;
3930
3931 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003932 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3933 return 0;
3934
John McCallaf8e6ed2009-11-12 03:15:40 +00003935 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003936 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003937 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003938 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003939 // FIXME: not all declaration name kinds are legal here
3940 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3941 UsingLoc, TypenameLoc,
3942 SS.getRange(), NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003943 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00003944 } else {
3945 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003946 UsingLoc, SS.getRange(),
3947 NNS, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00003948 }
John McCalled976492009-12-04 22:46:56 +00003949 } else {
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003950 D = UsingDecl::Create(Context, CurContext,
3951 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCalled976492009-12-04 22:46:56 +00003952 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003953 }
John McCalled976492009-12-04 22:46:56 +00003954 D->setAccess(AS);
3955 CurContext->addDecl(D);
3956
3957 if (!LookupContext) return D;
3958 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003959
John McCall77bb1aa2010-05-01 00:40:08 +00003960 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00003961 UD->setInvalidDecl();
3962 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003963 }
3964
John McCall604e7f12009-12-08 07:46:18 +00003965 // Look up the target name.
3966
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003967 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003968
John McCall604e7f12009-12-08 07:46:18 +00003969 // Unlike most lookups, we don't always want to hide tag
3970 // declarations: tag names are visible through the using declaration
3971 // even if hidden by ordinary names, *except* in a dependent context
3972 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003973 if (!IsInstantiation)
3974 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003975
John McCalla24dc2e2009-11-17 02:14:36 +00003976 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003977
John McCallf36e02d2009-10-09 21:13:30 +00003978 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003979 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003980 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003981 UD->setInvalidDecl();
3982 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003983 }
3984
John McCalled976492009-12-04 22:46:56 +00003985 if (R.isAmbiguous()) {
3986 UD->setInvalidDecl();
3987 return UD;
3988 }
Mike Stump1eb44332009-09-09 15:08:12 +00003989
John McCall7ba107a2009-11-18 02:36:19 +00003990 if (IsTypeName) {
3991 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003992 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003993 Diag(IdentLoc, diag::err_using_typename_non_type);
3994 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3995 Diag((*I)->getUnderlyingDecl()->getLocation(),
3996 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003997 UD->setInvalidDecl();
3998 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003999 }
4000 } else {
4001 // If we asked for a non-typename and we got a type, error out,
4002 // but only if this is an instantiation of an unresolved using
4003 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00004004 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00004005 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4006 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00004007 UD->setInvalidDecl();
4008 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00004009 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00004010 }
4011
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004012 // C++0x N2914 [namespace.udecl]p6:
4013 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00004014 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004015 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4016 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00004017 UD->setInvalidDecl();
4018 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00004019 }
Mike Stump1eb44332009-09-09 15:08:12 +00004020
John McCall9f54ad42009-12-10 09:41:52 +00004021 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4022 if (!CheckUsingShadowDecl(UD, *I, Previous))
4023 BuildUsingShadowDecl(S, UD, *I);
4024 }
John McCall9488ea12009-11-17 05:59:44 +00004025
4026 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00004027}
4028
John McCall9f54ad42009-12-10 09:41:52 +00004029/// Checks that the given using declaration is not an invalid
4030/// redeclaration. Note that this is checking only for the using decl
4031/// itself, not for any ill-formedness among the UsingShadowDecls.
4032bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4033 bool isTypeName,
4034 const CXXScopeSpec &SS,
4035 SourceLocation NameLoc,
4036 const LookupResult &Prev) {
4037 // C++03 [namespace.udecl]p8:
4038 // C++0x [namespace.udecl]p10:
4039 // A using-declaration is a declaration and can therefore be used
4040 // repeatedly where (and only where) multiple declarations are
4041 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00004042 //
4043 // That's in non-member contexts.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004044 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00004045 return false;
4046
4047 NestedNameSpecifier *Qual
4048 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4049
4050 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4051 NamedDecl *D = *I;
4052
4053 bool DTypename;
4054 NestedNameSpecifier *DQual;
4055 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4056 DTypename = UD->isTypeName();
4057 DQual = UD->getTargetNestedNameDecl();
4058 } else if (UnresolvedUsingValueDecl *UD
4059 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4060 DTypename = false;
4061 DQual = UD->getTargetNestedNameSpecifier();
4062 } else if (UnresolvedUsingTypenameDecl *UD
4063 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4064 DTypename = true;
4065 DQual = UD->getTargetNestedNameSpecifier();
4066 } else continue;
4067
4068 // using decls differ if one says 'typename' and the other doesn't.
4069 // FIXME: non-dependent using decls?
4070 if (isTypeName != DTypename) continue;
4071
4072 // using decls differ if they name different scopes (but note that
4073 // template instantiation can cause this check to trigger when it
4074 // didn't before instantiation).
4075 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4076 Context.getCanonicalNestedNameSpecifier(DQual))
4077 continue;
4078
4079 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00004080 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00004081 return true;
4082 }
4083
4084 return false;
4085}
4086
John McCall604e7f12009-12-08 07:46:18 +00004087
John McCalled976492009-12-04 22:46:56 +00004088/// Checks that the given nested-name qualifier used in a using decl
4089/// in the current context is appropriately related to the current
4090/// scope. If an error is found, diagnoses it and returns true.
4091bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4092 const CXXScopeSpec &SS,
4093 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004094 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004095
John McCall604e7f12009-12-08 07:46:18 +00004096 if (!CurContext->isRecord()) {
4097 // C++03 [namespace.udecl]p3:
4098 // C++0x [namespace.udecl]p8:
4099 // A using-declaration for a class member shall be a member-declaration.
4100
4101 // If we weren't able to compute a valid scope, it must be a
4102 // dependent class scope.
4103 if (!NamedContext || NamedContext->isRecord()) {
4104 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4105 << SS.getRange();
4106 return true;
4107 }
4108
4109 // Otherwise, everything is known to be fine.
4110 return false;
4111 }
4112
4113 // The current scope is a record.
4114
4115 // If the named context is dependent, we can't decide much.
4116 if (!NamedContext) {
4117 // FIXME: in C++0x, we can diagnose if we can prove that the
4118 // nested-name-specifier does not refer to a base class, which is
4119 // still possible in some cases.
4120
4121 // Otherwise we have to conservatively report that things might be
4122 // okay.
4123 return false;
4124 }
4125
4126 if (!NamedContext->isRecord()) {
4127 // Ideally this would point at the last name in the specifier,
4128 // but we don't have that level of source info.
4129 Diag(SS.getRange().getBegin(),
4130 diag::err_using_decl_nested_name_specifier_is_not_class)
4131 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4132 return true;
4133 }
4134
4135 if (getLangOptions().CPlusPlus0x) {
4136 // C++0x [namespace.udecl]p3:
4137 // In a using-declaration used as a member-declaration, the
4138 // nested-name-specifier shall name a base class of the class
4139 // being defined.
4140
4141 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4142 cast<CXXRecordDecl>(NamedContext))) {
4143 if (CurContext == NamedContext) {
4144 Diag(NameLoc,
4145 diag::err_using_decl_nested_name_specifier_is_current_class)
4146 << SS.getRange();
4147 return true;
4148 }
4149
4150 Diag(SS.getRange().getBegin(),
4151 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4152 << (NestedNameSpecifier*) SS.getScopeRep()
4153 << cast<CXXRecordDecl>(CurContext)
4154 << SS.getRange();
4155 return true;
4156 }
4157
4158 return false;
4159 }
4160
4161 // C++03 [namespace.udecl]p4:
4162 // A using-declaration used as a member-declaration shall refer
4163 // to a member of a base class of the class being defined [etc.].
4164
4165 // Salient point: SS doesn't have to name a base class as long as
4166 // lookup only finds members from base classes. Therefore we can
4167 // diagnose here only if we can prove that that can't happen,
4168 // i.e. if the class hierarchies provably don't intersect.
4169
4170 // TODO: it would be nice if "definitely valid" results were cached
4171 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4172 // need to be repeated.
4173
4174 struct UserData {
4175 llvm::DenseSet<const CXXRecordDecl*> Bases;
4176
4177 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4178 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4179 Data->Bases.insert(Base);
4180 return true;
4181 }
4182
4183 bool hasDependentBases(const CXXRecordDecl *Class) {
4184 return !Class->forallBases(collect, this);
4185 }
4186
4187 /// Returns true if the base is dependent or is one of the
4188 /// accumulated base classes.
4189 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4190 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4191 return !Data->Bases.count(Base);
4192 }
4193
4194 bool mightShareBases(const CXXRecordDecl *Class) {
4195 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4196 }
4197 };
4198
4199 UserData Data;
4200
4201 // Returns false if we find a dependent base.
4202 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4203 return false;
4204
4205 // Returns false if the class has a dependent base or if it or one
4206 // of its bases is present in the base set of the current context.
4207 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4208 return false;
4209
4210 Diag(SS.getRange().getBegin(),
4211 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4212 << (NestedNameSpecifier*) SS.getScopeRep()
4213 << cast<CXXRecordDecl>(CurContext)
4214 << SS.getRange();
4215
4216 return true;
John McCalled976492009-12-04 22:46:56 +00004217}
4218
John McCalld226f652010-08-21 09:40:31 +00004219Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004220 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004221 SourceLocation AliasLoc,
4222 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004223 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004224 SourceLocation IdentLoc,
4225 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004226
Anders Carlsson81c85c42009-03-28 23:53:49 +00004227 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004228 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4229 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004230
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004231 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004232 NamedDecl *PrevDecl
4233 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4234 ForRedeclaration);
4235 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4236 PrevDecl = 0;
4237
4238 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004239 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004240 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004241 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004242 // FIXME: At some point, we'll want to create the (redundant)
4243 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004244 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004245 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004246 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004247 }
Mike Stump1eb44332009-09-09 15:08:12 +00004248
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004249 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4250 diag::err_redefinition_different_kind;
4251 Diag(AliasLoc, DiagID) << Alias;
4252 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004253 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004254 }
4255
John McCalla24dc2e2009-11-17 02:14:36 +00004256 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004257 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004258
John McCallf36e02d2009-10-09 21:13:30 +00004259 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004260 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4261 CTC_NoKeywords, 0)) {
4262 if (R.getAsSingle<NamespaceDecl>() ||
4263 R.getAsSingle<NamespaceAliasDecl>()) {
4264 if (DeclContext *DC = computeDeclContext(SS, false))
4265 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4266 << Ident << DC << Corrected << SS.getRange()
4267 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4268 else
4269 Diag(IdentLoc, diag::err_using_directive_suggest)
4270 << Ident << Corrected
4271 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4272
4273 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4274 << Corrected;
4275
4276 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004277 } else {
4278 R.clear();
4279 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004280 }
4281 }
4282
4283 if (R.empty()) {
4284 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004285 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004286 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004287 }
Mike Stump1eb44332009-09-09 15:08:12 +00004288
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004289 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004290 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4291 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004292 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004293 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004294
John McCall3dbd3d52010-02-16 06:53:13 +00004295 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004296 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004297}
4298
Douglas Gregor39957dc2010-05-01 15:04:51 +00004299namespace {
4300 /// \brief Scoped object used to handle the state changes required in Sema
4301 /// to implicitly define the body of a C++ member function;
4302 class ImplicitlyDefinedFunctionScope {
4303 Sema &S;
4304 DeclContext *PreviousContext;
4305
4306 public:
4307 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4308 : S(S), PreviousContext(S.CurContext)
4309 {
4310 S.CurContext = Method;
4311 S.PushFunctionScope();
4312 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4313 }
4314
4315 ~ImplicitlyDefinedFunctionScope() {
4316 S.PopExpressionEvaluationContext();
4317 S.PopFunctionOrBlockScope();
4318 S.CurContext = PreviousContext;
4319 }
4320 };
4321}
4322
Douglas Gregor23c94db2010-07-02 17:43:08 +00004323CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4324 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004325 // C++ [class.ctor]p5:
4326 // A default constructor for a class X is a constructor of class X
4327 // that can be called without an argument. If there is no
4328 // user-declared constructor for class X, a default constructor is
4329 // implicitly declared. An implicitly-declared default constructor
4330 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004331 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4332 "Should not build implicit default constructor!");
4333
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004334 // C++ [except.spec]p14:
4335 // An implicitly declared special member function (Clause 12) shall have an
4336 // exception-specification. [...]
4337 ImplicitExceptionSpecification ExceptSpec(Context);
4338
4339 // Direct base-class destructors.
4340 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4341 BEnd = ClassDecl->bases_end();
4342 B != BEnd; ++B) {
4343 if (B->isVirtual()) // Handled below.
4344 continue;
4345
Douglas Gregor18274032010-07-03 00:47:00 +00004346 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4347 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4348 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4349 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4350 else if (CXXConstructorDecl *Constructor
4351 = BaseClassDecl->getDefaultConstructor())
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004352 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004353 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004354 }
4355
4356 // Virtual base-class destructors.
4357 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4358 BEnd = ClassDecl->vbases_end();
4359 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004360 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4361 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4362 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4363 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4364 else if (CXXConstructorDecl *Constructor
4365 = BaseClassDecl->getDefaultConstructor())
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004366 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004367 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004368 }
4369
4370 // Field destructors.
4371 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4372 FEnd = ClassDecl->field_end();
4373 F != FEnd; ++F) {
4374 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004375 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4376 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4377 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4378 ExceptSpec.CalledDecl(
4379 DeclareImplicitDefaultConstructor(FieldClassDecl));
4380 else if (CXXConstructorDecl *Constructor
4381 = FieldClassDecl->getDefaultConstructor())
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004382 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004383 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004384 }
4385
4386
4387 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004388 CanQualType ClassType
4389 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4390 DeclarationName Name
4391 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004392 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor32df23e2010-07-01 22:02:46 +00004393 CXXConstructorDecl *DefaultCon
Abramo Bagnara25777432010-08-11 22:01:17 +00004394 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004395 Context.getFunctionType(Context.VoidTy,
4396 0, 0, false, 0,
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004397 ExceptSpec.hasExceptionSpecification(),
4398 ExceptSpec.hasAnyExceptionSpecification(),
4399 ExceptSpec.size(),
4400 ExceptSpec.data(),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004401 FunctionType::ExtInfo()),
4402 /*TInfo=*/0,
4403 /*isExplicit=*/false,
4404 /*isInline=*/true,
4405 /*isImplicitlyDeclared=*/true);
4406 DefaultCon->setAccess(AS_public);
4407 DefaultCon->setImplicit();
4408 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004409
4410 // Note that we have declared this constructor.
4411 ClassDecl->setDeclaredDefaultConstructor(true);
4412 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4413
Douglas Gregor23c94db2010-07-02 17:43:08 +00004414 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004415 PushOnScopeChains(DefaultCon, S, false);
4416 ClassDecl->addDecl(DefaultCon);
4417
Douglas Gregor32df23e2010-07-01 22:02:46 +00004418 return DefaultCon;
4419}
4420
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004421void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4422 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004423 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004424 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004425 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004426
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004427 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004428 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004429
Douglas Gregor39957dc2010-05-01 15:04:51 +00004430 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004431 ErrorTrap Trap(*this);
4432 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4433 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004434 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004435 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004436 Constructor->setInvalidDecl();
4437 } else {
4438 Constructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004439 MarkVTableUsed(CurrentLocation, ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004440 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004441}
4442
Douglas Gregor23c94db2010-07-02 17:43:08 +00004443CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004444 // C++ [class.dtor]p2:
4445 // If a class has no user-declared destructor, a destructor is
4446 // declared implicitly. An implicitly-declared destructor is an
4447 // inline public member of its class.
4448
4449 // C++ [except.spec]p14:
4450 // An implicitly declared special member function (Clause 12) shall have
4451 // an exception-specification.
4452 ImplicitExceptionSpecification ExceptSpec(Context);
4453
4454 // Direct base-class destructors.
4455 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4456 BEnd = ClassDecl->bases_end();
4457 B != BEnd; ++B) {
4458 if (B->isVirtual()) // Handled below.
4459 continue;
4460
4461 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4462 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004463 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004464 }
4465
4466 // Virtual base-class destructors.
4467 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4468 BEnd = ClassDecl->vbases_end();
4469 B != BEnd; ++B) {
4470 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4471 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004472 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004473 }
4474
4475 // Field destructors.
4476 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4477 FEnd = ClassDecl->field_end();
4478 F != FEnd; ++F) {
4479 if (const RecordType *RecordTy
4480 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4481 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004482 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004483 }
4484
Douglas Gregor4923aa22010-07-02 20:37:36 +00004485 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004486 QualType Ty = Context.getFunctionType(Context.VoidTy,
4487 0, 0, false, 0,
4488 ExceptSpec.hasExceptionSpecification(),
4489 ExceptSpec.hasAnyExceptionSpecification(),
4490 ExceptSpec.size(),
4491 ExceptSpec.data(),
4492 FunctionType::ExtInfo());
4493
4494 CanQualType ClassType
4495 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4496 DeclarationName Name
4497 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004498 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004499 CXXDestructorDecl *Destructor
Abramo Bagnara25777432010-08-11 22:01:17 +00004500 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty,
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004501 /*isInline=*/true,
4502 /*isImplicitlyDeclared=*/true);
4503 Destructor->setAccess(AS_public);
4504 Destructor->setImplicit();
4505 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00004506
4507 // Note that we have declared this destructor.
4508 ClassDecl->setDeclaredDestructor(true);
4509 ++ASTContext::NumImplicitDestructorsDeclared;
4510
4511 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004512 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00004513 PushOnScopeChains(Destructor, S, false);
4514 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004515
4516 // This could be uniqued if it ever proves significant.
4517 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4518
4519 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00004520
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004521 return Destructor;
4522}
4523
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004524void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004525 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00004526 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004527 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004528 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004529 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004530
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004531 if (Destructor->isInvalidDecl())
4532 return;
4533
Douglas Gregor39957dc2010-05-01 15:04:51 +00004534 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004535
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004536 ErrorTrap Trap(*this);
John McCallef027fe2010-03-16 21:39:52 +00004537 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4538 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004539
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004540 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004541 Diag(CurrentLocation, diag::note_member_synthesized_at)
4542 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4543
4544 Destructor->setInvalidDecl();
4545 return;
4546 }
4547
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004548 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004549 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004550}
4551
Douglas Gregor06a9f362010-05-01 20:49:11 +00004552/// \brief Builds a statement that copies the given entity from \p From to
4553/// \c To.
4554///
4555/// This routine is used to copy the members of a class with an
4556/// implicitly-declared copy assignment operator. When the entities being
4557/// copied are arrays, this routine builds for loops to copy them.
4558///
4559/// \param S The Sema object used for type-checking.
4560///
4561/// \param Loc The location where the implicit copy is being generated.
4562///
4563/// \param T The type of the expressions being copied. Both expressions must
4564/// have this type.
4565///
4566/// \param To The expression we are copying to.
4567///
4568/// \param From The expression we are copying from.
4569///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004570/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4571/// Otherwise, it's a non-static member subobject.
4572///
Douglas Gregor06a9f362010-05-01 20:49:11 +00004573/// \param Depth Internal parameter recording the depth of the recursion.
4574///
4575/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00004576static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00004577BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00004578 Expr *To, Expr *From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004579 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00004580 // C++0x [class.copy]p30:
4581 // Each subobject is assigned in the manner appropriate to its type:
4582 //
4583 // - if the subobject is of class type, the copy assignment operator
4584 // for the class is used (as if by explicit qualification; that is,
4585 // ignoring any possible virtual overriding functions in more derived
4586 // classes);
4587 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4588 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4589
4590 // Look for operator=.
4591 DeclarationName Name
4592 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4593 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4594 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4595
4596 // Filter out any result that isn't a copy-assignment operator.
4597 LookupResult::Filter F = OpLookup.makeFilter();
4598 while (F.hasNext()) {
4599 NamedDecl *D = F.next();
4600 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4601 if (Method->isCopyAssignmentOperator())
4602 continue;
4603
4604 F.erase();
John McCallb0207482010-03-16 06:11:48 +00004605 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004606 F.done();
4607
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004608 // Suppress the protected check (C++ [class.protected]) for each of the
4609 // assignment operators we found. This strange dance is required when
4610 // we're assigning via a base classes's copy-assignment operator. To
4611 // ensure that we're getting the right base class subobject (without
4612 // ambiguities), we need to cast "this" to that subobject type; to
4613 // ensure that we don't go through the virtual call mechanism, we need
4614 // to qualify the operator= name with the base class (see below). However,
4615 // this means that if the base class has a protected copy assignment
4616 // operator, the protected member access check will fail. So, we
4617 // rewrite "protected" access to "public" access in this case, since we
4618 // know by construction that we're calling from a derived class.
4619 if (CopyingBaseSubobject) {
4620 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4621 L != LEnd; ++L) {
4622 if (L.getAccess() == AS_protected)
4623 L.setAccess(AS_public);
4624 }
4625 }
4626
Douglas Gregor06a9f362010-05-01 20:49:11 +00004627 // Create the nested-name-specifier that will be used to qualify the
4628 // reference to operator=; this is required to suppress the virtual
4629 // call mechanism.
4630 CXXScopeSpec SS;
4631 SS.setRange(Loc);
4632 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4633 T.getTypePtr()));
4634
4635 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00004636 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00004637 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004638 /*FirstQualifierInScope=*/0, OpLookup,
4639 /*TemplateArgs=*/0,
4640 /*SuppressQualifierCheck=*/true);
4641 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004642 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004643
4644 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00004645
John McCall60d7b3a2010-08-24 06:29:42 +00004646 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004647 OpEqualRef.takeAs<Expr>(),
John McCall9ae2f072010-08-23 23:25:46 +00004648 Loc, &From, 1, 0, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004649 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004650 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004651
4652 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004653 }
John McCallb0207482010-03-16 06:11:48 +00004654
Douglas Gregor06a9f362010-05-01 20:49:11 +00004655 // - if the subobject is of scalar type, the built-in assignment
4656 // operator is used.
4657 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4658 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00004659 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004660 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004661 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004662
4663 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004664 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004665
4666 // - if the subobject is an array, each element is assigned, in the
4667 // manner appropriate to the element type;
4668
4669 // Construct a loop over the array bounds, e.g.,
4670 //
4671 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4672 //
4673 // that will copy each of the array elements.
4674 QualType SizeType = S.Context.getSizeType();
4675
4676 // Create the iteration variable.
4677 IdentifierInfo *IterationVarName = 0;
4678 {
4679 llvm::SmallString<8> Str;
4680 llvm::raw_svector_ostream OS(Str);
4681 OS << "__i" << Depth;
4682 IterationVarName = &S.Context.Idents.get(OS.str());
4683 }
4684 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4685 IterationVarName, SizeType,
4686 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00004687 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004688
4689 // Initialize the iteration variable to zero.
4690 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004691 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004692
4693 // Create a reference to the iteration variable; we'll use this several
4694 // times throughout.
4695 Expr *IterationVarRef
4696 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4697 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4698
4699 // Create the DeclStmt that holds the iteration variable.
4700 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4701
4702 // Create the comparison against the array bound.
4703 llvm::APInt Upper = ArrayTy->getSize();
4704 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00004705 Expr *Comparison
4706 = new (S.Context) BinaryOperator(IterationVarRef->Retain(),
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004707 IntegerLiteral::Create(S.Context,
4708 Upper, SizeType, Loc),
4709 BO_NE, S.Context.BoolTy, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004710
4711 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004712 Expr *Increment
4713 = new (S.Context) UnaryOperator(IterationVarRef->Retain(),
John McCall2de56d12010-08-25 11:45:40 +00004714 UO_PreInc,
John McCall9ae2f072010-08-23 23:25:46 +00004715 SizeType, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004716
4717 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00004718 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4719 IterationVarRef, Loc));
4720 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4721 IterationVarRef, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00004722
4723 // Build the copy for an individual element of the array.
John McCall60d7b3a2010-08-24 06:29:42 +00004724 StmtResult Copy = BuildSingleCopyAssign(S, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004725 ArrayTy->getElementType(),
John McCall9ae2f072010-08-23 23:25:46 +00004726 To, From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004727 CopyingBaseSubobject, Depth+1);
Douglas Gregorff331c12010-07-25 18:17:45 +00004728 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004729 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004730
4731 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00004732 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00004733 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00004734 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00004735 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004736}
4737
Douglas Gregora376d102010-07-02 21:50:04 +00004738/// \brief Determine whether the given class has a copy assignment operator
4739/// that accepts a const-qualified argument.
4740static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4741 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4742
4743 if (!Class->hasDeclaredCopyAssignment())
4744 S.DeclareImplicitCopyAssignment(Class);
4745
4746 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4747 DeclarationName OpName
4748 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4749
4750 DeclContext::lookup_const_iterator Op, OpEnd;
4751 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4752 // C++ [class.copy]p9:
4753 // A user-declared copy assignment operator is a non-static non-template
4754 // member function of class X with exactly one parameter of type X, X&,
4755 // const X&, volatile X& or const volatile X&.
4756 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4757 if (!Method)
4758 continue;
4759
4760 if (Method->isStatic())
4761 continue;
4762 if (Method->getPrimaryTemplate())
4763 continue;
4764 const FunctionProtoType *FnType =
4765 Method->getType()->getAs<FunctionProtoType>();
4766 assert(FnType && "Overloaded operator has no prototype.");
4767 // Don't assert on this; an invalid decl might have been left in the AST.
4768 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4769 continue;
4770 bool AcceptsConst = true;
4771 QualType ArgType = FnType->getArgType(0);
4772 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4773 ArgType = Ref->getPointeeType();
4774 // Is it a non-const lvalue reference?
4775 if (!ArgType.isConstQualified())
4776 AcceptsConst = false;
4777 }
4778 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4779 continue;
4780
4781 // We have a single argument of type cv X or cv X&, i.e. we've found the
4782 // copy assignment operator. Return whether it accepts const arguments.
4783 return AcceptsConst;
4784 }
4785 assert(Class->isInvalidDecl() &&
4786 "No copy assignment operator declared in valid code.");
4787 return false;
4788}
4789
Douglas Gregor23c94db2010-07-02 17:43:08 +00004790CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00004791 // Note: The following rules are largely analoguous to the copy
4792 // constructor rules. Note that virtual bases are not taken into account
4793 // for determining the argument type of the operator. Note also that
4794 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00004795
4796
Douglas Gregord3c35902010-07-01 16:36:15 +00004797 // C++ [class.copy]p10:
4798 // If the class definition does not explicitly declare a copy
4799 // assignment operator, one is declared implicitly.
4800 // The implicitly-defined copy assignment operator for a class X
4801 // will have the form
4802 //
4803 // X& X::operator=(const X&)
4804 //
4805 // if
4806 bool HasConstCopyAssignment = true;
4807
4808 // -- each direct base class B of X has a copy assignment operator
4809 // whose parameter is of type const B&, const volatile B& or B,
4810 // and
4811 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4812 BaseEnd = ClassDecl->bases_end();
4813 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4814 assert(!Base->getType()->isDependentType() &&
4815 "Cannot generate implicit members for class with dependent bases.");
4816 const CXXRecordDecl *BaseClassDecl
4817 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004818 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004819 }
4820
4821 // -- for all the nonstatic data members of X that are of a class
4822 // type M (or array thereof), each such class type has a copy
4823 // assignment operator whose parameter is of type const M&,
4824 // const volatile M& or M.
4825 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4826 FieldEnd = ClassDecl->field_end();
4827 HasConstCopyAssignment && Field != FieldEnd;
4828 ++Field) {
4829 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4830 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4831 const CXXRecordDecl *FieldClassDecl
4832 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004833 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004834 }
4835 }
4836
4837 // Otherwise, the implicitly declared copy assignment operator will
4838 // have the form
4839 //
4840 // X& X::operator=(X&)
4841 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4842 QualType RetType = Context.getLValueReferenceType(ArgType);
4843 if (HasConstCopyAssignment)
4844 ArgType = ArgType.withConst();
4845 ArgType = Context.getLValueReferenceType(ArgType);
4846
Douglas Gregorb87786f2010-07-01 17:48:08 +00004847 // C++ [except.spec]p14:
4848 // An implicitly declared special member function (Clause 12) shall have an
4849 // exception-specification. [...]
4850 ImplicitExceptionSpecification ExceptSpec(Context);
4851 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4852 BaseEnd = ClassDecl->bases_end();
4853 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00004854 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004855 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004856
4857 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4858 DeclareImplicitCopyAssignment(BaseClassDecl);
4859
Douglas Gregorb87786f2010-07-01 17:48:08 +00004860 if (CXXMethodDecl *CopyAssign
4861 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4862 ExceptSpec.CalledDecl(CopyAssign);
4863 }
4864 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4865 FieldEnd = ClassDecl->field_end();
4866 Field != FieldEnd;
4867 ++Field) {
4868 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4869 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00004870 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004871 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004872
4873 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4874 DeclareImplicitCopyAssignment(FieldClassDecl);
4875
Douglas Gregorb87786f2010-07-01 17:48:08 +00004876 if (CXXMethodDecl *CopyAssign
4877 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4878 ExceptSpec.CalledDecl(CopyAssign);
4879 }
4880 }
4881
Douglas Gregord3c35902010-07-01 16:36:15 +00004882 // An implicitly-declared copy assignment operator is an inline public
4883 // member of its class.
4884 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnara25777432010-08-11 22:01:17 +00004885 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00004886 CXXMethodDecl *CopyAssignment
Abramo Bagnara25777432010-08-11 22:01:17 +00004887 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregord3c35902010-07-01 16:36:15 +00004888 Context.getFunctionType(RetType, &ArgType, 1,
4889 false, 0,
Douglas Gregorb87786f2010-07-01 17:48:08 +00004890 ExceptSpec.hasExceptionSpecification(),
4891 ExceptSpec.hasAnyExceptionSpecification(),
4892 ExceptSpec.size(),
4893 ExceptSpec.data(),
Douglas Gregord3c35902010-07-01 16:36:15 +00004894 FunctionType::ExtInfo()),
4895 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00004896 /*StorageClassAsWritten=*/SC_None,
Douglas Gregord3c35902010-07-01 16:36:15 +00004897 /*isInline=*/true);
4898 CopyAssignment->setAccess(AS_public);
4899 CopyAssignment->setImplicit();
4900 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
4901 CopyAssignment->setCopyAssignment(true);
4902
4903 // Add the parameter to the operator.
4904 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4905 ClassDecl->getLocation(),
4906 /*Id=*/0,
4907 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00004908 SC_None,
4909 SC_None, 0);
Douglas Gregord3c35902010-07-01 16:36:15 +00004910 CopyAssignment->setParams(&FromParam, 1);
4911
Douglas Gregora376d102010-07-02 21:50:04 +00004912 // Note that we have added this copy-assignment operator.
4913 ClassDecl->setDeclaredCopyAssignment(true);
4914 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4915
Douglas Gregor23c94db2010-07-02 17:43:08 +00004916 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00004917 PushOnScopeChains(CopyAssignment, S, false);
4918 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00004919
4920 AddOverriddenMethods(ClassDecl, CopyAssignment);
4921 return CopyAssignment;
4922}
4923
Douglas Gregor06a9f362010-05-01 20:49:11 +00004924void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4925 CXXMethodDecl *CopyAssignOperator) {
4926 assert((CopyAssignOperator->isImplicit() &&
4927 CopyAssignOperator->isOverloadedOperator() &&
4928 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004929 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00004930 "DefineImplicitCopyAssignment called for wrong function");
4931
4932 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4933
4934 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4935 CopyAssignOperator->setInvalidDecl();
4936 return;
4937 }
4938
4939 CopyAssignOperator->setUsed();
4940
4941 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004942 ErrorTrap Trap(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004943
4944 // C++0x [class.copy]p30:
4945 // The implicitly-defined or explicitly-defaulted copy assignment operator
4946 // for a non-union class X performs memberwise copy assignment of its
4947 // subobjects. The direct base classes of X are assigned first, in the
4948 // order of their declaration in the base-specifier-list, and then the
4949 // immediate non-static data members of X are assigned, in the order in
4950 // which they were declared in the class definition.
4951
4952 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00004953 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004954
4955 // The parameter for the "other" object, which we are copying from.
4956 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4957 Qualifiers OtherQuals = Other->getType().getQualifiers();
4958 QualType OtherRefType = Other->getType();
4959 if (const LValueReferenceType *OtherRef
4960 = OtherRefType->getAs<LValueReferenceType>()) {
4961 OtherRefType = OtherRef->getPointeeType();
4962 OtherQuals = OtherRefType.getQualifiers();
4963 }
4964
4965 // Our location for everything implicitly-generated.
4966 SourceLocation Loc = CopyAssignOperator->getLocation();
4967
4968 // Construct a reference to the "other" object. We'll be using this
4969 // throughout the generated ASTs.
4970 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4971 assert(OtherRef && "Reference to parameter cannot fail!");
4972
4973 // Construct the "this" pointer. We'll be using this throughout the generated
4974 // ASTs.
4975 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4976 assert(This && "Reference to this cannot fail!");
4977
4978 // Assign base classes.
4979 bool Invalid = false;
4980 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4981 E = ClassDecl->bases_end(); Base != E; ++Base) {
4982 // Form the assignment:
4983 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4984 QualType BaseType = Base->getType().getUnqualifiedType();
4985 CXXRecordDecl *BaseClassDecl = 0;
4986 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4987 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4988 else {
4989 Invalid = true;
4990 continue;
4991 }
4992
John McCallf871d0c2010-08-07 06:22:56 +00004993 CXXCastPath BasePath;
4994 BasePath.push_back(Base);
4995
Douglas Gregor06a9f362010-05-01 20:49:11 +00004996 // Construct the "from" expression, which is an implicit cast to the
4997 // appropriately-qualified base type.
4998 Expr *From = OtherRef->Retain();
4999 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall5baba9d2010-08-25 10:28:54 +00005000 CK_UncheckedDerivedToBase,
5001 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005002
5003 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00005004 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005005
5006 // Implicitly cast "this" to the appropriately-qualified base type.
5007 Expr *ToE = To.takeAs<Expr>();
5008 ImpCastExprToType(ToE,
5009 Context.getCVRQualifiedType(BaseType,
5010 CopyAssignOperator->getTypeQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00005011 CK_UncheckedDerivedToBase,
5012 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005013 To = Owned(ToE);
5014
5015 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00005016 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00005017 To.get(), From,
5018 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005019 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005020 Diag(CurrentLocation, diag::note_member_synthesized_at)
5021 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5022 CopyAssignOperator->setInvalidDecl();
5023 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005024 }
5025
5026 // Success! Record the copy.
5027 Statements.push_back(Copy.takeAs<Expr>());
5028 }
5029
5030 // \brief Reference to the __builtin_memcpy function.
5031 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005032 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005033 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005034
5035 // Assign non-static members.
5036 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5037 FieldEnd = ClassDecl->field_end();
5038 Field != FieldEnd; ++Field) {
5039 // Check for members of reference type; we can't copy those.
5040 if (Field->getType()->isReferenceType()) {
5041 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5042 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5043 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005044 Diag(CurrentLocation, diag::note_member_synthesized_at)
5045 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005046 Invalid = true;
5047 continue;
5048 }
5049
5050 // Check for members of const-qualified, non-class type.
5051 QualType BaseType = Context.getBaseElementType(Field->getType());
5052 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5053 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5054 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5055 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005056 Diag(CurrentLocation, diag::note_member_synthesized_at)
5057 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005058 Invalid = true;
5059 continue;
5060 }
5061
5062 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005063 if (FieldType->isIncompleteArrayType()) {
5064 assert(ClassDecl->hasFlexibleArrayMember() &&
5065 "Incomplete array type is not valid");
5066 continue;
5067 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005068
5069 // Build references to the field in the object we're copying from and to.
5070 CXXScopeSpec SS; // Intentionally empty
5071 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5072 LookupMemberName);
5073 MemberLookup.addDecl(*Field);
5074 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00005075 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
Douglas Gregor06a9f362010-05-01 20:49:11 +00005076 Loc, /*IsArrow=*/false,
5077 SS, 0, MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00005078 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005079 Loc, /*IsArrow=*/true,
5080 SS, 0, MemberLookup, 0);
5081 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5082 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5083
5084 // If the field should be copied with __builtin_memcpy rather than via
5085 // explicit assignments, do so. This optimization only applies for arrays
5086 // of scalars and arrays of class type with trivial copy-assignment
5087 // operators.
5088 if (FieldType->isArrayType() &&
5089 (!BaseType->isRecordType() ||
5090 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5091 ->hasTrivialCopyAssignment())) {
5092 // Compute the size of the memory buffer to be copied.
5093 QualType SizeType = Context.getSizeType();
5094 llvm::APInt Size(Context.getTypeSize(SizeType),
5095 Context.getTypeSizeInChars(BaseType).getQuantity());
5096 for (const ConstantArrayType *Array
5097 = Context.getAsConstantArrayType(FieldType);
5098 Array;
5099 Array = Context.getAsConstantArrayType(Array->getElementType())) {
5100 llvm::APInt ArraySize = Array->getSize();
5101 ArraySize.zextOrTrunc(Size.getBitWidth());
5102 Size *= ArraySize;
5103 }
5104
5105 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00005106 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5107 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005108
5109 bool NeedsCollectableMemCpy =
5110 (BaseType->isRecordType() &&
5111 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5112
5113 if (NeedsCollectableMemCpy) {
5114 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005115 // Create a reference to the __builtin_objc_memmove_collectable function.
5116 LookupResult R(*this,
5117 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005118 Loc, LookupOrdinaryName);
5119 LookupName(R, TUScope, true);
5120
5121 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5122 if (!CollectableMemCpy) {
5123 // Something went horribly wrong earlier, and we will have
5124 // complained about it.
5125 Invalid = true;
5126 continue;
5127 }
5128
5129 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5130 CollectableMemCpy->getType(),
5131 Loc, 0).takeAs<Expr>();
5132 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5133 }
5134 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005135 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005136 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005137 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5138 LookupOrdinaryName);
5139 LookupName(R, TUScope, true);
5140
5141 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5142 if (!BuiltinMemCpy) {
5143 // Something went horribly wrong earlier, and we will have complained
5144 // about it.
5145 Invalid = true;
5146 continue;
5147 }
5148
5149 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5150 BuiltinMemCpy->getType(),
5151 Loc, 0).takeAs<Expr>();
5152 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5153 }
5154
John McCallca0408f2010-08-23 06:44:23 +00005155 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005156 CallArgs.push_back(To.takeAs<Expr>());
5157 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005158 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00005159 llvm::SmallVector<SourceLocation, 4> Commas; // FIXME: Silly
5160 Commas.push_back(Loc);
5161 Commas.push_back(Loc);
John McCall60d7b3a2010-08-24 06:29:42 +00005162 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005163 if (NeedsCollectableMemCpy)
5164 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005165 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005166 Loc, move_arg(CallArgs),
5167 Commas.data(), Loc);
5168 else
5169 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00005170 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005171 Loc, move_arg(CallArgs),
5172 Commas.data(), Loc);
5173
Douglas Gregor06a9f362010-05-01 20:49:11 +00005174 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5175 Statements.push_back(Call.takeAs<Expr>());
5176 continue;
5177 }
5178
5179 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00005180 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCall9ae2f072010-08-23 23:25:46 +00005181 To.get(), From.get(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005182 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005183 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005184 Diag(CurrentLocation, diag::note_member_synthesized_at)
5185 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5186 CopyAssignOperator->setInvalidDecl();
5187 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005188 }
5189
5190 // Success! Record the copy.
5191 Statements.push_back(Copy.takeAs<Stmt>());
5192 }
5193
5194 if (!Invalid) {
5195 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00005196 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005197
John McCall60d7b3a2010-08-24 06:29:42 +00005198 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00005199 if (Return.isInvalid())
5200 Invalid = true;
5201 else {
5202 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005203
5204 if (Trap.hasErrorOccurred()) {
5205 Diag(CurrentLocation, diag::note_member_synthesized_at)
5206 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5207 Invalid = true;
5208 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005209 }
5210 }
5211
5212 if (Invalid) {
5213 CopyAssignOperator->setInvalidDecl();
5214 return;
5215 }
5216
John McCall60d7b3a2010-08-24 06:29:42 +00005217 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00005218 /*isStmtExpr=*/false);
5219 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5220 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005221}
5222
Douglas Gregor23c94db2010-07-02 17:43:08 +00005223CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5224 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005225 // C++ [class.copy]p4:
5226 // If the class definition does not explicitly declare a copy
5227 // constructor, one is declared implicitly.
5228
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005229 // C++ [class.copy]p5:
5230 // The implicitly-declared copy constructor for a class X will
5231 // have the form
5232 //
5233 // X::X(const X&)
5234 //
5235 // if
5236 bool HasConstCopyConstructor = true;
5237
5238 // -- each direct or virtual base class B of X has a copy
5239 // constructor whose first parameter is of type const B& or
5240 // const volatile B&, and
5241 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5242 BaseEnd = ClassDecl->bases_end();
5243 HasConstCopyConstructor && Base != BaseEnd;
5244 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005245 // Virtual bases are handled below.
5246 if (Base->isVirtual())
5247 continue;
5248
Douglas Gregor22584312010-07-02 23:41:54 +00005249 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005250 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005251 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5252 DeclareImplicitCopyConstructor(BaseClassDecl);
5253
Douglas Gregor598a8542010-07-01 18:27:03 +00005254 HasConstCopyConstructor
5255 = BaseClassDecl->hasConstCopyConstructor(Context);
5256 }
5257
5258 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5259 BaseEnd = ClassDecl->vbases_end();
5260 HasConstCopyConstructor && Base != BaseEnd;
5261 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005262 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005263 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005264 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5265 DeclareImplicitCopyConstructor(BaseClassDecl);
5266
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005267 HasConstCopyConstructor
5268 = BaseClassDecl->hasConstCopyConstructor(Context);
5269 }
5270
5271 // -- for all the nonstatic data members of X that are of a
5272 // class type M (or array thereof), each such class type
5273 // has a copy constructor whose first parameter is of type
5274 // const M& or const volatile M&.
5275 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5276 FieldEnd = ClassDecl->field_end();
5277 HasConstCopyConstructor && Field != FieldEnd;
5278 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005279 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005280 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005281 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005282 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005283 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5284 DeclareImplicitCopyConstructor(FieldClassDecl);
5285
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005286 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005287 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005288 }
5289 }
5290
5291 // Otherwise, the implicitly declared copy constructor will have
5292 // the form
5293 //
5294 // X::X(X&)
5295 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5296 QualType ArgType = ClassType;
5297 if (HasConstCopyConstructor)
5298 ArgType = ArgType.withConst();
5299 ArgType = Context.getLValueReferenceType(ArgType);
5300
Douglas Gregor0d405db2010-07-01 20:59:04 +00005301 // C++ [except.spec]p14:
5302 // An implicitly declared special member function (Clause 12) shall have an
5303 // exception-specification. [...]
5304 ImplicitExceptionSpecification ExceptSpec(Context);
5305 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5306 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5307 BaseEnd = ClassDecl->bases_end();
5308 Base != BaseEnd;
5309 ++Base) {
5310 // Virtual bases are handled below.
5311 if (Base->isVirtual())
5312 continue;
5313
Douglas Gregor22584312010-07-02 23:41:54 +00005314 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005315 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005316 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5317 DeclareImplicitCopyConstructor(BaseClassDecl);
5318
Douglas Gregor0d405db2010-07-01 20:59:04 +00005319 if (CXXConstructorDecl *CopyConstructor
5320 = BaseClassDecl->getCopyConstructor(Context, Quals))
5321 ExceptSpec.CalledDecl(CopyConstructor);
5322 }
5323 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5324 BaseEnd = ClassDecl->vbases_end();
5325 Base != BaseEnd;
5326 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005327 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005328 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005329 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5330 DeclareImplicitCopyConstructor(BaseClassDecl);
5331
Douglas Gregor0d405db2010-07-01 20:59:04 +00005332 if (CXXConstructorDecl *CopyConstructor
5333 = BaseClassDecl->getCopyConstructor(Context, Quals))
5334 ExceptSpec.CalledDecl(CopyConstructor);
5335 }
5336 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5337 FieldEnd = ClassDecl->field_end();
5338 Field != FieldEnd;
5339 ++Field) {
5340 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5341 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005342 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005343 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005344 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5345 DeclareImplicitCopyConstructor(FieldClassDecl);
5346
Douglas Gregor0d405db2010-07-01 20:59:04 +00005347 if (CXXConstructorDecl *CopyConstructor
5348 = FieldClassDecl->getCopyConstructor(Context, Quals))
5349 ExceptSpec.CalledDecl(CopyConstructor);
5350 }
5351 }
5352
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005353 // An implicitly-declared copy constructor is an inline public
5354 // member of its class.
5355 DeclarationName Name
5356 = Context.DeclarationNames.getCXXConstructorName(
5357 Context.getCanonicalType(ClassType));
Abramo Bagnara25777432010-08-11 22:01:17 +00005358 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005359 CXXConstructorDecl *CopyConstructor
Abramo Bagnara25777432010-08-11 22:01:17 +00005360 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005361 Context.getFunctionType(Context.VoidTy,
5362 &ArgType, 1,
5363 false, 0,
Douglas Gregor0d405db2010-07-01 20:59:04 +00005364 ExceptSpec.hasExceptionSpecification(),
5365 ExceptSpec.hasAnyExceptionSpecification(),
5366 ExceptSpec.size(),
5367 ExceptSpec.data(),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005368 FunctionType::ExtInfo()),
5369 /*TInfo=*/0,
5370 /*isExplicit=*/false,
5371 /*isInline=*/true,
5372 /*isImplicitlyDeclared=*/true);
5373 CopyConstructor->setAccess(AS_public);
5374 CopyConstructor->setImplicit();
5375 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5376
Douglas Gregor22584312010-07-02 23:41:54 +00005377 // Note that we have declared this constructor.
5378 ClassDecl->setDeclaredCopyConstructor(true);
5379 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5380
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005381 // Add the parameter to the constructor.
5382 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5383 ClassDecl->getLocation(),
5384 /*IdentifierInfo=*/0,
5385 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00005386 SC_None,
5387 SC_None, 0);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005388 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00005389 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00005390 PushOnScopeChains(CopyConstructor, S, false);
5391 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005392
5393 return CopyConstructor;
5394}
5395
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005396void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5397 CXXConstructorDecl *CopyConstructor,
5398 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00005399 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00005400 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005401 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005402 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005403
Anders Carlsson63010a72010-04-23 16:24:12 +00005404 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005405 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005406
Douglas Gregor39957dc2010-05-01 15:04:51 +00005407 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005408 ErrorTrap Trap(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005409
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005410 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5411 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00005412 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005413 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00005414 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005415 } else {
5416 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5417 CopyConstructor->getLocation(),
5418 MultiStmtArg(*this, 0, 0),
5419 /*isStmtExpr=*/false)
5420 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00005421 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005422
5423 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005424}
5425
John McCall60d7b3a2010-08-24 06:29:42 +00005426ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005427Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00005428 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00005429 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005430 bool RequiresZeroInit,
John McCall7a1fad32010-08-24 07:32:53 +00005431 unsigned ConstructKind) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005432 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005433
Douglas Gregor2f599792010-04-02 18:24:57 +00005434 // C++0x [class.copy]p34:
5435 // When certain criteria are met, an implementation is allowed to
5436 // omit the copy/move construction of a class object, even if the
5437 // copy/move constructor and/or destructor for the object have
5438 // side effects. [...]
5439 // - when a temporary class object that has not been bound to a
5440 // reference (12.2) would be copied/moved to a class object
5441 // with the same cv-unqualified type, the copy/move operation
5442 // can be omitted by constructing the temporary object
5443 // directly into the target of the omitted copy/move
5444 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
5445 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
5446 Elidable = SubExpr->isTemporaryObject() &&
Douglas Gregorb8f7de92010-08-22 18:27:02 +00005447 ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor2f599792010-04-02 18:24:57 +00005448 Context.hasSameUnqualifiedType(SubExpr->getType(),
5449 Context.getTypeDeclType(Constructor->getParent()));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005450 }
Mike Stump1eb44332009-09-09 15:08:12 +00005451
5452 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005453 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlsson72e96fd2010-05-02 22:54:08 +00005454 ConstructKind);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005455}
5456
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005457/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5458/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00005459ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005460Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5461 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00005462 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005463 bool RequiresZeroInit,
John McCall7a1fad32010-08-24 07:32:53 +00005464 unsigned ConstructKind) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00005465 unsigned NumExprs = ExprArgs.size();
5466 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005467
Douglas Gregor7edfb692009-11-23 12:27:39 +00005468 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005469 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00005470 Constructor, Elidable, Exprs, NumExprs,
John McCall7a1fad32010-08-24 07:32:53 +00005471 RequiresZeroInit,
5472 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind)));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005473}
5474
Mike Stump1eb44332009-09-09 15:08:12 +00005475bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005476 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00005477 MultiExprArg Exprs) {
John McCall60d7b3a2010-08-24 06:29:42 +00005478 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00005479 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00005480 move(Exprs), false, CXXConstructExpr::CK_Complete);
Anders Carlssonfe2de492009-08-25 05:18:00 +00005481 if (TempResult.isInvalid())
5482 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005483
Anders Carlssonda3f4e22009-08-25 05:12:04 +00005484 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005485 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00005486 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00005487 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00005488
Anders Carlssonfe2de492009-08-25 05:18:00 +00005489 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00005490}
5491
John McCall68c6c9a2010-02-02 09:10:11 +00005492void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5493 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00005494 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregorfb2db462010-05-22 17:12:29 +00005495 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00005496 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall4f9506a2010-02-02 08:45:54 +00005497 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00005498 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005499 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00005500 << VD->getDeclName()
5501 << VD->getType());
John McCall626e96e2010-08-01 20:20:59 +00005502
5503 if (!VD->isInvalidDecl() && VD->hasGlobalStorage())
5504 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall4f9506a2010-02-02 08:45:54 +00005505 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005506}
5507
Mike Stump1eb44332009-09-09 15:08:12 +00005508/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005509/// ActOnDeclarator, when a C++ direct initializer is present.
5510/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00005511void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005512 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00005513 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005514 SourceLocation *CommaLocs,
5515 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00005516 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005517
5518 // If there is no declaration, there was an error parsing it. Just ignore
5519 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005520 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005521 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005522
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005523 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5524 if (!VDecl) {
5525 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5526 RealDecl->setInvalidDecl();
5527 return;
5528 }
5529
Douglas Gregor83ddad32009-08-26 21:14:46 +00005530 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005531 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005532 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5533 //
5534 // Clients that want to distinguish between the two forms, can check for
5535 // direct initializer using VarDecl::hasCXXDirectInitializer().
5536 // A major benefit is that clients that don't particularly care about which
5537 // exactly form was it (like the CodeGen) can handle both cases without
5538 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005539
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005540 // C++ 8.5p11:
5541 // The form of initialization (using parentheses or '=') is generally
5542 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005543 // class type.
5544
Douglas Gregor4dffad62010-02-11 22:55:30 +00005545 if (!VDecl->getType()->isDependentType() &&
5546 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00005547 diag::err_typecheck_decl_incomplete_type)) {
5548 VDecl->setInvalidDecl();
5549 return;
5550 }
5551
Douglas Gregor90f93822009-12-22 22:17:25 +00005552 // The variable can not have an abstract class type.
5553 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5554 diag::err_abstract_type_in_decl,
5555 AbstractVariableType))
5556 VDecl->setInvalidDecl();
5557
Sebastian Redl31310a22010-02-01 20:16:42 +00005558 const VarDecl *Def;
5559 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00005560 Diag(VDecl->getLocation(), diag::err_redefinition)
5561 << VDecl->getDeclName();
5562 Diag(Def->getLocation(), diag::note_previous_definition);
5563 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005564 return;
5565 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00005566
Douglas Gregor3a91abf2010-08-24 05:27:49 +00005567 // C++ [class.static.data]p4
5568 // If a static data member is of const integral or const
5569 // enumeration type, its declaration in the class definition can
5570 // specify a constant-initializer which shall be an integral
5571 // constant expression (5.19). In that case, the member can appear
5572 // in integral constant expressions. The member shall still be
5573 // defined in a namespace scope if it is used in the program and the
5574 // namespace scope definition shall not contain an initializer.
5575 //
5576 // We already performed a redefinition check above, but for static
5577 // data members we also need to check whether there was an in-class
5578 // declaration with an initializer.
5579 const VarDecl* PrevInit = 0;
5580 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5581 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5582 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5583 return;
5584 }
5585
Douglas Gregor4dffad62010-02-11 22:55:30 +00005586 // If either the declaration has a dependent type or if any of the
5587 // expressions is type-dependent, we represent the initialization
5588 // via a ParenListExpr for later use during template instantiation.
5589 if (VDecl->getType()->isDependentType() ||
5590 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
5591 // Let clients know that initialization was done with a direct initializer.
5592 VDecl->setCXXDirectInitializer(true);
5593
5594 // Store the initialization expressions as a ParenListExpr.
5595 unsigned NumExprs = Exprs.size();
5596 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5597 (Expr **)Exprs.release(),
5598 NumExprs, RParenLoc));
5599 return;
5600 }
Douglas Gregor90f93822009-12-22 22:17:25 +00005601
5602 // Capture the variable that is being initialized and the style of
5603 // initialization.
5604 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5605
5606 // FIXME: Poor source location information.
5607 InitializationKind Kind
5608 = InitializationKind::CreateDirect(VDecl->getLocation(),
5609 LParenLoc, RParenLoc);
5610
5611 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00005612 Exprs.get(), Exprs.size());
John McCall60d7b3a2010-08-24 06:29:42 +00005613 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregor90f93822009-12-22 22:17:25 +00005614 if (Result.isInvalid()) {
5615 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005616 return;
5617 }
Douglas Gregor90f93822009-12-22 22:17:25 +00005618
John McCall9ae2f072010-08-23 23:25:46 +00005619 Result = MaybeCreateCXXExprWithTemporaries(Result.get());
Douglas Gregor838db382010-02-11 01:19:42 +00005620 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005621 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005622
John McCall4204f072010-08-02 21:13:48 +00005623 if (!VDecl->isInvalidDecl() &&
5624 !VDecl->getDeclContext()->isDependentContext() &&
Sebastian Redl36281c62010-09-08 04:46:19 +00005625 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() &&
John McCall4204f072010-08-02 21:13:48 +00005626 !VDecl->getInit()->isConstantInitializer(Context,
5627 VDecl->getType()->isReferenceType()))
5628 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5629 << VDecl->getInit()->getSourceRange();
5630
John McCall68c6c9a2010-02-02 09:10:11 +00005631 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5632 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005633}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00005634
Douglas Gregor39da0b82009-09-09 23:08:42 +00005635/// \brief Given a constructor and the set of arguments provided for the
5636/// constructor, convert the arguments and add any required default arguments
5637/// to form a proper call to this constructor.
5638///
5639/// \returns true if an error occurred, false otherwise.
5640bool
5641Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5642 MultiExprArg ArgsPtr,
5643 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00005644 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00005645 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5646 unsigned NumArgs = ArgsPtr.size();
5647 Expr **Args = (Expr **)ArgsPtr.get();
5648
5649 const FunctionProtoType *Proto
5650 = Constructor->getType()->getAs<FunctionProtoType>();
5651 assert(Proto && "Constructor without a prototype?");
5652 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00005653
5654 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005655 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00005656 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005657 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00005658 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005659
5660 VariadicCallType CallType =
5661 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5662 llvm::SmallVector<Expr *, 8> AllArgs;
5663 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5664 Proto, 0, Args, NumArgs, AllArgs,
5665 CallType);
5666 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5667 ConvertedArgs.push_back(AllArgs[i]);
5668 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00005669}
5670
Anders Carlsson20d45d22009-12-12 00:32:00 +00005671static inline bool
5672CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5673 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00005674 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00005675 if (isa<NamespaceDecl>(DC)) {
5676 return SemaRef.Diag(FnDecl->getLocation(),
5677 diag::err_operator_new_delete_declared_in_namespace)
5678 << FnDecl->getDeclName();
5679 }
5680
5681 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00005682 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005683 return SemaRef.Diag(FnDecl->getLocation(),
5684 diag::err_operator_new_delete_declared_static)
5685 << FnDecl->getDeclName();
5686 }
5687
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00005688 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00005689}
5690
Anders Carlsson156c78e2009-12-13 17:53:43 +00005691static inline bool
5692CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5693 CanQualType ExpectedResultType,
5694 CanQualType ExpectedFirstParamType,
5695 unsigned DependentParamTypeDiag,
5696 unsigned InvalidParamTypeDiag) {
5697 QualType ResultType =
5698 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5699
5700 // Check that the result type is not dependent.
5701 if (ResultType->isDependentType())
5702 return SemaRef.Diag(FnDecl->getLocation(),
5703 diag::err_operator_new_delete_dependent_result_type)
5704 << FnDecl->getDeclName() << ExpectedResultType;
5705
5706 // Check that the result type is what we expect.
5707 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5708 return SemaRef.Diag(FnDecl->getLocation(),
5709 diag::err_operator_new_delete_invalid_result_type)
5710 << FnDecl->getDeclName() << ExpectedResultType;
5711
5712 // A function template must have at least 2 parameters.
5713 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5714 return SemaRef.Diag(FnDecl->getLocation(),
5715 diag::err_operator_new_delete_template_too_few_parameters)
5716 << FnDecl->getDeclName();
5717
5718 // The function decl must have at least 1 parameter.
5719 if (FnDecl->getNumParams() == 0)
5720 return SemaRef.Diag(FnDecl->getLocation(),
5721 diag::err_operator_new_delete_too_few_parameters)
5722 << FnDecl->getDeclName();
5723
5724 // Check the the first parameter type is not dependent.
5725 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5726 if (FirstParamType->isDependentType())
5727 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5728 << FnDecl->getDeclName() << ExpectedFirstParamType;
5729
5730 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00005731 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00005732 ExpectedFirstParamType)
5733 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5734 << FnDecl->getDeclName() << ExpectedFirstParamType;
5735
5736 return false;
5737}
5738
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005739static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00005740CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005741 // C++ [basic.stc.dynamic.allocation]p1:
5742 // A program is ill-formed if an allocation function is declared in a
5743 // namespace scope other than global scope or declared static in global
5744 // scope.
5745 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5746 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00005747
5748 CanQualType SizeTy =
5749 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5750
5751 // C++ [basic.stc.dynamic.allocation]p1:
5752 // The return type shall be void*. The first parameter shall have type
5753 // std::size_t.
5754 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5755 SizeTy,
5756 diag::err_operator_new_dependent_param_type,
5757 diag::err_operator_new_param_type))
5758 return true;
5759
5760 // C++ [basic.stc.dynamic.allocation]p1:
5761 // The first parameter shall not have an associated default argument.
5762 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00005763 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00005764 diag::err_operator_new_default_arg)
5765 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5766
5767 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00005768}
5769
5770static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005771CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5772 // C++ [basic.stc.dynamic.deallocation]p1:
5773 // A program is ill-formed if deallocation functions are declared in a
5774 // namespace scope other than global scope or declared static in global
5775 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00005776 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5777 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005778
5779 // C++ [basic.stc.dynamic.deallocation]p2:
5780 // Each deallocation function shall return void and its first parameter
5781 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00005782 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5783 SemaRef.Context.VoidPtrTy,
5784 diag::err_operator_delete_dependent_param_type,
5785 diag::err_operator_delete_param_type))
5786 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005787
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005788 return false;
5789}
5790
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005791/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5792/// of this overloaded operator is well-formed. If so, returns false;
5793/// otherwise, emits appropriate diagnostics and returns true.
5794bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005795 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005796 "Expected an overloaded operator declaration");
5797
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005798 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5799
Mike Stump1eb44332009-09-09 15:08:12 +00005800 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005801 // The allocation and deallocation functions, operator new,
5802 // operator new[], operator delete and operator delete[], are
5803 // described completely in 3.7.3. The attributes and restrictions
5804 // found in the rest of this subclause do not apply to them unless
5805 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00005806 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005807 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00005808
Anders Carlssona3ccda52009-12-12 00:26:23 +00005809 if (Op == OO_New || Op == OO_Array_New)
5810 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005811
5812 // C++ [over.oper]p6:
5813 // An operator function shall either be a non-static member
5814 // function or be a non-member function and have at least one
5815 // parameter whose type is a class, a reference to a class, an
5816 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005817 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5818 if (MethodDecl->isStatic())
5819 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005820 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005821 } else {
5822 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005823 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5824 ParamEnd = FnDecl->param_end();
5825 Param != ParamEnd; ++Param) {
5826 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00005827 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5828 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005829 ClassOrEnumParam = true;
5830 break;
5831 }
5832 }
5833
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005834 if (!ClassOrEnumParam)
5835 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005836 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005837 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005838 }
5839
5840 // C++ [over.oper]p8:
5841 // An operator function cannot have default arguments (8.3.6),
5842 // except where explicitly stated below.
5843 //
Mike Stump1eb44332009-09-09 15:08:12 +00005844 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005845 // (C++ [over.call]p1).
5846 if (Op != OO_Call) {
5847 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5848 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00005849 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00005850 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00005851 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00005852 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005853 }
5854 }
5855
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005856 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5857 { false, false, false }
5858#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5859 , { Unary, Binary, MemberOnly }
5860#include "clang/Basic/OperatorKinds.def"
5861 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005862
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005863 bool CanBeUnaryOperator = OperatorUses[Op][0];
5864 bool CanBeBinaryOperator = OperatorUses[Op][1];
5865 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005866
5867 // C++ [over.oper]p8:
5868 // [...] Operator functions cannot have more or fewer parameters
5869 // than the number required for the corresponding operator, as
5870 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00005871 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005872 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005873 if (Op != OO_Call &&
5874 ((NumParams == 1 && !CanBeUnaryOperator) ||
5875 (NumParams == 2 && !CanBeBinaryOperator) ||
5876 (NumParams < 1) || (NumParams > 2))) {
5877 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00005878 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005879 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005880 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005881 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005882 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005883 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005884 assert(CanBeBinaryOperator &&
5885 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00005886 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005887 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005888
Chris Lattner416e46f2008-11-21 07:57:12 +00005889 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005890 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005891 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005892
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005893 // Overloaded operators other than operator() cannot be variadic.
5894 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00005895 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005896 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005897 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005898 }
5899
5900 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005901 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5902 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005903 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005904 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005905 }
5906
5907 // C++ [over.inc]p1:
5908 // The user-defined function called operator++ implements the
5909 // prefix and postfix ++ operator. If this function is a member
5910 // function with no parameters, or a non-member function with one
5911 // parameter of class or enumeration type, it defines the prefix
5912 // increment operator ++ for objects of that type. If the function
5913 // is a member function with one parameter (which shall be of type
5914 // int) or a non-member function with two parameters (the second
5915 // of which shall be of type int), it defines the postfix
5916 // increment operator ++ for objects of that type.
5917 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5918 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5919 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005920 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005921 ParamIsInt = BT->getKind() == BuiltinType::Int;
5922
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005923 if (!ParamIsInt)
5924 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005925 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005926 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005927 }
5928
Sebastian Redl64b45f72009-01-05 20:52:13 +00005929 // Notify the class if it got an assignment operator.
5930 if (Op == OO_Equal) {
5931 // Would have returned earlier otherwise.
5932 assert(isa<CXXMethodDecl>(FnDecl) &&
5933 "Overloaded = not member, but not filtered.");
5934 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5935 Method->getParent()->addedAssignmentOperator(Context, Method);
5936 }
5937
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005938 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005939}
Chris Lattner5a003a42008-12-17 07:09:26 +00005940
Sean Hunta6c058d2010-01-13 09:01:02 +00005941/// CheckLiteralOperatorDeclaration - Check whether the declaration
5942/// of this literal operator function is well-formed. If so, returns
5943/// false; otherwise, emits appropriate diagnostics and returns true.
5944bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5945 DeclContext *DC = FnDecl->getDeclContext();
5946 Decl::Kind Kind = DC->getDeclKind();
5947 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5948 Kind != Decl::LinkageSpec) {
5949 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5950 << FnDecl->getDeclName();
5951 return true;
5952 }
5953
5954 bool Valid = false;
5955
Sean Hunt216c2782010-04-07 23:11:06 +00005956 // template <char...> type operator "" name() is the only valid template
5957 // signature, and the only valid signature with no parameters.
5958 if (FnDecl->param_size() == 0) {
5959 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5960 // Must have only one template parameter
5961 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5962 if (Params->size() == 1) {
5963 NonTypeTemplateParmDecl *PmDecl =
5964 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00005965
Sean Hunt216c2782010-04-07 23:11:06 +00005966 // The template parameter must be a char parameter pack.
5967 // FIXME: This test will always fail because non-type parameter packs
5968 // have not been implemented.
5969 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5970 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5971 Valid = true;
5972 }
5973 }
5974 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00005975 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00005976 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5977
Sean Hunta6c058d2010-01-13 09:01:02 +00005978 QualType T = (*Param)->getType();
5979
Sean Hunt30019c02010-04-07 22:57:35 +00005980 // unsigned long long int, long double, and any character type are allowed
5981 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00005982 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5983 Context.hasSameType(T, Context.LongDoubleTy) ||
5984 Context.hasSameType(T, Context.CharTy) ||
5985 Context.hasSameType(T, Context.WCharTy) ||
5986 Context.hasSameType(T, Context.Char16Ty) ||
5987 Context.hasSameType(T, Context.Char32Ty)) {
5988 if (++Param == FnDecl->param_end())
5989 Valid = true;
5990 goto FinishedParams;
5991 }
5992
Sean Hunt30019c02010-04-07 22:57:35 +00005993 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00005994 const PointerType *PT = T->getAs<PointerType>();
5995 if (!PT)
5996 goto FinishedParams;
5997 T = PT->getPointeeType();
5998 if (!T.isConstQualified())
5999 goto FinishedParams;
6000 T = T.getUnqualifiedType();
6001
6002 // Move on to the second parameter;
6003 ++Param;
6004
6005 // If there is no second parameter, the first must be a const char *
6006 if (Param == FnDecl->param_end()) {
6007 if (Context.hasSameType(T, Context.CharTy))
6008 Valid = true;
6009 goto FinishedParams;
6010 }
6011
6012 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6013 // are allowed as the first parameter to a two-parameter function
6014 if (!(Context.hasSameType(T, Context.CharTy) ||
6015 Context.hasSameType(T, Context.WCharTy) ||
6016 Context.hasSameType(T, Context.Char16Ty) ||
6017 Context.hasSameType(T, Context.Char32Ty)))
6018 goto FinishedParams;
6019
6020 // The second and final parameter must be an std::size_t
6021 T = (*Param)->getType().getUnqualifiedType();
6022 if (Context.hasSameType(T, Context.getSizeType()) &&
6023 ++Param == FnDecl->param_end())
6024 Valid = true;
6025 }
6026
6027 // FIXME: This diagnostic is absolutely terrible.
6028FinishedParams:
6029 if (!Valid) {
6030 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6031 << FnDecl->getDeclName();
6032 return true;
6033 }
6034
6035 return false;
6036}
6037
Douglas Gregor074149e2009-01-05 19:45:36 +00006038/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6039/// linkage specification, including the language and (if present)
6040/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6041/// the location of the language string literal, which is provided
6042/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6043/// the '{' brace. Otherwise, this linkage specification does not
6044/// have any braces.
John McCalld226f652010-08-21 09:40:31 +00006045Decl *Sema::ActOnStartLinkageSpecification(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006046 SourceLocation ExternLoc,
6047 SourceLocation LangLoc,
Benjamin Kramerd5663812010-05-03 13:08:54 +00006048 llvm::StringRef Lang,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006049 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00006050 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006051 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006052 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006053 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006054 Language = LinkageSpecDecl::lang_cxx;
6055 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00006056 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00006057 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006058 }
Mike Stump1eb44332009-09-09 15:08:12 +00006059
Chris Lattnercc98eac2008-12-17 07:13:27 +00006060 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00006061
Douglas Gregor074149e2009-01-05 19:45:36 +00006062 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00006063 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00006064 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006065 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00006066 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00006067 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006068}
6069
Abramo Bagnara35f9a192010-07-30 16:47:02 +00006070/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006071/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6072/// valid, it's the position of the closing '}' brace in a linkage
6073/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006074Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6075 Decl *LinkageSpec,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006076 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00006077 if (LinkageSpec)
6078 PopDeclContext();
6079 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006080}
6081
Douglas Gregord308e622009-05-18 20:51:54 +00006082/// \brief Perform semantic analysis for the variable declaration that
6083/// occurs within a C++ catch clause, returning the newly-created
6084/// variable.
6085VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00006086 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006087 IdentifierInfo *Name,
6088 SourceLocation Loc,
6089 SourceRange Range) {
6090 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006091
6092 // Arrays and functions decay.
6093 if (ExDeclType->isArrayType())
6094 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6095 else if (ExDeclType->isFunctionType())
6096 ExDeclType = Context.getPointerType(ExDeclType);
6097
6098 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6099 // The exception-declaration shall not denote a pointer or reference to an
6100 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006101 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006102 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00006103 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006104 Invalid = true;
6105 }
Douglas Gregord308e622009-05-18 20:51:54 +00006106
Douglas Gregora2762912010-03-08 01:47:36 +00006107 // GCC allows catching pointers and references to incomplete types
6108 // as an extension; so do we, but we warn by default.
6109
Sebastian Redl4b07b292008-12-22 19:15:10 +00006110 QualType BaseType = ExDeclType;
6111 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006112 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006113 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006114 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006115 BaseType = Ptr->getPointeeType();
6116 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006117 DK = diag::ext_catch_incomplete_ptr;
6118 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006119 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006120 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006121 BaseType = Ref->getPointeeType();
6122 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006123 DK = diag::ext_catch_incomplete_ref;
6124 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006125 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006126 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006127 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6128 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006129 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006130
Mike Stump1eb44332009-09-09 15:08:12 +00006131 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006132 RequireNonAbstractType(Loc, ExDeclType,
6133 diag::err_abstract_type_in_decl,
6134 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006135 Invalid = true;
6136
John McCall5a180392010-07-24 00:37:23 +00006137 // Only the non-fragile NeXT runtime currently supports C++ catches
6138 // of ObjC types, and no runtime supports catching ObjC types by value.
6139 if (!Invalid && getLangOptions().ObjC1) {
6140 QualType T = ExDeclType;
6141 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6142 T = RT->getPointeeType();
6143
6144 if (T->isObjCObjectType()) {
6145 Diag(Loc, diag::err_objc_object_catch);
6146 Invalid = true;
6147 } else if (T->isObjCObjectPointerType()) {
6148 if (!getLangOptions().NeXTRuntime) {
6149 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6150 Invalid = true;
6151 } else if (!getLangOptions().ObjCNonFragileABI) {
6152 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6153 Invalid = true;
6154 }
6155 }
6156 }
6157
Mike Stump1eb44332009-09-09 15:08:12 +00006158 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCalld931b082010-08-26 03:08:43 +00006159 Name, ExDeclType, TInfo, SC_None,
6160 SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006161 ExDecl->setExceptionVariable(true);
6162
Douglas Gregor6d182892010-03-05 23:38:39 +00006163 if (!Invalid) {
6164 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6165 // C++ [except.handle]p16:
6166 // The object declared in an exception-declaration or, if the
6167 // exception-declaration does not specify a name, a temporary (12.2) is
6168 // copy-initialized (8.5) from the exception object. [...]
6169 // The object is destroyed when the handler exits, after the destruction
6170 // of any automatic objects initialized within the handler.
6171 //
6172 // We just pretend to initialize the object with itself, then make sure
6173 // it can be destroyed later.
6174 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6175 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
6176 Loc, ExDeclType, 0);
6177 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6178 SourceLocation());
6179 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00006180 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00006181 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6d182892010-03-05 23:38:39 +00006182 if (Result.isInvalid())
6183 Invalid = true;
6184 else
6185 FinalizeVarWithDestructor(ExDecl, RecordTy);
6186 }
6187 }
6188
Douglas Gregord308e622009-05-18 20:51:54 +00006189 if (Invalid)
6190 ExDecl->setInvalidDecl();
6191
6192 return ExDecl;
6193}
6194
6195/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6196/// handler.
John McCalld226f652010-08-21 09:40:31 +00006197Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006198 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6199 QualType ExDeclType = TInfo->getType();
Douglas Gregord308e622009-05-18 20:51:54 +00006200
6201 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00006202 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006203 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006204 LookupOrdinaryName,
6205 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006206 // The scope should be freshly made just for us. There is just no way
6207 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006208 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006209 if (PrevDecl->isTemplateParameter()) {
6210 // Maybe we will complain about the shadowed template parameter.
6211 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006212 }
6213 }
6214
Chris Lattnereaaebc72009-04-25 08:06:05 +00006215 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006216 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6217 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006218 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006219 }
6220
John McCalla93c9342009-12-07 02:54:59 +00006221 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006222 D.getIdentifier(),
6223 D.getIdentifierLoc(),
6224 D.getDeclSpec().getSourceRange());
6225
Chris Lattnereaaebc72009-04-25 08:06:05 +00006226 if (Invalid)
6227 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00006228
Sebastian Redl4b07b292008-12-22 19:15:10 +00006229 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006230 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00006231 PushOnScopeChains(ExDecl, S);
6232 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006233 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006234
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006235 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00006236 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006237}
Anders Carlssonfb311762009-03-14 00:25:26 +00006238
John McCalld226f652010-08-21 09:40:31 +00006239Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00006240 Expr *AssertExpr,
6241 Expr *AssertMessageExpr_) {
6242 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00006243
Anders Carlssonc3082412009-03-14 00:33:21 +00006244 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6245 llvm::APSInt Value(32);
6246 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6247 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6248 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006249 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00006250 }
Anders Carlssonfb311762009-03-14 00:25:26 +00006251
Anders Carlssonc3082412009-03-14 00:33:21 +00006252 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00006253 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00006254 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00006255 }
6256 }
Mike Stump1eb44332009-09-09 15:08:12 +00006257
Mike Stump1eb44332009-09-09 15:08:12 +00006258 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00006259 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00006260
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006261 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00006262 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00006263}
Sebastian Redl50de12f2009-03-24 22:27:57 +00006264
Douglas Gregor1d869352010-04-07 16:53:43 +00006265/// \brief Perform semantic analysis of the given friend type declaration.
6266///
6267/// \returns A friend declaration that.
6268FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6269 TypeSourceInfo *TSInfo) {
6270 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6271
6272 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006273 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00006274
Douglas Gregor06245bf2010-04-07 17:57:12 +00006275 if (!getLangOptions().CPlusPlus0x) {
6276 // C++03 [class.friend]p2:
6277 // An elaborated-type-specifier shall be used in a friend declaration
6278 // for a class.*
6279 //
6280 // * The class-key of the elaborated-type-specifier is required.
6281 if (!ActiveTemplateInstantiations.empty()) {
6282 // Do not complain about the form of friend template types during
6283 // template instantiation; we will already have complained when the
6284 // template was declared.
6285 } else if (!T->isElaboratedTypeSpecifier()) {
6286 // If we evaluated the type to a record type, suggest putting
6287 // a tag in front.
6288 if (const RecordType *RT = T->getAs<RecordType>()) {
6289 RecordDecl *RD = RT->getDecl();
6290
6291 std::string InsertionText = std::string(" ") + RD->getKindName();
6292
6293 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6294 << (unsigned) RD->getTagKind()
6295 << T
6296 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6297 InsertionText);
6298 } else {
6299 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6300 << T
6301 << SourceRange(FriendLoc, TypeRange.getEnd());
6302 }
6303 } else if (T->getAs<EnumType>()) {
6304 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00006305 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00006306 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00006307 }
6308 }
6309
Douglas Gregor06245bf2010-04-07 17:57:12 +00006310 // C++0x [class.friend]p3:
6311 // If the type specifier in a friend declaration designates a (possibly
6312 // cv-qualified) class type, that class is declared as a friend; otherwise,
6313 // the friend declaration is ignored.
6314
6315 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6316 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00006317
6318 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6319}
6320
John McCalldd4a3b02009-09-16 22:47:08 +00006321/// Handle a friend type declaration. This works in tandem with
6322/// ActOnTag.
6323///
6324/// Notes on friend class templates:
6325///
6326/// We generally treat friend class declarations as if they were
6327/// declaring a class. So, for example, the elaborated type specifier
6328/// in a friend declaration is required to obey the restrictions of a
6329/// class-head (i.e. no typedefs in the scope chain), template
6330/// parameters are required to match up with simple template-ids, &c.
6331/// However, unlike when declaring a template specialization, it's
6332/// okay to refer to a template specialization without an empty
6333/// template parameter declaration, e.g.
6334/// friend class A<T>::B<unsigned>;
6335/// We permit this as a special case; if there are any template
6336/// parameters present at all, require proper matching, i.e.
6337/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00006338Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00006339 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00006340 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00006341
6342 assert(DS.isFriendSpecified());
6343 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6344
John McCalldd4a3b02009-09-16 22:47:08 +00006345 // Try to convert the decl specifier to a type. This works for
6346 // friend templates because ActOnTag never produces a ClassTemplateDecl
6347 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00006348 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00006349 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6350 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00006351 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00006352 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006353
John McCalldd4a3b02009-09-16 22:47:08 +00006354 // This is definitely an error in C++98. It's probably meant to
6355 // be forbidden in C++0x, too, but the specification is just
6356 // poorly written.
6357 //
6358 // The problem is with declarations like the following:
6359 // template <T> friend A<T>::foo;
6360 // where deciding whether a class C is a friend or not now hinges
6361 // on whether there exists an instantiation of A that causes
6362 // 'foo' to equal C. There are restrictions on class-heads
6363 // (which we declare (by fiat) elaborated friend declarations to
6364 // be) that makes this tractable.
6365 //
6366 // FIXME: handle "template <> friend class A<T>;", which
6367 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00006368 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00006369 Diag(Loc, diag::err_tagless_friend_type_template)
6370 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006371 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00006372 }
Douglas Gregor1d869352010-04-07 16:53:43 +00006373
John McCall02cace72009-08-28 07:59:38 +00006374 // C++98 [class.friend]p1: A friend of a class is a function
6375 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00006376 // This is fixed in DR77, which just barely didn't make the C++03
6377 // deadline. It's also a very silly restriction that seriously
6378 // affects inner classes and which nobody else seems to implement;
6379 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00006380 //
6381 // But note that we could warn about it: it's always useless to
6382 // friend one of your own members (it's not, however, worthless to
6383 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00006384
John McCalldd4a3b02009-09-16 22:47:08 +00006385 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00006386 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00006387 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00006388 NumTempParamLists,
John McCalldd4a3b02009-09-16 22:47:08 +00006389 (TemplateParameterList**) TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00006390 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00006391 DS.getFriendSpecLoc());
6392 else
Douglas Gregor1d869352010-04-07 16:53:43 +00006393 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6394
6395 if (!D)
John McCalld226f652010-08-21 09:40:31 +00006396 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00006397
John McCalldd4a3b02009-09-16 22:47:08 +00006398 D->setAccess(AS_public);
6399 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00006400
John McCalld226f652010-08-21 09:40:31 +00006401 return D;
John McCall02cace72009-08-28 07:59:38 +00006402}
6403
John McCalld226f652010-08-21 09:40:31 +00006404Decl *Sema::ActOnFriendFunctionDecl(Scope *S,
6405 Declarator &D,
6406 bool IsDefinition,
John McCallbbbcdd92009-09-11 21:02:39 +00006407 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00006408 const DeclSpec &DS = D.getDeclSpec();
6409
6410 assert(DS.isFriendSpecified());
6411 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6412
6413 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00006414 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6415 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00006416
6417 // C++ [class.friend]p1
6418 // A friend of a class is a function or class....
6419 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00006420 // It *doesn't* see through dependent types, which is correct
6421 // according to [temp.arg.type]p3:
6422 // If a declaration acquires a function type through a
6423 // type dependent on a template-parameter and this causes
6424 // a declaration that does not use the syntactic form of a
6425 // function declarator to have a function type, the program
6426 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00006427 if (!T->isFunctionType()) {
6428 Diag(Loc, diag::err_unexpected_friend);
6429
6430 // It might be worthwhile to try to recover by creating an
6431 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00006432 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006433 }
6434
6435 // C++ [namespace.memdef]p3
6436 // - If a friend declaration in a non-local class first declares a
6437 // class or function, the friend class or function is a member
6438 // of the innermost enclosing namespace.
6439 // - The name of the friend is not found by simple name lookup
6440 // until a matching declaration is provided in that namespace
6441 // scope (either before or after the class declaration granting
6442 // friendship).
6443 // - If a friend function is called, its name may be found by the
6444 // name lookup that considers functions from namespaces and
6445 // classes associated with the types of the function arguments.
6446 // - When looking for a prior declaration of a class or a function
6447 // declared as a friend, scopes outside the innermost enclosing
6448 // namespace scope are not considered.
6449
John McCall02cace72009-08-28 07:59:38 +00006450 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00006451 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6452 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00006453 assert(Name);
6454
John McCall67d1a672009-08-06 02:15:43 +00006455 // The context we found the declaration in, or in which we should
6456 // create the declaration.
6457 DeclContext *DC;
6458
6459 // FIXME: handle local classes
6460
6461 // Recover from invalid scope qualifiers as if they just weren't there.
Abramo Bagnara25777432010-08-11 22:01:17 +00006462 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00006463 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00006464 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
6465 DC = computeDeclContext(ScopeQual);
6466
6467 // FIXME: handle dependent contexts
John McCalld226f652010-08-21 09:40:31 +00006468 if (!DC) return 0;
6469 if (RequireCompleteDeclContext(ScopeQual, DC)) return 0;
John McCall67d1a672009-08-06 02:15:43 +00006470
John McCall68263142009-11-18 22:49:29 +00006471 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00006472
John McCall9da9cdf2010-05-28 01:41:47 +00006473 // Ignore things found implicitly in the wrong scope.
John McCall67d1a672009-08-06 02:15:43 +00006474 // TODO: better diagnostics for this case. Suggesting the right
6475 // qualified scope would be nice...
John McCall9da9cdf2010-05-28 01:41:47 +00006476 LookupResult::Filter F = Previous.makeFilter();
6477 while (F.hasNext()) {
6478 NamedDecl *D = F.next();
Sebastian Redl7a126a42010-08-31 00:36:30 +00006479 if (!DC->InEnclosingNamespaceSetOf(
6480 D->getDeclContext()->getRedeclContext()))
John McCall9da9cdf2010-05-28 01:41:47 +00006481 F.erase();
6482 }
6483 F.done();
6484
6485 if (Previous.empty()) {
John McCall02cace72009-08-28 07:59:38 +00006486 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00006487 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
John McCalld226f652010-08-21 09:40:31 +00006488 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006489 }
6490
6491 // C++ [class.friend]p1: A friend of a class is a function or
6492 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00006493 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00006494 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6495
John McCall67d1a672009-08-06 02:15:43 +00006496 // Otherwise walk out to the nearest namespace scope looking for matches.
6497 } else {
6498 // TODO: handle local class contexts.
6499
6500 DC = CurContext;
6501 while (true) {
6502 // Skip class contexts. If someone can cite chapter and verse
6503 // for this behavior, that would be nice --- it's what GCC and
6504 // EDG do, and it seems like a reasonable intent, but the spec
6505 // really only says that checks for unqualified existing
6506 // declarations should stop at the nearest enclosing namespace,
6507 // not that they should only consider the nearest enclosing
6508 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00006509 while (DC->isRecord())
6510 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00006511
John McCall68263142009-11-18 22:49:29 +00006512 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00006513
6514 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00006515 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00006516 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00006517
John McCall67d1a672009-08-06 02:15:43 +00006518 if (DC->isFileContext()) break;
6519 DC = DC->getParent();
6520 }
6521
6522 // C++ [class.friend]p1: A friend of a class is a function or
6523 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00006524 // C++0x changes this for both friend types and functions.
6525 // Most C++ 98 compilers do seem to give an error here, so
6526 // we do, too.
John McCall68263142009-11-18 22:49:29 +00006527 if (!Previous.empty() && DC->Equals(CurContext)
6528 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00006529 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6530 }
6531
Douglas Gregor182ddf02009-09-28 00:08:27 +00006532 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00006533 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006534 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6535 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6536 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00006537 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006538 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6539 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00006540 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006541 }
John McCall67d1a672009-08-06 02:15:43 +00006542 }
6543
Douglas Gregor182ddf02009-09-28 00:08:27 +00006544 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00006545 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00006546 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00006547 IsDefinition,
6548 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00006549 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00006550
Douglas Gregor182ddf02009-09-28 00:08:27 +00006551 assert(ND->getDeclContext() == DC);
6552 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00006553
John McCallab88d972009-08-31 22:39:49 +00006554 // Add the function declaration to the appropriate lookup tables,
6555 // adjusting the redeclarations list as necessary. We don't
6556 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00006557 //
John McCallab88d972009-08-31 22:39:49 +00006558 // Also update the scope-based lookup if the target context's
6559 // lookup context is in lexical scope.
6560 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00006561 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00006562 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006563 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00006564 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006565 }
John McCall02cace72009-08-28 07:59:38 +00006566
6567 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00006568 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00006569 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00006570 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00006571 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00006572
John McCalld226f652010-08-21 09:40:31 +00006573 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00006574}
6575
John McCalld226f652010-08-21 09:40:31 +00006576void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6577 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00006578
Sebastian Redl50de12f2009-03-24 22:27:57 +00006579 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6580 if (!Fn) {
6581 Diag(DelLoc, diag::err_deleted_non_function);
6582 return;
6583 }
6584 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6585 Diag(DelLoc, diag::err_deleted_decl_not_first);
6586 Diag(Prev->getLocation(), diag::note_previous_declaration);
6587 // If the declaration wasn't the first, we delete the function anyway for
6588 // recovery.
6589 }
6590 Fn->setDeleted();
6591}
Sebastian Redl13e88542009-04-27 21:33:24 +00006592
6593static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6594 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6595 ++CI) {
6596 Stmt *SubStmt = *CI;
6597 if (!SubStmt)
6598 continue;
6599 if (isa<ReturnStmt>(SubStmt))
6600 Self.Diag(SubStmt->getSourceRange().getBegin(),
6601 diag::err_return_in_constructor_handler);
6602 if (!isa<Expr>(SubStmt))
6603 SearchForReturnInStmt(Self, SubStmt);
6604 }
6605}
6606
6607void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6608 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6609 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6610 SearchForReturnInStmt(*this, Handler);
6611 }
6612}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006613
Mike Stump1eb44332009-09-09 15:08:12 +00006614bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006615 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00006616 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6617 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006618
Chandler Carruth73857792010-02-15 11:53:20 +00006619 if (Context.hasSameType(NewTy, OldTy) ||
6620 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006621 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006622
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006623 // Check if the return types are covariant
6624 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00006625
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006626 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006627 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6628 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006629 NewClassTy = NewPT->getPointeeType();
6630 OldClassTy = OldPT->getPointeeType();
6631 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006632 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6633 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6634 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6635 NewClassTy = NewRT->getPointeeType();
6636 OldClassTy = OldRT->getPointeeType();
6637 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006638 }
6639 }
Mike Stump1eb44332009-09-09 15:08:12 +00006640
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006641 // The return types aren't either both pointers or references to a class type.
6642 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006643 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006644 diag::err_different_return_type_for_overriding_virtual_function)
6645 << New->getDeclName() << NewTy << OldTy;
6646 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00006647
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006648 return true;
6649 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006650
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006651 // C++ [class.virtual]p6:
6652 // If the return type of D::f differs from the return type of B::f, the
6653 // class type in the return type of D::f shall be complete at the point of
6654 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00006655 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6656 if (!RT->isBeingDefined() &&
6657 RequireCompleteType(New->getLocation(), NewClassTy,
6658 PDiag(diag::err_covariant_return_incomplete)
6659 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006660 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00006661 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006662
Douglas Gregora4923eb2009-11-16 21:35:15 +00006663 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006664 // Check if the new class derives from the old class.
6665 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6666 Diag(New->getLocation(),
6667 diag::err_covariant_return_not_derived)
6668 << New->getDeclName() << NewTy << OldTy;
6669 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6670 return true;
6671 }
Mike Stump1eb44332009-09-09 15:08:12 +00006672
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006673 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00006674 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00006675 diag::err_covariant_return_inaccessible_base,
6676 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6677 // FIXME: Should this point to the return type?
6678 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006679 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6680 return true;
6681 }
6682 }
Mike Stump1eb44332009-09-09 15:08:12 +00006683
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006684 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006685 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006686 Diag(New->getLocation(),
6687 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006688 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006689 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6690 return true;
6691 };
Mike Stump1eb44332009-09-09 15:08:12 +00006692
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006693
6694 // The new class type must have the same or less qualifiers as the old type.
6695 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6696 Diag(New->getLocation(),
6697 diag::err_covariant_return_type_class_type_more_qualified)
6698 << New->getDeclName() << NewTy << OldTy;
6699 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6700 return true;
6701 };
Mike Stump1eb44332009-09-09 15:08:12 +00006702
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006703 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006704}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006705
Sean Huntbbd37c62009-11-21 08:43:09 +00006706bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6707 const CXXMethodDecl *Old)
6708{
6709 if (Old->hasAttr<FinalAttr>()) {
6710 Diag(New->getLocation(), diag::err_final_function_overridden)
6711 << New->getDeclName();
6712 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6713 return true;
6714 }
6715
6716 return false;
6717}
6718
Douglas Gregor4ba31362009-12-01 17:24:26 +00006719/// \brief Mark the given method pure.
6720///
6721/// \param Method the method to be marked pure.
6722///
6723/// \param InitRange the source range that covers the "0" initializer.
6724bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6725 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6726 Method->setPure();
6727
6728 // A class is abstract if at least one function is pure virtual.
6729 Method->getParent()->setAbstract(true);
6730 return false;
6731 }
6732
6733 if (!Method->isInvalidDecl())
6734 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6735 << Method->getDeclName() << InitRange;
6736 return true;
6737}
6738
John McCall731ad842009-12-19 09:28:58 +00006739/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6740/// an initializer for the out-of-line declaration 'Dcl'. The scope
6741/// is a fresh scope pushed for just this purpose.
6742///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006743/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6744/// static data member of class X, names should be looked up in the scope of
6745/// class X.
John McCalld226f652010-08-21 09:40:31 +00006746void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006747 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006748 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006749
John McCall731ad842009-12-19 09:28:58 +00006750 // We should only get called for declarations with scope specifiers, like:
6751 // int foo::bar;
6752 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006753 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006754}
6755
6756/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00006757/// initializer for the out-of-line declaration 'D'.
6758void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006759 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006760 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006761
John McCall731ad842009-12-19 09:28:58 +00006762 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006763 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006764}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006765
6766/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6767/// C++ if/switch/while/for statement.
6768/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00006769DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006770 // C++ 6.4p2:
6771 // The declarator shall not specify a function or an array.
6772 // The type-specifier-seq shall not contain typedef and shall not declare a
6773 // new class or enumeration.
6774 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6775 "Parser allowed 'typedef' as storage class of condition decl.");
6776
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006777 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00006778 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6779 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006780
6781 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6782 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6783 // would be created and CXXConditionDeclExpr wants a VarDecl.
6784 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6785 << D.getSourceRange();
6786 return DeclResult();
6787 } else if (OwnedTag && OwnedTag->isDefinition()) {
6788 // The type-specifier-seq shall not declare a new class or enumeration.
6789 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6790 }
6791
John McCalld226f652010-08-21 09:40:31 +00006792 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006793 if (!Dcl)
6794 return DeclResult();
6795
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006796 return Dcl;
6797}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006798
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006799void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6800 bool DefinitionRequired) {
6801 // Ignore any vtable uses in unevaluated operands or for classes that do
6802 // not have a vtable.
6803 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6804 CurContext->isDependentContext() ||
6805 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00006806 return;
6807
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006808 // Try to insert this class into the map.
6809 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6810 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6811 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6812 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00006813 // If we already had an entry, check to see if we are promoting this vtable
6814 // to required a definition. If so, we need to reappend to the VTableUses
6815 // list, since we may have already processed the first entry.
6816 if (DefinitionRequired && !Pos.first->second) {
6817 Pos.first->second = true;
6818 } else {
6819 // Otherwise, we can early exit.
6820 return;
6821 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006822 }
6823
6824 // Local classes need to have their virtual members marked
6825 // immediately. For all other classes, we mark their virtual members
6826 // at the end of the translation unit.
6827 if (Class->isLocalClass())
6828 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00006829 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006830 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00006831}
6832
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006833bool Sema::DefineUsedVTables() {
6834 // If any dynamic classes have their key function defined within
6835 // this translation unit, then those vtables are considered "used" and must
6836 // be emitted.
6837 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6838 if (const CXXMethodDecl *KeyFunction
6839 = Context.getKeyFunction(DynamicClasses[I])) {
6840 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006841 if (KeyFunction->hasBody(Definition))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006842 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6843 }
6844 }
6845
6846 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00006847 return false;
6848
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006849 // Note: The VTableUses vector could grow as a result of marking
6850 // the members of a class as "used", so we check the size each
6851 // time through the loop and prefer indices (with are stable) to
6852 // iterators (which are not).
6853 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00006854 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006855 if (!Class)
6856 continue;
6857
6858 SourceLocation Loc = VTableUses[I].second;
6859
6860 // If this class has a key function, but that key function is
6861 // defined in another translation unit, we don't need to emit the
6862 // vtable even though we're using it.
6863 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006864 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006865 switch (KeyFunction->getTemplateSpecializationKind()) {
6866 case TSK_Undeclared:
6867 case TSK_ExplicitSpecialization:
6868 case TSK_ExplicitInstantiationDeclaration:
6869 // The key function is in another translation unit.
6870 continue;
6871
6872 case TSK_ExplicitInstantiationDefinition:
6873 case TSK_ImplicitInstantiation:
6874 // We will be instantiating the key function.
6875 break;
6876 }
6877 } else if (!KeyFunction) {
6878 // If we have a class with no key function that is the subject
6879 // of an explicit instantiation declaration, suppress the
6880 // vtable; it will live with the explicit instantiation
6881 // definition.
6882 bool IsExplicitInstantiationDeclaration
6883 = Class->getTemplateSpecializationKind()
6884 == TSK_ExplicitInstantiationDeclaration;
6885 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6886 REnd = Class->redecls_end();
6887 R != REnd; ++R) {
6888 TemplateSpecializationKind TSK
6889 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6890 if (TSK == TSK_ExplicitInstantiationDeclaration)
6891 IsExplicitInstantiationDeclaration = true;
6892 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6893 IsExplicitInstantiationDeclaration = false;
6894 break;
6895 }
6896 }
6897
6898 if (IsExplicitInstantiationDeclaration)
6899 continue;
6900 }
6901
6902 // Mark all of the virtual members of this class as referenced, so
6903 // that we can build a vtable. Then, tell the AST consumer that a
6904 // vtable for this class is required.
6905 MarkVirtualMembersReferenced(Loc, Class);
6906 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6907 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6908
6909 // Optionally warn if we're emitting a weak vtable.
6910 if (Class->getLinkage() == ExternalLinkage &&
6911 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006912 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006913 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6914 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006915 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006916 VTableUses.clear();
6917
Anders Carlssond6a637f2009-12-07 08:24:59 +00006918 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006919}
Anders Carlssond6a637f2009-12-07 08:24:59 +00006920
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006921void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6922 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00006923 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6924 e = RD->method_end(); i != e; ++i) {
6925 CXXMethodDecl *MD = *i;
6926
6927 // C++ [basic.def.odr]p2:
6928 // [...] A virtual member function is used if it is not pure. [...]
6929 if (MD->isVirtual() && !MD->isPure())
6930 MarkDeclarationReferenced(Loc, MD);
6931 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006932
6933 // Only classes that have virtual bases need a VTT.
6934 if (RD->getNumVBases() == 0)
6935 return;
6936
6937 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6938 e = RD->bases_end(); i != e; ++i) {
6939 const CXXRecordDecl *Base =
6940 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006941 if (Base->getNumVBases() == 0)
6942 continue;
6943 MarkVirtualMembersReferenced(Loc, Base);
6944 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00006945}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006946
6947/// SetIvarInitializers - This routine builds initialization ASTs for the
6948/// Objective-C implementation whose ivars need be initialized.
6949void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6950 if (!getLangOptions().CPlusPlus)
6951 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00006952 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006953 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6954 CollectIvarsToConstructOrDestruct(OID, ivars);
6955 if (ivars.empty())
6956 return;
6957 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6958 for (unsigned i = 0; i < ivars.size(); i++) {
6959 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00006960 if (Field->isInvalidDecl())
6961 continue;
6962
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006963 CXXBaseOrMemberInitializer *Member;
6964 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6965 InitializationKind InitKind =
6966 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6967
6968 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00006969 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00006970 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00006971 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006972 // Note, MemberInit could actually come back empty if no initialization
6973 // is required (e.g., because it would call a trivial default constructor)
6974 if (!MemberInit.get() || MemberInit.isInvalid())
6975 continue;
6976
6977 Member =
6978 new (Context) CXXBaseOrMemberInitializer(Context,
6979 Field, SourceLocation(),
6980 SourceLocation(),
6981 MemberInit.takeAs<Expr>(),
6982 SourceLocation());
6983 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00006984
6985 // Be sure that the destructor is accessible and is marked as referenced.
6986 if (const RecordType *RecordTy
6987 = Context.getBaseElementType(Field->getType())
6988 ->getAs<RecordType>()) {
6989 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00006990 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00006991 MarkDeclarationReferenced(Field->getLocation(), Destructor);
6992 CheckDestructorAccess(Field->getLocation(), Destructor,
6993 PDiag(diag::err_access_dtor_ivar)
6994 << Context.getBaseElementType(Field->getType()));
6995 }
6996 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006997 }
6998 ObjCImplementation->setIvarInitializers(Context,
6999 AllToInit.data(), AllToInit.size());
7000 }
7001}