blob: 08a34a5d0f766b4f2761f04740dddfad54a17050 [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
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000019#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000022#include "clang/AST/RecordLayout.h"
23#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000024#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000025#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000026#include "clang/Sema/DeclSpec.h"
27#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000029#include "clang/Lex/Preprocessor.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000031#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000032#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000033
34using namespace clang;
35
Chris Lattner8123a952008-04-10 02:22:51 +000036//===----------------------------------------------------------------------===//
37// CheckDefaultArgumentVisitor
38//===----------------------------------------------------------------------===//
39
Chris Lattner9e979552008-04-12 23:52:44 +000040namespace {
41 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
42 /// the default argument of a parameter to determine whether it
43 /// contains any ill-formed subexpressions. For example, this will
44 /// diagnose the use of local variables or parameters within the
45 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000046 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000047 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000048 Expr *DefaultArg;
49 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000050
Chris Lattner9e979552008-04-12 23:52:44 +000051 public:
Mike Stump1eb44332009-09-09 15:08:12 +000052 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000053 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000054
Chris Lattner9e979552008-04-12 23:52:44 +000055 bool VisitExpr(Expr *Node);
56 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000057 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000058 };
Chris Lattner8123a952008-04-10 02:22:51 +000059
Chris Lattner9e979552008-04-12 23:52:44 +000060 /// VisitExpr - Visit all of the children of this expression.
61 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
62 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000063 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000064 E = Node->child_end(); I != E; ++I)
65 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000066 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000067 }
68
Chris Lattner9e979552008-04-12 23:52:44 +000069 /// VisitDeclRefExpr - Visit a reference to a declaration, to
70 /// determine whether this declaration can be used in the default
71 /// argument expression.
72 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000073 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000074 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
75 // C++ [dcl.fct.default]p9
76 // Default arguments are evaluated each time the function is
77 // called. The order of evaluation of function arguments is
78 // unspecified. Consequently, parameters of a function shall not
79 // be used in default argument expressions, even if they are not
80 // evaluated. Parameters of a function declared before a default
81 // argument expression are in scope and can hide namespace and
82 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000083 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000084 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000085 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000086 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000087 // C++ [dcl.fct.default]p7
88 // Local variables shall not be used in default argument
89 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000090 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000091 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000092 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000093 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000094 }
Chris Lattner8123a952008-04-10 02:22:51 +000095
Douglas Gregor3996f232008-11-04 13:41:56 +000096 return false;
97 }
Chris Lattner9e979552008-04-12 23:52:44 +000098
Douglas Gregor796da182008-11-04 14:32:21 +000099 /// VisitCXXThisExpr - Visit a C++ "this" expression.
100 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
101 // C++ [dcl.fct.default]p8:
102 // The keyword this shall not be used in a default argument of a
103 // member function.
104 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000105 diag::err_param_default_argument_references_this)
106 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000107 }
Chris Lattner8123a952008-04-10 02:22:51 +0000108}
109
Anders Carlssoned961f92009-08-25 02:29:20 +0000110bool
111Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000112 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000113 if (RequireCompleteType(Param->getLocation(), Param->getType(),
114 diag::err_typecheck_decl_incomplete_type)) {
115 Param->setInvalidDecl();
116 return true;
117 }
118
Anders Carlssoned961f92009-08-25 02:29:20 +0000119 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Anders Carlssoned961f92009-08-25 02:29:20 +0000121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Douglas Gregor99a2e602009-12-16 01:38:02 +0000127 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
128 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
129 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000130 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
131 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +0000132 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000133 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000134 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000135 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000136
Anders Carlsson0ece4912009-12-15 20:51:39 +0000137 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Anders Carlssoned961f92009-08-25 02:29:20 +0000139 // Okay: add the default argument to the parameter
140 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Anders Carlssoned961f92009-08-25 02:29:20 +0000142 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Anders Carlsson9351c172009-08-25 03:18:48 +0000144 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000145}
146
Chris Lattner8123a952008-04-10 02:22:51 +0000147/// ActOnParamDefaultArgument - Check whether the default argument
148/// provided for a function parameter is well-formed. If so, attach it
149/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000150void
John McCalld226f652010-08-21 09:40:31 +0000151Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000152 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000153 if (!param || !defarg.get())
154 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000155
John McCalld226f652010-08-21 09:40:31 +0000156 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000157 UnparsedDefaultArgLocs.erase(Param);
158
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000159 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000160
161 // Default arguments are only permitted in C++
162 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000163 Diag(EqualLoc, diag::err_param_default_argument)
164 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000165 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000166 return;
167 }
168
Anders Carlsson66e30672009-08-25 01:02:06 +0000169 // Check that the default argument is well-formed
170 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
171 if (DefaultArgChecker.Visit(DefaultArg.get())) {
172 Param->setInvalidDecl();
173 return;
174 }
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Anders Carlssoned961f92009-08-25 02:29:20 +0000176 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000177}
178
Douglas Gregor61366e92008-12-24 00:01:03 +0000179/// ActOnParamUnparsedDefaultArgument - We've seen a default
180/// argument for a function parameter, but we can't parse it yet
181/// because we're inside a class definition. Note that this default
182/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000183void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000184 SourceLocation EqualLoc,
185 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000186 if (!param)
187 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000188
John McCalld226f652010-08-21 09:40:31 +0000189 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000190 if (Param)
191 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Anders Carlsson5e300d12009-06-12 16:51:40 +0000193 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000194}
195
Douglas Gregor72b505b2008-12-16 21:30:33 +0000196/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
197/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000198void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000199 if (!param)
200 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000201
John McCalld226f652010-08-21 09:40:31 +0000202 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Anders Carlsson5e300d12009-06-12 16:51:40 +0000204 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000205
Anders Carlsson5e300d12009-06-12 16:51:40 +0000206 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000207}
208
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000209/// CheckExtraCXXDefaultArguments - Check for any extra default
210/// arguments in the declarator, which is not a function declaration
211/// or definition and therefore is not permitted to have default
212/// arguments. This routine should be invoked for every declarator
213/// that is not a function declaration or definition.
214void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
215 // C++ [dcl.fct.default]p3
216 // A default argument expression shall be specified only in the
217 // parameter-declaration-clause of a function declaration or in a
218 // template-parameter (14.1). It shall not be specified for a
219 // parameter pack. If it is specified in a
220 // parameter-declaration-clause, it shall not occur within a
221 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000222 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000223 DeclaratorChunk &chunk = D.getTypeObject(i);
224 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000225 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
226 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000227 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000228 if (Param->hasUnparsedDefaultArg()) {
229 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000230 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
231 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
232 delete Toks;
233 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000234 } else if (Param->getDefaultArg()) {
235 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
236 << Param->getDefaultArg()->getSourceRange();
237 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000238 }
239 }
240 }
241 }
242}
243
Chris Lattner3d1cee32008-04-08 05:04:30 +0000244// MergeCXXFunctionDecl - Merge two declarations of the same C++
245// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000246// type. Subroutine of MergeFunctionDecl. Returns true if there was an
247// error, false otherwise.
248bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
249 bool Invalid = false;
250
Chris Lattner3d1cee32008-04-08 05:04:30 +0000251 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000252 // For non-template functions, default arguments can be added in
253 // later declarations of a function in the same
254 // scope. Declarations in different scopes have completely
255 // distinct sets of default arguments. That is, declarations in
256 // inner scopes do not acquire default arguments from
257 // declarations in outer scopes, and vice versa. In a given
258 // function declaration, all parameters subsequent to a
259 // parameter with a default argument shall have default
260 // arguments supplied in this or previous declarations. A
261 // default argument shall not be redefined by a later
262 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000263 //
264 // C++ [dcl.fct.default]p6:
265 // Except for member functions of class templates, the default arguments
266 // in a member function definition that appears outside of the class
267 // definition are added to the set of default arguments provided by the
268 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000269 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
270 ParmVarDecl *OldParam = Old->getParamDecl(p);
271 ParmVarDecl *NewParam = New->getParamDecl(p);
272
Douglas Gregor6cc15182009-09-11 18:44:32 +0000273 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000274 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
275 // hint here. Alternatively, we could walk the type-source information
276 // for NewParam to find the last source location in the type... but it
277 // isn't worth the effort right now. This is the kind of test case that
278 // is hard to get right:
279
280 // int f(int);
281 // void g(int (*fp)(int) = f);
282 // void g(int (*fp)(int) = &f);
Mike Stump1eb44332009-09-09 15:08:12 +0000283 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000284 diag::err_param_default_argument_redefinition)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000285 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000286
287 // Look for the function declaration where the default argument was
288 // actually written, which may be a declaration prior to Old.
289 for (FunctionDecl *Older = Old->getPreviousDeclaration();
290 Older; Older = Older->getPreviousDeclaration()) {
291 if (!Older->getParamDecl(p)->hasDefaultArg())
292 break;
293
294 OldParam = Older->getParamDecl(p);
295 }
296
297 Diag(OldParam->getLocation(), diag::note_previous_definition)
298 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000299 Invalid = true;
Douglas Gregord85cef52009-09-17 19:51:30 +0000300 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000301 // Merge the old default argument into the new parameter.
302 // It's important to use getInit() here; getDefaultArg()
303 // strips off any top-level CXXExprWithTemporaries.
John McCallbf73b352010-03-12 18:31:32 +0000304 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000305 if (OldParam->hasUninstantiatedDefaultArg())
306 NewParam->setUninstantiatedDefaultArg(
307 OldParam->getUninstantiatedDefaultArg());
308 else
John McCall3d6c1782010-05-04 01:53:42 +0000309 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000310 } else if (NewParam->hasDefaultArg()) {
311 if (New->getDescribedFunctionTemplate()) {
312 // Paragraph 4, quoted above, only applies to non-template functions.
313 Diag(NewParam->getLocation(),
314 diag::err_param_default_argument_template_redecl)
315 << NewParam->getDefaultArgRange();
316 Diag(Old->getLocation(), diag::note_template_prev_declaration)
317 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000318 } else if (New->getTemplateSpecializationKind()
319 != TSK_ImplicitInstantiation &&
320 New->getTemplateSpecializationKind() != TSK_Undeclared) {
321 // C++ [temp.expr.spec]p21:
322 // Default function arguments shall not be specified in a declaration
323 // or a definition for one of the following explicit specializations:
324 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000325 // - the explicit specialization of a member function template;
326 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000327 // template where the class template specialization to which the
328 // member function specialization belongs is implicitly
329 // instantiated.
330 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
331 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
332 << New->getDeclName()
333 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000334 } else if (New->getDeclContext()->isDependentContext()) {
335 // C++ [dcl.fct.default]p6 (DR217):
336 // Default arguments for a member function of a class template shall
337 // be specified on the initial declaration of the member function
338 // within the class template.
339 //
340 // Reading the tea leaves a bit in DR217 and its reference to DR205
341 // leads me to the conclusion that one cannot add default function
342 // arguments for an out-of-line definition of a member function of a
343 // dependent type.
344 int WhichKind = 2;
345 if (CXXRecordDecl *Record
346 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
347 if (Record->getDescribedClassTemplate())
348 WhichKind = 0;
349 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
350 WhichKind = 1;
351 else
352 WhichKind = 2;
353 }
354
355 Diag(NewParam->getLocation(),
356 diag::err_param_default_argument_member_template_redecl)
357 << WhichKind
358 << NewParam->getDefaultArgRange();
359 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000360 }
361 }
362
Douglas Gregore13ad832010-02-12 07:32:17 +0000363 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000364 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000365
Douglas Gregorcda9c672009-02-16 17:45:42 +0000366 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000367}
368
369/// CheckCXXDefaultArguments - Verify that the default arguments for a
370/// function declaration are well-formed according to C++
371/// [dcl.fct.default].
372void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
373 unsigned NumParams = FD->getNumParams();
374 unsigned p;
375
376 // Find first parameter with a default argument
377 for (p = 0; p < NumParams; ++p) {
378 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000379 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000380 break;
381 }
382
383 // C++ [dcl.fct.default]p4:
384 // In a given function declaration, all parameters
385 // subsequent to a parameter with a default argument shall
386 // have default arguments supplied in this or previous
387 // declarations. A default argument shall not be redefined
388 // by a later declaration (not even to the same value).
389 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000390 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000391 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000392 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000393 if (Param->isInvalidDecl())
394 /* We already complained about this parameter. */;
395 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000396 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000397 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000398 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000399 else
Mike Stump1eb44332009-09-09 15:08:12 +0000400 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000401 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Chris Lattner3d1cee32008-04-08 05:04:30 +0000403 LastMissingDefaultArg = p;
404 }
405 }
406
407 if (LastMissingDefaultArg > 0) {
408 // Some default arguments were missing. Clear out all of the
409 // default arguments up to (and including) the last missing
410 // default argument, so that we leave the function parameters
411 // in a semantically valid state.
412 for (p = 0; p <= LastMissingDefaultArg; ++p) {
413 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000414 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000415 Param->setDefaultArg(0);
416 }
417 }
418 }
419}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000420
Douglas Gregorb48fe382008-10-31 09:07:45 +0000421/// isCurrentClassName - Determine whether the identifier II is the
422/// name of the class type currently being defined. In the case of
423/// nested classes, this will only return true if II is the name of
424/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000425bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
426 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000427 assert(getLangOptions().CPlusPlus && "No class names in C!");
428
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000429 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000430 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000431 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000432 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
433 } else
434 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
435
Douglas Gregor6f7a17b2010-02-05 06:12:42 +0000436 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +0000437 return &II == CurDecl->getIdentifier();
438 else
439 return false;
440}
441
Mike Stump1eb44332009-09-09 15:08:12 +0000442/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000443///
444/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
445/// and returns NULL otherwise.
446CXXBaseSpecifier *
447Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
448 SourceRange SpecifierRange,
449 bool Virtual, AccessSpecifier Access,
Nick Lewycky56062202010-07-26 16:56:01 +0000450 TypeSourceInfo *TInfo) {
451 QualType BaseType = TInfo->getType();
452
Douglas Gregor2943aed2009-03-03 04:44:36 +0000453 // C++ [class.union]p1:
454 // A union shall not have base classes.
455 if (Class->isUnion()) {
456 Diag(Class->getLocation(), diag::err_base_clause_on_union)
457 << SpecifierRange;
458 return 0;
459 }
460
461 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000462 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000463 Class->getTagKind() == TTK_Class,
464 Access, TInfo);
465
466 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000467
468 // Base specifiers must be record types.
469 if (!BaseType->isRecordType()) {
470 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
471 return 0;
472 }
473
474 // C++ [class.union]p1:
475 // A union shall not be used as a base class.
476 if (BaseType->isUnionType()) {
477 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
478 return 0;
479 }
480
481 // C++ [class.derived]p2:
482 // The class-name in a base-specifier shall not be an incompletely
483 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000484 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000485 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +0000486 << SpecifierRange)) {
487 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000488 return 0;
John McCall572fc622010-08-17 07:23:57 +0000489 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000490
Eli Friedman1d954f62009-08-15 21:55:26 +0000491 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000492 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000493 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +0000494 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000495 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000496 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
497 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +0000498
Sean Huntbbd37c62009-11-21 08:43:09 +0000499 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
500 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
501 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregor9af2f522009-12-01 16:58:18 +0000502 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
503 << BaseType;
Sean Huntbbd37c62009-11-21 08:43:09 +0000504 return 0;
505 }
Douglas Gregor2943aed2009-03-03 04:44:36 +0000506
Eli Friedmand0137332009-12-05 23:03:49 +0000507 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
John McCall572fc622010-08-17 07:23:57 +0000508
509 if (BaseDecl->isInvalidDecl())
510 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +0000511
512 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +0000513 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +0000514 Class->getTagKind() == TTK_Class,
515 Access, TInfo);
Anders Carlsson51f94042009-12-03 17:49:57 +0000516}
517
518void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
519 const CXXRecordDecl *BaseClass,
520 bool BaseIsVirtual) {
Eli Friedmand0137332009-12-05 23:03:49 +0000521 // A class with a non-empty base class is not empty.
522 // FIXME: Standard ref?
523 if (!BaseClass->isEmpty())
524 Class->setEmpty(false);
525
526 // C++ [class.virtual]p1:
527 // A class that [...] inherits a virtual function is called a polymorphic
528 // class.
529 if (BaseClass->isPolymorphic())
530 Class->setPolymorphic(true);
Anders Carlsson51f94042009-12-03 17:49:57 +0000531
Douglas Gregor2943aed2009-03-03 04:44:36 +0000532 // C++ [dcl.init.aggr]p1:
533 // An aggregate is [...] a class with [...] no base classes [...].
534 Class->setAggregate(false);
Eli Friedmand0137332009-12-05 23:03:49 +0000535
536 // C++ [class]p4:
537 // A POD-struct is an aggregate class...
Douglas Gregor2943aed2009-03-03 04:44:36 +0000538 Class->setPOD(false);
539
Anders Carlsson51f94042009-12-03 17:49:57 +0000540 if (BaseIsVirtual) {
Anders Carlsson347ba892009-04-16 00:08:20 +0000541 // C++ [class.ctor]p5:
542 // A constructor is trivial if its class has no virtual base classes.
543 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000544
545 // C++ [class.copy]p6:
546 // A copy constructor is trivial if its class has no virtual base classes.
547 Class->setHasTrivialCopyConstructor(false);
548
549 // C++ [class.copy]p11:
550 // A copy assignment operator is trivial if its class has no virtual
551 // base classes.
552 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000553
554 // C++0x [meta.unary.prop] is_empty:
555 // T is a class type, but not a union type, with ... no virtual base
556 // classes
557 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000558 } else {
559 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000560 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000561 // class have trivial constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000562 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000563 Class->setHasTrivialConstructor(false);
564
565 // C++ [class.copy]p6:
566 // A copy constructor is trivial if all the direct base classes of its
567 // class have trivial copy constructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000568 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000569 Class->setHasTrivialCopyConstructor(false);
570
571 // C++ [class.copy]p11:
572 // A copy assignment operator is trivial if all the direct base classes
573 // of its class have trivial copy assignment operators.
Anders Carlsson51f94042009-12-03 17:49:57 +0000574 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000575 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000576 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000577
578 // C++ [class.ctor]p3:
579 // A destructor is trivial if all the direct base classes of its class
580 // have trivial destructors.
Anders Carlsson51f94042009-12-03 17:49:57 +0000581 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000582 Class->setHasTrivialDestructor(false);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000583}
584
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000585/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
586/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000587/// example:
588/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000589/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000590Sema::BaseResult
John McCalld226f652010-08-21 09:40:31 +0000591Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000592 bool Virtual, AccessSpecifier Access,
593 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000594 if (!classdecl)
595 return true;
596
Douglas Gregor40808ce2009-03-09 23:48:35 +0000597 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +0000598 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +0000599 if (!Class)
600 return true;
601
Nick Lewycky56062202010-07-26 16:56:01 +0000602 TypeSourceInfo *TInfo = 0;
603 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000604 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Nick Lewycky56062202010-07-26 16:56:01 +0000605 Virtual, Access, TInfo))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000606 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Douglas Gregor2943aed2009-03-03 04:44:36 +0000608 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000609}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000610
Douglas Gregor2943aed2009-03-03 04:44:36 +0000611/// \brief Performs the actual work of attaching the given base class
612/// specifiers to a C++ class.
613bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
614 unsigned NumBases) {
615 if (NumBases == 0)
616 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000617
618 // Used to keep track of which base types we have already seen, so
619 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000620 // that the key is always the unqualified canonical type of the base
621 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000622 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
623
624 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000625 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000626 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000627 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000628 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000629 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +0000630 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian0ed5c5d2010-05-20 23:34:56 +0000631 if (!Class->hasObjectMember()) {
632 if (const RecordType *FDTTy =
633 NewBaseType.getTypePtr()->getAs<RecordType>())
634 if (FDTTy->getDecl()->hasObjectMember())
635 Class->setHasObjectMember(true);
636 }
637
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000638 if (KnownBaseTypes[NewBaseType]) {
639 // C++ [class.mi]p3:
640 // A class shall not be specified as a direct base class of a
641 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000642 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000643 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000644 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000645 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000646
647 // Delete the duplicate base class specifier; we're going to
648 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000649 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000650
651 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000652 } else {
653 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000654 KnownBaseTypes[NewBaseType] = Bases[idx];
655 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000656 }
657 }
658
659 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +0000660 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000661
662 // Delete the remaining (good) base class specifiers, since their
663 // data has been copied into the CXXRecordDecl.
664 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000665 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000666
667 return Invalid;
668}
669
670/// ActOnBaseSpecifiers - Attach the given base specifiers to the
671/// class, after checking whether there are any duplicate base
672/// classes.
John McCalld226f652010-08-21 09:40:31 +0000673void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000674 unsigned NumBases) {
675 if (!ClassDecl || !Bases || !NumBases)
676 return;
677
678 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +0000679 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000680 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000681}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000682
John McCall3cb0ebd2010-03-10 03:28:59 +0000683static CXXRecordDecl *GetClassForType(QualType T) {
684 if (const RecordType *RT = T->getAs<RecordType>())
685 return cast<CXXRecordDecl>(RT->getDecl());
686 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
687 return ICT->getDecl();
688 else
689 return 0;
690}
691
Douglas Gregora8f32e02009-10-06 17:59:45 +0000692/// \brief Determine whether the type \p Derived is a C++ class that is
693/// derived from the type \p Base.
694bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
695 if (!getLangOptions().CPlusPlus)
696 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +0000697
698 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
699 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000700 return false;
701
John McCall3cb0ebd2010-03-10 03:28:59 +0000702 CXXRecordDecl *BaseRD = GetClassForType(Base);
703 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000704 return false;
705
John McCall86ff3082010-02-04 22:26:26 +0000706 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
707 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000708}
709
710/// \brief Determine whether the type \p Derived is a C++ class that is
711/// derived from the type \p Base.
712bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
713 if (!getLangOptions().CPlusPlus)
714 return false;
715
John McCall3cb0ebd2010-03-10 03:28:59 +0000716 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
717 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000718 return false;
719
John McCall3cb0ebd2010-03-10 03:28:59 +0000720 CXXRecordDecl *BaseRD = GetClassForType(Base);
721 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +0000722 return false;
723
Douglas Gregora8f32e02009-10-06 17:59:45 +0000724 return DerivedRD->isDerivedFrom(BaseRD, Paths);
725}
726
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000727void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +0000728 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000729 assert(BasePathArray.empty() && "Base path array must be empty!");
730 assert(Paths.isRecordingPaths() && "Must record paths!");
731
732 const CXXBasePath &Path = Paths.front();
733
734 // We first go backward and check if we have a virtual base.
735 // FIXME: It would be better if CXXBasePath had the base specifier for
736 // the nearest virtual base.
737 unsigned Start = 0;
738 for (unsigned I = Path.size(); I != 0; --I) {
739 if (Path[I - 1].Base->isVirtual()) {
740 Start = I - 1;
741 break;
742 }
743 }
744
745 // Now add all bases.
746 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +0000747 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000748}
749
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000750/// \brief Determine whether the given base path includes a virtual
751/// base class.
John McCallf871d0c2010-08-07 06:22:56 +0000752bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
753 for (CXXCastPath::const_iterator B = BasePath.begin(),
754 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000755 B != BEnd; ++B)
756 if ((*B)->isVirtual())
757 return true;
758
759 return false;
760}
761
Douglas Gregora8f32e02009-10-06 17:59:45 +0000762/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
763/// conversion (where Derived and Base are class types) is
764/// well-formed, meaning that the conversion is unambiguous (and
765/// that all of the base classes are accessible). Returns true
766/// and emits a diagnostic if the code is ill-formed, returns false
767/// otherwise. Loc is the location where this routine should point to
768/// if there is an error, and Range is the source range to highlight
769/// if there is an error.
770bool
771Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +0000772 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000773 unsigned AmbigiousBaseConvID,
774 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000775 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +0000776 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000777 // First, determine whether the path from Derived to Base is
778 // ambiguous. This is slightly more expensive than checking whether
779 // the Derived to Base conversion exists, because here we need to
780 // explore multiple paths to determine if there is an ambiguity.
781 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
782 /*DetectVirtual=*/false);
783 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
784 assert(DerivationOkay &&
785 "Can only be used with a derived-to-base conversion");
786 (void)DerivationOkay;
787
788 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000789 if (InaccessibleBaseID) {
790 // Check that the base class can be accessed.
791 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
792 InaccessibleBaseID)) {
793 case AR_inaccessible:
794 return true;
795 case AR_accessible:
796 case AR_dependent:
797 case AR_delayed:
798 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +0000799 }
John McCall6b2accb2010-02-10 09:31:12 +0000800 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000801
802 // Build a base path if necessary.
803 if (BasePath)
804 BuildBasePathArray(Paths, *BasePath);
805 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000806 }
807
808 // We know that the derived-to-base conversion is ambiguous, and
809 // we're going to produce a diagnostic. Perform the derived-to-base
810 // search just one more time to compute all of the possible paths so
811 // that we can print them out. This is more expensive than any of
812 // the previous derived-to-base checks we've done, but at this point
813 // performance isn't as much of an issue.
814 Paths.clear();
815 Paths.setRecordingPaths(true);
816 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
817 assert(StillOkay && "Can only be used with a derived-to-base conversion");
818 (void)StillOkay;
819
820 // Build up a textual representation of the ambiguous paths, e.g.,
821 // D -> B -> A, that will be used to illustrate the ambiguous
822 // conversions in the diagnostic. We only print one of the paths
823 // to each base class subobject.
824 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
825
826 Diag(Loc, AmbigiousBaseConvID)
827 << Derived << Base << PathDisplayStr << Range << Name;
828 return true;
829}
830
831bool
832Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000833 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +0000834 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000835 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +0000836 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +0000837 IgnoreAccess ? 0
838 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000839 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +0000840 Loc, Range, DeclarationName(),
841 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000842}
843
844
845/// @brief Builds a string representing ambiguous paths from a
846/// specific derived class to different subobjects of the same base
847/// class.
848///
849/// This function builds a string that can be used in error messages
850/// to show the different paths that one can take through the
851/// inheritance hierarchy to go from the derived class to different
852/// subobjects of a base class. The result looks something like this:
853/// @code
854/// struct D -> struct B -> struct A
855/// struct D -> struct C -> struct A
856/// @endcode
857std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
858 std::string PathDisplayStr;
859 std::set<unsigned> DisplayedPaths;
860 for (CXXBasePaths::paths_iterator Path = Paths.begin();
861 Path != Paths.end(); ++Path) {
862 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
863 // We haven't displayed a path to this particular base
864 // class subobject yet.
865 PathDisplayStr += "\n ";
866 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
867 for (CXXBasePath::const_iterator Element = Path->begin();
868 Element != Path->end(); ++Element)
869 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
870 }
871 }
872
873 return PathDisplayStr;
874}
875
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000876//===----------------------------------------------------------------------===//
877// C++ class member Handling
878//===----------------------------------------------------------------------===//
879
Abramo Bagnara6206d532010-06-05 05:09:32 +0000880/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCalld226f652010-08-21 09:40:31 +0000881Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
882 SourceLocation ASLoc,
883 SourceLocation ColonLoc) {
Abramo Bagnara6206d532010-06-05 05:09:32 +0000884 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +0000885 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +0000886 ASLoc, ColonLoc);
887 CurContext->addHiddenDecl(ASDecl);
John McCalld226f652010-08-21 09:40:31 +0000888 return ASDecl;
Abramo Bagnara6206d532010-06-05 05:09:32 +0000889}
890
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000891/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
892/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
893/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000894/// any.
John McCalld226f652010-08-21 09:40:31 +0000895Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000896Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000897 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld1a78462009-11-24 23:38:44 +0000898 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
899 bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000900 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +0000901 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
902 DeclarationName Name = NameInfo.getName();
903 SourceLocation Loc = NameInfo.getLoc();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000904 Expr *BitWidth = static_cast<Expr*>(BW);
905 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000906
John McCall4bde1e12010-06-04 08:34:12 +0000907 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +0000908 assert(!DS.isFriendSpecified());
909
John McCall4bde1e12010-06-04 08:34:12 +0000910 bool isFunc = false;
911 if (D.isFunctionDeclarator())
912 isFunc = true;
913 else if (D.getNumTypeObjects() == 0 &&
914 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
915 QualType TDType = GetTypeFromParser(DS.getTypeRep());
916 isFunc = TDType->isFunctionType();
917 }
918
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000919 // C++ 9.2p6: A member shall not be declared to have automatic storage
920 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000921 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
922 // data members and cannot be applied to names declared const or static,
923 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000924 switch (DS.getStorageClassSpec()) {
925 case DeclSpec::SCS_unspecified:
926 case DeclSpec::SCS_typedef:
927 case DeclSpec::SCS_static:
928 // FALL THROUGH.
929 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000930 case DeclSpec::SCS_mutable:
931 if (isFunc) {
932 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000933 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000934 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000935 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Sebastian Redla11f42f2008-11-17 23:24:37 +0000937 // FIXME: It would be nicer if the keyword was ignored only for this
938 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000939 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +0000940 }
941 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000942 default:
943 if (DS.getStorageClassSpecLoc().isValid())
944 Diag(DS.getStorageClassSpecLoc(),
945 diag::err_storageclass_invalid_for_member);
946 else
947 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
948 D.getMutableDeclSpec().ClearStorageClassSpecs();
949 }
950
Sebastian Redl669d5d72008-11-14 23:42:31 +0000951 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
952 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000953 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000954
955 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000956 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000957 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000958 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
959 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000960 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000961 } else {
John McCalld226f652010-08-21 09:40:31 +0000962 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000963 if (!Member) {
964 if (BitWidth) DeleteExpr(BitWidth);
John McCalld226f652010-08-21 09:40:31 +0000965 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +0000966 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000967
968 // Non-instance-fields can't have a bitfield.
969 if (BitWidth) {
970 if (Member->isInvalidDecl()) {
971 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000972 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000973 // C++ 9.6p3: A bit-field shall not be a static member.
974 // "static member 'A' cannot be a bit-field"
975 Diag(Loc, diag::err_static_not_bitfield)
976 << Name << BitWidth->getSourceRange();
977 } else if (isa<TypedefDecl>(Member)) {
978 // "typedef member 'x' cannot be a bit-field"
979 Diag(Loc, diag::err_typedef_not_bitfield)
980 << Name << BitWidth->getSourceRange();
981 } else {
982 // A function typedef ("typedef int f(); f a;").
983 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
984 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000985 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000986 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000987 }
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Chris Lattner8b963ef2009-03-05 23:01:03 +0000989 DeleteExpr(BitWidth);
990 BitWidth = 0;
991 Member->setInvalidDecl();
992 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000993
994 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000995
Douglas Gregor37b372b2009-08-20 22:52:58 +0000996 // If we have declared a member function template, set the access of the
997 // templated declaration as well.
998 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
999 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001000 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001001
Douglas Gregor10bd3682008-11-17 22:58:34 +00001002 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001003
Douglas Gregor021c3b32009-03-11 23:00:04 +00001004 if (Init)
John McCalld226f652010-08-21 09:40:31 +00001005 AddInitializerToDecl(Member, ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001006 if (Deleted) // FIXME: Source location is not very good.
John McCalld226f652010-08-21 09:40:31 +00001007 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001008
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001009 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +00001010 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001011 return 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001012 }
John McCalld226f652010-08-21 09:40:31 +00001013 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001014}
1015
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001016/// \brief Find the direct and/or virtual base specifiers that
1017/// correspond to the given base type, for use in base initialization
1018/// within a constructor.
1019static bool FindBaseInitializer(Sema &SemaRef,
1020 CXXRecordDecl *ClassDecl,
1021 QualType BaseType,
1022 const CXXBaseSpecifier *&DirectBaseSpec,
1023 const CXXBaseSpecifier *&VirtualBaseSpec) {
1024 // First, check for a direct base class.
1025 DirectBaseSpec = 0;
1026 for (CXXRecordDecl::base_class_const_iterator Base
1027 = ClassDecl->bases_begin();
1028 Base != ClassDecl->bases_end(); ++Base) {
1029 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1030 // We found a direct base of this type. That's what we're
1031 // initializing.
1032 DirectBaseSpec = &*Base;
1033 break;
1034 }
1035 }
1036
1037 // Check for a virtual base class.
1038 // FIXME: We might be able to short-circuit this if we know in advance that
1039 // there are no virtual bases.
1040 VirtualBaseSpec = 0;
1041 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1042 // We haven't found a base yet; search the class hierarchy for a
1043 // virtual base class.
1044 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1045 /*DetectVirtual=*/false);
1046 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1047 BaseType, Paths)) {
1048 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1049 Path != Paths.end(); ++Path) {
1050 if (Path->back().Base->isVirtual()) {
1051 VirtualBaseSpec = Path->back().Base;
1052 break;
1053 }
1054 }
1055 }
1056 }
1057
1058 return DirectBaseSpec || VirtualBaseSpec;
1059}
1060
Douglas Gregor7ad83902008-11-05 04:29:56 +00001061/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001062Sema::MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001063Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001064 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001065 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001066 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +00001067 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001068 SourceLocation IdLoc,
1069 SourceLocation LParenLoc,
1070 ExprTy **Args, unsigned NumArgs,
1071 SourceLocation *CommaLocs,
1072 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001073 if (!ConstructorD)
1074 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001076 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001077
1078 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001079 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001080 if (!Constructor) {
1081 // The user wrote a constructor initializer on a function that is
1082 // not a C++ constructor. Ignore the error for now, because we may
1083 // have more member initializers coming; we'll diagnose it just
1084 // once in ActOnMemInitializers.
1085 return true;
1086 }
1087
1088 CXXRecordDecl *ClassDecl = Constructor->getParent();
1089
1090 // C++ [class.base.init]p2:
1091 // Names in a mem-initializer-id are looked up in the scope of the
1092 // constructor’s class and, if not found in that scope, are looked
1093 // up in the scope containing the constructor’s
1094 // definition. [Note: if the constructor’s class contains a member
1095 // with the same name as a direct or virtual base class of the
1096 // class, a mem-initializer-id naming the member or base class and
1097 // composed of a single identifier refers to the class member. A
1098 // mem-initializer-id for the hidden base class may be specified
1099 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001100 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001101 // Look for a member, first.
1102 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001103 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001104 = ClassDecl->lookup(MemberOrBase);
1105 if (Result.first != Result.second)
1106 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001107
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001108 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +00001109
Eli Friedman59c04372009-07-29 19:44:27 +00001110 if (Member)
1111 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001112 LParenLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001113 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001114 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001115 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001116 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001117
1118 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001119 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCall2b194412009-12-21 10:41:20 +00001120 } else {
1121 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1122 LookupParsedName(R, S, &SS);
1123
1124 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1125 if (!TyD) {
1126 if (R.isAmbiguous()) return true;
1127
John McCallfd225442010-04-09 19:01:14 +00001128 // We don't want access-control diagnostics here.
1129 R.suppressDiagnostics();
1130
Douglas Gregor7a886e12010-01-19 06:46:48 +00001131 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1132 bool NotUnknownSpecialization = false;
1133 DeclContext *DC = computeDeclContext(SS, false);
1134 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1135 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1136
1137 if (!NotUnknownSpecialization) {
1138 // When the scope specifier can refer to a member of an unknown
1139 // specialization, we take it as a type name.
Douglas Gregor107de902010-04-24 15:35:55 +00001140 BaseType = CheckTypenameType(ETK_None,
1141 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00001142 *MemberOrBase, SourceLocation(),
1143 SS.getRange(), IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001144 if (BaseType.isNull())
1145 return true;
1146
Douglas Gregor7a886e12010-01-19 06:46:48 +00001147 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001148 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001149 }
1150 }
1151
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001152 // If no results were found, try to correct typos.
Douglas Gregor7a886e12010-01-19 06:46:48 +00001153 if (R.empty() && BaseType.isNull() &&
Douglas Gregoraaf87162010-04-14 20:04:41 +00001154 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1155 R.isSingleResult()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001156 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1157 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1158 // We have found a non-static data member with a similar
1159 // name to what was typed; complain and initialize that
1160 // member.
1161 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1162 << MemberOrBase << true << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001163 << FixItHint::CreateReplacement(R.getNameLoc(),
1164 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001165 Diag(Member->getLocation(), diag::note_previous_decl)
1166 << Member->getDeclName();
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001167
1168 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1169 LParenLoc, RParenLoc);
1170 }
1171 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1172 const CXXBaseSpecifier *DirectBaseSpec;
1173 const CXXBaseSpecifier *VirtualBaseSpec;
1174 if (FindBaseInitializer(*this, ClassDecl,
1175 Context.getTypeDeclType(Type),
1176 DirectBaseSpec, VirtualBaseSpec)) {
1177 // We have found a direct or virtual base class with a
1178 // similar name to what was typed; complain and initialize
1179 // that base class.
1180 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1181 << MemberOrBase << false << R.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +00001182 << FixItHint::CreateReplacement(R.getNameLoc(),
1183 R.getLookupName().getAsString());
Douglas Gregor0d535c82010-01-07 00:26:25 +00001184
1185 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1186 : VirtualBaseSpec;
1187 Diag(BaseSpec->getSourceRange().getBegin(),
1188 diag::note_base_class_specified_here)
1189 << BaseSpec->getType()
1190 << BaseSpec->getSourceRange();
1191
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001192 TyD = Type;
1193 }
1194 }
1195 }
1196
Douglas Gregor7a886e12010-01-19 06:46:48 +00001197 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001198 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1199 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1200 return true;
1201 }
John McCall2b194412009-12-21 10:41:20 +00001202 }
1203
Douglas Gregor7a886e12010-01-19 06:46:48 +00001204 if (BaseType.isNull()) {
1205 BaseType = Context.getTypeDeclType(TyD);
1206 if (SS.isSet()) {
1207 NestedNameSpecifier *Qualifier =
1208 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001209
Douglas Gregor7a886e12010-01-19 06:46:48 +00001210 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001211 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001212 }
John McCall2b194412009-12-21 10:41:20 +00001213 }
1214 }
Mike Stump1eb44332009-09-09 15:08:12 +00001215
John McCalla93c9342009-12-07 02:54:59 +00001216 if (!TInfo)
1217 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001218
John McCalla93c9342009-12-07 02:54:59 +00001219 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor802ab452009-12-02 22:36:29 +00001220 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman59c04372009-07-29 19:44:27 +00001221}
1222
John McCallb4190042009-11-04 23:02:40 +00001223/// Checks an initializer expression for use of uninitialized fields, such as
1224/// containing the field that is being initialized. Returns true if there is an
1225/// uninitialized field was used an updates the SourceLocation parameter; false
1226/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00001227static bool InitExprContainsUninitializedFields(const Stmt *S,
1228 const FieldDecl *LhsField,
1229 SourceLocation *L) {
1230 if (isa<CallExpr>(S)) {
1231 // Do not descend into function calls or constructors, as the use
1232 // of an uninitialized field may be valid. One would have to inspect
1233 // the contents of the function/ctor to determine if it is safe or not.
1234 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1235 // may be safe, depending on what the function/ctor does.
1236 return false;
1237 }
1238 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1239 const NamedDecl *RhsField = ME->getMemberDecl();
John McCallb4190042009-11-04 23:02:40 +00001240 if (RhsField == LhsField) {
1241 // Initializing a field with itself. Throw a warning.
1242 // But wait; there are exceptions!
1243 // Exception #1: The field may not belong to this record.
1244 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00001245 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00001246 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1247 // Even though the field matches, it does not belong to this record.
1248 return false;
1249 }
1250 // None of the exceptions triggered; return true to indicate an
1251 // uninitialized field was used.
1252 *L = ME->getMemberLoc();
1253 return true;
1254 }
1255 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001256 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1257 it != e; ++it) {
1258 if (!*it) {
1259 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00001260 continue;
1261 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001262 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1263 return true;
John McCallb4190042009-11-04 23:02:40 +00001264 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00001265 return false;
John McCallb4190042009-11-04 23:02:40 +00001266}
1267
Eli Friedman59c04372009-07-29 19:44:27 +00001268Sema::MemInitResult
1269Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1270 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregor802ab452009-12-02 22:36:29 +00001271 SourceLocation LParenLoc,
Eli Friedman59c04372009-07-29 19:44:27 +00001272 SourceLocation RParenLoc) {
John McCallb4190042009-11-04 23:02:40 +00001273 // Diagnose value-uses of fields to initialize themselves, e.g.
1274 // foo(foo)
1275 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00001276 // TODO: implement -Wuninitialized and fold this into that framework.
John McCallb4190042009-11-04 23:02:40 +00001277 for (unsigned i = 0; i < NumArgs; ++i) {
1278 SourceLocation L;
1279 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1280 // FIXME: Return true in the case when other fields are used before being
1281 // uninitialized. For example, let this field be the i'th field. When
1282 // initializing the i'th field, throw a warning if any of the >= i'th
1283 // fields are used, as they are not yet initialized.
1284 // Right now we are only handling the case where the i'th field uses
1285 // itself in its initializer.
1286 Diag(L, diag::warn_field_is_uninit);
1287 }
1288 }
1289
Eli Friedman59c04372009-07-29 19:44:27 +00001290 bool HasDependentArg = false;
1291 for (unsigned i = 0; i < NumArgs; i++)
1292 HasDependentArg |= Args[i]->isTypeDependent();
1293
Eli Friedman0f2b97d2010-07-24 21:19:15 +00001294 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001295 // Can't check initialization for a member of dependent type or when
1296 // any of the arguments are type-dependent expressions.
1297 OwningExprResult Init
1298 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1299 RParenLoc));
1300
1301 // Erase any temporaries within this evaluation context; we're not
1302 // going to track them in the AST, since we'll be rebuilding the
1303 // ASTs during template instantiation.
1304 ExprTemporaries.erase(
1305 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1306 ExprTemporaries.end());
1307
1308 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1309 LParenLoc,
1310 Init.takeAs<Expr>(),
1311 RParenLoc);
1312
Douglas Gregor7ad83902008-11-05 04:29:56 +00001313 }
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001314
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001315 if (Member->isInvalidDecl())
1316 return true;
Anders Carlssonf8a9a792009-11-13 19:21:49 +00001317
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001318 // Initialize the member.
1319 InitializedEntity MemberEntity =
1320 InitializedEntity::InitializeMember(Member, 0);
1321 InitializationKind Kind =
1322 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1323
1324 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1325
1326 OwningExprResult MemberInit =
1327 InitSeq.Perform(*this, MemberEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001328 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001329 if (MemberInit.isInvalid())
1330 return true;
1331
1332 // C++0x [class.base.init]p7:
1333 // The initialization of each base and member constitutes a
1334 // full-expression.
1335 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1336 if (MemberInit.isInvalid())
1337 return true;
1338
1339 // If we are in a dependent context, template instantiation will
1340 // perform this type-checking again. Just save the arguments that we
1341 // received in a ParenListExpr.
1342 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1343 // of the information that we have about the member
1344 // initializer. However, deconstructing the ASTs is a dicey process,
1345 // and this approach is far more likely to get the corner cases right.
1346 if (CurContext->isDependentContext()) {
1347 // Bump the reference count of all of the arguments.
1348 for (unsigned I = 0; I != NumArgs; ++I)
1349 Args[I]->Retain();
1350
1351 OwningExprResult Init
1352 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1353 RParenLoc));
1354 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1355 LParenLoc,
1356 Init.takeAs<Expr>(),
1357 RParenLoc);
1358 }
1359
Douglas Gregor802ab452009-12-02 22:36:29 +00001360 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001361 LParenLoc,
1362 MemberInit.takeAs<Expr>(),
1363 RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001364}
1365
1366Sema::MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00001367Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregor802ab452009-12-02 22:36:29 +00001368 Expr **Args, unsigned NumArgs,
1369 SourceLocation LParenLoc, SourceLocation RParenLoc,
1370 CXXRecordDecl *ClassDecl) {
Eli Friedman59c04372009-07-29 19:44:27 +00001371 bool HasDependentArg = false;
1372 for (unsigned i = 0; i < NumArgs; i++)
1373 HasDependentArg |= Args[i]->isTypeDependent();
1374
Douglas Gregor3956b1a2010-06-16 16:03:14 +00001375 SourceLocation BaseLoc
1376 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1377
1378 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1379 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1380 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1381
1382 // C++ [class.base.init]p2:
1383 // [...] Unless the mem-initializer-id names a nonstatic data
1384 // member of the constructor’s class or a direct or virtual base
1385 // of that class, the mem-initializer is ill-formed. A
1386 // mem-initializer-list can initialize a base class using any
1387 // name that denotes that base class type.
1388 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1389
1390 // Check for direct and virtual base classes.
1391 const CXXBaseSpecifier *DirectBaseSpec = 0;
1392 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1393 if (!Dependent) {
1394 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1395 VirtualBaseSpec);
1396
1397 // C++ [base.class.init]p2:
1398 // Unless the mem-initializer-id names a nonstatic data member of the
1399 // constructor's class or a direct or virtual base of that class, the
1400 // mem-initializer is ill-formed.
1401 if (!DirectBaseSpec && !VirtualBaseSpec) {
1402 // If the class has any dependent bases, then it's possible that
1403 // one of those types will resolve to the same type as
1404 // BaseType. Therefore, just treat this as a dependent base
1405 // class initialization. FIXME: Should we try to check the
1406 // initialization anyway? It seems odd.
1407 if (ClassDecl->hasAnyDependentBases())
1408 Dependent = true;
1409 else
1410 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1411 << BaseType << Context.getTypeDeclType(ClassDecl)
1412 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1413 }
1414 }
1415
1416 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001417 // Can't check initialization for a base of dependent type or when
1418 // any of the arguments are type-dependent expressions.
1419 OwningExprResult BaseInit
1420 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1421 RParenLoc));
Eli Friedman59c04372009-07-29 19:44:27 +00001422
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001423 // Erase any temporaries within this evaluation context; we're not
1424 // going to track them in the AST, since we'll be rebuilding the
1425 // ASTs during template instantiation.
1426 ExprTemporaries.erase(
1427 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1428 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001430 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001431 /*IsVirtual=*/false,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001432 LParenLoc,
1433 BaseInit.takeAs<Expr>(),
1434 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001435 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001436
1437 // C++ [base.class.init]p2:
1438 // If a mem-initializer-id is ambiguous because it designates both
1439 // a direct non-virtual base class and an inherited virtual base
1440 // class, the mem-initializer is ill-formed.
1441 if (DirectBaseSpec && VirtualBaseSpec)
1442 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001443 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001444
1445 CXXBaseSpecifier *BaseSpec
1446 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1447 if (!BaseSpec)
1448 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1449
1450 // Initialize the base.
1451 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00001452 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001453 InitializationKind Kind =
1454 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1455
1456 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1457
1458 OwningExprResult BaseInit =
1459 InitSeq.Perform(*this, BaseEntity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00001460 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001461 if (BaseInit.isInvalid())
1462 return true;
1463
1464 // C++0x [class.base.init]p7:
1465 // The initialization of each base and member constitutes a
1466 // full-expression.
1467 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1468 if (BaseInit.isInvalid())
1469 return true;
1470
1471 // If we are in a dependent context, template instantiation will
1472 // perform this type-checking again. Just save the arguments that we
1473 // received in a ParenListExpr.
1474 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1475 // of the information that we have about the base
1476 // initializer. However, deconstructing the ASTs is a dicey process,
1477 // and this approach is far more likely to get the corner cases right.
1478 if (CurContext->isDependentContext()) {
1479 // Bump the reference count of all of the arguments.
1480 for (unsigned I = 0; I != NumArgs; ++I)
1481 Args[I]->Retain();
1482
1483 OwningExprResult Init
1484 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1485 RParenLoc));
1486 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001487 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001488 LParenLoc,
1489 Init.takeAs<Expr>(),
1490 RParenLoc);
1491 }
1492
1493 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson80638c52010-04-12 00:51:03 +00001494 BaseSpec->isVirtual(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001495 LParenLoc,
1496 BaseInit.takeAs<Expr>(),
1497 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001498}
1499
Anders Carlssone5ef7402010-04-23 03:10:23 +00001500/// ImplicitInitializerKind - How an implicit base or member initializer should
1501/// initialize its base or member.
1502enum ImplicitInitializerKind {
1503 IIK_Default,
1504 IIK_Copy,
1505 IIK_Move
1506};
1507
Anders Carlssondefefd22010-04-23 02:00:02 +00001508static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001509BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001510 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00001511 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00001512 bool IsInheritedVirtualBase,
1513 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00001514 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00001515 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1516 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00001517
John McCallca0408f2010-08-23 06:44:23 +00001518 Sema::OwningExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00001519
1520 switch (ImplicitInitKind) {
1521 case IIK_Default: {
1522 InitializationKind InitKind
1523 = InitializationKind::CreateDefault(Constructor->getLocation());
1524 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1525 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1526 Sema::MultiExprArg(SemaRef, 0, 0));
1527 break;
1528 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001529
Anders Carlssone5ef7402010-04-23 03:10:23 +00001530 case IIK_Copy: {
1531 ParmVarDecl *Param = Constructor->getParamDecl(0);
1532 QualType ParamType = Param->getType().getNonReferenceType();
1533
1534 Expr *CopyCtorArg =
1535 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregor62b71f42010-05-03 15:43:53 +00001536 Constructor->getLocation(), ParamType, 0);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001537
Anders Carlssonc7957502010-04-24 22:02:54 +00001538 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00001539 QualType ArgTy =
1540 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1541 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00001542
1543 CXXCastPath BasePath;
1544 BasePath.push_back(BaseSpec);
Sebastian Redl906082e2010-07-20 04:20:21 +00001545 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
Anders Carlssonc7957502010-04-24 22:02:54 +00001546 CastExpr::CK_UncheckedDerivedToBase,
John McCallf871d0c2010-08-07 06:22:56 +00001547 ImplicitCastExpr::LValue, &BasePath);
Anders Carlssonc7957502010-04-24 22:02:54 +00001548
Anders Carlssone5ef7402010-04-23 03:10:23 +00001549 InitializationKind InitKind
1550 = InitializationKind::CreateDirect(Constructor->getLocation(),
1551 SourceLocation(), SourceLocation());
1552 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1553 &CopyCtorArg, 1);
1554 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1555 Sema::MultiExprArg(SemaRef,
John McCallca0408f2010-08-23 06:44:23 +00001556 &CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00001557 break;
1558 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001559
Anders Carlssone5ef7402010-04-23 03:10:23 +00001560 case IIK_Move:
1561 assert(false && "Unhandled initializer kind!");
1562 }
1563
Anders Carlsson84688f22010-04-20 23:11:20 +00001564 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1565 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00001566 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00001567
Anders Carlssondefefd22010-04-23 02:00:02 +00001568 CXXBaseInit =
Anders Carlsson84688f22010-04-20 23:11:20 +00001569 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1570 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1571 SourceLocation()),
1572 BaseSpec->isVirtual(),
1573 SourceLocation(),
1574 BaseInit.takeAs<Expr>(),
1575 SourceLocation());
1576
Anders Carlssondefefd22010-04-23 02:00:02 +00001577 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00001578}
1579
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001580static bool
1581BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001582 ImplicitInitializerKind ImplicitInitKind,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001583 FieldDecl *Field,
1584 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00001585 if (Field->isInvalidDecl())
1586 return true;
1587
Chandler Carruthf186b542010-06-29 23:50:44 +00001588 SourceLocation Loc = Constructor->getLocation();
1589
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001590 if (ImplicitInitKind == IIK_Copy) {
1591 ParmVarDecl *Param = Constructor->getParamDecl(0);
1592 QualType ParamType = Param->getType().getNonReferenceType();
1593
1594 Expr *MemberExprBase =
1595 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001596 Loc, ParamType, 0);
1597
1598 // Build a reference to this field within the parameter.
1599 CXXScopeSpec SS;
1600 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1601 Sema::LookupMemberName);
1602 MemberLookup.addDecl(Field, AS_public);
1603 MemberLookup.resolveKind();
1604 Sema::OwningExprResult CopyCtorArg
1605 = SemaRef.BuildMemberReferenceExpr(SemaRef.Owned(MemberExprBase),
1606 ParamType, Loc,
1607 /*IsArrow=*/false,
1608 SS,
1609 /*FirstQualifierInScope=*/0,
1610 MemberLookup,
1611 /*TemplateArgs=*/0);
1612 if (CopyCtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001613 return true;
1614
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001615 // When the field we are copying is an array, create index variables for
1616 // each dimension of the array. We use these index variables to subscript
1617 // the source array, and other clients (e.g., CodeGen) will perform the
1618 // necessary iteration with these index variables.
1619 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1620 QualType BaseType = Field->getType();
1621 QualType SizeType = SemaRef.Context.getSizeType();
1622 while (const ConstantArrayType *Array
1623 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1624 // Create the iteration variable for this array index.
1625 IdentifierInfo *IterationVarName = 0;
1626 {
1627 llvm::SmallString<8> Str;
1628 llvm::raw_svector_ostream OS(Str);
1629 OS << "__i" << IndexVariables.size();
1630 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1631 }
1632 VarDecl *IterationVar
1633 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1634 IterationVarName, SizeType,
1635 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
1636 VarDecl::None, VarDecl::None);
1637 IndexVariables.push_back(IterationVar);
1638
1639 // Create a reference to the iteration variable.
1640 Sema::OwningExprResult IterationVarRef
1641 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1642 assert(!IterationVarRef.isInvalid() &&
1643 "Reference to invented variable cannot fail!");
1644
1645 // Subscript the array with this iteration variable.
1646 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(move(CopyCtorArg),
1647 Loc,
1648 move(IterationVarRef),
1649 Loc);
1650 if (CopyCtorArg.isInvalid())
1651 return true;
1652
1653 BaseType = Array->getElementType();
1654 }
1655
1656 // Construct the entity that we will be initializing. For an array, this
1657 // will be first element in the array, which may require several levels
1658 // of array-subscript entities.
1659 llvm::SmallVector<InitializedEntity, 4> Entities;
1660 Entities.reserve(1 + IndexVariables.size());
1661 Entities.push_back(InitializedEntity::InitializeMember(Field));
1662 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1663 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1664 0,
1665 Entities.back()));
1666
1667 // Direct-initialize to use the copy constructor.
1668 InitializationKind InitKind =
1669 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1670
1671 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1672 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1673 &CopyCtorArgE, 1);
1674
1675 Sema::OwningExprResult MemberInit
1676 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallca0408f2010-08-23 06:44:23 +00001677 Sema::MultiExprArg(SemaRef, &CopyCtorArgE, 1));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001678 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1679 if (MemberInit.isInvalid())
1680 return true;
1681
1682 CXXMemberInit
1683 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1684 MemberInit.takeAs<Expr>(), Loc,
1685 IndexVariables.data(),
1686 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00001687 return false;
1688 }
1689
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001690 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1691
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001692 QualType FieldBaseElementType =
1693 SemaRef.Context.getBaseElementType(Field->getType());
1694
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001695 if (FieldBaseElementType->isRecordType()) {
1696 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00001697 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00001698 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001699
1700 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1701 Sema::OwningExprResult MemberInit =
1702 InitSeq.Perform(SemaRef, InitEntity, InitKind,
1703 Sema::MultiExprArg(SemaRef, 0, 0));
1704 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1705 if (MemberInit.isInvalid())
1706 return true;
1707
1708 CXXMemberInit =
1709 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruthf186b542010-06-29 23:50:44 +00001710 Field, Loc, Loc,
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001711 MemberInit.takeAs<Expr>(),
Chandler Carruthf186b542010-06-29 23:50:44 +00001712 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001713 return false;
1714 }
Anders Carlsson114a2972010-04-23 03:07:47 +00001715
1716 if (FieldBaseElementType->isReferenceType()) {
1717 SemaRef.Diag(Constructor->getLocation(),
1718 diag::err_uninitialized_member_in_ctor)
1719 << (int)Constructor->isImplicit()
1720 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1721 << 0 << Field->getDeclName();
1722 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1723 return true;
1724 }
1725
1726 if (FieldBaseElementType.isConstQualified()) {
1727 SemaRef.Diag(Constructor->getLocation(),
1728 diag::err_uninitialized_member_in_ctor)
1729 << (int)Constructor->isImplicit()
1730 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1731 << 1 << Field->getDeclName();
1732 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1733 return true;
1734 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001735
1736 // Nothing to initialize.
1737 CXXMemberInit = 0;
1738 return false;
1739}
John McCallf1860e52010-05-20 23:23:51 +00001740
1741namespace {
1742struct BaseAndFieldInfo {
1743 Sema &S;
1744 CXXConstructorDecl *Ctor;
1745 bool AnyErrorsInInits;
1746 ImplicitInitializerKind IIK;
1747 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1748 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1749
1750 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1751 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1752 // FIXME: Handle implicit move constructors.
1753 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1754 IIK = IIK_Copy;
1755 else
1756 IIK = IIK_Default;
1757 }
1758};
1759}
1760
Chandler Carruthe861c602010-06-30 02:59:29 +00001761static void RecordFieldInitializer(BaseAndFieldInfo &Info,
1762 FieldDecl *Top, FieldDecl *Field,
1763 CXXBaseOrMemberInitializer *Init) {
1764 // If the member doesn't need to be initialized, Init will still be null.
1765 if (!Init)
1766 return;
1767
1768 Info.AllToInit.push_back(Init);
1769 if (Field != Top) {
1770 Init->setMember(Top);
1771 Init->setAnonUnionMember(Field);
1772 }
1773}
1774
John McCallf1860e52010-05-20 23:23:51 +00001775static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1776 FieldDecl *Top, FieldDecl *Field) {
1777
Chandler Carruthe861c602010-06-30 02:59:29 +00001778 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallf1860e52010-05-20 23:23:51 +00001779 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Chandler Carruthe861c602010-06-30 02:59:29 +00001780 RecordFieldInitializer(Info, Top, Field, Init);
John McCallf1860e52010-05-20 23:23:51 +00001781 return false;
1782 }
1783
1784 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1785 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1786 assert(FieldClassType && "anonymous struct/union without record type");
John McCallf1860e52010-05-20 23:23:51 +00001787 CXXRecordDecl *FieldClassDecl
1788 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruthe861c602010-06-30 02:59:29 +00001789
1790 // Even though union members never have non-trivial default
1791 // constructions in C++03, we still build member initializers for aggregate
1792 // record types which can be union members, and C++0x allows non-trivial
1793 // default constructors for union members, so we ensure that only one
1794 // member is initialized for these.
1795 if (FieldClassDecl->isUnion()) {
1796 // First check for an explicit initializer for one field.
1797 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1798 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1799 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
1800 RecordFieldInitializer(Info, Top, *FA, Init);
1801
1802 // Once we've initialized a field of an anonymous union, the union
1803 // field in the class is also initialized, so exit immediately.
1804 return false;
Argyrios Kyrtzidis881b36c2010-08-16 17:27:13 +00001805 } else if ((*FA)->isAnonymousStructOrUnion()) {
1806 if (CollectFieldInitializer(Info, Top, *FA))
1807 return true;
Chandler Carruthe861c602010-06-30 02:59:29 +00001808 }
1809 }
1810
1811 // Fallthrough and construct a default initializer for the union as
1812 // a whole, which can call its default constructor if such a thing exists
1813 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1814 // behavior going forward with C++0x, when anonymous unions there are
1815 // finalized, we should revisit this.
1816 } else {
1817 // For structs, we simply descend through to initialize all members where
1818 // necessary.
1819 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1820 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1821 if (CollectFieldInitializer(Info, Top, *FA))
1822 return true;
1823 }
1824 }
John McCallf1860e52010-05-20 23:23:51 +00001825 }
1826
1827 // Don't try to build an implicit initializer if there were semantic
1828 // errors in any of the initializers (and therefore we might be
1829 // missing some that the user actually wrote).
1830 if (Info.AnyErrorsInInits)
1831 return false;
1832
1833 CXXBaseOrMemberInitializer *Init = 0;
1834 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1835 return true;
John McCallf1860e52010-05-20 23:23:51 +00001836
Chandler Carruthe861c602010-06-30 02:59:29 +00001837 RecordFieldInitializer(Info, Top, Field, Init);
John McCallf1860e52010-05-20 23:23:51 +00001838 return false;
1839}
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001840
Eli Friedman80c30da2009-11-09 19:20:36 +00001841bool
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00001842Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001843 CXXBaseOrMemberInitializer **Initializers,
1844 unsigned NumInitializers,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00001845 bool AnyErrors) {
John McCalld6ca8da2010-04-10 07:37:23 +00001846 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001847 // Just store the initializers as written, they will be checked during
1848 // instantiation.
1849 if (NumInitializers > 0) {
1850 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1851 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1852 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1853 memcpy(baseOrMemberInitializers, Initializers,
1854 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1855 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1856 }
1857
1858 return false;
1859 }
1860
John McCallf1860e52010-05-20 23:23:51 +00001861 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00001862
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001863 // We need to build the initializer AST according to order of construction
1864 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00001865 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00001866 if (!ClassDecl)
1867 return true;
1868
Eli Friedman80c30da2009-11-09 19:20:36 +00001869 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001871 for (unsigned i = 0; i < NumInitializers; i++) {
1872 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001873
1874 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00001875 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001876 else
John McCallf1860e52010-05-20 23:23:51 +00001877 Info.AllBaseFields[Member->getMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001878 }
1879
Anders Carlsson711f34a2010-04-21 19:52:01 +00001880 // Keep track of the direct virtual bases.
1881 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1882 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1883 E = ClassDecl->bases_end(); I != E; ++I) {
1884 if (I->isVirtual())
1885 DirectVBases.insert(I);
1886 }
1887
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001888 // Push virtual bases before others.
1889 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1890 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1891
1892 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001893 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1894 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001895 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00001896 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlssondefefd22010-04-23 02:00:02 +00001897 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001898 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001899 VBase, IsInheritedVirtualBase,
1900 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001901 HadError = true;
1902 continue;
1903 }
Anders Carlsson84688f22010-04-20 23:11:20 +00001904
John McCallf1860e52010-05-20 23:23:51 +00001905 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001906 }
1907 }
Mike Stump1eb44332009-09-09 15:08:12 +00001908
John McCallf1860e52010-05-20 23:23:51 +00001909 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001910 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1911 E = ClassDecl->bases_end(); Base != E; ++Base) {
1912 // Virtuals are in the virtual base list and already constructed.
1913 if (Base->isVirtual())
1914 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001915
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001916 if (CXXBaseOrMemberInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00001917 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1918 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001919 } else if (!AnyErrors) {
Anders Carlssondefefd22010-04-23 02:00:02 +00001920 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00001921 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00001922 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00001923 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001924 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001925 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00001926 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001927
John McCallf1860e52010-05-20 23:23:51 +00001928 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001929 }
1930 }
Mike Stump1eb44332009-09-09 15:08:12 +00001931
John McCallf1860e52010-05-20 23:23:51 +00001932 // Fields.
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001933 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001934 E = ClassDecl->field_end(); Field != E; ++Field) {
1935 if ((*Field)->getType()->isIncompleteArrayType()) {
1936 assert(ClassDecl->hasFlexibleArrayMember() &&
1937 "Incomplete array type is not valid");
1938 continue;
1939 }
John McCallf1860e52010-05-20 23:23:51 +00001940 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlssonddfb75f2010-04-23 02:15:47 +00001941 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00001942 }
Mike Stump1eb44332009-09-09 15:08:12 +00001943
John McCallf1860e52010-05-20 23:23:51 +00001944 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001945 if (NumInitializers > 0) {
1946 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1947 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1948 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00001949 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCallef027fe2010-03-16 21:39:52 +00001950 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001951 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00001952
John McCallef027fe2010-03-16 21:39:52 +00001953 // Constructors implicitly reference the base and member
1954 // destructors.
1955 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1956 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001957 }
Eli Friedman80c30da2009-11-09 19:20:36 +00001958
1959 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001960}
1961
Eli Friedman6347f422009-07-21 19:28:10 +00001962static void *GetKeyForTopLevelField(FieldDecl *Field) {
1963 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001964 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001965 if (RT->getDecl()->isAnonymousStructOrUnion())
1966 return static_cast<void *>(RT->getDecl());
1967 }
1968 return static_cast<void *>(Field);
1969}
1970
Anders Carlssonea356fb2010-04-02 05:42:15 +00001971static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1972 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001973}
1974
Anders Carlssonea356fb2010-04-02 05:42:15 +00001975static void *GetKeyForMember(ASTContext &Context,
1976 CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001977 bool MemberMaybeAnon = false) {
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001978 if (!Member->isMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00001979 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001980
Eli Friedman6347f422009-07-21 19:28:10 +00001981 // For fields injected into the class via declaration of an anonymous union,
1982 // use its anonymous union class declaration as the unique key.
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001983 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001984
Anders Carlsson8f1a2402010-03-30 15:39:27 +00001985 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1986 // data member of the class. Data member used in the initializer list is
1987 // in AnonUnionMember field.
1988 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1989 Field = Member->getAnonUnionMember();
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001990
John McCall3c3ccdb2010-04-10 09:28:51 +00001991 // If the field is a member of an anonymous struct or union, our key
1992 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00001993 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00001994 if (RD->isAnonymousStructOrUnion()) {
1995 while (true) {
1996 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1997 if (Parent->isAnonymousStructOrUnion())
1998 RD = Parent;
1999 else
2000 break;
2001 }
2002
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002003 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00002004 }
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002006 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00002007}
2008
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002009static void
2010DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00002011 const CXXConstructorDecl *Constructor,
John McCalld6ca8da2010-04-10 07:37:23 +00002012 CXXBaseOrMemberInitializer **Inits,
2013 unsigned NumInits) {
2014 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00002015 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002016
John McCalld6ca8da2010-04-10 07:37:23 +00002017 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
2018 == Diagnostic::Ignored)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002019 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002020
John McCalld6ca8da2010-04-10 07:37:23 +00002021 // Build the list of bases and members in the order that they'll
2022 // actually be initialized. The explicit initializers should be in
2023 // this same order but may be missing things.
2024 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Anders Carlsson071d6102010-04-02 03:38:04 +00002026 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2027
John McCalld6ca8da2010-04-10 07:37:23 +00002028 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002029 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002030 ClassDecl->vbases_begin(),
2031 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00002032 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002033
John McCalld6ca8da2010-04-10 07:37:23 +00002034 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00002035 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002036 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002037 if (Base->isVirtual())
2038 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00002039 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002040 }
Mike Stump1eb44332009-09-09 15:08:12 +00002041
John McCalld6ca8da2010-04-10 07:37:23 +00002042 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002043 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2044 E = ClassDecl->field_end(); Field != E; ++Field)
John McCalld6ca8da2010-04-10 07:37:23 +00002045 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00002046
John McCalld6ca8da2010-04-10 07:37:23 +00002047 unsigned NumIdealInits = IdealInitKeys.size();
2048 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00002049
John McCalld6ca8da2010-04-10 07:37:23 +00002050 CXXBaseOrMemberInitializer *PrevInit = 0;
2051 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2052 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2053 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
2054
2055 // Scan forward to try to find this initializer in the idealized
2056 // initializers list.
2057 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2058 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002059 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002060
2061 // If we didn't find this initializer, it must be because we
2062 // scanned past it on a previous iteration. That can only
2063 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00002064 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00002065 Sema::SemaDiagnosticBuilder D =
2066 SemaRef.Diag(PrevInit->getSourceLocation(),
2067 diag::warn_initializer_out_of_order);
2068
2069 if (PrevInit->isMemberInitializer())
2070 D << 0 << PrevInit->getMember()->getDeclName();
2071 else
2072 D << 1 << PrevInit->getBaseClassInfo()->getType();
2073
2074 if (Init->isMemberInitializer())
2075 D << 0 << Init->getMember()->getDeclName();
2076 else
2077 D << 1 << Init->getBaseClassInfo()->getType();
2078
2079 // Move back to the initializer's location in the ideal list.
2080 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2081 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00002082 break;
John McCalld6ca8da2010-04-10 07:37:23 +00002083
2084 assert(IdealIndex != NumIdealInits &&
2085 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002086 }
John McCalld6ca8da2010-04-10 07:37:23 +00002087
2088 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00002089 }
Anders Carlssona7b35212009-03-25 02:58:17 +00002090}
2091
John McCall3c3ccdb2010-04-10 09:28:51 +00002092namespace {
2093bool CheckRedundantInit(Sema &S,
2094 CXXBaseOrMemberInitializer *Init,
2095 CXXBaseOrMemberInitializer *&PrevInit) {
2096 if (!PrevInit) {
2097 PrevInit = Init;
2098 return false;
2099 }
2100
2101 if (FieldDecl *Field = Init->getMember())
2102 S.Diag(Init->getSourceLocation(),
2103 diag::err_multiple_mem_initialization)
2104 << Field->getDeclName()
2105 << Init->getSourceRange();
2106 else {
2107 Type *BaseClass = Init->getBaseClass();
2108 assert(BaseClass && "neither field nor base");
2109 S.Diag(Init->getSourceLocation(),
2110 diag::err_multiple_base_initialization)
2111 << QualType(BaseClass, 0)
2112 << Init->getSourceRange();
2113 }
2114 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2115 << 0 << PrevInit->getSourceRange();
2116
2117 return true;
2118}
2119
2120typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2121typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2122
2123bool CheckRedundantUnionInit(Sema &S,
2124 CXXBaseOrMemberInitializer *Init,
2125 RedundantUnionMap &Unions) {
2126 FieldDecl *Field = Init->getMember();
2127 RecordDecl *Parent = Field->getParent();
2128 if (!Parent->isAnonymousStructOrUnion())
2129 return false;
2130
2131 NamedDecl *Child = Field;
2132 do {
2133 if (Parent->isUnion()) {
2134 UnionEntry &En = Unions[Parent];
2135 if (En.first && En.first != Child) {
2136 S.Diag(Init->getSourceLocation(),
2137 diag::err_multiple_mem_union_initialization)
2138 << Field->getDeclName()
2139 << Init->getSourceRange();
2140 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2141 << 0 << En.second->getSourceRange();
2142 return true;
2143 } else if (!En.first) {
2144 En.first = Child;
2145 En.second = Init;
2146 }
2147 }
2148
2149 Child = Parent;
2150 Parent = cast<RecordDecl>(Parent->getDeclContext());
2151 } while (Parent->isAnonymousStructOrUnion());
2152
2153 return false;
2154}
2155}
2156
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002157/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00002158void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002159 SourceLocation ColonLoc,
2160 MemInitTy **meminits, unsigned NumMemInits,
2161 bool AnyErrors) {
2162 if (!ConstructorDecl)
2163 return;
2164
2165 AdjustDeclIfTemplate(ConstructorDecl);
2166
2167 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002168 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002169
2170 if (!Constructor) {
2171 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2172 return;
2173 }
2174
2175 CXXBaseOrMemberInitializer **MemInits =
2176 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00002177
2178 // Mapping for the duplicate initializers check.
2179 // For member initializers, this is keyed with a FieldDecl*.
2180 // For base initializers, this is keyed with a Type*.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002181 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00002182
2183 // Mapping for the inconsistent anonymous-union initializers check.
2184 RedundantUnionMap MemberUnions;
2185
Anders Carlssonea356fb2010-04-02 05:42:15 +00002186 bool HadError = false;
2187 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall3c3ccdb2010-04-10 09:28:51 +00002188 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002189
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00002190 // Set the source order index.
2191 Init->setSourceOrder(i);
2192
John McCall3c3ccdb2010-04-10 09:28:51 +00002193 if (Init->isMemberInitializer()) {
2194 FieldDecl *Field = Init->getMember();
2195 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2196 CheckRedundantUnionInit(*this, Init, MemberUnions))
2197 HadError = true;
2198 } else {
2199 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2200 if (CheckRedundantInit(*this, Init, Members[Key]))
2201 HadError = true;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002202 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002203 }
2204
Anders Carlssonea356fb2010-04-02 05:42:15 +00002205 if (HadError)
2206 return;
2207
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002208 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00002209
2210 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00002211}
2212
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002213void
John McCallef027fe2010-03-16 21:39:52 +00002214Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2215 CXXRecordDecl *ClassDecl) {
2216 // Ignore dependent contexts.
2217 if (ClassDecl->isDependentContext())
Anders Carlsson9f853df2009-11-17 04:44:12 +00002218 return;
John McCall58e6f342010-03-16 05:22:47 +00002219
2220 // FIXME: all the access-control diagnostics are positioned on the
2221 // field/base declaration. That's probably good; that said, the
2222 // user might reasonably want to know why the destructor is being
2223 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002224
Anders Carlsson9f853df2009-11-17 04:44:12 +00002225 // Non-static data members.
2226 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2227 E = ClassDecl->field_end(); I != E; ++I) {
2228 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00002229 if (Field->isInvalidDecl())
2230 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00002231 QualType FieldType = Context.getBaseElementType(Field->getType());
2232
2233 const RecordType* RT = FieldType->getAs<RecordType>();
2234 if (!RT)
2235 continue;
2236
2237 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2238 if (FieldClassDecl->hasTrivialDestructor())
2239 continue;
2240
Douglas Gregordb89f282010-07-01 22:47:18 +00002241 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002242 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002243 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00002244 << Field->getDeclName()
2245 << FieldType);
2246
John McCallef027fe2010-03-16 21:39:52 +00002247 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002248 }
2249
John McCall58e6f342010-03-16 05:22:47 +00002250 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2251
Anders Carlsson9f853df2009-11-17 04:44:12 +00002252 // Bases.
2253 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2254 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00002255 // Bases are always records in a well-formed non-dependent class.
2256 const RecordType *RT = Base->getType()->getAs<RecordType>();
2257
2258 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00002259 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00002260 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00002261
2262 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002263 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002264 if (BaseClassDecl->hasTrivialDestructor())
2265 continue;
John McCall58e6f342010-03-16 05:22:47 +00002266
Douglas Gregordb89f282010-07-01 22:47:18 +00002267 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002268
2269 // FIXME: caret should be on the start of the class name
2270 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002271 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00002272 << Base->getType()
2273 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00002274
John McCallef027fe2010-03-16 21:39:52 +00002275 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00002276 }
2277
2278 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002279 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2280 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00002281
2282 // Bases are always records in a well-formed non-dependent class.
2283 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2284
2285 // Ignore direct virtual bases.
2286 if (DirectVirtualBases.count(RT))
2287 continue;
2288
Anders Carlsson9f853df2009-11-17 04:44:12 +00002289 // Ignore trivial destructors.
John McCall58e6f342010-03-16 05:22:47 +00002290 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002291 if (BaseClassDecl->hasTrivialDestructor())
2292 continue;
John McCall58e6f342010-03-16 05:22:47 +00002293
Douglas Gregordb89f282010-07-01 22:47:18 +00002294 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall58e6f342010-03-16 05:22:47 +00002295 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002296 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00002297 << VBase->getType());
2298
John McCallef027fe2010-03-16 21:39:52 +00002299 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002300 }
2301}
2302
John McCalld226f652010-08-21 09:40:31 +00002303void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00002304 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002305 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002306
Mike Stump1eb44332009-09-09 15:08:12 +00002307 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002308 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlssonec3332b2010-04-02 03:43:34 +00002309 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00002310}
2311
Mike Stump1eb44332009-09-09 15:08:12 +00002312bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002313 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002314 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00002315 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002316 else
John McCall94c3b562010-08-18 09:41:07 +00002317 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00002318}
2319
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002320bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00002321 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002322 if (!getLangOptions().CPlusPlus)
2323 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002324
Anders Carlsson11f21a02009-03-23 19:10:31 +00002325 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00002326 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00002327
Ted Kremenek6217b802009-07-29 21:53:49 +00002328 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002329 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002330 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002331 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00002332
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002333 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00002334 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00002335 }
Mike Stump1eb44332009-09-09 15:08:12 +00002336
Ted Kremenek6217b802009-07-29 21:53:49 +00002337 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002338 if (!RT)
2339 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002340
John McCall86ff3082010-02-04 22:26:26 +00002341 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002342
John McCall94c3b562010-08-18 09:41:07 +00002343 // We can't answer whether something is abstract until it has a
2344 // definition. If it's currently being defined, we'll walk back
2345 // over all the declarations when we have a full definition.
2346 const CXXRecordDecl *Def = RD->getDefinition();
2347 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00002348 return false;
2349
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002350 if (!RD->isAbstract())
2351 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002352
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00002353 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00002354 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00002355
John McCall94c3b562010-08-18 09:41:07 +00002356 return true;
2357}
2358
2359void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2360 // Check if we've already emitted the list of pure virtual functions
2361 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002362 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00002363 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002364
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002365 CXXFinalOverriderMap FinalOverriders;
2366 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00002367
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002368 // Keep a set of seen pure methods so we won't diagnose the same method
2369 // more than once.
2370 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2371
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002372 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2373 MEnd = FinalOverriders.end();
2374 M != MEnd;
2375 ++M) {
2376 for (OverridingMethods::iterator SO = M->second.begin(),
2377 SOEnd = M->second.end();
2378 SO != SOEnd; ++SO) {
2379 // C++ [class.abstract]p4:
2380 // A class is abstract if it contains or inherits at least one
2381 // pure virtual function for which the final overrider is pure
2382 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00002383
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002384 //
2385 if (SO->second.size() != 1)
2386 continue;
2387
2388 if (!SO->second.front().Method->isPure())
2389 continue;
2390
Anders Carlssonffdb2d22010-06-03 01:00:02 +00002391 if (!SeenPureMethods.insert(SO->second.front().Method))
2392 continue;
2393
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002394 Diag(SO->second.front().Method->getLocation(),
2395 diag::note_pure_virtual_function)
2396 << SO->second.front().Method->getDeclName();
2397 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002398 }
2399
2400 if (!PureVirtualClassDiagSet)
2401 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2402 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00002403}
2404
Anders Carlsson8211eff2009-03-24 01:19:16 +00002405namespace {
John McCall94c3b562010-08-18 09:41:07 +00002406struct AbstractUsageInfo {
2407 Sema &S;
2408 CXXRecordDecl *Record;
2409 CanQualType AbstractType;
2410 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00002411
John McCall94c3b562010-08-18 09:41:07 +00002412 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2413 : S(S), Record(Record),
2414 AbstractType(S.Context.getCanonicalType(
2415 S.Context.getTypeDeclType(Record))),
2416 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00002417
John McCall94c3b562010-08-18 09:41:07 +00002418 void DiagnoseAbstractType() {
2419 if (Invalid) return;
2420 S.DiagnoseAbstractType(Record);
2421 Invalid = true;
2422 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00002423
John McCall94c3b562010-08-18 09:41:07 +00002424 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2425};
2426
2427struct CheckAbstractUsage {
2428 AbstractUsageInfo &Info;
2429 const NamedDecl *Ctx;
2430
2431 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2432 : Info(Info), Ctx(Ctx) {}
2433
2434 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2435 switch (TL.getTypeLocClass()) {
2436#define ABSTRACT_TYPELOC(CLASS, PARENT)
2437#define TYPELOC(CLASS, PARENT) \
2438 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2439#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00002440 }
John McCall94c3b562010-08-18 09:41:07 +00002441 }
Mike Stump1eb44332009-09-09 15:08:12 +00002442
John McCall94c3b562010-08-18 09:41:07 +00002443 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2444 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2445 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2446 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2447 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002448 }
John McCall94c3b562010-08-18 09:41:07 +00002449 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002450
John McCall94c3b562010-08-18 09:41:07 +00002451 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2452 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2453 }
Mike Stump1eb44332009-09-09 15:08:12 +00002454
John McCall94c3b562010-08-18 09:41:07 +00002455 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2456 // Visit the type parameters from a permissive context.
2457 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2458 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2459 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2460 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2461 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2462 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00002463 }
John McCall94c3b562010-08-18 09:41:07 +00002464 }
Mike Stump1eb44332009-09-09 15:08:12 +00002465
John McCall94c3b562010-08-18 09:41:07 +00002466 // Visit pointee types from a permissive context.
2467#define CheckPolymorphic(Type) \
2468 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2469 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2470 }
2471 CheckPolymorphic(PointerTypeLoc)
2472 CheckPolymorphic(ReferenceTypeLoc)
2473 CheckPolymorphic(MemberPointerTypeLoc)
2474 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00002475
John McCall94c3b562010-08-18 09:41:07 +00002476 /// Handle all the types we haven't given a more specific
2477 /// implementation for above.
2478 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2479 // Every other kind of type that we haven't called out already
2480 // that has an inner type is either (1) sugar or (2) contains that
2481 // inner type in some way as a subobject.
2482 if (TypeLoc Next = TL.getNextTypeLoc())
2483 return Visit(Next, Sel);
2484
2485 // If there's no inner type and we're in a permissive context,
2486 // don't diagnose.
2487 if (Sel == Sema::AbstractNone) return;
2488
2489 // Check whether the type matches the abstract type.
2490 QualType T = TL.getType();
2491 if (T->isArrayType()) {
2492 Sel = Sema::AbstractArrayType;
2493 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00002494 }
John McCall94c3b562010-08-18 09:41:07 +00002495 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2496 if (CT != Info.AbstractType) return;
2497
2498 // It matched; do some magic.
2499 if (Sel == Sema::AbstractArrayType) {
2500 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2501 << T << TL.getSourceRange();
2502 } else {
2503 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2504 << Sel << T << TL.getSourceRange();
2505 }
2506 Info.DiagnoseAbstractType();
2507 }
2508};
2509
2510void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2511 Sema::AbstractDiagSelID Sel) {
2512 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2513}
2514
2515}
2516
2517/// Check for invalid uses of an abstract type in a method declaration.
2518static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2519 CXXMethodDecl *MD) {
2520 // No need to do the check on definitions, which require that
2521 // the return/param types be complete.
2522 if (MD->isThisDeclarationADefinition())
2523 return;
2524
2525 // For safety's sake, just ignore it if we don't have type source
2526 // information. This should never happen for non-implicit methods,
2527 // but...
2528 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2529 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2530}
2531
2532/// Check for invalid uses of an abstract type within a class definition.
2533static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2534 CXXRecordDecl *RD) {
2535 for (CXXRecordDecl::decl_iterator
2536 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2537 Decl *D = *I;
2538 if (D->isImplicit()) continue;
2539
2540 // Methods and method templates.
2541 if (isa<CXXMethodDecl>(D)) {
2542 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2543 } else if (isa<FunctionTemplateDecl>(D)) {
2544 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2545 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2546
2547 // Fields and static variables.
2548 } else if (isa<FieldDecl>(D)) {
2549 FieldDecl *FD = cast<FieldDecl>(D);
2550 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2551 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2552 } else if (isa<VarDecl>(D)) {
2553 VarDecl *VD = cast<VarDecl>(D);
2554 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2555 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2556
2557 // Nested classes and class templates.
2558 } else if (isa<CXXRecordDecl>(D)) {
2559 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2560 } else if (isa<ClassTemplateDecl>(D)) {
2561 CheckAbstractClassUsage(Info,
2562 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2563 }
2564 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00002565}
2566
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002567/// \brief Perform semantic checks on a class definition that has been
2568/// completing, introducing implicitly-declared members, checking for
2569/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002570void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002571 if (!Record || Record->isInvalidDecl())
2572 return;
2573
Eli Friedmanff2d8782009-12-16 20:00:27 +00002574 if (!Record->isDependentType())
Douglas Gregor23c94db2010-07-02 17:43:08 +00002575 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor159ef1e2010-01-06 04:44:19 +00002576
Eli Friedmanff2d8782009-12-16 20:00:27 +00002577 if (Record->isInvalidDecl())
2578 return;
2579
John McCall233a6412010-01-28 07:38:46 +00002580 // Set access bits correctly on the directly-declared conversions.
2581 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2582 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2583 Convs->setAccess(I, (*I)->getAccess());
2584
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002585 // Determine whether we need to check for final overriders. We do
2586 // this either when there are virtual base classes (in which case we
2587 // may end up finding multiple final overriders for a given virtual
2588 // function) or any of the base classes is abstract (in which case
2589 // we might detect that this class is abstract).
2590 bool CheckFinalOverriders = false;
2591 if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2592 !Record->isDependentType()) {
2593 if (Record->getNumVBases())
2594 CheckFinalOverriders = true;
2595 else if (!Record->isAbstract()) {
2596 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2597 BEnd = Record->bases_end();
2598 B != BEnd; ++B) {
2599 CXXRecordDecl *BaseDecl
2600 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2601 if (BaseDecl->isAbstract()) {
2602 CheckFinalOverriders = true;
2603 break;
2604 }
2605 }
2606 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002607 }
2608
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00002609 if (CheckFinalOverriders) {
2610 CXXFinalOverriderMap FinalOverriders;
2611 Record->getFinalOverriders(FinalOverriders);
2612
2613 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2614 MEnd = FinalOverriders.end();
2615 M != MEnd; ++M) {
2616 for (OverridingMethods::iterator SO = M->second.begin(),
2617 SOEnd = M->second.end();
2618 SO != SOEnd; ++SO) {
2619 assert(SO->second.size() > 0 &&
2620 "All virtual functions have overridding virtual functions");
2621 if (SO->second.size() == 1) {
2622 // C++ [class.abstract]p4:
2623 // A class is abstract if it contains or inherits at least one
2624 // pure virtual function for which the final overrider is pure
2625 // virtual.
2626 if (SO->second.front().Method->isPure())
2627 Record->setAbstract(true);
2628 continue;
2629 }
2630
2631 // C++ [class.virtual]p2:
2632 // In a derived class, if a virtual member function of a base
2633 // class subobject has more than one final overrider the
2634 // program is ill-formed.
2635 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2636 << (NamedDecl *)M->first << Record;
2637 Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2638 for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2639 OMEnd = SO->second.end();
2640 OM != OMEnd; ++OM)
2641 Diag(OM->Method->getLocation(), diag::note_final_overrider)
2642 << (NamedDecl *)M->first << OM->Method->getParent();
2643
2644 Record->setInvalidDecl();
2645 }
2646 }
2647 }
2648
John McCall94c3b562010-08-18 09:41:07 +00002649 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2650 AbstractUsageInfo Info(*this, Record);
2651 CheckAbstractClassUsage(Info, Record);
2652 }
Douglas Gregor325e5932010-04-15 00:00:53 +00002653
2654 // If this is not an aggregate type and has no user-declared constructor,
2655 // complain about any non-static data members of reference or const scalar
2656 // type, since they will never get initializers.
2657 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2658 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2659 bool Complained = false;
2660 for (RecordDecl::field_iterator F = Record->field_begin(),
2661 FEnd = Record->field_end();
2662 F != FEnd; ++F) {
2663 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00002664 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00002665 if (!Complained) {
2666 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2667 << Record->getTagKind() << Record;
2668 Complained = true;
2669 }
2670
2671 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2672 << F->getType()->isReferenceType()
2673 << F->getDeclName();
2674 }
2675 }
2676 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002677
2678 if (Record->isDynamicClass())
2679 DynamicClasses.push_back(Record);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002680}
2681
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002682void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00002683 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002684 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002685 SourceLocation RBrac,
2686 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002687 if (!TagDecl)
2688 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002689
Douglas Gregor42af25f2009-05-11 19:58:34 +00002690 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00002691
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002692 ActOnFields(S, RLoc, TagDecl,
John McCalld226f652010-08-21 09:40:31 +00002693 // strict aliasing violation!
2694 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00002695 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00002696
Douglas Gregor23c94db2010-07-02 17:43:08 +00002697 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00002698 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002699}
2700
Douglas Gregord92ec472010-07-01 05:10:53 +00002701namespace {
2702 /// \brief Helper class that collects exception specifications for
2703 /// implicitly-declared special member functions.
2704 class ImplicitExceptionSpecification {
2705 ASTContext &Context;
2706 bool AllowsAllExceptions;
2707 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2708 llvm::SmallVector<QualType, 4> Exceptions;
2709
2710 public:
2711 explicit ImplicitExceptionSpecification(ASTContext &Context)
2712 : Context(Context), AllowsAllExceptions(false) { }
2713
2714 /// \brief Whether the special member function should have any
2715 /// exception specification at all.
2716 bool hasExceptionSpecification() const {
2717 return !AllowsAllExceptions;
2718 }
2719
2720 /// \brief Whether the special member function should have a
2721 /// throw(...) exception specification (a Microsoft extension).
2722 bool hasAnyExceptionSpecification() const {
2723 return false;
2724 }
2725
2726 /// \brief The number of exceptions in the exception specification.
2727 unsigned size() const { return Exceptions.size(); }
2728
2729 /// \brief The set of exceptions in the exception specification.
2730 const QualType *data() const { return Exceptions.data(); }
2731
2732 /// \brief Note that
2733 void CalledDecl(CXXMethodDecl *Method) {
2734 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor4681ca82010-07-01 15:29:53 +00002735 if (AllowsAllExceptions || !Method)
Douglas Gregord92ec472010-07-01 05:10:53 +00002736 return;
2737
2738 const FunctionProtoType *Proto
2739 = Method->getType()->getAs<FunctionProtoType>();
2740
2741 // If this function can throw any exceptions, make a note of that.
2742 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2743 AllowsAllExceptions = true;
2744 ExceptionsSeen.clear();
2745 Exceptions.clear();
2746 return;
2747 }
2748
2749 // Record the exceptions in this function's exception specification.
2750 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2751 EEnd = Proto->exception_end();
2752 E != EEnd; ++E)
2753 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2754 Exceptions.push_back(*E);
2755 }
2756 };
2757}
2758
2759
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002760/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2761/// special functions, such as the default constructor, copy
2762/// constructor, or destructor, to the given C++ class (C++
2763/// [special]p1). This routine can only be executed just before the
2764/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002765void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00002766 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00002767 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002768
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00002769 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00002770 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002771
Douglas Gregora376d102010-07-02 21:50:04 +00002772 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2773 ++ASTContext::NumImplicitCopyAssignmentOperators;
2774
2775 // If we have a dynamic class, then the copy assignment operator may be
2776 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2777 // it shows up in the right place in the vtable and that we diagnose
2778 // problems with the implicit exception specification.
2779 if (ClassDecl->isDynamicClass())
2780 DeclareImplicitCopyAssignment(ClassDecl);
2781 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002782
Douglas Gregor4923aa22010-07-02 20:37:36 +00002783 if (!ClassDecl->hasUserDeclaredDestructor()) {
2784 ++ASTContext::NumImplicitDestructors;
2785
2786 // If we have a dynamic class, then the destructor may be virtual, so we
2787 // have to declare the destructor immediately. This ensures that, e.g., it
2788 // shows up in the right place in the vtable and that we diagnose problems
2789 // with the implicit exception specification.
2790 if (ClassDecl->isDynamicClass())
2791 DeclareImplicitDestructor(ClassDecl);
2792 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00002793}
2794
John McCalld226f652010-08-21 09:40:31 +00002795void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00002796 if (!D)
2797 return;
2798
2799 TemplateParameterList *Params = 0;
2800 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2801 Params = Template->getTemplateParameters();
2802 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2803 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2804 Params = PartialSpec->getTemplateParameters();
2805 else
Douglas Gregor6569d682009-05-27 23:11:45 +00002806 return;
2807
Douglas Gregor6569d682009-05-27 23:11:45 +00002808 for (TemplateParameterList::iterator Param = Params->begin(),
2809 ParamEnd = Params->end();
2810 Param != ParamEnd; ++Param) {
2811 NamedDecl *Named = cast<NamedDecl>(*Param);
2812 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00002813 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00002814 IdResolver.AddDecl(Named);
2815 }
2816 }
2817}
2818
John McCalld226f652010-08-21 09:40:31 +00002819void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002820 if (!RecordD) return;
2821 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00002822 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00002823 PushDeclContext(S, Record);
2824}
2825
John McCalld226f652010-08-21 09:40:31 +00002826void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00002827 if (!RecordD) return;
2828 PopDeclContext();
2829}
2830
Douglas Gregor72b505b2008-12-16 21:30:33 +00002831/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2832/// parsing a top-level (non-nested) C++ class, and we are now
2833/// parsing those parts of the given Method declaration that could
2834/// not be parsed earlier (C++ [class.mem]p2), such as default
2835/// arguments. This action should enter the scope of the given
2836/// Method declaration as if we had just parsed the qualified method
2837/// name. However, it should not bring the parameters into scope;
2838/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00002839void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002840}
2841
2842/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2843/// C++ method declaration. We're (re-)introducing the given
2844/// function parameter into scope for use in parsing later parts of
2845/// the method declaration. For example, we could see an
2846/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00002847void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002848 if (!ParamD)
2849 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002850
John McCalld226f652010-08-21 09:40:31 +00002851 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00002852
2853 // If this parameter has an unparsed default argument, clear it out
2854 // to make way for the parsed default argument.
2855 if (Param->hasUnparsedDefaultArg())
2856 Param->setDefaultArg(0);
2857
John McCalld226f652010-08-21 09:40:31 +00002858 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002859 if (Param->getDeclName())
2860 IdResolver.AddDecl(Param);
2861}
2862
2863/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2864/// processing the delayed method declaration for Method. The method
2865/// declaration is now considered finished. There may be a separate
2866/// ActOnStartOfFunctionDef action later (not necessarily
2867/// immediately!) for this method, if it was also defined inside the
2868/// class body.
John McCalld226f652010-08-21 09:40:31 +00002869void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002870 if (!MethodD)
2871 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002872
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002873 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00002874
John McCalld226f652010-08-21 09:40:31 +00002875 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002876
2877 // Now that we have our default arguments, check the constructor
2878 // again. It could produce additional diagnostics or affect whether
2879 // the class has implicitly-declared destructors, among other
2880 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002881 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2882 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002883
2884 // Check the default arguments, which we may have added.
2885 if (!Method->isInvalidDecl())
2886 CheckCXXDefaultArguments(Method);
2887}
2888
Douglas Gregor42a552f2008-11-05 20:51:48 +00002889/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002890/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002891/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002892/// emit diagnostics and set the invalid bit to true. In any case, the type
2893/// will be updated to reflect a well-formed type for the constructor and
2894/// returned.
2895QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2896 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002897 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002898
2899 // C++ [class.ctor]p3:
2900 // A constructor shall not be virtual (10.3) or static (9.4). A
2901 // constructor can be invoked for a const, volatile or const
2902 // volatile object. A constructor shall not be declared const,
2903 // volatile, or const volatile (9.3.2).
2904 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002905 if (!D.isInvalidType())
2906 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2907 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2908 << SourceRange(D.getIdentifierLoc());
2909 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002910 }
2911 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002912 if (!D.isInvalidType())
2913 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2914 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2915 << SourceRange(D.getIdentifierLoc());
2916 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002917 SC = FunctionDecl::None;
2918 }
Mike Stump1eb44332009-09-09 15:08:12 +00002919
Chris Lattner65401802009-04-25 08:28:21 +00002920 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2921 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00002922 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002923 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2924 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002925 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002926 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2927 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00002928 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002929 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2930 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002931 }
Mike Stump1eb44332009-09-09 15:08:12 +00002932
Douglas Gregor42a552f2008-11-05 20:51:48 +00002933 // Rebuild the function type "R" without any type qualifiers (in
2934 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00002935 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00002936 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner65401802009-04-25 08:28:21 +00002937 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2938 Proto->getNumArgs(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002939 Proto->isVariadic(), 0,
2940 Proto->hasExceptionSpec(),
2941 Proto->hasAnyExceptionSpec(),
2942 Proto->getNumExceptions(),
2943 Proto->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00002944 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002945}
2946
Douglas Gregor72b505b2008-12-16 21:30:33 +00002947/// CheckConstructor - Checks a fully-formed constructor for
2948/// well-formedness, issuing any diagnostics required. Returns true if
2949/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002950void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002951 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002952 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2953 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002954 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002955
2956 // C++ [class.copy]p3:
2957 // A declaration of a constructor for a class X is ill-formed if
2958 // its first parameter is of type (optionally cv-qualified) X and
2959 // either there are no other parameters or else all other
2960 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002961 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002962 ((Constructor->getNumParams() == 1) ||
2963 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00002964 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2965 Constructor->getTemplateSpecializationKind()
2966 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002967 QualType ParamType = Constructor->getParamDecl(0)->getType();
2968 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2969 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002970 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002971 const char *ConstRef
2972 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2973 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00002974 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00002975 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002976
2977 // FIXME: Rather that making the constructor invalid, we should endeavor
2978 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00002979 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002980 }
2981 }
Mike Stump1eb44332009-09-09 15:08:12 +00002982
John McCall3d043362010-04-13 07:45:41 +00002983 // Notify the class that we've added a constructor. In principle we
2984 // don't need to do this for out-of-line declarations; in practice
2985 // we only instantiate the most recent declaration of a method, so
2986 // we have to call this for everything but friends.
2987 if (!Constructor->getFriendObjectKind())
2988 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002989}
2990
John McCall15442822010-08-04 01:04:25 +00002991/// CheckDestructor - Checks a fully-formed destructor definition for
2992/// well-formedness, issuing any diagnostics required. Returns true
2993/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002994bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00002995 CXXRecordDecl *RD = Destructor->getParent();
2996
2997 if (Destructor->isVirtual()) {
2998 SourceLocation Loc;
2999
3000 if (!Destructor->isImplicit())
3001 Loc = Destructor->getLocation();
3002 else
3003 Loc = RD->getLocation();
3004
3005 // If we have a virtual destructor, look up the deallocation function
3006 FunctionDecl *OperatorDelete = 0;
3007 DeclarationName Name =
3008 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00003009 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00003010 return true;
John McCall5efd91a2010-07-03 18:33:00 +00003011
3012 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00003013
3014 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00003015 }
Anders Carlsson37909802009-11-30 21:24:50 +00003016
3017 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00003018}
3019
Mike Stump1eb44332009-09-09 15:08:12 +00003020static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003021FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3022 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3023 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00003024 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003025}
3026
Douglas Gregor42a552f2008-11-05 20:51:48 +00003027/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3028/// the well-formednes of the destructor declarator @p D with type @p
3029/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00003030/// emit diagnostics and set the declarator to invalid. Even if this happens,
3031/// will be updated to reflect a well-formed type for the destructor and
3032/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00003033QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
Chris Lattner65401802009-04-25 08:28:21 +00003034 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003035 // C++ [class.dtor]p1:
3036 // [...] A typedef-name that names a class is a class-name
3037 // (7.1.3); however, a typedef-name that names a class shall not
3038 // be used as the identifier in the declarator for a destructor
3039 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003040 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregord92ec472010-07-01 05:10:53 +00003041 if (isa<TypedefType>(DeclaratorType))
Chris Lattner65401802009-04-25 08:28:21 +00003042 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00003043 << DeclaratorType;
Douglas Gregor42a552f2008-11-05 20:51:48 +00003044
3045 // C++ [class.dtor]p2:
3046 // A destructor is used to destroy objects of its class type. A
3047 // destructor takes no parameters, and no return type can be
3048 // specified for it (not even void). The address of a destructor
3049 // shall not be taken. A destructor shall not be static. A
3050 // destructor can be invoked for a const, volatile or const
3051 // volatile object. A destructor shall not be declared const,
3052 // volatile or const volatile (9.3.2).
3053 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00003054 if (!D.isInvalidType())
3055 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3056 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00003057 << SourceRange(D.getIdentifierLoc())
3058 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3059
Douglas Gregor42a552f2008-11-05 20:51:48 +00003060 SC = FunctionDecl::None;
3061 }
Chris Lattner65401802009-04-25 08:28:21 +00003062 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003063 // Destructors don't have return types, but the parser will
3064 // happily parse something like:
3065 //
3066 // class X {
3067 // float ~X();
3068 // };
3069 //
3070 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003071 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3072 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3073 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003074 }
Mike Stump1eb44332009-09-09 15:08:12 +00003075
Chris Lattner65401802009-04-25 08:28:21 +00003076 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3077 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00003078 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003079 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3080 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003081 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003082 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3083 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00003084 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003085 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3086 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00003087 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003088 }
3089
3090 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00003091 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003092 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3093
3094 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00003095 FTI.freeArgs();
3096 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00003097 }
3098
Mike Stump1eb44332009-09-09 15:08:12 +00003099 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00003100 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00003101 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00003102 D.setInvalidType();
3103 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00003104
3105 // Rebuild the function type "R" without any type qualifiers or
3106 // parameters (in case any of the errors above fired) and with
3107 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00003108 // types.
3109 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3110 if (!Proto)
3111 return QualType();
3112
Douglas Gregorce056bc2010-02-21 22:15:06 +00003113 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Douglas Gregord92ec472010-07-01 05:10:53 +00003114 Proto->hasExceptionSpec(),
3115 Proto->hasAnyExceptionSpec(),
3116 Proto->getNumExceptions(),
3117 Proto->exception_begin(),
3118 Proto->getExtInfo());
Douglas Gregor42a552f2008-11-05 20:51:48 +00003119}
3120
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003121/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3122/// well-formednes of the conversion function declarator @p D with
3123/// type @p R. If there are any errors in the declarator, this routine
3124/// will emit diagnostics and return true. Otherwise, it will return
3125/// false. Either way, the type @p R will be updated to reflect a
3126/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00003127void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003128 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003129 // C++ [class.conv.fct]p1:
3130 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00003131 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00003132 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003133 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00003134 if (!D.isInvalidType())
3135 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3136 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3137 << SourceRange(D.getIdentifierLoc());
3138 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003139 SC = FunctionDecl::None;
3140 }
John McCalla3f81372010-04-13 00:04:31 +00003141
3142 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3143
Chris Lattner6e475012009-04-25 08:35:12 +00003144 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003145 // Conversion functions don't have return types, but the parser will
3146 // happily parse something like:
3147 //
3148 // class X {
3149 // float operator bool();
3150 // };
3151 //
3152 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003153 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3154 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3155 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00003156 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003157 }
3158
John McCalla3f81372010-04-13 00:04:31 +00003159 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3160
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003161 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00003162 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003163 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3164
3165 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00003166 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00003167 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00003168 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003169 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00003170 D.setInvalidType();
3171 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003172
John McCalla3f81372010-04-13 00:04:31 +00003173 // Diagnose "&operator bool()" and other such nonsense. This
3174 // is actually a gcc extension which we don't support.
3175 if (Proto->getResultType() != ConvType) {
3176 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3177 << Proto->getResultType();
3178 D.setInvalidType();
3179 ConvType = Proto->getResultType();
3180 }
3181
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003182 // C++ [class.conv.fct]p4:
3183 // The conversion-type-id shall not represent a function type nor
3184 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003185 if (ConvType->isArrayType()) {
3186 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3187 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003188 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003189 } else if (ConvType->isFunctionType()) {
3190 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3191 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00003192 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003193 }
3194
3195 // Rebuild the function type "R" without any parameters (in case any
3196 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00003197 // return type.
John McCalla3f81372010-04-13 00:04:31 +00003198 if (D.isInvalidType()) {
3199 R = Context.getFunctionType(ConvType, 0, 0, false,
3200 Proto->getTypeQuals(),
3201 Proto->hasExceptionSpec(),
3202 Proto->hasAnyExceptionSpec(),
3203 Proto->getNumExceptions(),
3204 Proto->exception_begin(),
3205 Proto->getExtInfo());
3206 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003207
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003208 // C++0x explicit conversion operators.
3209 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00003210 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003211 diag::warn_explicit_conversion_functions)
3212 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003213}
3214
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003215/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3216/// the declaration of the given C++ conversion function. This routine
3217/// is responsible for recording the conversion function in the C++
3218/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00003219Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003220 assert(Conversion && "Expected to receive a conversion function declaration");
3221
Douglas Gregor9d350972008-12-12 08:25:50 +00003222 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003223
3224 // Make sure we aren't redeclaring the conversion function.
3225 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003226
3227 // C++ [class.conv.fct]p1:
3228 // [...] A conversion function is never used to convert a
3229 // (possibly cv-qualified) object to the (possibly cv-qualified)
3230 // same object type (or a reference to it), to a (possibly
3231 // cv-qualified) base class of that type (or a reference to it),
3232 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00003233 // FIXME: Suppress this warning if the conversion function ends up being a
3234 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00003235 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003236 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00003237 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003238 ConvType = ConvTypeRef->getPointeeType();
3239 if (ConvType->isRecordType()) {
3240 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3241 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00003242 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003243 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003244 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00003245 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003246 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003247 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00003248 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00003249 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003250 }
3251
Douglas Gregor48026d22010-01-11 18:40:55 +00003252 if (Conversion->getPrimaryTemplate()) {
3253 // ignore specializations
3254 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003255 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor0c551062010-01-11 18:53:25 +00003256 = Conversion->getDescribedFunctionTemplate()) {
3257 if (ClassDecl->replaceConversion(
3258 ConversionTemplate->getPreviousDeclaration(),
3259 ConversionTemplate))
John McCalld226f652010-08-21 09:40:31 +00003260 return ConversionTemplate;
Douglas Gregor0c551062010-01-11 18:53:25 +00003261 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3262 Conversion))
John McCalld226f652010-08-21 09:40:31 +00003263 return Conversion;
Douglas Gregor70316a02008-12-26 15:00:45 +00003264 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00003265 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003266 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00003267 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregor48026d22010-01-11 18:40:55 +00003268 else
Fariborz Jahaniandebc6292009-09-12 19:02:34 +00003269 ClassDecl->addConversionFunction(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003270
John McCalld226f652010-08-21 09:40:31 +00003271 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00003272}
3273
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003274//===----------------------------------------------------------------------===//
3275// Namespace Handling
3276//===----------------------------------------------------------------------===//
3277
3278/// ActOnStartNamespaceDef - This is called at the start of a namespace
3279/// definition.
John McCalld226f652010-08-21 09:40:31 +00003280Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003281 SourceLocation IdentLoc,
3282 IdentifierInfo *II,
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003283 SourceLocation LBrace,
3284 AttributeList *AttrList) {
Douglas Gregor21e09b62010-08-19 20:55:47 +00003285 // anonymous namespace starts at its left brace
3286 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3287 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003288 Namespc->setLBracLoc(LBrace);
3289
3290 Scope *DeclRegionScope = NamespcScope->getParent();
3291
Anders Carlsson2a3503d2010-02-07 01:09:23 +00003292 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3293
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003294 if (const VisibilityAttr *attr = Namespc->getAttr<VisibilityAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00003295 PushPragmaVisibility(attr->getVisibility(), attr->getLocation());
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003296
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003297 if (II) {
3298 // C++ [namespace.def]p2:
3299 // The identifier in an original-namespace-definition shall not have been
3300 // previously defined in the declarative region in which the
3301 // original-namespace-definition appears. The identifier in an
3302 // original-namespace-definition is the name of the namespace. Subsequently
3303 // in that declarative region, it is treated as an original-namespace-name.
3304
John McCallf36e02d2009-10-09 21:13:30 +00003305 NamedDecl *PrevDecl
Douglas Gregorc83c6872010-04-15 22:33:43 +00003306 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00003307 ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00003308
Douglas Gregor44b43212008-12-11 16:49:14 +00003309 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3310 // This is an extended namespace definition.
3311 // Attach this namespace decl to the chain of extended namespace
3312 // definitions.
3313 OrigNS->setNextNamespace(Namespc);
3314 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003315
Mike Stump1eb44332009-09-09 15:08:12 +00003316 // Remove the previous declaration from the scope.
John McCalld226f652010-08-21 09:40:31 +00003317 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00003318 IdResolver.RemoveDecl(OrigNS);
John McCalld226f652010-08-21 09:40:31 +00003319 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003320 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003321 } else if (PrevDecl) {
3322 // This is an invalid name redefinition.
3323 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3324 << Namespc->getDeclName();
3325 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3326 Namespc->setInvalidDecl();
3327 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003328 } else if (II->isStr("std") &&
3329 CurContext->getLookupContext()->isTranslationUnit()) {
3330 // This is the first "real" definition of the namespace "std", so update
3331 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003332 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003333 // We had already defined a dummy namespace "std". Link this new
3334 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003335 StdNS->setNextNamespace(Namespc);
3336 StdNS->setLocation(IdentLoc);
3337 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00003338 }
3339
3340 // Make our StdNamespace cache point at the first real definition of the
3341 // "std" namespace.
3342 StdNamespace = Namespc;
Mike Stump1eb44332009-09-09 15:08:12 +00003343 }
Douglas Gregor44b43212008-12-11 16:49:14 +00003344
3345 PushOnScopeChains(Namespc, DeclRegionScope);
3346 } else {
John McCall9aeed322009-10-01 00:25:31 +00003347 // Anonymous namespaces.
John McCall5fdd7642009-12-16 02:06:49 +00003348 assert(Namespc->isAnonymousNamespace());
John McCall5fdd7642009-12-16 02:06:49 +00003349
3350 // Link the anonymous namespace into its parent.
3351 NamespaceDecl *PrevDecl;
3352 DeclContext *Parent = CurContext->getLookupContext();
3353 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3354 PrevDecl = TU->getAnonymousNamespace();
3355 TU->setAnonymousNamespace(Namespc);
3356 } else {
3357 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3358 PrevDecl = ND->getAnonymousNamespace();
3359 ND->setAnonymousNamespace(Namespc);
3360 }
3361
3362 // Link the anonymous namespace with its previous declaration.
3363 if (PrevDecl) {
3364 assert(PrevDecl->isAnonymousNamespace());
3365 assert(!PrevDecl->getNextNamespace());
3366 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3367 PrevDecl->setNextNamespace(Namespc);
3368 }
John McCall9aeed322009-10-01 00:25:31 +00003369
Douglas Gregora4181472010-03-24 00:46:35 +00003370 CurContext->addDecl(Namespc);
3371
John McCall9aeed322009-10-01 00:25:31 +00003372 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3373 // behaves as if it were replaced by
3374 // namespace unique { /* empty body */ }
3375 // using namespace unique;
3376 // namespace unique { namespace-body }
3377 // where all occurrences of 'unique' in a translation unit are
3378 // replaced by the same identifier and this identifier differs
3379 // from all other identifiers in the entire program.
3380
3381 // We just create the namespace with an empty name and then add an
3382 // implicit using declaration, just like the standard suggests.
3383 //
3384 // CodeGen enforces the "universally unique" aspect by giving all
3385 // declarations semantically contained within an anonymous
3386 // namespace internal linkage.
3387
John McCall5fdd7642009-12-16 02:06:49 +00003388 if (!PrevDecl) {
3389 UsingDirectiveDecl* UD
3390 = UsingDirectiveDecl::Create(Context, CurContext,
3391 /* 'using' */ LBrace,
3392 /* 'namespace' */ SourceLocation(),
3393 /* qualifier */ SourceRange(),
3394 /* NNS */ NULL,
3395 /* identifier */ SourceLocation(),
3396 Namespc,
3397 /* Ancestor */ CurContext);
3398 UD->setImplicit();
3399 CurContext->addDecl(UD);
3400 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003401 }
3402
3403 // Although we could have an invalid decl (i.e. the namespace name is a
3404 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00003405 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3406 // for the namespace has the declarations that showed up in that particular
3407 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00003408 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00003409 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003410}
3411
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003412/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3413/// is a namespace alias, returns the namespace it points to.
3414static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3415 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3416 return AD->getNamespace();
3417 return dyn_cast_or_null<NamespaceDecl>(D);
3418}
3419
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003420/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3421/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00003422void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003423 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3424 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3425 Namespc->setRBracLoc(RBrace);
3426 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003427 if (Namespc->hasAttr<VisibilityAttr>())
3428 PopPragmaVisibility();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003429}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003430
Douglas Gregor66992202010-06-29 17:53:46 +00003431/// \brief Retrieve the special "std" namespace, which may require us to
3432/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003433NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00003434 if (!StdNamespace) {
3435 // The "std" namespace has not yet been defined, so build one implicitly.
3436 StdNamespace = NamespaceDecl::Create(Context,
3437 Context.getTranslationUnitDecl(),
3438 SourceLocation(),
3439 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003440 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00003441 }
3442
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003443 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00003444}
3445
John McCalld226f652010-08-21 09:40:31 +00003446Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003447 SourceLocation UsingLoc,
3448 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003449 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003450 SourceLocation IdentLoc,
3451 IdentifierInfo *NamespcName,
3452 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00003453 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3454 assert(NamespcName && "Invalid NamespcName.");
3455 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003456 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00003457
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003458 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00003459 NestedNameSpecifier *Qualifier = 0;
3460 if (SS.isSet())
3461 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3462
Douglas Gregoreb11cd02009-01-14 22:20:51 +00003463 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00003464 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3465 LookupParsedName(R, S, &SS);
3466 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00003467 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00003468
Douglas Gregor66992202010-06-29 17:53:46 +00003469 if (R.empty()) {
3470 // Allow "using namespace std;" or "using namespace ::std;" even if
3471 // "std" hasn't been defined yet, for GCC compatibility.
3472 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3473 NamespcName->isStr("std")) {
3474 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00003475 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00003476 R.resolveKind();
3477 }
3478 // Otherwise, attempt typo correction.
3479 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3480 CTC_NoKeywords, 0)) {
3481 if (R.getAsSingle<NamespaceDecl>() ||
3482 R.getAsSingle<NamespaceAliasDecl>()) {
3483 if (DeclContext *DC = computeDeclContext(SS, false))
3484 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3485 << NamespcName << DC << Corrected << SS.getRange()
3486 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3487 else
3488 Diag(IdentLoc, diag::err_using_directive_suggest)
3489 << NamespcName << Corrected
3490 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3491 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3492 << Corrected;
3493
3494 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00003495 } else {
3496 R.clear();
3497 R.setLookupName(NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00003498 }
3499 }
3500 }
3501
John McCallf36e02d2009-10-09 21:13:30 +00003502 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003503 NamedDecl *Named = R.getFoundDecl();
3504 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3505 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003506 // C++ [namespace.udir]p1:
3507 // A using-directive specifies that the names in the nominated
3508 // namespace can be used in the scope in which the
3509 // using-directive appears after the using-directive. During
3510 // unqualified name lookup (3.4.1), the names appear as if they
3511 // were declared in the nearest enclosing namespace which
3512 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00003513 // namespace. [Note: in this context, "contains" means "contains
3514 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003515
3516 // Find enclosing context containing both using-directive and
3517 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003518 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003519 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3520 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3521 CommonAncestor = CommonAncestor->getParent();
3522
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003523 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00003524 SS.getRange(),
3525 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00003526 IdentLoc, Named, CommonAncestor);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003527 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003528 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00003529 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00003530 }
3531
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003532 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00003533 delete AttrList;
John McCalld226f652010-08-21 09:40:31 +00003534 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003535}
3536
3537void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3538 // If scope has associated entity, then using directive is at namespace
3539 // or translation unit scope. We add UsingDirectiveDecls, into
3540 // it's lookup structure.
3541 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003542 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003543 else
3544 // Otherwise it is block-sope. using-directives will affect lookup
3545 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00003546 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00003547}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003548
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003549
John McCalld226f652010-08-21 09:40:31 +00003550Decl *Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00003551 AccessSpecifier AS,
John McCall60fa3cf2009-12-11 02:10:03 +00003552 bool HasUsingKeyword,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003553 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003554 CXXScopeSpec &SS,
Douglas Gregor12c118a2009-11-04 16:30:06 +00003555 UnqualifiedId &Name,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003556 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003557 bool IsTypeName,
3558 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003559 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00003560
Douglas Gregor12c118a2009-11-04 16:30:06 +00003561 switch (Name.getKind()) {
3562 case UnqualifiedId::IK_Identifier:
3563 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00003564 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00003565 case UnqualifiedId::IK_ConversionFunctionId:
3566 break;
3567
3568 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00003569 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00003570 // C++0x inherited constructors.
3571 if (getLangOptions().CPlusPlus0x) break;
3572
Douglas Gregor12c118a2009-11-04 16:30:06 +00003573 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3574 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003575 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003576
3577 case UnqualifiedId::IK_DestructorName:
3578 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3579 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00003580 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003581
3582 case UnqualifiedId::IK_TemplateId:
3583 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3584 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00003585 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00003586 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003587
3588 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3589 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00003590 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00003591 return 0;
John McCall604e7f12009-12-08 07:46:18 +00003592
John McCall60fa3cf2009-12-11 02:10:03 +00003593 // Warn about using declarations.
3594 // TODO: store that the declaration was written without 'using' and
3595 // talk about access decls instead of using decls in the
3596 // diagnostics.
3597 if (!HasUsingKeyword) {
3598 UsingLoc = Name.getSourceRange().getBegin();
3599
3600 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00003601 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00003602 }
3603
John McCall9488ea12009-11-17 05:59:44 +00003604 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003605 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003606 /* IsInstantiation */ false,
3607 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00003608 if (UD)
3609 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00003610
John McCalld226f652010-08-21 09:40:31 +00003611 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00003612}
3613
Douglas Gregor09acc982010-07-07 23:08:52 +00003614/// \brief Determine whether a using declaration considers the given
3615/// declarations as "equivalent", e.g., if they are redeclarations of
3616/// the same entity or are both typedefs of the same type.
3617static bool
3618IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3619 bool &SuppressRedeclaration) {
3620 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3621 SuppressRedeclaration = false;
3622 return true;
3623 }
3624
3625 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3626 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3627 SuppressRedeclaration = true;
3628 return Context.hasSameType(TD1->getUnderlyingType(),
3629 TD2->getUnderlyingType());
3630 }
3631
3632 return false;
3633}
3634
3635
John McCall9f54ad42009-12-10 09:41:52 +00003636/// Determines whether to create a using shadow decl for a particular
3637/// decl, given the set of decls existing prior to this using lookup.
3638bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3639 const LookupResult &Previous) {
3640 // Diagnose finding a decl which is not from a base class of the
3641 // current class. We do this now because there are cases where this
3642 // function will silently decide not to build a shadow decl, which
3643 // will pre-empt further diagnostics.
3644 //
3645 // We don't need to do this in C++0x because we do the check once on
3646 // the qualifier.
3647 //
3648 // FIXME: diagnose the following if we care enough:
3649 // struct A { int foo; };
3650 // struct B : A { using A::foo; };
3651 // template <class T> struct C : A {};
3652 // template <class T> struct D : C<T> { using B::foo; } // <---
3653 // This is invalid (during instantiation) in C++03 because B::foo
3654 // resolves to the using decl in B, which is not a base class of D<T>.
3655 // We can't diagnose it immediately because C<T> is an unknown
3656 // specialization. The UsingShadowDecl in D<T> then points directly
3657 // to A::foo, which will look well-formed when we instantiate.
3658 // The right solution is to not collapse the shadow-decl chain.
3659 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3660 DeclContext *OrigDC = Orig->getDeclContext();
3661
3662 // Handle enums and anonymous structs.
3663 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3664 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3665 while (OrigRec->isAnonymousStructOrUnion())
3666 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3667
3668 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3669 if (OrigDC == CurContext) {
3670 Diag(Using->getLocation(),
3671 diag::err_using_decl_nested_name_specifier_is_current_class)
3672 << Using->getNestedNameRange();
3673 Diag(Orig->getLocation(), diag::note_using_decl_target);
3674 return true;
3675 }
3676
3677 Diag(Using->getNestedNameRange().getBegin(),
3678 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3679 << Using->getTargetNestedNameDecl()
3680 << cast<CXXRecordDecl>(CurContext)
3681 << Using->getNestedNameRange();
3682 Diag(Orig->getLocation(), diag::note_using_decl_target);
3683 return true;
3684 }
3685 }
3686
3687 if (Previous.empty()) return false;
3688
3689 NamedDecl *Target = Orig;
3690 if (isa<UsingShadowDecl>(Target))
3691 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3692
John McCalld7533ec2009-12-11 02:33:26 +00003693 // If the target happens to be one of the previous declarations, we
3694 // don't have a conflict.
3695 //
3696 // FIXME: but we might be increasing its access, in which case we
3697 // should redeclare it.
3698 NamedDecl *NonTag = 0, *Tag = 0;
3699 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3700 I != E; ++I) {
3701 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00003702 bool Result;
3703 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3704 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00003705
3706 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3707 }
3708
John McCall9f54ad42009-12-10 09:41:52 +00003709 if (Target->isFunctionOrFunctionTemplate()) {
3710 FunctionDecl *FD;
3711 if (isa<FunctionTemplateDecl>(Target))
3712 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3713 else
3714 FD = cast<FunctionDecl>(Target);
3715
3716 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00003717 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00003718 case Ovl_Overload:
3719 return false;
3720
3721 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00003722 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003723 break;
3724
3725 // We found a decl with the exact signature.
3726 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00003727 // If we're in a record, we want to hide the target, so we
3728 // return true (without a diagnostic) to tell the caller not to
3729 // build a shadow decl.
3730 if (CurContext->isRecord())
3731 return true;
3732
3733 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00003734 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003735 break;
3736 }
3737
3738 Diag(Target->getLocation(), diag::note_using_decl_target);
3739 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3740 return true;
3741 }
3742
3743 // Target is not a function.
3744
John McCall9f54ad42009-12-10 09:41:52 +00003745 if (isa<TagDecl>(Target)) {
3746 // No conflict between a tag and a non-tag.
3747 if (!Tag) return false;
3748
John McCall41ce66f2009-12-10 19:51:03 +00003749 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003750 Diag(Target->getLocation(), diag::note_using_decl_target);
3751 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3752 return true;
3753 }
3754
3755 // No conflict between a tag and a non-tag.
3756 if (!NonTag) return false;
3757
John McCall41ce66f2009-12-10 19:51:03 +00003758 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00003759 Diag(Target->getLocation(), diag::note_using_decl_target);
3760 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3761 return true;
3762}
3763
John McCall9488ea12009-11-17 05:59:44 +00003764/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00003765UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00003766 UsingDecl *UD,
3767 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00003768
3769 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00003770 NamedDecl *Target = Orig;
3771 if (isa<UsingShadowDecl>(Target)) {
3772 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3773 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00003774 }
3775
3776 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00003777 = UsingShadowDecl::Create(Context, CurContext,
3778 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00003779 UD->addShadowDecl(Shadow);
3780
3781 if (S)
John McCall604e7f12009-12-08 07:46:18 +00003782 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00003783 else
John McCall604e7f12009-12-08 07:46:18 +00003784 CurContext->addDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003785 Shadow->setAccess(UD->getAccess());
John McCall9488ea12009-11-17 05:59:44 +00003786
John McCall32daa422010-03-31 01:36:47 +00003787 // Register it as a conversion if appropriate.
3788 if (Shadow->getDeclName().getNameKind()
3789 == DeclarationName::CXXConversionFunctionName)
3790 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3791
John McCall604e7f12009-12-08 07:46:18 +00003792 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3793 Shadow->setInvalidDecl();
3794
John McCall9f54ad42009-12-10 09:41:52 +00003795 return Shadow;
3796}
John McCall604e7f12009-12-08 07:46:18 +00003797
John McCall9f54ad42009-12-10 09:41:52 +00003798/// Hides a using shadow declaration. This is required by the current
3799/// using-decl implementation when a resolvable using declaration in a
3800/// class is followed by a declaration which would hide or override
3801/// one or more of the using decl's targets; for example:
3802///
3803/// struct Base { void foo(int); };
3804/// struct Derived : Base {
3805/// using Base::foo;
3806/// void foo(int);
3807/// };
3808///
3809/// The governing language is C++03 [namespace.udecl]p12:
3810///
3811/// When a using-declaration brings names from a base class into a
3812/// derived class scope, member functions in the derived class
3813/// override and/or hide member functions with the same name and
3814/// parameter types in a base class (rather than conflicting).
3815///
3816/// There are two ways to implement this:
3817/// (1) optimistically create shadow decls when they're not hidden
3818/// by existing declarations, or
3819/// (2) don't create any shadow decls (or at least don't make them
3820/// visible) until we've fully parsed/instantiated the class.
3821/// The problem with (1) is that we might have to retroactively remove
3822/// a shadow decl, which requires several O(n) operations because the
3823/// decl structures are (very reasonably) not designed for removal.
3824/// (2) avoids this but is very fiddly and phase-dependent.
3825void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00003826 if (Shadow->getDeclName().getNameKind() ==
3827 DeclarationName::CXXConversionFunctionName)
3828 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3829
John McCall9f54ad42009-12-10 09:41:52 +00003830 // Remove it from the DeclContext...
3831 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003832
John McCall9f54ad42009-12-10 09:41:52 +00003833 // ...and the scope, if applicable...
3834 if (S) {
John McCalld226f652010-08-21 09:40:31 +00003835 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00003836 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00003837 }
3838
John McCall9f54ad42009-12-10 09:41:52 +00003839 // ...and the using decl.
3840 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3841
3842 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00003843 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00003844}
3845
John McCall7ba107a2009-11-18 02:36:19 +00003846/// Builds a using declaration.
3847///
3848/// \param IsInstantiation - Whether this call arises from an
3849/// instantiation of an unresolved using declaration. We treat
3850/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00003851NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3852 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003853 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003854 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00003855 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00003856 bool IsInstantiation,
3857 bool IsTypeName,
3858 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00003859 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003860 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00003861 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00003862
Anders Carlsson550b14b2009-08-28 05:49:21 +00003863 // FIXME: We ignore attributes for now.
3864 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00003865
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003866 if (SS.isEmpty()) {
3867 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00003868 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003869 }
Mike Stump1eb44332009-09-09 15:08:12 +00003870
John McCall9f54ad42009-12-10 09:41:52 +00003871 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003872 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00003873 ForRedeclaration);
3874 Previous.setHideTags(false);
3875 if (S) {
3876 LookupName(Previous, S);
3877
3878 // It is really dumb that we have to do this.
3879 LookupResult::Filter F = Previous.makeFilter();
3880 while (F.hasNext()) {
3881 NamedDecl *D = F.next();
3882 if (!isDeclInScope(D, CurContext, S))
3883 F.erase();
3884 }
3885 F.done();
3886 } else {
3887 assert(IsInstantiation && "no scope in non-instantiation");
3888 assert(CurContext->isRecord() && "scope not record in instantiation");
3889 LookupQualifiedName(Previous, CurContext);
3890 }
3891
Mike Stump1eb44332009-09-09 15:08:12 +00003892 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003893 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3894
John McCall9f54ad42009-12-10 09:41:52 +00003895 // Check for invalid redeclarations.
3896 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3897 return 0;
3898
3899 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00003900 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3901 return 0;
3902
John McCallaf8e6ed2009-11-12 03:15:40 +00003903 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00003904 NamedDecl *D;
John McCallaf8e6ed2009-11-12 03:15:40 +00003905 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00003906 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00003907 // FIXME: not all declaration name kinds are legal here
3908 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3909 UsingLoc, TypenameLoc,
3910 SS.getRange(), NNS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003911 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00003912 } else {
3913 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003914 UsingLoc, SS.getRange(),
3915 NNS, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00003916 }
John McCalled976492009-12-04 22:46:56 +00003917 } else {
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003918 D = UsingDecl::Create(Context, CurContext,
3919 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCalled976492009-12-04 22:46:56 +00003920 IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00003921 }
John McCalled976492009-12-04 22:46:56 +00003922 D->setAccess(AS);
3923 CurContext->addDecl(D);
3924
3925 if (!LookupContext) return D;
3926 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00003927
John McCall77bb1aa2010-05-01 00:40:08 +00003928 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00003929 UD->setInvalidDecl();
3930 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003931 }
3932
John McCall604e7f12009-12-08 07:46:18 +00003933 // Look up the target name.
3934
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003935 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00003936
John McCall604e7f12009-12-08 07:46:18 +00003937 // Unlike most lookups, we don't always want to hide tag
3938 // declarations: tag names are visible through the using declaration
3939 // even if hidden by ordinary names, *except* in a dependent context
3940 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00003941 if (!IsInstantiation)
3942 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00003943
John McCalla24dc2e2009-11-17 02:14:36 +00003944 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00003945
John McCallf36e02d2009-10-09 21:13:30 +00003946 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00003947 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00003948 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003949 UD->setInvalidDecl();
3950 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003951 }
3952
John McCalled976492009-12-04 22:46:56 +00003953 if (R.isAmbiguous()) {
3954 UD->setInvalidDecl();
3955 return UD;
3956 }
Mike Stump1eb44332009-09-09 15:08:12 +00003957
John McCall7ba107a2009-11-18 02:36:19 +00003958 if (IsTypeName) {
3959 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00003960 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003961 Diag(IdentLoc, diag::err_using_typename_non_type);
3962 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3963 Diag((*I)->getUnderlyingDecl()->getLocation(),
3964 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003965 UD->setInvalidDecl();
3966 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003967 }
3968 } else {
3969 // If we asked for a non-typename and we got a type, error out,
3970 // but only if this is an instantiation of an unresolved using
3971 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00003972 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00003973 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3974 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00003975 UD->setInvalidDecl();
3976 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00003977 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00003978 }
3979
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003980 // C++0x N2914 [namespace.udecl]p6:
3981 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00003982 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003983 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3984 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00003985 UD->setInvalidDecl();
3986 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00003987 }
Mike Stump1eb44332009-09-09 15:08:12 +00003988
John McCall9f54ad42009-12-10 09:41:52 +00003989 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3990 if (!CheckUsingShadowDecl(UD, *I, Previous))
3991 BuildUsingShadowDecl(S, UD, *I);
3992 }
John McCall9488ea12009-11-17 05:59:44 +00003993
3994 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003995}
3996
John McCall9f54ad42009-12-10 09:41:52 +00003997/// Checks that the given using declaration is not an invalid
3998/// redeclaration. Note that this is checking only for the using decl
3999/// itself, not for any ill-formedness among the UsingShadowDecls.
4000bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4001 bool isTypeName,
4002 const CXXScopeSpec &SS,
4003 SourceLocation NameLoc,
4004 const LookupResult &Prev) {
4005 // C++03 [namespace.udecl]p8:
4006 // C++0x [namespace.udecl]p10:
4007 // A using-declaration is a declaration and can therefore be used
4008 // repeatedly where (and only where) multiple declarations are
4009 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00004010 //
4011 // That's in non-member contexts.
4012 if (!CurContext->getLookupContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00004013 return false;
4014
4015 NestedNameSpecifier *Qual
4016 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4017
4018 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4019 NamedDecl *D = *I;
4020
4021 bool DTypename;
4022 NestedNameSpecifier *DQual;
4023 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4024 DTypename = UD->isTypeName();
4025 DQual = UD->getTargetNestedNameDecl();
4026 } else if (UnresolvedUsingValueDecl *UD
4027 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4028 DTypename = false;
4029 DQual = UD->getTargetNestedNameSpecifier();
4030 } else if (UnresolvedUsingTypenameDecl *UD
4031 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4032 DTypename = true;
4033 DQual = UD->getTargetNestedNameSpecifier();
4034 } else continue;
4035
4036 // using decls differ if one says 'typename' and the other doesn't.
4037 // FIXME: non-dependent using decls?
4038 if (isTypeName != DTypename) continue;
4039
4040 // using decls differ if they name different scopes (but note that
4041 // template instantiation can cause this check to trigger when it
4042 // didn't before instantiation).
4043 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4044 Context.getCanonicalNestedNameSpecifier(DQual))
4045 continue;
4046
4047 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00004048 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00004049 return true;
4050 }
4051
4052 return false;
4053}
4054
John McCall604e7f12009-12-08 07:46:18 +00004055
John McCalled976492009-12-04 22:46:56 +00004056/// Checks that the given nested-name qualifier used in a using decl
4057/// in the current context is appropriately related to the current
4058/// scope. If an error is found, diagnoses it and returns true.
4059bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4060 const CXXScopeSpec &SS,
4061 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00004062 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00004063
John McCall604e7f12009-12-08 07:46:18 +00004064 if (!CurContext->isRecord()) {
4065 // C++03 [namespace.udecl]p3:
4066 // C++0x [namespace.udecl]p8:
4067 // A using-declaration for a class member shall be a member-declaration.
4068
4069 // If we weren't able to compute a valid scope, it must be a
4070 // dependent class scope.
4071 if (!NamedContext || NamedContext->isRecord()) {
4072 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4073 << SS.getRange();
4074 return true;
4075 }
4076
4077 // Otherwise, everything is known to be fine.
4078 return false;
4079 }
4080
4081 // The current scope is a record.
4082
4083 // If the named context is dependent, we can't decide much.
4084 if (!NamedContext) {
4085 // FIXME: in C++0x, we can diagnose if we can prove that the
4086 // nested-name-specifier does not refer to a base class, which is
4087 // still possible in some cases.
4088
4089 // Otherwise we have to conservatively report that things might be
4090 // okay.
4091 return false;
4092 }
4093
4094 if (!NamedContext->isRecord()) {
4095 // Ideally this would point at the last name in the specifier,
4096 // but we don't have that level of source info.
4097 Diag(SS.getRange().getBegin(),
4098 diag::err_using_decl_nested_name_specifier_is_not_class)
4099 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4100 return true;
4101 }
4102
4103 if (getLangOptions().CPlusPlus0x) {
4104 // C++0x [namespace.udecl]p3:
4105 // In a using-declaration used as a member-declaration, the
4106 // nested-name-specifier shall name a base class of the class
4107 // being defined.
4108
4109 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4110 cast<CXXRecordDecl>(NamedContext))) {
4111 if (CurContext == NamedContext) {
4112 Diag(NameLoc,
4113 diag::err_using_decl_nested_name_specifier_is_current_class)
4114 << SS.getRange();
4115 return true;
4116 }
4117
4118 Diag(SS.getRange().getBegin(),
4119 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4120 << (NestedNameSpecifier*) SS.getScopeRep()
4121 << cast<CXXRecordDecl>(CurContext)
4122 << SS.getRange();
4123 return true;
4124 }
4125
4126 return false;
4127 }
4128
4129 // C++03 [namespace.udecl]p4:
4130 // A using-declaration used as a member-declaration shall refer
4131 // to a member of a base class of the class being defined [etc.].
4132
4133 // Salient point: SS doesn't have to name a base class as long as
4134 // lookup only finds members from base classes. Therefore we can
4135 // diagnose here only if we can prove that that can't happen,
4136 // i.e. if the class hierarchies provably don't intersect.
4137
4138 // TODO: it would be nice if "definitely valid" results were cached
4139 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4140 // need to be repeated.
4141
4142 struct UserData {
4143 llvm::DenseSet<const CXXRecordDecl*> Bases;
4144
4145 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4146 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4147 Data->Bases.insert(Base);
4148 return true;
4149 }
4150
4151 bool hasDependentBases(const CXXRecordDecl *Class) {
4152 return !Class->forallBases(collect, this);
4153 }
4154
4155 /// Returns true if the base is dependent or is one of the
4156 /// accumulated base classes.
4157 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4158 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4159 return !Data->Bases.count(Base);
4160 }
4161
4162 bool mightShareBases(const CXXRecordDecl *Class) {
4163 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4164 }
4165 };
4166
4167 UserData Data;
4168
4169 // Returns false if we find a dependent base.
4170 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4171 return false;
4172
4173 // Returns false if the class has a dependent base or if it or one
4174 // of its bases is present in the base set of the current context.
4175 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4176 return false;
4177
4178 Diag(SS.getRange().getBegin(),
4179 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4180 << (NestedNameSpecifier*) SS.getScopeRep()
4181 << cast<CXXRecordDecl>(CurContext)
4182 << SS.getRange();
4183
4184 return true;
John McCalled976492009-12-04 22:46:56 +00004185}
4186
John McCalld226f652010-08-21 09:40:31 +00004187Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004188 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004189 SourceLocation AliasLoc,
4190 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004191 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00004192 SourceLocation IdentLoc,
4193 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00004194
Anders Carlsson81c85c42009-03-28 23:53:49 +00004195 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00004196 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4197 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00004198
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004199 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00004200 NamedDecl *PrevDecl
4201 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4202 ForRedeclaration);
4203 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4204 PrevDecl = 0;
4205
4206 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00004207 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004208 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00004209 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00004210 // FIXME: At some point, we'll want to create the (redundant)
4211 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00004212 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00004213 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00004214 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00004215 }
Mike Stump1eb44332009-09-09 15:08:12 +00004216
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004217 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4218 diag::err_redefinition_different_kind;
4219 Diag(AliasLoc, DiagID) << Alias;
4220 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00004221 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00004222 }
4223
John McCalla24dc2e2009-11-17 02:14:36 +00004224 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00004225 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004226
John McCallf36e02d2009-10-09 21:13:30 +00004227 if (R.empty()) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004228 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4229 CTC_NoKeywords, 0)) {
4230 if (R.getAsSingle<NamespaceDecl>() ||
4231 R.getAsSingle<NamespaceAliasDecl>()) {
4232 if (DeclContext *DC = computeDeclContext(SS, false))
4233 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4234 << Ident << DC << Corrected << SS.getRange()
4235 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4236 else
4237 Diag(IdentLoc, diag::err_using_directive_suggest)
4238 << Ident << Corrected
4239 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4240
4241 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4242 << Corrected;
4243
4244 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00004245 } else {
4246 R.clear();
4247 R.setLookupName(Ident);
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004248 }
4249 }
4250
4251 if (R.empty()) {
4252 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00004253 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00004254 }
Anders Carlsson5721c682009-03-28 06:42:02 +00004255 }
Mike Stump1eb44332009-09-09 15:08:12 +00004256
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004257 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00004258 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4259 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00004260 (NestedNameSpecifier *)SS.getScopeRep(),
John McCallf36e02d2009-10-09 21:13:30 +00004261 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00004262
John McCall3dbd3d52010-02-16 06:53:13 +00004263 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00004264 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00004265}
4266
Douglas Gregor39957dc2010-05-01 15:04:51 +00004267namespace {
4268 /// \brief Scoped object used to handle the state changes required in Sema
4269 /// to implicitly define the body of a C++ member function;
4270 class ImplicitlyDefinedFunctionScope {
4271 Sema &S;
4272 DeclContext *PreviousContext;
4273
4274 public:
4275 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4276 : S(S), PreviousContext(S.CurContext)
4277 {
4278 S.CurContext = Method;
4279 S.PushFunctionScope();
4280 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4281 }
4282
4283 ~ImplicitlyDefinedFunctionScope() {
4284 S.PopExpressionEvaluationContext();
4285 S.PopFunctionOrBlockScope();
4286 S.CurContext = PreviousContext;
4287 }
4288 };
4289}
4290
Douglas Gregor23c94db2010-07-02 17:43:08 +00004291CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4292 CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004293 // C++ [class.ctor]p5:
4294 // A default constructor for a class X is a constructor of class X
4295 // that can be called without an argument. If there is no
4296 // user-declared constructor for class X, a default constructor is
4297 // implicitly declared. An implicitly-declared default constructor
4298 // is an inline public member of its class.
Douglas Gregor18274032010-07-03 00:47:00 +00004299 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4300 "Should not build implicit default constructor!");
4301
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004302 // C++ [except.spec]p14:
4303 // An implicitly declared special member function (Clause 12) shall have an
4304 // exception-specification. [...]
4305 ImplicitExceptionSpecification ExceptSpec(Context);
4306
4307 // Direct base-class destructors.
4308 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4309 BEnd = ClassDecl->bases_end();
4310 B != BEnd; ++B) {
4311 if (B->isVirtual()) // Handled below.
4312 continue;
4313
Douglas Gregor18274032010-07-03 00:47:00 +00004314 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4315 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4316 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4317 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4318 else if (CXXConstructorDecl *Constructor
4319 = BaseClassDecl->getDefaultConstructor())
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004320 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004321 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004322 }
4323
4324 // Virtual base-class destructors.
4325 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4326 BEnd = ClassDecl->vbases_end();
4327 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00004328 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4329 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4330 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4331 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4332 else if (CXXConstructorDecl *Constructor
4333 = BaseClassDecl->getDefaultConstructor())
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004334 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004335 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004336 }
4337
4338 // Field destructors.
4339 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4340 FEnd = ClassDecl->field_end();
4341 F != FEnd; ++F) {
4342 if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00004343 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4344 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4345 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4346 ExceptSpec.CalledDecl(
4347 DeclareImplicitDefaultConstructor(FieldClassDecl));
4348 else if (CXXConstructorDecl *Constructor
4349 = FieldClassDecl->getDefaultConstructor())
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004350 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00004351 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004352 }
4353
4354
4355 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00004356 CanQualType ClassType
4357 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4358 DeclarationName Name
4359 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004360 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor32df23e2010-07-01 22:02:46 +00004361 CXXConstructorDecl *DefaultCon
Abramo Bagnara25777432010-08-11 22:01:17 +00004362 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor32df23e2010-07-01 22:02:46 +00004363 Context.getFunctionType(Context.VoidTy,
4364 0, 0, false, 0,
Douglas Gregoreb8c6702010-07-01 22:31:05 +00004365 ExceptSpec.hasExceptionSpecification(),
4366 ExceptSpec.hasAnyExceptionSpecification(),
4367 ExceptSpec.size(),
4368 ExceptSpec.data(),
Douglas Gregor32df23e2010-07-01 22:02:46 +00004369 FunctionType::ExtInfo()),
4370 /*TInfo=*/0,
4371 /*isExplicit=*/false,
4372 /*isInline=*/true,
4373 /*isImplicitlyDeclared=*/true);
4374 DefaultCon->setAccess(AS_public);
4375 DefaultCon->setImplicit();
4376 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00004377
4378 // Note that we have declared this constructor.
4379 ClassDecl->setDeclaredDefaultConstructor(true);
4380 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4381
Douglas Gregor23c94db2010-07-02 17:43:08 +00004382 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00004383 PushOnScopeChains(DefaultCon, S, false);
4384 ClassDecl->addDecl(DefaultCon);
4385
Douglas Gregor32df23e2010-07-01 22:02:46 +00004386 return DefaultCon;
4387}
4388
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004389void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4390 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004391 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004392 !Constructor->isUsed(false)) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00004393 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00004394
Anders Carlssonf6513ed2010-04-23 16:04:08 +00004395 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00004396 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00004397
Douglas Gregor39957dc2010-05-01 15:04:51 +00004398 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004399 ErrorTrap Trap(*this);
4400 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4401 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004402 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00004403 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004404 Constructor->setInvalidDecl();
4405 } else {
4406 Constructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004407 MarkVTableUsed(CurrentLocation, ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00004408 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00004409}
4410
Douglas Gregor23c94db2010-07-02 17:43:08 +00004411CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004412 // C++ [class.dtor]p2:
4413 // If a class has no user-declared destructor, a destructor is
4414 // declared implicitly. An implicitly-declared destructor is an
4415 // inline public member of its class.
4416
4417 // C++ [except.spec]p14:
4418 // An implicitly declared special member function (Clause 12) shall have
4419 // an exception-specification.
4420 ImplicitExceptionSpecification ExceptSpec(Context);
4421
4422 // Direct base-class destructors.
4423 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4424 BEnd = ClassDecl->bases_end();
4425 B != BEnd; ++B) {
4426 if (B->isVirtual()) // Handled below.
4427 continue;
4428
4429 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4430 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004431 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004432 }
4433
4434 // Virtual base-class destructors.
4435 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4436 BEnd = ClassDecl->vbases_end();
4437 B != BEnd; ++B) {
4438 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4439 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004440 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004441 }
4442
4443 // Field destructors.
4444 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4445 FEnd = ClassDecl->field_end();
4446 F != FEnd; ++F) {
4447 if (const RecordType *RecordTy
4448 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4449 ExceptSpec.CalledDecl(
Douglas Gregordb89f282010-07-01 22:47:18 +00004450 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004451 }
4452
Douglas Gregor4923aa22010-07-02 20:37:36 +00004453 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004454 QualType Ty = Context.getFunctionType(Context.VoidTy,
4455 0, 0, false, 0,
4456 ExceptSpec.hasExceptionSpecification(),
4457 ExceptSpec.hasAnyExceptionSpecification(),
4458 ExceptSpec.size(),
4459 ExceptSpec.data(),
4460 FunctionType::ExtInfo());
4461
4462 CanQualType ClassType
4463 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4464 DeclarationName Name
4465 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnara25777432010-08-11 22:01:17 +00004466 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004467 CXXDestructorDecl *Destructor
Abramo Bagnara25777432010-08-11 22:01:17 +00004468 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty,
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004469 /*isInline=*/true,
4470 /*isImplicitlyDeclared=*/true);
4471 Destructor->setAccess(AS_public);
4472 Destructor->setImplicit();
4473 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00004474
4475 // Note that we have declared this destructor.
4476 ClassDecl->setDeclaredDestructor(true);
4477 ++ASTContext::NumImplicitDestructorsDeclared;
4478
4479 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004480 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00004481 PushOnScopeChains(Destructor, S, false);
4482 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004483
4484 // This could be uniqued if it ever proves significant.
4485 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4486
4487 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00004488
Douglas Gregorfabd43a2010-07-01 19:09:28 +00004489 return Destructor;
4490}
4491
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004492void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00004493 CXXDestructorDecl *Destructor) {
Douglas Gregorc070cc62010-06-17 23:14:26 +00004494 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004495 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00004496 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004497 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004498
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004499 if (Destructor->isInvalidDecl())
4500 return;
4501
Douglas Gregor39957dc2010-05-01 15:04:51 +00004502 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004503
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004504 ErrorTrap Trap(*this);
John McCallef027fe2010-03-16 21:39:52 +00004505 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4506 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00004507
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004508 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00004509 Diag(CurrentLocation, diag::note_member_synthesized_at)
4510 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4511
4512 Destructor->setInvalidDecl();
4513 return;
4514 }
4515
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004516 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004517 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00004518}
4519
Douglas Gregor06a9f362010-05-01 20:49:11 +00004520/// \brief Builds a statement that copies the given entity from \p From to
4521/// \c To.
4522///
4523/// This routine is used to copy the members of a class with an
4524/// implicitly-declared copy assignment operator. When the entities being
4525/// copied are arrays, this routine builds for loops to copy them.
4526///
4527/// \param S The Sema object used for type-checking.
4528///
4529/// \param Loc The location where the implicit copy is being generated.
4530///
4531/// \param T The type of the expressions being copied. Both expressions must
4532/// have this type.
4533///
4534/// \param To The expression we are copying to.
4535///
4536/// \param From The expression we are copying from.
4537///
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004538/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4539/// Otherwise, it's a non-static member subobject.
4540///
Douglas Gregor06a9f362010-05-01 20:49:11 +00004541/// \param Depth Internal parameter recording the depth of the recursion.
4542///
4543/// \returns A statement or a loop that copies the expressions.
4544static Sema::OwningStmtResult
4545BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
4546 Sema::OwningExprResult To, Sema::OwningExprResult From,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004547 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00004548 typedef Sema::OwningStmtResult OwningStmtResult;
4549 typedef Sema::OwningExprResult OwningExprResult;
4550
4551 // C++0x [class.copy]p30:
4552 // Each subobject is assigned in the manner appropriate to its type:
4553 //
4554 // - if the subobject is of class type, the copy assignment operator
4555 // for the class is used (as if by explicit qualification; that is,
4556 // ignoring any possible virtual overriding functions in more derived
4557 // classes);
4558 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4559 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4560
4561 // Look for operator=.
4562 DeclarationName Name
4563 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4564 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4565 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4566
4567 // Filter out any result that isn't a copy-assignment operator.
4568 LookupResult::Filter F = OpLookup.makeFilter();
4569 while (F.hasNext()) {
4570 NamedDecl *D = F.next();
4571 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4572 if (Method->isCopyAssignmentOperator())
4573 continue;
4574
4575 F.erase();
John McCallb0207482010-03-16 06:11:48 +00004576 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004577 F.done();
4578
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004579 // Suppress the protected check (C++ [class.protected]) for each of the
4580 // assignment operators we found. This strange dance is required when
4581 // we're assigning via a base classes's copy-assignment operator. To
4582 // ensure that we're getting the right base class subobject (without
4583 // ambiguities), we need to cast "this" to that subobject type; to
4584 // ensure that we don't go through the virtual call mechanism, we need
4585 // to qualify the operator= name with the base class (see below). However,
4586 // this means that if the base class has a protected copy assignment
4587 // operator, the protected member access check will fail. So, we
4588 // rewrite "protected" access to "public" access in this case, since we
4589 // know by construction that we're calling from a derived class.
4590 if (CopyingBaseSubobject) {
4591 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4592 L != LEnd; ++L) {
4593 if (L.getAccess() == AS_protected)
4594 L.setAccess(AS_public);
4595 }
4596 }
4597
Douglas Gregor06a9f362010-05-01 20:49:11 +00004598 // Create the nested-name-specifier that will be used to qualify the
4599 // reference to operator=; this is required to suppress the virtual
4600 // call mechanism.
4601 CXXScopeSpec SS;
4602 SS.setRange(Loc);
4603 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4604 T.getTypePtr()));
4605
4606 // Create the reference to operator=.
4607 OwningExprResult OpEqualRef
4608 = S.BuildMemberReferenceExpr(move(To), T, Loc, /*isArrow=*/false, SS,
4609 /*FirstQualifierInScope=*/0, OpLookup,
4610 /*TemplateArgs=*/0,
4611 /*SuppressQualifierCheck=*/true);
4612 if (OpEqualRef.isInvalid())
4613 return S.StmtError();
4614
4615 // Build the call to the assignment operator.
4616 Expr *FromE = From.takeAs<Expr>();
4617 OwningExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
4618 OpEqualRef.takeAs<Expr>(),
4619 Loc, &FromE, 1, 0, Loc);
4620 if (Call.isInvalid())
4621 return S.StmtError();
4622
4623 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004624 }
John McCallb0207482010-03-16 06:11:48 +00004625
Douglas Gregor06a9f362010-05-01 20:49:11 +00004626 // - if the subobject is of scalar type, the built-in assignment
4627 // operator is used.
4628 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4629 if (!ArrayTy) {
4630 OwningExprResult Assignment = S.CreateBuiltinBinOp(Loc,
4631 BinaryOperator::Assign,
4632 To.takeAs<Expr>(),
4633 From.takeAs<Expr>());
4634 if (Assignment.isInvalid())
4635 return S.StmtError();
4636
4637 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004638 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00004639
4640 // - if the subobject is an array, each element is assigned, in the
4641 // manner appropriate to the element type;
4642
4643 // Construct a loop over the array bounds, e.g.,
4644 //
4645 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4646 //
4647 // that will copy each of the array elements.
4648 QualType SizeType = S.Context.getSizeType();
4649
4650 // Create the iteration variable.
4651 IdentifierInfo *IterationVarName = 0;
4652 {
4653 llvm::SmallString<8> Str;
4654 llvm::raw_svector_ostream OS(Str);
4655 OS << "__i" << Depth;
4656 IterationVarName = &S.Context.Idents.get(OS.str());
4657 }
4658 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4659 IterationVarName, SizeType,
4660 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
4661 VarDecl::None, VarDecl::None);
4662
4663 // Initialize the iteration variable to zero.
4664 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
4665 IterationVar->setInit(new (S.Context) IntegerLiteral(Zero, SizeType, Loc));
4666
4667 // Create a reference to the iteration variable; we'll use this several
4668 // times throughout.
4669 Expr *IterationVarRef
4670 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4671 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4672
4673 // Create the DeclStmt that holds the iteration variable.
4674 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4675
4676 // Create the comparison against the array bound.
4677 llvm::APInt Upper = ArrayTy->getSize();
4678 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
4679 OwningExprResult Comparison
4680 = S.Owned(new (S.Context) BinaryOperator(IterationVarRef->Retain(),
4681 new (S.Context) IntegerLiteral(Upper, SizeType, Loc),
4682 BinaryOperator::NE, S.Context.BoolTy, Loc));
4683
4684 // Create the pre-increment of the iteration variable.
4685 OwningExprResult Increment
4686 = S.Owned(new (S.Context) UnaryOperator(IterationVarRef->Retain(),
4687 UnaryOperator::PreInc,
4688 SizeType, Loc));
4689
4690 // Subscript the "from" and "to" expressions with the iteration variable.
4691 From = S.CreateBuiltinArraySubscriptExpr(move(From), Loc,
4692 S.Owned(IterationVarRef->Retain()),
4693 Loc);
4694 To = S.CreateBuiltinArraySubscriptExpr(move(To), Loc,
4695 S.Owned(IterationVarRef->Retain()),
4696 Loc);
4697 assert(!From.isInvalid() && "Builtin subscripting can't fail!");
4698 assert(!To.isInvalid() && "Builtin subscripting can't fail!");
4699
4700 // Build the copy for an individual element of the array.
4701 OwningStmtResult Copy = BuildSingleCopyAssign(S, Loc,
4702 ArrayTy->getElementType(),
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004703 move(To), move(From),
4704 CopyingBaseSubobject, Depth+1);
Douglas Gregorff331c12010-07-25 18:17:45 +00004705 if (Copy.isInvalid())
Douglas Gregor06a9f362010-05-01 20:49:11 +00004706 return S.StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00004707
4708 // Construct the loop that copies all elements of this array.
4709 return S.ActOnForStmt(Loc, Loc, S.Owned(InitStmt),
4710 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00004711 0, S.MakeFullExpr(Increment),
Douglas Gregor06a9f362010-05-01 20:49:11 +00004712 Loc, move(Copy));
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00004713}
4714
Douglas Gregora376d102010-07-02 21:50:04 +00004715/// \brief Determine whether the given class has a copy assignment operator
4716/// that accepts a const-qualified argument.
4717static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4718 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4719
4720 if (!Class->hasDeclaredCopyAssignment())
4721 S.DeclareImplicitCopyAssignment(Class);
4722
4723 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4724 DeclarationName OpName
4725 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4726
4727 DeclContext::lookup_const_iterator Op, OpEnd;
4728 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4729 // C++ [class.copy]p9:
4730 // A user-declared copy assignment operator is a non-static non-template
4731 // member function of class X with exactly one parameter of type X, X&,
4732 // const X&, volatile X& or const volatile X&.
4733 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4734 if (!Method)
4735 continue;
4736
4737 if (Method->isStatic())
4738 continue;
4739 if (Method->getPrimaryTemplate())
4740 continue;
4741 const FunctionProtoType *FnType =
4742 Method->getType()->getAs<FunctionProtoType>();
4743 assert(FnType && "Overloaded operator has no prototype.");
4744 // Don't assert on this; an invalid decl might have been left in the AST.
4745 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4746 continue;
4747 bool AcceptsConst = true;
4748 QualType ArgType = FnType->getArgType(0);
4749 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4750 ArgType = Ref->getPointeeType();
4751 // Is it a non-const lvalue reference?
4752 if (!ArgType.isConstQualified())
4753 AcceptsConst = false;
4754 }
4755 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4756 continue;
4757
4758 // We have a single argument of type cv X or cv X&, i.e. we've found the
4759 // copy assignment operator. Return whether it accepts const arguments.
4760 return AcceptsConst;
4761 }
4762 assert(Class->isInvalidDecl() &&
4763 "No copy assignment operator declared in valid code.");
4764 return false;
4765}
4766
Douglas Gregor23c94db2010-07-02 17:43:08 +00004767CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregord3c35902010-07-01 16:36:15 +00004768 // Note: The following rules are largely analoguous to the copy
4769 // constructor rules. Note that virtual bases are not taken into account
4770 // for determining the argument type of the operator. Note also that
4771 // operators taking an object instead of a reference are allowed.
Douglas Gregor18274032010-07-03 00:47:00 +00004772
4773
Douglas Gregord3c35902010-07-01 16:36:15 +00004774 // C++ [class.copy]p10:
4775 // If the class definition does not explicitly declare a copy
4776 // assignment operator, one is declared implicitly.
4777 // The implicitly-defined copy assignment operator for a class X
4778 // will have the form
4779 //
4780 // X& X::operator=(const X&)
4781 //
4782 // if
4783 bool HasConstCopyAssignment = true;
4784
4785 // -- each direct base class B of X has a copy assignment operator
4786 // whose parameter is of type const B&, const volatile B& or B,
4787 // and
4788 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4789 BaseEnd = ClassDecl->bases_end();
4790 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4791 assert(!Base->getType()->isDependentType() &&
4792 "Cannot generate implicit members for class with dependent bases.");
4793 const CXXRecordDecl *BaseClassDecl
4794 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004795 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004796 }
4797
4798 // -- for all the nonstatic data members of X that are of a class
4799 // type M (or array thereof), each such class type has a copy
4800 // assignment operator whose parameter is of type const M&,
4801 // const volatile M& or M.
4802 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4803 FieldEnd = ClassDecl->field_end();
4804 HasConstCopyAssignment && Field != FieldEnd;
4805 ++Field) {
4806 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4807 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4808 const CXXRecordDecl *FieldClassDecl
4809 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004810 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregord3c35902010-07-01 16:36:15 +00004811 }
4812 }
4813
4814 // Otherwise, the implicitly declared copy assignment operator will
4815 // have the form
4816 //
4817 // X& X::operator=(X&)
4818 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4819 QualType RetType = Context.getLValueReferenceType(ArgType);
4820 if (HasConstCopyAssignment)
4821 ArgType = ArgType.withConst();
4822 ArgType = Context.getLValueReferenceType(ArgType);
4823
Douglas Gregorb87786f2010-07-01 17:48:08 +00004824 // C++ [except.spec]p14:
4825 // An implicitly declared special member function (Clause 12) shall have an
4826 // exception-specification. [...]
4827 ImplicitExceptionSpecification ExceptSpec(Context);
4828 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4829 BaseEnd = ClassDecl->bases_end();
4830 Base != BaseEnd; ++Base) {
Douglas Gregora376d102010-07-02 21:50:04 +00004831 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004832 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004833
4834 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4835 DeclareImplicitCopyAssignment(BaseClassDecl);
4836
Douglas Gregorb87786f2010-07-01 17:48:08 +00004837 if (CXXMethodDecl *CopyAssign
4838 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4839 ExceptSpec.CalledDecl(CopyAssign);
4840 }
4841 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4842 FieldEnd = ClassDecl->field_end();
4843 Field != FieldEnd;
4844 ++Field) {
4845 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4846 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora376d102010-07-02 21:50:04 +00004847 CXXRecordDecl *FieldClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00004848 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora376d102010-07-02 21:50:04 +00004849
4850 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4851 DeclareImplicitCopyAssignment(FieldClassDecl);
4852
Douglas Gregorb87786f2010-07-01 17:48:08 +00004853 if (CXXMethodDecl *CopyAssign
4854 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4855 ExceptSpec.CalledDecl(CopyAssign);
4856 }
4857 }
4858
Douglas Gregord3c35902010-07-01 16:36:15 +00004859 // An implicitly-declared copy assignment operator is an inline public
4860 // member of its class.
4861 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnara25777432010-08-11 22:01:17 +00004862 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00004863 CXXMethodDecl *CopyAssignment
Abramo Bagnara25777432010-08-11 22:01:17 +00004864 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregord3c35902010-07-01 16:36:15 +00004865 Context.getFunctionType(RetType, &ArgType, 1,
4866 false, 0,
Douglas Gregorb87786f2010-07-01 17:48:08 +00004867 ExceptSpec.hasExceptionSpecification(),
4868 ExceptSpec.hasAnyExceptionSpecification(),
4869 ExceptSpec.size(),
4870 ExceptSpec.data(),
Douglas Gregord3c35902010-07-01 16:36:15 +00004871 FunctionType::ExtInfo()),
4872 /*TInfo=*/0, /*isStatic=*/false,
4873 /*StorageClassAsWritten=*/FunctionDecl::None,
4874 /*isInline=*/true);
4875 CopyAssignment->setAccess(AS_public);
4876 CopyAssignment->setImplicit();
4877 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
4878 CopyAssignment->setCopyAssignment(true);
4879
4880 // Add the parameter to the operator.
4881 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4882 ClassDecl->getLocation(),
4883 /*Id=*/0,
4884 ArgType, /*TInfo=*/0,
4885 VarDecl::None,
4886 VarDecl::None, 0);
4887 CopyAssignment->setParams(&FromParam, 1);
4888
Douglas Gregora376d102010-07-02 21:50:04 +00004889 // Note that we have added this copy-assignment operator.
4890 ClassDecl->setDeclaredCopyAssignment(true);
4891 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4892
Douglas Gregor23c94db2010-07-02 17:43:08 +00004893 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00004894 PushOnScopeChains(CopyAssignment, S, false);
4895 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00004896
4897 AddOverriddenMethods(ClassDecl, CopyAssignment);
4898 return CopyAssignment;
4899}
4900
Douglas Gregor06a9f362010-05-01 20:49:11 +00004901void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4902 CXXMethodDecl *CopyAssignOperator) {
4903 assert((CopyAssignOperator->isImplicit() &&
4904 CopyAssignOperator->isOverloadedOperator() &&
4905 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00004906 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00004907 "DefineImplicitCopyAssignment called for wrong function");
4908
4909 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4910
4911 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4912 CopyAssignOperator->setInvalidDecl();
4913 return;
4914 }
4915
4916 CopyAssignOperator->setUsed();
4917
4918 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00004919 ErrorTrap Trap(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004920
4921 // C++0x [class.copy]p30:
4922 // The implicitly-defined or explicitly-defaulted copy assignment operator
4923 // for a non-union class X performs memberwise copy assignment of its
4924 // subobjects. The direct base classes of X are assigned first, in the
4925 // order of their declaration in the base-specifier-list, and then the
4926 // immediate non-static data members of X are assigned, in the order in
4927 // which they were declared in the class definition.
4928
4929 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00004930 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004931
4932 // The parameter for the "other" object, which we are copying from.
4933 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4934 Qualifiers OtherQuals = Other->getType().getQualifiers();
4935 QualType OtherRefType = Other->getType();
4936 if (const LValueReferenceType *OtherRef
4937 = OtherRefType->getAs<LValueReferenceType>()) {
4938 OtherRefType = OtherRef->getPointeeType();
4939 OtherQuals = OtherRefType.getQualifiers();
4940 }
4941
4942 // Our location for everything implicitly-generated.
4943 SourceLocation Loc = CopyAssignOperator->getLocation();
4944
4945 // Construct a reference to the "other" object. We'll be using this
4946 // throughout the generated ASTs.
4947 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4948 assert(OtherRef && "Reference to parameter cannot fail!");
4949
4950 // Construct the "this" pointer. We'll be using this throughout the generated
4951 // ASTs.
4952 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4953 assert(This && "Reference to this cannot fail!");
4954
4955 // Assign base classes.
4956 bool Invalid = false;
4957 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4958 E = ClassDecl->bases_end(); Base != E; ++Base) {
4959 // Form the assignment:
4960 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4961 QualType BaseType = Base->getType().getUnqualifiedType();
4962 CXXRecordDecl *BaseClassDecl = 0;
4963 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4964 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4965 else {
4966 Invalid = true;
4967 continue;
4968 }
4969
John McCallf871d0c2010-08-07 06:22:56 +00004970 CXXCastPath BasePath;
4971 BasePath.push_back(Base);
4972
Douglas Gregor06a9f362010-05-01 20:49:11 +00004973 // Construct the "from" expression, which is an implicit cast to the
4974 // appropriately-qualified base type.
4975 Expr *From = OtherRef->Retain();
4976 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
Sebastian Redl906082e2010-07-20 04:20:21 +00004977 CastExpr::CK_UncheckedDerivedToBase,
John McCallf871d0c2010-08-07 06:22:56 +00004978 ImplicitCastExpr::LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004979
4980 // Dereference "this".
4981 OwningExprResult To = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4982 Owned(This->Retain()));
4983
4984 // Implicitly cast "this" to the appropriately-qualified base type.
4985 Expr *ToE = To.takeAs<Expr>();
4986 ImpCastExprToType(ToE,
4987 Context.getCVRQualifiedType(BaseType,
4988 CopyAssignOperator->getTypeQualifiers()),
4989 CastExpr::CK_UncheckedDerivedToBase,
John McCallf871d0c2010-08-07 06:22:56 +00004990 ImplicitCastExpr::LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004991 To = Owned(ToE);
4992
4993 // Build the copy.
4994 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00004995 move(To), Owned(From),
4996 /*CopyingBaseSubobject=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00004997 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00004998 Diag(CurrentLocation, diag::note_member_synthesized_at)
4999 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5000 CopyAssignOperator->setInvalidDecl();
5001 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005002 }
5003
5004 // Success! Record the copy.
5005 Statements.push_back(Copy.takeAs<Expr>());
5006 }
5007
5008 // \brief Reference to the __builtin_memcpy function.
5009 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005010 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005011 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005012
5013 // Assign non-static members.
5014 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5015 FieldEnd = ClassDecl->field_end();
5016 Field != FieldEnd; ++Field) {
5017 // Check for members of reference type; we can't copy those.
5018 if (Field->getType()->isReferenceType()) {
5019 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5020 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5021 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005022 Diag(CurrentLocation, diag::note_member_synthesized_at)
5023 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005024 Invalid = true;
5025 continue;
5026 }
5027
5028 // Check for members of const-qualified, non-class type.
5029 QualType BaseType = Context.getBaseElementType(Field->getType());
5030 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5031 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5032 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5033 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005034 Diag(CurrentLocation, diag::note_member_synthesized_at)
5035 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005036 Invalid = true;
5037 continue;
5038 }
5039
5040 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00005041 if (FieldType->isIncompleteArrayType()) {
5042 assert(ClassDecl->hasFlexibleArrayMember() &&
5043 "Incomplete array type is not valid");
5044 continue;
5045 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005046
5047 // Build references to the field in the object we're copying from and to.
5048 CXXScopeSpec SS; // Intentionally empty
5049 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5050 LookupMemberName);
5051 MemberLookup.addDecl(*Field);
5052 MemberLookup.resolveKind();
5053 OwningExprResult From = BuildMemberReferenceExpr(Owned(OtherRef->Retain()),
5054 OtherRefType,
5055 Loc, /*IsArrow=*/false,
5056 SS, 0, MemberLookup, 0);
5057 OwningExprResult To = BuildMemberReferenceExpr(Owned(This->Retain()),
5058 This->getType(),
5059 Loc, /*IsArrow=*/true,
5060 SS, 0, MemberLookup, 0);
5061 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5062 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5063
5064 // If the field should be copied with __builtin_memcpy rather than via
5065 // explicit assignments, do so. This optimization only applies for arrays
5066 // of scalars and arrays of class type with trivial copy-assignment
5067 // operators.
5068 if (FieldType->isArrayType() &&
5069 (!BaseType->isRecordType() ||
5070 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5071 ->hasTrivialCopyAssignment())) {
5072 // Compute the size of the memory buffer to be copied.
5073 QualType SizeType = Context.getSizeType();
5074 llvm::APInt Size(Context.getTypeSize(SizeType),
5075 Context.getTypeSizeInChars(BaseType).getQuantity());
5076 for (const ConstantArrayType *Array
5077 = Context.getAsConstantArrayType(FieldType);
5078 Array;
5079 Array = Context.getAsConstantArrayType(Array->getElementType())) {
5080 llvm::APInt ArraySize = Array->getSize();
5081 ArraySize.zextOrTrunc(Size.getBitWidth());
5082 Size *= ArraySize;
5083 }
5084
5085 // Take the address of the field references for "from" and "to".
5086 From = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(From));
5087 To = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(To));
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005088
5089 bool NeedsCollectableMemCpy =
5090 (BaseType->isRecordType() &&
5091 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5092
5093 if (NeedsCollectableMemCpy) {
5094 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00005095 // Create a reference to the __builtin_objc_memmove_collectable function.
5096 LookupResult R(*this,
5097 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005098 Loc, LookupOrdinaryName);
5099 LookupName(R, TUScope, true);
5100
5101 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5102 if (!CollectableMemCpy) {
5103 // Something went horribly wrong earlier, and we will have
5104 // complained about it.
5105 Invalid = true;
5106 continue;
5107 }
5108
5109 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5110 CollectableMemCpy->getType(),
5111 Loc, 0).takeAs<Expr>();
5112 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5113 }
5114 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005115 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00005116 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00005117 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5118 LookupOrdinaryName);
5119 LookupName(R, TUScope, true);
5120
5121 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5122 if (!BuiltinMemCpy) {
5123 // Something went horribly wrong earlier, and we will have complained
5124 // about it.
5125 Invalid = true;
5126 continue;
5127 }
5128
5129 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5130 BuiltinMemCpy->getType(),
5131 Loc, 0).takeAs<Expr>();
5132 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5133 }
5134
John McCallca0408f2010-08-23 06:44:23 +00005135 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005136 CallArgs.push_back(To.takeAs<Expr>());
5137 CallArgs.push_back(From.takeAs<Expr>());
5138 CallArgs.push_back(new (Context) IntegerLiteral(Size, SizeType, Loc));
5139 llvm::SmallVector<SourceLocation, 4> Commas; // FIXME: Silly
5140 Commas.push_back(Loc);
5141 Commas.push_back(Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00005142 OwningExprResult Call = ExprError();
5143 if (NeedsCollectableMemCpy)
5144 Call = ActOnCallExpr(/*Scope=*/0,
5145 Owned(CollectableMemCpyRef->Retain()),
5146 Loc, move_arg(CallArgs),
5147 Commas.data(), Loc);
5148 else
5149 Call = ActOnCallExpr(/*Scope=*/0,
5150 Owned(BuiltinMemCpyRef->Retain()),
5151 Loc, move_arg(CallArgs),
5152 Commas.data(), Loc);
5153
Douglas Gregor06a9f362010-05-01 20:49:11 +00005154 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5155 Statements.push_back(Call.takeAs<Expr>());
5156 continue;
5157 }
5158
5159 // Build the copy of this field.
5160 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Douglas Gregor6cdc1612010-05-04 15:20:55 +00005161 move(To), move(From),
5162 /*CopyingBaseSubobject=*/false);
Douglas Gregor06a9f362010-05-01 20:49:11 +00005163 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00005164 Diag(CurrentLocation, diag::note_member_synthesized_at)
5165 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5166 CopyAssignOperator->setInvalidDecl();
5167 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00005168 }
5169
5170 // Success! Record the copy.
5171 Statements.push_back(Copy.takeAs<Stmt>());
5172 }
5173
5174 if (!Invalid) {
5175 // Add a "return *this;"
5176 OwningExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
5177 Owned(This->Retain()));
5178
5179 OwningStmtResult Return = ActOnReturnStmt(Loc, move(ThisObj));
5180 if (Return.isInvalid())
5181 Invalid = true;
5182 else {
5183 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005184
5185 if (Trap.hasErrorOccurred()) {
5186 Diag(CurrentLocation, diag::note_member_synthesized_at)
5187 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5188 Invalid = true;
5189 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00005190 }
5191 }
5192
5193 if (Invalid) {
5194 CopyAssignOperator->setInvalidDecl();
5195 return;
5196 }
5197
5198 OwningStmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
5199 /*isStmtExpr=*/false);
5200 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5201 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005202}
5203
Douglas Gregor23c94db2010-07-02 17:43:08 +00005204CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5205 CXXRecordDecl *ClassDecl) {
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005206 // C++ [class.copy]p4:
5207 // If the class definition does not explicitly declare a copy
5208 // constructor, one is declared implicitly.
5209
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005210 // C++ [class.copy]p5:
5211 // The implicitly-declared copy constructor for a class X will
5212 // have the form
5213 //
5214 // X::X(const X&)
5215 //
5216 // if
5217 bool HasConstCopyConstructor = true;
5218
5219 // -- each direct or virtual base class B of X has a copy
5220 // constructor whose first parameter is of type const B& or
5221 // const volatile B&, and
5222 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5223 BaseEnd = ClassDecl->bases_end();
5224 HasConstCopyConstructor && Base != BaseEnd;
5225 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005226 // Virtual bases are handled below.
5227 if (Base->isVirtual())
5228 continue;
5229
Douglas Gregor22584312010-07-02 23:41:54 +00005230 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005231 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005232 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5233 DeclareImplicitCopyConstructor(BaseClassDecl);
5234
Douglas Gregor598a8542010-07-01 18:27:03 +00005235 HasConstCopyConstructor
5236 = BaseClassDecl->hasConstCopyConstructor(Context);
5237 }
5238
5239 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5240 BaseEnd = ClassDecl->vbases_end();
5241 HasConstCopyConstructor && Base != BaseEnd;
5242 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005243 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005244 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005245 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5246 DeclareImplicitCopyConstructor(BaseClassDecl);
5247
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005248 HasConstCopyConstructor
5249 = BaseClassDecl->hasConstCopyConstructor(Context);
5250 }
5251
5252 // -- for all the nonstatic data members of X that are of a
5253 // class type M (or array thereof), each such class type
5254 // has a copy constructor whose first parameter is of type
5255 // const M& or const volatile M&.
5256 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5257 FieldEnd = ClassDecl->field_end();
5258 HasConstCopyConstructor && Field != FieldEnd;
5259 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00005260 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005261 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005262 CXXRecordDecl *FieldClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00005263 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005264 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5265 DeclareImplicitCopyConstructor(FieldClassDecl);
5266
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005267 HasConstCopyConstructor
Douglas Gregor598a8542010-07-01 18:27:03 +00005268 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005269 }
5270 }
5271
5272 // Otherwise, the implicitly declared copy constructor will have
5273 // the form
5274 //
5275 // X::X(X&)
5276 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5277 QualType ArgType = ClassType;
5278 if (HasConstCopyConstructor)
5279 ArgType = ArgType.withConst();
5280 ArgType = Context.getLValueReferenceType(ArgType);
5281
Douglas Gregor0d405db2010-07-01 20:59:04 +00005282 // C++ [except.spec]p14:
5283 // An implicitly declared special member function (Clause 12) shall have an
5284 // exception-specification. [...]
5285 ImplicitExceptionSpecification ExceptSpec(Context);
5286 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5287 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5288 BaseEnd = ClassDecl->bases_end();
5289 Base != BaseEnd;
5290 ++Base) {
5291 // Virtual bases are handled below.
5292 if (Base->isVirtual())
5293 continue;
5294
Douglas Gregor22584312010-07-02 23:41:54 +00005295 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005296 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005297 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5298 DeclareImplicitCopyConstructor(BaseClassDecl);
5299
Douglas Gregor0d405db2010-07-01 20:59:04 +00005300 if (CXXConstructorDecl *CopyConstructor
5301 = BaseClassDecl->getCopyConstructor(Context, Quals))
5302 ExceptSpec.CalledDecl(CopyConstructor);
5303 }
5304 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5305 BaseEnd = ClassDecl->vbases_end();
5306 Base != BaseEnd;
5307 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00005308 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005309 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005310 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5311 DeclareImplicitCopyConstructor(BaseClassDecl);
5312
Douglas Gregor0d405db2010-07-01 20:59:04 +00005313 if (CXXConstructorDecl *CopyConstructor
5314 = BaseClassDecl->getCopyConstructor(Context, Quals))
5315 ExceptSpec.CalledDecl(CopyConstructor);
5316 }
5317 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5318 FieldEnd = ClassDecl->field_end();
5319 Field != FieldEnd;
5320 ++Field) {
5321 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5322 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005323 CXXRecordDecl *FieldClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00005324 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor22584312010-07-02 23:41:54 +00005325 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5326 DeclareImplicitCopyConstructor(FieldClassDecl);
5327
Douglas Gregor0d405db2010-07-01 20:59:04 +00005328 if (CXXConstructorDecl *CopyConstructor
5329 = FieldClassDecl->getCopyConstructor(Context, Quals))
5330 ExceptSpec.CalledDecl(CopyConstructor);
5331 }
5332 }
5333
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005334 // An implicitly-declared copy constructor is an inline public
5335 // member of its class.
5336 DeclarationName Name
5337 = Context.DeclarationNames.getCXXConstructorName(
5338 Context.getCanonicalType(ClassType));
Abramo Bagnara25777432010-08-11 22:01:17 +00005339 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005340 CXXConstructorDecl *CopyConstructor
Abramo Bagnara25777432010-08-11 22:01:17 +00005341 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005342 Context.getFunctionType(Context.VoidTy,
5343 &ArgType, 1,
5344 false, 0,
Douglas Gregor0d405db2010-07-01 20:59:04 +00005345 ExceptSpec.hasExceptionSpecification(),
5346 ExceptSpec.hasAnyExceptionSpecification(),
5347 ExceptSpec.size(),
5348 ExceptSpec.data(),
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005349 FunctionType::ExtInfo()),
5350 /*TInfo=*/0,
5351 /*isExplicit=*/false,
5352 /*isInline=*/true,
5353 /*isImplicitlyDeclared=*/true);
5354 CopyConstructor->setAccess(AS_public);
5355 CopyConstructor->setImplicit();
5356 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5357
Douglas Gregor22584312010-07-02 23:41:54 +00005358 // Note that we have declared this constructor.
5359 ClassDecl->setDeclaredCopyConstructor(true);
5360 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5361
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005362 // Add the parameter to the constructor.
5363 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5364 ClassDecl->getLocation(),
5365 /*IdentifierInfo=*/0,
5366 ArgType, /*TInfo=*/0,
5367 VarDecl::None,
5368 VarDecl::None, 0);
5369 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor23c94db2010-07-02 17:43:08 +00005370 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00005371 PushOnScopeChains(CopyConstructor, S, false);
5372 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005373
5374 return CopyConstructor;
5375}
5376
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005377void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5378 CXXConstructorDecl *CopyConstructor,
5379 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00005380 assert((CopyConstructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00005381 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorc070cc62010-06-17 23:14:26 +00005382 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005383 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00005384
Anders Carlsson63010a72010-04-23 16:24:12 +00005385 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005386 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005387
Douglas Gregor39957dc2010-05-01 15:04:51 +00005388 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005389 ErrorTrap Trap(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005390
Douglas Gregorc63d2c82010-05-12 16:39:35 +00005391 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5392 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00005393 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005394 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00005395 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005396 } else {
5397 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5398 CopyConstructor->getLocation(),
5399 MultiStmtArg(*this, 0, 0),
5400 /*isStmtExpr=*/false)
5401 .takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00005402 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00005403
5404 CopyConstructor->setUsed();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005405}
5406
Anders Carlssonda3f4e22009-08-25 05:12:04 +00005407Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005408Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00005409 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00005410 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005411 bool RequiresZeroInit,
Anders Carlsson72e96fd2010-05-02 22:54:08 +00005412 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005413 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005414
Douglas Gregor2f599792010-04-02 18:24:57 +00005415 // C++0x [class.copy]p34:
5416 // When certain criteria are met, an implementation is allowed to
5417 // omit the copy/move construction of a class object, even if the
5418 // copy/move constructor and/or destructor for the object have
5419 // side effects. [...]
5420 // - when a temporary class object that has not been bound to a
5421 // reference (12.2) would be copied/moved to a class object
5422 // with the same cv-unqualified type, the copy/move operation
5423 // can be omitted by constructing the temporary object
5424 // directly into the target of the omitted copy/move
5425 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
5426 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
5427 Elidable = SubExpr->isTemporaryObject() &&
Douglas Gregorb8f7de92010-08-22 18:27:02 +00005428 ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor2f599792010-04-02 18:24:57 +00005429 Context.hasSameUnqualifiedType(SubExpr->getType(),
5430 Context.getTypeDeclType(Constructor->getParent()));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005431 }
Mike Stump1eb44332009-09-09 15:08:12 +00005432
5433 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005434 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlsson72e96fd2010-05-02 22:54:08 +00005435 ConstructKind);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00005436}
5437
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005438/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5439/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00005440Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00005441Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5442 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00005443 MultiExprArg ExprArgs,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005444 bool RequiresZeroInit,
Anders Carlsson72e96fd2010-05-02 22:54:08 +00005445 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00005446 unsigned NumExprs = ExprArgs.size();
5447 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00005448
Douglas Gregor7edfb692009-11-23 12:27:39 +00005449 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00005450 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor16006c92009-12-16 18:50:27 +00005451 Constructor, Elidable, Exprs, NumExprs,
Anders Carlsson72e96fd2010-05-02 22:54:08 +00005452 RequiresZeroInit, ConstructKind));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005453}
5454
Mike Stump1eb44332009-09-09 15:08:12 +00005455bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00005456 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00005457 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00005458 OwningExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00005459 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00005460 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00005461 if (TempResult.isInvalid())
5462 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005463
Anders Carlssonda3f4e22009-08-25 05:12:04 +00005464 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005465 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson0ece4912009-12-15 20:51:39 +00005466 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00005467 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00005468
Anders Carlssonfe2de492009-08-25 05:18:00 +00005469 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00005470}
5471
John McCall68c6c9a2010-02-02 09:10:11 +00005472void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5473 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor333de062010-02-25 18:11:54 +00005474 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregorfb2db462010-05-22 17:12:29 +00005475 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00005476 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall4f9506a2010-02-02 08:45:54 +00005477 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall58e6f342010-03-16 05:22:47 +00005478 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005479 PDiag(diag::err_access_dtor_var)
John McCall58e6f342010-03-16 05:22:47 +00005480 << VD->getDeclName()
5481 << VD->getType());
John McCall626e96e2010-08-01 20:20:59 +00005482
5483 if (!VD->isInvalidDecl() && VD->hasGlobalStorage())
5484 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall4f9506a2010-02-02 08:45:54 +00005485 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005486}
5487
Mike Stump1eb44332009-09-09 15:08:12 +00005488/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005489/// ActOnDeclarator, when a C++ direct initializer is present.
5490/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00005491void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005492 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00005493 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005494 SourceLocation *CommaLocs,
5495 SourceLocation RParenLoc) {
Daniel Dunbar51846262009-12-24 19:19:26 +00005496 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005497
5498 // If there is no declaration, there was an error parsing it. Just ignore
5499 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005500 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005501 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005502
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005503 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5504 if (!VDecl) {
5505 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5506 RealDecl->setInvalidDecl();
5507 return;
5508 }
5509
Douglas Gregor83ddad32009-08-26 21:14:46 +00005510 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005511 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005512 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5513 //
5514 // Clients that want to distinguish between the two forms, can check for
5515 // direct initializer using VarDecl::hasCXXDirectInitializer().
5516 // A major benefit is that clients that don't particularly care about which
5517 // exactly form was it (like the CodeGen) can handle both cases without
5518 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005519
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005520 // C++ 8.5p11:
5521 // The form of initialization (using parentheses or '=') is generally
5522 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005523 // class type.
5524
Douglas Gregor4dffad62010-02-11 22:55:30 +00005525 if (!VDecl->getType()->isDependentType() &&
5526 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00005527 diag::err_typecheck_decl_incomplete_type)) {
5528 VDecl->setInvalidDecl();
5529 return;
5530 }
5531
Douglas Gregor90f93822009-12-22 22:17:25 +00005532 // The variable can not have an abstract class type.
5533 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5534 diag::err_abstract_type_in_decl,
5535 AbstractVariableType))
5536 VDecl->setInvalidDecl();
5537
Sebastian Redl31310a22010-02-01 20:16:42 +00005538 const VarDecl *Def;
5539 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00005540 Diag(VDecl->getLocation(), diag::err_redefinition)
5541 << VDecl->getDeclName();
5542 Diag(Def->getLocation(), diag::note_previous_definition);
5543 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00005544 return;
5545 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00005546
5547 // If either the declaration has a dependent type or if any of the
5548 // expressions is type-dependent, we represent the initialization
5549 // via a ParenListExpr for later use during template instantiation.
5550 if (VDecl->getType()->isDependentType() ||
5551 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
5552 // Let clients know that initialization was done with a direct initializer.
5553 VDecl->setCXXDirectInitializer(true);
5554
5555 // Store the initialization expressions as a ParenListExpr.
5556 unsigned NumExprs = Exprs.size();
5557 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5558 (Expr **)Exprs.release(),
5559 NumExprs, RParenLoc));
5560 return;
5561 }
Douglas Gregor90f93822009-12-22 22:17:25 +00005562
5563 // Capture the variable that is being initialized and the style of
5564 // initialization.
5565 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5566
5567 // FIXME: Poor source location information.
5568 InitializationKind Kind
5569 = InitializationKind::CreateDirect(VDecl->getLocation(),
5570 LParenLoc, RParenLoc);
5571
5572 InitializationSequence InitSeq(*this, Entity, Kind,
5573 (Expr**)Exprs.get(), Exprs.size());
5574 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
5575 if (Result.isInvalid()) {
5576 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005577 return;
5578 }
Douglas Gregor90f93822009-12-22 22:17:25 +00005579
5580 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregor838db382010-02-11 01:19:42 +00005581 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005582 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00005583
John McCall4204f072010-08-02 21:13:48 +00005584 if (!VDecl->isInvalidDecl() &&
5585 !VDecl->getDeclContext()->isDependentContext() &&
5586 VDecl->hasGlobalStorage() &&
5587 !VDecl->getInit()->isConstantInitializer(Context,
5588 VDecl->getType()->isReferenceType()))
5589 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5590 << VDecl->getInit()->getSourceRange();
5591
John McCall68c6c9a2010-02-02 09:10:11 +00005592 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5593 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005594}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00005595
Douglas Gregor39da0b82009-09-09 23:08:42 +00005596/// \brief Given a constructor and the set of arguments provided for the
5597/// constructor, convert the arguments and add any required default arguments
5598/// to form a proper call to this constructor.
5599///
5600/// \returns true if an error occurred, false otherwise.
5601bool
5602Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5603 MultiExprArg ArgsPtr,
5604 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00005605 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00005606 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5607 unsigned NumArgs = ArgsPtr.size();
5608 Expr **Args = (Expr **)ArgsPtr.get();
5609
5610 const FunctionProtoType *Proto
5611 = Constructor->getType()->getAs<FunctionProtoType>();
5612 assert(Proto && "Constructor without a prototype?");
5613 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00005614
5615 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005616 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00005617 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005618 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00005619 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00005620
5621 VariadicCallType CallType =
5622 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5623 llvm::SmallVector<Expr *, 8> AllArgs;
5624 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5625 Proto, 0, Args, NumArgs, AllArgs,
5626 CallType);
5627 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5628 ConvertedArgs.push_back(AllArgs[i]);
5629 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00005630}
5631
Anders Carlsson20d45d22009-12-12 00:32:00 +00005632static inline bool
5633CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5634 const FunctionDecl *FnDecl) {
5635 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
5636 if (isa<NamespaceDecl>(DC)) {
5637 return SemaRef.Diag(FnDecl->getLocation(),
5638 diag::err_operator_new_delete_declared_in_namespace)
5639 << FnDecl->getDeclName();
5640 }
5641
5642 if (isa<TranslationUnitDecl>(DC) &&
5643 FnDecl->getStorageClass() == FunctionDecl::Static) {
5644 return SemaRef.Diag(FnDecl->getLocation(),
5645 diag::err_operator_new_delete_declared_static)
5646 << FnDecl->getDeclName();
5647 }
5648
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00005649 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00005650}
5651
Anders Carlsson156c78e2009-12-13 17:53:43 +00005652static inline bool
5653CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5654 CanQualType ExpectedResultType,
5655 CanQualType ExpectedFirstParamType,
5656 unsigned DependentParamTypeDiag,
5657 unsigned InvalidParamTypeDiag) {
5658 QualType ResultType =
5659 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5660
5661 // Check that the result type is not dependent.
5662 if (ResultType->isDependentType())
5663 return SemaRef.Diag(FnDecl->getLocation(),
5664 diag::err_operator_new_delete_dependent_result_type)
5665 << FnDecl->getDeclName() << ExpectedResultType;
5666
5667 // Check that the result type is what we expect.
5668 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5669 return SemaRef.Diag(FnDecl->getLocation(),
5670 diag::err_operator_new_delete_invalid_result_type)
5671 << FnDecl->getDeclName() << ExpectedResultType;
5672
5673 // A function template must have at least 2 parameters.
5674 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5675 return SemaRef.Diag(FnDecl->getLocation(),
5676 diag::err_operator_new_delete_template_too_few_parameters)
5677 << FnDecl->getDeclName();
5678
5679 // The function decl must have at least 1 parameter.
5680 if (FnDecl->getNumParams() == 0)
5681 return SemaRef.Diag(FnDecl->getLocation(),
5682 diag::err_operator_new_delete_too_few_parameters)
5683 << FnDecl->getDeclName();
5684
5685 // Check the the first parameter type is not dependent.
5686 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5687 if (FirstParamType->isDependentType())
5688 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5689 << FnDecl->getDeclName() << ExpectedFirstParamType;
5690
5691 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00005692 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00005693 ExpectedFirstParamType)
5694 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5695 << FnDecl->getDeclName() << ExpectedFirstParamType;
5696
5697 return false;
5698}
5699
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005700static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00005701CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00005702 // C++ [basic.stc.dynamic.allocation]p1:
5703 // A program is ill-formed if an allocation function is declared in a
5704 // namespace scope other than global scope or declared static in global
5705 // scope.
5706 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5707 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00005708
5709 CanQualType SizeTy =
5710 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5711
5712 // C++ [basic.stc.dynamic.allocation]p1:
5713 // The return type shall be void*. The first parameter shall have type
5714 // std::size_t.
5715 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5716 SizeTy,
5717 diag::err_operator_new_dependent_param_type,
5718 diag::err_operator_new_param_type))
5719 return true;
5720
5721 // C++ [basic.stc.dynamic.allocation]p1:
5722 // The first parameter shall not have an associated default argument.
5723 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00005724 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00005725 diag::err_operator_new_default_arg)
5726 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5727
5728 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00005729}
5730
5731static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005732CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5733 // C++ [basic.stc.dynamic.deallocation]p1:
5734 // A program is ill-formed if deallocation functions are declared in a
5735 // namespace scope other than global scope or declared static in global
5736 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00005737 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5738 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005739
5740 // C++ [basic.stc.dynamic.deallocation]p2:
5741 // Each deallocation function shall return void and its first parameter
5742 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00005743 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5744 SemaRef.Context.VoidPtrTy,
5745 diag::err_operator_delete_dependent_param_type,
5746 diag::err_operator_delete_param_type))
5747 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005748
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005749 return false;
5750}
5751
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005752/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5753/// of this overloaded operator is well-formed. If so, returns false;
5754/// otherwise, emits appropriate diagnostics and returns true.
5755bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005756 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005757 "Expected an overloaded operator declaration");
5758
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005759 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5760
Mike Stump1eb44332009-09-09 15:08:12 +00005761 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005762 // The allocation and deallocation functions, operator new,
5763 // operator new[], operator delete and operator delete[], are
5764 // described completely in 3.7.3. The attributes and restrictions
5765 // found in the rest of this subclause do not apply to them unless
5766 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00005767 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00005768 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00005769
Anders Carlssona3ccda52009-12-12 00:26:23 +00005770 if (Op == OO_New || Op == OO_Array_New)
5771 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005772
5773 // C++ [over.oper]p6:
5774 // An operator function shall either be a non-static member
5775 // function or be a non-member function and have at least one
5776 // parameter whose type is a class, a reference to a class, an
5777 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005778 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5779 if (MethodDecl->isStatic())
5780 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005781 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005782 } else {
5783 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005784 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5785 ParamEnd = FnDecl->param_end();
5786 Param != ParamEnd; ++Param) {
5787 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00005788 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5789 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005790 ClassOrEnumParam = true;
5791 break;
5792 }
5793 }
5794
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005795 if (!ClassOrEnumParam)
5796 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005797 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005798 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005799 }
5800
5801 // C++ [over.oper]p8:
5802 // An operator function cannot have default arguments (8.3.6),
5803 // except where explicitly stated below.
5804 //
Mike Stump1eb44332009-09-09 15:08:12 +00005805 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005806 // (C++ [over.call]p1).
5807 if (Op != OO_Call) {
5808 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5809 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00005810 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00005811 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00005812 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00005813 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005814 }
5815 }
5816
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005817 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5818 { false, false, false }
5819#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5820 , { Unary, Binary, MemberOnly }
5821#include "clang/Basic/OperatorKinds.def"
5822 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005823
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005824 bool CanBeUnaryOperator = OperatorUses[Op][0];
5825 bool CanBeBinaryOperator = OperatorUses[Op][1];
5826 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005827
5828 // C++ [over.oper]p8:
5829 // [...] Operator functions cannot have more or fewer parameters
5830 // than the number required for the corresponding operator, as
5831 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00005832 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005833 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005834 if (Op != OO_Call &&
5835 ((NumParams == 1 && !CanBeUnaryOperator) ||
5836 (NumParams == 2 && !CanBeBinaryOperator) ||
5837 (NumParams < 1) || (NumParams > 2))) {
5838 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00005839 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005840 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005841 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005842 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00005843 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005844 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005845 assert(CanBeBinaryOperator &&
5846 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00005847 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00005848 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005849
Chris Lattner416e46f2008-11-21 07:57:12 +00005850 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005851 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005852 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005853
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005854 // Overloaded operators other than operator() cannot be variadic.
5855 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00005856 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005857 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005858 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005859 }
5860
5861 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005862 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5863 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00005864 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005865 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005866 }
5867
5868 // C++ [over.inc]p1:
5869 // The user-defined function called operator++ implements the
5870 // prefix and postfix ++ operator. If this function is a member
5871 // function with no parameters, or a non-member function with one
5872 // parameter of class or enumeration type, it defines the prefix
5873 // increment operator ++ for objects of that type. If the function
5874 // is a member function with one parameter (which shall be of type
5875 // int) or a non-member function with two parameters (the second
5876 // of which shall be of type int), it defines the postfix
5877 // increment operator ++ for objects of that type.
5878 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5879 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5880 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00005881 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005882 ParamIsInt = BT->getKind() == BuiltinType::Int;
5883
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00005884 if (!ParamIsInt)
5885 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00005886 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00005887 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005888 }
5889
Sebastian Redl64b45f72009-01-05 20:52:13 +00005890 // Notify the class if it got an assignment operator.
5891 if (Op == OO_Equal) {
5892 // Would have returned earlier otherwise.
5893 assert(isa<CXXMethodDecl>(FnDecl) &&
5894 "Overloaded = not member, but not filtered.");
5895 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5896 Method->getParent()->addedAssignmentOperator(Context, Method);
5897 }
5898
Douglas Gregor43c7bad2008-11-17 16:14:12 +00005899 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00005900}
Chris Lattner5a003a42008-12-17 07:09:26 +00005901
Sean Hunta6c058d2010-01-13 09:01:02 +00005902/// CheckLiteralOperatorDeclaration - Check whether the declaration
5903/// of this literal operator function is well-formed. If so, returns
5904/// false; otherwise, emits appropriate diagnostics and returns true.
5905bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5906 DeclContext *DC = FnDecl->getDeclContext();
5907 Decl::Kind Kind = DC->getDeclKind();
5908 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5909 Kind != Decl::LinkageSpec) {
5910 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5911 << FnDecl->getDeclName();
5912 return true;
5913 }
5914
5915 bool Valid = false;
5916
Sean Hunt216c2782010-04-07 23:11:06 +00005917 // template <char...> type operator "" name() is the only valid template
5918 // signature, and the only valid signature with no parameters.
5919 if (FnDecl->param_size() == 0) {
5920 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5921 // Must have only one template parameter
5922 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5923 if (Params->size() == 1) {
5924 NonTypeTemplateParmDecl *PmDecl =
5925 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00005926
Sean Hunt216c2782010-04-07 23:11:06 +00005927 // The template parameter must be a char parameter pack.
5928 // FIXME: This test will always fail because non-type parameter packs
5929 // have not been implemented.
5930 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5931 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5932 Valid = true;
5933 }
5934 }
5935 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00005936 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00005937 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5938
Sean Hunta6c058d2010-01-13 09:01:02 +00005939 QualType T = (*Param)->getType();
5940
Sean Hunt30019c02010-04-07 22:57:35 +00005941 // unsigned long long int, long double, and any character type are allowed
5942 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00005943 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5944 Context.hasSameType(T, Context.LongDoubleTy) ||
5945 Context.hasSameType(T, Context.CharTy) ||
5946 Context.hasSameType(T, Context.WCharTy) ||
5947 Context.hasSameType(T, Context.Char16Ty) ||
5948 Context.hasSameType(T, Context.Char32Ty)) {
5949 if (++Param == FnDecl->param_end())
5950 Valid = true;
5951 goto FinishedParams;
5952 }
5953
Sean Hunt30019c02010-04-07 22:57:35 +00005954 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00005955 const PointerType *PT = T->getAs<PointerType>();
5956 if (!PT)
5957 goto FinishedParams;
5958 T = PT->getPointeeType();
5959 if (!T.isConstQualified())
5960 goto FinishedParams;
5961 T = T.getUnqualifiedType();
5962
5963 // Move on to the second parameter;
5964 ++Param;
5965
5966 // If there is no second parameter, the first must be a const char *
5967 if (Param == FnDecl->param_end()) {
5968 if (Context.hasSameType(T, Context.CharTy))
5969 Valid = true;
5970 goto FinishedParams;
5971 }
5972
5973 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5974 // are allowed as the first parameter to a two-parameter function
5975 if (!(Context.hasSameType(T, Context.CharTy) ||
5976 Context.hasSameType(T, Context.WCharTy) ||
5977 Context.hasSameType(T, Context.Char16Ty) ||
5978 Context.hasSameType(T, Context.Char32Ty)))
5979 goto FinishedParams;
5980
5981 // The second and final parameter must be an std::size_t
5982 T = (*Param)->getType().getUnqualifiedType();
5983 if (Context.hasSameType(T, Context.getSizeType()) &&
5984 ++Param == FnDecl->param_end())
5985 Valid = true;
5986 }
5987
5988 // FIXME: This diagnostic is absolutely terrible.
5989FinishedParams:
5990 if (!Valid) {
5991 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5992 << FnDecl->getDeclName();
5993 return true;
5994 }
5995
5996 return false;
5997}
5998
Douglas Gregor074149e2009-01-05 19:45:36 +00005999/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6000/// linkage specification, including the language and (if present)
6001/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6002/// the location of the language string literal, which is provided
6003/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6004/// the '{' brace. Otherwise, this linkage specification does not
6005/// have any braces.
John McCalld226f652010-08-21 09:40:31 +00006006Decl *Sema::ActOnStartLinkageSpecification(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006007 SourceLocation ExternLoc,
6008 SourceLocation LangLoc,
Benjamin Kramerd5663812010-05-03 13:08:54 +00006009 llvm::StringRef Lang,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006010 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00006011 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006012 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006013 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00006014 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00006015 Language = LinkageSpecDecl::lang_cxx;
6016 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00006017 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00006018 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006019 }
Mike Stump1eb44332009-09-09 15:08:12 +00006020
Chris Lattnercc98eac2008-12-17 07:13:27 +00006021 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00006022
Douglas Gregor074149e2009-01-05 19:45:36 +00006023 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00006024 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00006025 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006026 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00006027 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00006028 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00006029}
6030
Abramo Bagnara35f9a192010-07-30 16:47:02 +00006031/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00006032/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6033/// valid, it's the position of the closing '}' brace in a linkage
6034/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00006035Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6036 Decl *LinkageSpec,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006037 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00006038 if (LinkageSpec)
6039 PopDeclContext();
6040 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00006041}
6042
Douglas Gregord308e622009-05-18 20:51:54 +00006043/// \brief Perform semantic analysis for the variable declaration that
6044/// occurs within a C++ catch clause, returning the newly-created
6045/// variable.
6046VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCalla93c9342009-12-07 02:54:59 +00006047 TypeSourceInfo *TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006048 IdentifierInfo *Name,
6049 SourceLocation Loc,
6050 SourceRange Range) {
6051 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006052
6053 // Arrays and functions decay.
6054 if (ExDeclType->isArrayType())
6055 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6056 else if (ExDeclType->isFunctionType())
6057 ExDeclType = Context.getPointerType(ExDeclType);
6058
6059 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6060 // The exception-declaration shall not denote a pointer or reference to an
6061 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006062 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00006063 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00006064 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006065 Invalid = true;
6066 }
Douglas Gregord308e622009-05-18 20:51:54 +00006067
Douglas Gregora2762912010-03-08 01:47:36 +00006068 // GCC allows catching pointers and references to incomplete types
6069 // as an extension; so do we, but we warn by default.
6070
Sebastian Redl4b07b292008-12-22 19:15:10 +00006071 QualType BaseType = ExDeclType;
6072 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00006073 unsigned DK = diag::err_catch_incomplete;
Douglas Gregora2762912010-03-08 01:47:36 +00006074 bool IncompleteCatchIsInvalid = true;
Ted Kremenek6217b802009-07-29 21:53:49 +00006075 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006076 BaseType = Ptr->getPointeeType();
6077 Mode = 1;
Douglas Gregora2762912010-03-08 01:47:36 +00006078 DK = diag::ext_catch_incomplete_ptr;
6079 IncompleteCatchIsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006080 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006081 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006082 BaseType = Ref->getPointeeType();
6083 Mode = 2;
Douglas Gregora2762912010-03-08 01:47:36 +00006084 DK = diag::ext_catch_incomplete_ref;
6085 IncompleteCatchIsInvalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006086 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00006087 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregora2762912010-03-08 01:47:36 +00006088 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6089 IncompleteCatchIsInvalid)
Sebastian Redl4b07b292008-12-22 19:15:10 +00006090 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006091
Mike Stump1eb44332009-09-09 15:08:12 +00006092 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00006093 RequireNonAbstractType(Loc, ExDeclType,
6094 diag::err_abstract_type_in_decl,
6095 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00006096 Invalid = true;
6097
John McCall5a180392010-07-24 00:37:23 +00006098 // Only the non-fragile NeXT runtime currently supports C++ catches
6099 // of ObjC types, and no runtime supports catching ObjC types by value.
6100 if (!Invalid && getLangOptions().ObjC1) {
6101 QualType T = ExDeclType;
6102 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6103 T = RT->getPointeeType();
6104
6105 if (T->isObjCObjectType()) {
6106 Diag(Loc, diag::err_objc_object_catch);
6107 Invalid = true;
6108 } else if (T->isObjCObjectPointerType()) {
6109 if (!getLangOptions().NeXTRuntime) {
6110 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6111 Invalid = true;
6112 } else if (!getLangOptions().ObjCNonFragileABI) {
6113 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6114 Invalid = true;
6115 }
6116 }
6117 }
6118
Mike Stump1eb44332009-09-09 15:08:12 +00006119 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Douglas Gregor16573fa2010-04-19 22:54:31 +00006120 Name, ExDeclType, TInfo, VarDecl::None,
6121 VarDecl::None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00006122 ExDecl->setExceptionVariable(true);
6123
Douglas Gregor6d182892010-03-05 23:38:39 +00006124 if (!Invalid) {
6125 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6126 // C++ [except.handle]p16:
6127 // The object declared in an exception-declaration or, if the
6128 // exception-declaration does not specify a name, a temporary (12.2) is
6129 // copy-initialized (8.5) from the exception object. [...]
6130 // The object is destroyed when the handler exits, after the destruction
6131 // of any automatic objects initialized within the handler.
6132 //
6133 // We just pretend to initialize the object with itself, then make sure
6134 // it can be destroyed later.
6135 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6136 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
6137 Loc, ExDeclType, 0);
6138 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6139 SourceLocation());
6140 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
6141 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00006142 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6d182892010-03-05 23:38:39 +00006143 if (Result.isInvalid())
6144 Invalid = true;
6145 else
6146 FinalizeVarWithDestructor(ExDecl, RecordTy);
6147 }
6148 }
6149
Douglas Gregord308e622009-05-18 20:51:54 +00006150 if (Invalid)
6151 ExDecl->setInvalidDecl();
6152
6153 return ExDecl;
6154}
6155
6156/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6157/// handler.
John McCalld226f652010-08-21 09:40:31 +00006158Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00006159 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6160 QualType ExDeclType = TInfo->getType();
Douglas Gregord308e622009-05-18 20:51:54 +00006161
6162 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00006163 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00006164 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00006165 LookupOrdinaryName,
6166 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006167 // The scope should be freshly made just for us. There is just no way
6168 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00006169 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00006170 if (PrevDecl->isTemplateParameter()) {
6171 // Maybe we will complain about the shadowed template parameter.
6172 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006173 }
6174 }
6175
Chris Lattnereaaebc72009-04-25 08:06:05 +00006176 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00006177 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6178 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00006179 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006180 }
6181
John McCalla93c9342009-12-07 02:54:59 +00006182 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00006183 D.getIdentifier(),
6184 D.getIdentifierLoc(),
6185 D.getDeclSpec().getSourceRange());
6186
Chris Lattnereaaebc72009-04-25 08:06:05 +00006187 if (Invalid)
6188 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00006189
Sebastian Redl4b07b292008-12-22 19:15:10 +00006190 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00006191 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00006192 PushOnScopeChains(ExDecl, S);
6193 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006194 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00006195
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006196 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00006197 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00006198}
Anders Carlssonfb311762009-03-14 00:25:26 +00006199
John McCalld226f652010-08-21 09:40:31 +00006200Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006201 ExprArg assertexpr,
6202 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00006203 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00006204 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00006205 cast<StringLiteral>((Expr *)assertmessageexpr.get());
6206
Anders Carlssonc3082412009-03-14 00:33:21 +00006207 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6208 llvm::APSInt Value(32);
6209 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6210 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6211 AssertExpr->getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006212 return 0;
Anders Carlssonc3082412009-03-14 00:33:21 +00006213 }
Anders Carlssonfb311762009-03-14 00:25:26 +00006214
Anders Carlssonc3082412009-03-14 00:33:21 +00006215 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00006216 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00006217 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00006218 }
6219 }
Mike Stump1eb44332009-09-09 15:08:12 +00006220
Anders Carlsson77d81422009-03-15 17:35:16 +00006221 assertexpr.release();
6222 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00006223 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00006224 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00006225
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006226 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00006227 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00006228}
Sebastian Redl50de12f2009-03-24 22:27:57 +00006229
Douglas Gregor1d869352010-04-07 16:53:43 +00006230/// \brief Perform semantic analysis of the given friend type declaration.
6231///
6232/// \returns A friend declaration that.
6233FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6234 TypeSourceInfo *TSInfo) {
6235 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6236
6237 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00006238 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00006239
Douglas Gregor06245bf2010-04-07 17:57:12 +00006240 if (!getLangOptions().CPlusPlus0x) {
6241 // C++03 [class.friend]p2:
6242 // An elaborated-type-specifier shall be used in a friend declaration
6243 // for a class.*
6244 //
6245 // * The class-key of the elaborated-type-specifier is required.
6246 if (!ActiveTemplateInstantiations.empty()) {
6247 // Do not complain about the form of friend template types during
6248 // template instantiation; we will already have complained when the
6249 // template was declared.
6250 } else if (!T->isElaboratedTypeSpecifier()) {
6251 // If we evaluated the type to a record type, suggest putting
6252 // a tag in front.
6253 if (const RecordType *RT = T->getAs<RecordType>()) {
6254 RecordDecl *RD = RT->getDecl();
6255
6256 std::string InsertionText = std::string(" ") + RD->getKindName();
6257
6258 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6259 << (unsigned) RD->getTagKind()
6260 << T
6261 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6262 InsertionText);
6263 } else {
6264 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6265 << T
6266 << SourceRange(FriendLoc, TypeRange.getEnd());
6267 }
6268 } else if (T->getAs<EnumType>()) {
6269 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00006270 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00006271 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00006272 }
6273 }
6274
Douglas Gregor06245bf2010-04-07 17:57:12 +00006275 // C++0x [class.friend]p3:
6276 // If the type specifier in a friend declaration designates a (possibly
6277 // cv-qualified) class type, that class is declared as a friend; otherwise,
6278 // the friend declaration is ignored.
6279
6280 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6281 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00006282
6283 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6284}
6285
John McCalldd4a3b02009-09-16 22:47:08 +00006286/// Handle a friend type declaration. This works in tandem with
6287/// ActOnTag.
6288///
6289/// Notes on friend class templates:
6290///
6291/// We generally treat friend class declarations as if they were
6292/// declaring a class. So, for example, the elaborated type specifier
6293/// in a friend declaration is required to obey the restrictions of a
6294/// class-head (i.e. no typedefs in the scope chain), template
6295/// parameters are required to match up with simple template-ids, &c.
6296/// However, unlike when declaring a template specialization, it's
6297/// okay to refer to a template specialization without an empty
6298/// template parameter declaration, e.g.
6299/// friend class A<T>::B<unsigned>;
6300/// We permit this as a special case; if there are any template
6301/// parameters present at all, require proper matching, i.e.
6302/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +00006303Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCalldd4a3b02009-09-16 22:47:08 +00006304 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +00006305 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00006306
6307 assert(DS.isFriendSpecified());
6308 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6309
John McCalldd4a3b02009-09-16 22:47:08 +00006310 // Try to convert the decl specifier to a type. This works for
6311 // friend templates because ActOnTag never produces a ClassTemplateDecl
6312 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +00006313 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +00006314 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6315 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +00006316 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +00006317 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006318
John McCalldd4a3b02009-09-16 22:47:08 +00006319 // This is definitely an error in C++98. It's probably meant to
6320 // be forbidden in C++0x, too, but the specification is just
6321 // poorly written.
6322 //
6323 // The problem is with declarations like the following:
6324 // template <T> friend A<T>::foo;
6325 // where deciding whether a class C is a friend or not now hinges
6326 // on whether there exists an instantiation of A that causes
6327 // 'foo' to equal C. There are restrictions on class-heads
6328 // (which we declare (by fiat) elaborated friend declarations to
6329 // be) that makes this tractable.
6330 //
6331 // FIXME: handle "template <> friend class A<T>;", which
6332 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +00006333 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +00006334 Diag(Loc, diag::err_tagless_friend_type_template)
6335 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00006336 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +00006337 }
Douglas Gregor1d869352010-04-07 16:53:43 +00006338
John McCall02cace72009-08-28 07:59:38 +00006339 // C++98 [class.friend]p1: A friend of a class is a function
6340 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +00006341 // This is fixed in DR77, which just barely didn't make the C++03
6342 // deadline. It's also a very silly restriction that seriously
6343 // affects inner classes and which nobody else seems to implement;
6344 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +00006345 //
6346 // But note that we could warn about it: it's always useless to
6347 // friend one of your own members (it's not, however, worthless to
6348 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +00006349
John McCalldd4a3b02009-09-16 22:47:08 +00006350 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +00006351 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +00006352 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +00006353 NumTempParamLists,
John McCalldd4a3b02009-09-16 22:47:08 +00006354 (TemplateParameterList**) TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +00006355 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +00006356 DS.getFriendSpecLoc());
6357 else
Douglas Gregor1d869352010-04-07 16:53:43 +00006358 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6359
6360 if (!D)
John McCalld226f652010-08-21 09:40:31 +00006361 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +00006362
John McCalldd4a3b02009-09-16 22:47:08 +00006363 D->setAccess(AS_public);
6364 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +00006365
John McCalld226f652010-08-21 09:40:31 +00006366 return D;
John McCall02cace72009-08-28 07:59:38 +00006367}
6368
John McCalld226f652010-08-21 09:40:31 +00006369Decl *Sema::ActOnFriendFunctionDecl(Scope *S,
6370 Declarator &D,
6371 bool IsDefinition,
John McCallbbbcdd92009-09-11 21:02:39 +00006372 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +00006373 const DeclSpec &DS = D.getDeclSpec();
6374
6375 assert(DS.isFriendSpecified());
6376 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6377
6378 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +00006379 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6380 QualType T = TInfo->getType();
John McCall67d1a672009-08-06 02:15:43 +00006381
6382 // C++ [class.friend]p1
6383 // A friend of a class is a function or class....
6384 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00006385 // It *doesn't* see through dependent types, which is correct
6386 // according to [temp.arg.type]p3:
6387 // If a declaration acquires a function type through a
6388 // type dependent on a template-parameter and this causes
6389 // a declaration that does not use the syntactic form of a
6390 // function declarator to have a function type, the program
6391 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00006392 if (!T->isFunctionType()) {
6393 Diag(Loc, diag::err_unexpected_friend);
6394
6395 // It might be worthwhile to try to recover by creating an
6396 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +00006397 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006398 }
6399
6400 // C++ [namespace.memdef]p3
6401 // - If a friend declaration in a non-local class first declares a
6402 // class or function, the friend class or function is a member
6403 // of the innermost enclosing namespace.
6404 // - The name of the friend is not found by simple name lookup
6405 // until a matching declaration is provided in that namespace
6406 // scope (either before or after the class declaration granting
6407 // friendship).
6408 // - If a friend function is called, its name may be found by the
6409 // name lookup that considers functions from namespaces and
6410 // classes associated with the types of the function arguments.
6411 // - When looking for a prior declaration of a class or a function
6412 // declared as a friend, scopes outside the innermost enclosing
6413 // namespace scope are not considered.
6414
John McCall02cace72009-08-28 07:59:38 +00006415 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00006416 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6417 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +00006418 assert(Name);
6419
John McCall67d1a672009-08-06 02:15:43 +00006420 // The context we found the declaration in, or in which we should
6421 // create the declaration.
6422 DeclContext *DC;
6423
6424 // FIXME: handle local classes
6425
6426 // Recover from invalid scope qualifiers as if they just weren't there.
Abramo Bagnara25777432010-08-11 22:01:17 +00006427 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00006428 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +00006429 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
6430 DC = computeDeclContext(ScopeQual);
6431
6432 // FIXME: handle dependent contexts
John McCalld226f652010-08-21 09:40:31 +00006433 if (!DC) return 0;
6434 if (RequireCompleteDeclContext(ScopeQual, DC)) return 0;
John McCall67d1a672009-08-06 02:15:43 +00006435
John McCall68263142009-11-18 22:49:29 +00006436 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00006437
John McCall9da9cdf2010-05-28 01:41:47 +00006438 // Ignore things found implicitly in the wrong scope.
John McCall67d1a672009-08-06 02:15:43 +00006439 // TODO: better diagnostics for this case. Suggesting the right
6440 // qualified scope would be nice...
John McCall9da9cdf2010-05-28 01:41:47 +00006441 LookupResult::Filter F = Previous.makeFilter();
6442 while (F.hasNext()) {
6443 NamedDecl *D = F.next();
6444 if (!D->getDeclContext()->getLookupContext()->Equals(DC))
6445 F.erase();
6446 }
6447 F.done();
6448
6449 if (Previous.empty()) {
John McCall02cace72009-08-28 07:59:38 +00006450 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00006451 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
John McCalld226f652010-08-21 09:40:31 +00006452 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006453 }
6454
6455 // C++ [class.friend]p1: A friend of a class is a function or
6456 // class that is not a member of the class . . .
Douglas Gregor182ddf02009-09-28 00:08:27 +00006457 if (DC->Equals(CurContext))
John McCall67d1a672009-08-06 02:15:43 +00006458 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6459
John McCall67d1a672009-08-06 02:15:43 +00006460 // Otherwise walk out to the nearest namespace scope looking for matches.
6461 } else {
6462 // TODO: handle local class contexts.
6463
6464 DC = CurContext;
6465 while (true) {
6466 // Skip class contexts. If someone can cite chapter and verse
6467 // for this behavior, that would be nice --- it's what GCC and
6468 // EDG do, and it seems like a reasonable intent, but the spec
6469 // really only says that checks for unqualified existing
6470 // declarations should stop at the nearest enclosing namespace,
6471 // not that they should only consider the nearest enclosing
6472 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +00006473 while (DC->isRecord())
6474 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +00006475
John McCall68263142009-11-18 22:49:29 +00006476 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +00006477
6478 // TODO: decide what we think about using declarations.
John McCall68263142009-11-18 22:49:29 +00006479 if (!Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +00006480 break;
Douglas Gregor182ddf02009-09-28 00:08:27 +00006481
John McCall67d1a672009-08-06 02:15:43 +00006482 if (DC->isFileContext()) break;
6483 DC = DC->getParent();
6484 }
6485
6486 // C++ [class.friend]p1: A friend of a class is a function or
6487 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00006488 // C++0x changes this for both friend types and functions.
6489 // Most C++ 98 compilers do seem to give an error here, so
6490 // we do, too.
John McCall68263142009-11-18 22:49:29 +00006491 if (!Previous.empty() && DC->Equals(CurContext)
6492 && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00006493 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6494 }
6495
Douglas Gregor182ddf02009-09-28 00:08:27 +00006496 if (DC->isFileContext()) {
John McCall67d1a672009-08-06 02:15:43 +00006497 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006498 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6499 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6500 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +00006501 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006502 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6503 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +00006504 return 0;
John McCall67d1a672009-08-06 02:15:43 +00006505 }
John McCall67d1a672009-08-06 02:15:43 +00006506 }
6507
Douglas Gregor182ddf02009-09-28 00:08:27 +00006508 bool Redeclaration = false;
John McCalla93c9342009-12-07 02:54:59 +00006509 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregora735b202009-10-13 14:39:41 +00006510 move(TemplateParams),
John McCall3f9a8a62009-08-11 06:59:38 +00006511 IsDefinition,
6512 Redeclaration);
John McCalld226f652010-08-21 09:40:31 +00006513 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +00006514
Douglas Gregor182ddf02009-09-28 00:08:27 +00006515 assert(ND->getDeclContext() == DC);
6516 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +00006517
John McCallab88d972009-08-31 22:39:49 +00006518 // Add the function declaration to the appropriate lookup tables,
6519 // adjusting the redeclarations list as necessary. We don't
6520 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00006521 //
John McCallab88d972009-08-31 22:39:49 +00006522 // Also update the scope-based lookup if the target context's
6523 // lookup context is in lexical scope.
6524 if (!CurContext->isDependentContext()) {
6525 DC = DC->getLookupContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +00006526 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006527 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +00006528 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +00006529 }
John McCall02cace72009-08-28 07:59:38 +00006530
6531 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +00006532 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +00006533 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00006534 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00006535 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00006536
John McCalld226f652010-08-21 09:40:31 +00006537 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +00006538}
6539
John McCalld226f652010-08-21 09:40:31 +00006540void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6541 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00006542
Sebastian Redl50de12f2009-03-24 22:27:57 +00006543 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6544 if (!Fn) {
6545 Diag(DelLoc, diag::err_deleted_non_function);
6546 return;
6547 }
6548 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6549 Diag(DelLoc, diag::err_deleted_decl_not_first);
6550 Diag(Prev->getLocation(), diag::note_previous_declaration);
6551 // If the declaration wasn't the first, we delete the function anyway for
6552 // recovery.
6553 }
6554 Fn->setDeleted();
6555}
Sebastian Redl13e88542009-04-27 21:33:24 +00006556
6557static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6558 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6559 ++CI) {
6560 Stmt *SubStmt = *CI;
6561 if (!SubStmt)
6562 continue;
6563 if (isa<ReturnStmt>(SubStmt))
6564 Self.Diag(SubStmt->getSourceRange().getBegin(),
6565 diag::err_return_in_constructor_handler);
6566 if (!isa<Expr>(SubStmt))
6567 SearchForReturnInStmt(Self, SubStmt);
6568 }
6569}
6570
6571void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6572 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6573 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6574 SearchForReturnInStmt(*this, Handler);
6575 }
6576}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006577
Mike Stump1eb44332009-09-09 15:08:12 +00006578bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006579 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +00006580 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6581 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006582
Chandler Carruth73857792010-02-15 11:53:20 +00006583 if (Context.hasSameType(NewTy, OldTy) ||
6584 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006585 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006586
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006587 // Check if the return types are covariant
6588 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00006589
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006590 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006591 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6592 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006593 NewClassTy = NewPT->getPointeeType();
6594 OldClassTy = OldPT->getPointeeType();
6595 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006596 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6597 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6598 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6599 NewClassTy = NewRT->getPointeeType();
6600 OldClassTy = OldRT->getPointeeType();
6601 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006602 }
6603 }
Mike Stump1eb44332009-09-09 15:08:12 +00006604
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006605 // The return types aren't either both pointers or references to a class type.
6606 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006607 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006608 diag::err_different_return_type_for_overriding_virtual_function)
6609 << New->getDeclName() << NewTy << OldTy;
6610 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00006611
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006612 return true;
6613 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006614
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006615 // C++ [class.virtual]p6:
6616 // If the return type of D::f differs from the return type of B::f, the
6617 // class type in the return type of D::f shall be complete at the point of
6618 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +00006619 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6620 if (!RT->isBeingDefined() &&
6621 RequireCompleteType(New->getLocation(), NewClassTy,
6622 PDiag(diag::err_covariant_return_incomplete)
6623 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006624 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +00006625 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +00006626
Douglas Gregora4923eb2009-11-16 21:35:15 +00006627 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006628 // Check if the new class derives from the old class.
6629 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6630 Diag(New->getLocation(),
6631 diag::err_covariant_return_not_derived)
6632 << New->getDeclName() << NewTy << OldTy;
6633 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6634 return true;
6635 }
Mike Stump1eb44332009-09-09 15:08:12 +00006636
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006637 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +00006638 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +00006639 diag::err_covariant_return_inaccessible_base,
6640 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6641 // FIXME: Should this point to the return type?
6642 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006643 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6644 return true;
6645 }
6646 }
Mike Stump1eb44332009-09-09 15:08:12 +00006647
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006648 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +00006649 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006650 Diag(New->getLocation(),
6651 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006652 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006653 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6654 return true;
6655 };
Mike Stump1eb44332009-09-09 15:08:12 +00006656
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006657
6658 // The new class type must have the same or less qualifiers as the old type.
6659 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6660 Diag(New->getLocation(),
6661 diag::err_covariant_return_type_class_type_more_qualified)
6662 << New->getDeclName() << NewTy << OldTy;
6663 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6664 return true;
6665 };
Mike Stump1eb44332009-09-09 15:08:12 +00006666
Anders Carlssonc3a68b22009-05-14 19:52:19 +00006667 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00006668}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006669
Sean Huntbbd37c62009-11-21 08:43:09 +00006670bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6671 const CXXMethodDecl *Old)
6672{
6673 if (Old->hasAttr<FinalAttr>()) {
6674 Diag(New->getLocation(), diag::err_final_function_overridden)
6675 << New->getDeclName();
6676 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6677 return true;
6678 }
6679
6680 return false;
6681}
6682
Douglas Gregor4ba31362009-12-01 17:24:26 +00006683/// \brief Mark the given method pure.
6684///
6685/// \param Method the method to be marked pure.
6686///
6687/// \param InitRange the source range that covers the "0" initializer.
6688bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6689 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6690 Method->setPure();
6691
6692 // A class is abstract if at least one function is pure virtual.
6693 Method->getParent()->setAbstract(true);
6694 return false;
6695 }
6696
6697 if (!Method->isInvalidDecl())
6698 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6699 << Method->getDeclName() << InitRange;
6700 return true;
6701}
6702
John McCall731ad842009-12-19 09:28:58 +00006703/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6704/// an initializer for the out-of-line declaration 'Dcl'. The scope
6705/// is a fresh scope pushed for just this purpose.
6706///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006707/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6708/// static data member of class X, names should be looked up in the scope of
6709/// class X.
John McCalld226f652010-08-21 09:40:31 +00006710void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006711 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006712 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006713
John McCall731ad842009-12-19 09:28:58 +00006714 // We should only get called for declarations with scope specifiers, like:
6715 // int foo::bar;
6716 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006717 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006718}
6719
6720/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +00006721/// initializer for the out-of-line declaration 'D'.
6722void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006723 // If there is no declaration, there was an error parsing it.
John McCall731ad842009-12-19 09:28:58 +00006724 if (D == 0) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006725
John McCall731ad842009-12-19 09:28:58 +00006726 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +00006727 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00006728}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006729
6730/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6731/// C++ if/switch/while/for statement.
6732/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +00006733DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006734 // C++ 6.4p2:
6735 // The declarator shall not specify a function or an array.
6736 // The type-specifier-seq shall not contain typedef and shall not declare a
6737 // new class or enumeration.
6738 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6739 "Parser allowed 'typedef' as storage class of condition decl.");
6740
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006741 TagDecl *OwnedTag = 0;
John McCallbf1a0282010-06-04 23:28:52 +00006742 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6743 QualType Ty = TInfo->getType();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006744
6745 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6746 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6747 // would be created and CXXConditionDeclExpr wants a VarDecl.
6748 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6749 << D.getSourceRange();
6750 return DeclResult();
6751 } else if (OwnedTag && OwnedTag->isDefinition()) {
6752 // The type-specifier-seq shall not declare a new class or enumeration.
6753 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6754 }
6755
John McCalld226f652010-08-21 09:40:31 +00006756 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006757 if (!Dcl)
6758 return DeclResult();
6759
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00006760 return Dcl;
6761}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006762
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006763void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6764 bool DefinitionRequired) {
6765 // Ignore any vtable uses in unevaluated operands or for classes that do
6766 // not have a vtable.
6767 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6768 CurContext->isDependentContext() ||
6769 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00006770 return;
6771
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006772 // Try to insert this class into the map.
6773 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6774 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6775 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6776 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +00006777 // If we already had an entry, check to see if we are promoting this vtable
6778 // to required a definition. If so, we need to reappend to the VTableUses
6779 // list, since we may have already processed the first entry.
6780 if (DefinitionRequired && !Pos.first->second) {
6781 Pos.first->second = true;
6782 } else {
6783 // Otherwise, we can early exit.
6784 return;
6785 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006786 }
6787
6788 // Local classes need to have their virtual members marked
6789 // immediately. For all other classes, we mark their virtual members
6790 // at the end of the translation unit.
6791 if (Class->isLocalClass())
6792 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +00006793 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006794 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +00006795}
6796
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006797bool Sema::DefineUsedVTables() {
6798 // If any dynamic classes have their key function defined within
6799 // this translation unit, then those vtables are considered "used" and must
6800 // be emitted.
6801 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6802 if (const CXXMethodDecl *KeyFunction
6803 = Context.getKeyFunction(DynamicClasses[I])) {
6804 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006805 if (KeyFunction->hasBody(Definition))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006806 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6807 }
6808 }
6809
6810 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +00006811 return false;
6812
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006813 // Note: The VTableUses vector could grow as a result of marking
6814 // the members of a class as "used", so we check the size each
6815 // time through the loop and prefer indices (with are stable) to
6816 // iterators (which are not).
6817 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +00006818 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006819 if (!Class)
6820 continue;
6821
6822 SourceLocation Loc = VTableUses[I].second;
6823
6824 // If this class has a key function, but that key function is
6825 // defined in another translation unit, we don't need to emit the
6826 // vtable even though we're using it.
6827 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006828 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006829 switch (KeyFunction->getTemplateSpecializationKind()) {
6830 case TSK_Undeclared:
6831 case TSK_ExplicitSpecialization:
6832 case TSK_ExplicitInstantiationDeclaration:
6833 // The key function is in another translation unit.
6834 continue;
6835
6836 case TSK_ExplicitInstantiationDefinition:
6837 case TSK_ImplicitInstantiation:
6838 // We will be instantiating the key function.
6839 break;
6840 }
6841 } else if (!KeyFunction) {
6842 // If we have a class with no key function that is the subject
6843 // of an explicit instantiation declaration, suppress the
6844 // vtable; it will live with the explicit instantiation
6845 // definition.
6846 bool IsExplicitInstantiationDeclaration
6847 = Class->getTemplateSpecializationKind()
6848 == TSK_ExplicitInstantiationDeclaration;
6849 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6850 REnd = Class->redecls_end();
6851 R != REnd; ++R) {
6852 TemplateSpecializationKind TSK
6853 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6854 if (TSK == TSK_ExplicitInstantiationDeclaration)
6855 IsExplicitInstantiationDeclaration = true;
6856 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6857 IsExplicitInstantiationDeclaration = false;
6858 break;
6859 }
6860 }
6861
6862 if (IsExplicitInstantiationDeclaration)
6863 continue;
6864 }
6865
6866 // Mark all of the virtual members of this class as referenced, so
6867 // that we can build a vtable. Then, tell the AST consumer that a
6868 // vtable for this class is required.
6869 MarkVirtualMembersReferenced(Loc, Class);
6870 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6871 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6872
6873 // Optionally warn if we're emitting a weak vtable.
6874 if (Class->getLinkage() == ExternalLinkage &&
6875 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006876 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006877 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6878 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006879 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00006880 VTableUses.clear();
6881
Anders Carlssond6a637f2009-12-07 08:24:59 +00006882 return true;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006883}
Anders Carlssond6a637f2009-12-07 08:24:59 +00006884
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006885void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6886 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +00006887 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6888 e = RD->method_end(); i != e; ++i) {
6889 CXXMethodDecl *MD = *i;
6890
6891 // C++ [basic.def.odr]p2:
6892 // [...] A virtual member function is used if it is not pure. [...]
6893 if (MD->isVirtual() && !MD->isPure())
6894 MarkDeclarationReferenced(Loc, MD);
6895 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006896
6897 // Only classes that have virtual bases need a VTT.
6898 if (RD->getNumVBases() == 0)
6899 return;
6900
6901 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6902 e = RD->bases_end(); i != e; ++i) {
6903 const CXXRecordDecl *Base =
6904 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +00006905 if (Base->getNumVBases() == 0)
6906 continue;
6907 MarkVirtualMembersReferenced(Loc, Base);
6908 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00006909}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006910
6911/// SetIvarInitializers - This routine builds initialization ASTs for the
6912/// Objective-C implementation whose ivars need be initialized.
6913void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6914 if (!getLangOptions().CPlusPlus)
6915 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00006916 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006917 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6918 CollectIvarsToConstructOrDestruct(OID, ivars);
6919 if (ivars.empty())
6920 return;
6921 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6922 for (unsigned i = 0; i < ivars.size(); i++) {
6923 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00006924 if (Field->isInvalidDecl())
6925 continue;
6926
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006927 CXXBaseOrMemberInitializer *Member;
6928 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6929 InitializationKind InitKind =
6930 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6931
6932 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
6933 Sema::OwningExprResult MemberInit =
6934 InitSeq.Perform(*this, InitEntity, InitKind,
6935 Sema::MultiExprArg(*this, 0, 0));
6936 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
6937 // Note, MemberInit could actually come back empty if no initialization
6938 // is required (e.g., because it would call a trivial default constructor)
6939 if (!MemberInit.get() || MemberInit.isInvalid())
6940 continue;
6941
6942 Member =
6943 new (Context) CXXBaseOrMemberInitializer(Context,
6944 Field, SourceLocation(),
6945 SourceLocation(),
6946 MemberInit.takeAs<Expr>(),
6947 SourceLocation());
6948 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00006949
6950 // Be sure that the destructor is accessible and is marked as referenced.
6951 if (const RecordType *RecordTy
6952 = Context.getBaseElementType(Field->getType())
6953 ->getAs<RecordType>()) {
6954 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +00006955 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00006956 MarkDeclarationReferenced(Field->getLocation(), Destructor);
6957 CheckDestructorAccess(Field->getLocation(), Destructor,
6958 PDiag(diag::err_access_dtor_ivar)
6959 << Context.getBaseElementType(Field->getType()));
6960 }
6961 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00006962 }
6963 ObjCImplementation->setIvarInitializers(Context,
6964 AllToInit.data(), AllToInit.size());
6965 }
6966}