blob: 79b017b330058621150780a60b5dd6538a43c838 [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
14#include "Sema.h"
Douglas Gregor7ad83902008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregor02189362008-10-22 21:13:31 +000019#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000020#include "clang/AST/StmtVisitor.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000021#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000022#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000023#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Chris Lattner8123a952008-04-10 02:22:51 +000025#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000026#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000027#include <map>
Chris Lattner3d1cee32008-04-08 05:04:30 +000028
29using namespace clang;
30
Chris Lattner8123a952008-04-10 02:22:51 +000031//===----------------------------------------------------------------------===//
32// CheckDefaultArgumentVisitor
33//===----------------------------------------------------------------------===//
34
Chris Lattner9e979552008-04-12 23:52:44 +000035namespace {
36 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
37 /// the default argument of a parameter to determine whether it
38 /// contains any ill-formed subexpressions. For example, this will
39 /// diagnose the use of local variables or parameters within the
40 /// default argument expression.
Mike Stump1eb44332009-09-09 15:08:12 +000041 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000042 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000043 Expr *DefaultArg;
44 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000045
Chris Lattner9e979552008-04-12 23:52:44 +000046 public:
Mike Stump1eb44332009-09-09 15:08:12 +000047 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000048 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000049
Chris Lattner9e979552008-04-12 23:52:44 +000050 bool VisitExpr(Expr *Node);
51 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000052 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000053 };
Chris Lattner8123a952008-04-10 02:22:51 +000054
Chris Lattner9e979552008-04-12 23:52:44 +000055 /// VisitExpr - Visit all of the children of this expression.
56 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
57 bool IsInvalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +000058 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattnerb77792e2008-07-26 22:17:49 +000059 E = Node->child_end(); I != E; ++I)
60 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000061 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000062 }
63
Chris Lattner9e979552008-04-12 23:52:44 +000064 /// VisitDeclRefExpr - Visit a reference to a declaration, to
65 /// determine whether this declaration can be used in the default
66 /// argument expression.
67 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000068 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000069 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
70 // C++ [dcl.fct.default]p9
71 // Default arguments are evaluated each time the function is
72 // called. The order of evaluation of function arguments is
73 // unspecified. Consequently, parameters of a function shall not
74 // be used in default argument expressions, even if they are not
75 // evaluated. Parameters of a function declared before a default
76 // argument expression are in scope and can hide namespace and
77 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000078 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000079 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000080 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000081 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000082 // C++ [dcl.fct.default]p7
83 // Local variables shall not be used in default argument
84 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000085 if (VDecl->isBlockVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000088 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000089 }
Chris Lattner8123a952008-04-10 02:22:51 +000090
Douglas Gregor3996f232008-11-04 13:41:56 +000091 return false;
92 }
Chris Lattner9e979552008-04-12 23:52:44 +000093
Douglas Gregor796da182008-11-04 14:32:21 +000094 /// VisitCXXThisExpr - Visit a C++ "this" expression.
95 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
96 // C++ [dcl.fct.default]p8:
97 // The keyword this shall not be used in a default argument of a
98 // member function.
99 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000100 diag::err_param_default_argument_references_this)
101 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000102 }
Chris Lattner8123a952008-04-10 02:22:51 +0000103}
104
Anders Carlssoned961f92009-08-25 02:29:20 +0000105bool
106Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump1eb44332009-09-09 15:08:12 +0000107 SourceLocation EqualLoc) {
Anders Carlssoned961f92009-08-25 02:29:20 +0000108 QualType ParamType = Param->getType();
109
Anders Carlsson5653ca52009-08-25 13:46:13 +0000110 if (RequireCompleteType(Param->getLocation(), Param->getType(),
111 diag::err_typecheck_decl_incomplete_type)) {
112 Param->setInvalidDecl();
113 return true;
114 }
115
Anders Carlssoned961f92009-08-25 02:29:20 +0000116 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000117
Anders Carlssoned961f92009-08-25 02:29:20 +0000118 // C++ [dcl.fct.default]p5
119 // A default argument expression is implicitly converted (clause
120 // 4) to the parameter type. The default argument expression has
121 // the same semantic constraints as the initializer expression in
122 // a declaration of a variable of the parameter type, using the
123 // copy-initialization semantics (8.5).
Mike Stump1eb44332009-09-09 15:08:12 +0000124 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
Anders Carlssoned961f92009-08-25 02:29:20 +0000125 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson9351c172009-08-25 03:18:48 +0000126 return true;
Anders Carlssoned961f92009-08-25 02:29:20 +0000127
128 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Anders Carlssoned961f92009-08-25 02:29:20 +0000130 // Okay: add the default argument to the parameter
131 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000132
Anders Carlssoned961f92009-08-25 02:29:20 +0000133 DefaultArg.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000134
Anders Carlsson9351c172009-08-25 03:18:48 +0000135 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000136}
137
Chris Lattner8123a952008-04-10 02:22:51 +0000138/// ActOnParamDefaultArgument - Check whether the default argument
139/// provided for a function parameter is well-formed. If so, attach it
140/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000141void
Mike Stump1eb44332009-09-09 15:08:12 +0000142Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000143 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000144 if (!param || !defarg.get())
145 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Chris Lattnerb28317a2009-03-28 19:18:32 +0000147 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000148 UnparsedDefaultArgLocs.erase(Param);
149
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000150 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000151 QualType ParamType = Param->getType();
152
153 // Default arguments are only permitted in C++
154 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000155 Diag(EqualLoc, diag::err_param_default_argument)
156 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000157 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000158 return;
159 }
160
Anders Carlsson66e30672009-08-25 01:02:06 +0000161 // Check that the default argument is well-formed
162 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
163 if (DefaultArgChecker.Visit(DefaultArg.get())) {
164 Param->setInvalidDecl();
165 return;
166 }
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Anders Carlssoned961f92009-08-25 02:29:20 +0000168 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000169}
170
Douglas Gregor61366e92008-12-24 00:01:03 +0000171/// ActOnParamUnparsedDefaultArgument - We've seen a default
172/// argument for a function parameter, but we can't parse it yet
173/// because we're inside a class definition. Note that this default
174/// argument will be parsed later.
Mike Stump1eb44332009-09-09 15:08:12 +0000175void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000176 SourceLocation EqualLoc,
177 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000178 if (!param)
179 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Chris Lattnerb28317a2009-03-28 19:18:32 +0000181 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000182 if (Param)
183 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Anders Carlsson5e300d12009-06-12 16:51:40 +0000185 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000186}
187
Douglas Gregor72b505b2008-12-16 21:30:33 +0000188/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
189/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000190void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000191 if (!param)
192 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000193
Anders Carlsson5e300d12009-06-12 16:51:40 +0000194 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Anders Carlsson5e300d12009-06-12 16:51:40 +0000196 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Anders Carlsson5e300d12009-06-12 16:51:40 +0000198 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000199}
200
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000201/// CheckExtraCXXDefaultArguments - Check for any extra default
202/// arguments in the declarator, which is not a function declaration
203/// or definition and therefore is not permitted to have default
204/// arguments. This routine should be invoked for every declarator
205/// that is not a function declaration or definition.
206void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
207 // C++ [dcl.fct.default]p3
208 // A default argument expression shall be specified only in the
209 // parameter-declaration-clause of a function declaration or in a
210 // template-parameter (14.1). It shall not be specified for a
211 // parameter pack. If it is specified in a
212 // parameter-declaration-clause, it shall not occur within a
213 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000214 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000215 DeclaratorChunk &chunk = D.getTypeObject(i);
216 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000217 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
218 ParmVarDecl *Param =
219 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000220 if (Param->hasUnparsedDefaultArg()) {
221 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000222 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
223 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
224 delete Toks;
225 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000226 } else if (Param->getDefaultArg()) {
227 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
228 << Param->getDefaultArg()->getSourceRange();
229 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000230 }
231 }
232 }
233 }
234}
235
Chris Lattner3d1cee32008-04-08 05:04:30 +0000236// MergeCXXFunctionDecl - Merge two declarations of the same C++
237// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000238// type. Subroutine of MergeFunctionDecl. Returns true if there was an
239// error, false otherwise.
240bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
241 bool Invalid = false;
242
Chris Lattner3d1cee32008-04-08 05:04:30 +0000243 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000244 // For non-template functions, default arguments can be added in
245 // later declarations of a function in the same
246 // scope. Declarations in different scopes have completely
247 // distinct sets of default arguments. That is, declarations in
248 // inner scopes do not acquire default arguments from
249 // declarations in outer scopes, and vice versa. In a given
250 // function declaration, all parameters subsequent to a
251 // parameter with a default argument shall have default
252 // arguments supplied in this or previous declarations. A
253 // default argument shall not be redefined by a later
254 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000255 //
256 // C++ [dcl.fct.default]p6:
257 // Except for member functions of class templates, the default arguments
258 // in a member function definition that appears outside of the class
259 // definition are added to the set of default arguments provided by the
260 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000261 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
262 ParmVarDecl *OldParam = Old->getParamDecl(p);
263 ParmVarDecl *NewParam = New->getParamDecl(p);
264
Douglas Gregor6cc15182009-09-11 18:44:32 +0000265 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000266 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000267 diag::err_param_default_argument_redefinition)
Douglas Gregor6cc15182009-09-11 18:44:32 +0000268 << NewParam->getDefaultArgRange();
269
270 // Look for the function declaration where the default argument was
271 // actually written, which may be a declaration prior to Old.
272 for (FunctionDecl *Older = Old->getPreviousDeclaration();
273 Older; Older = Older->getPreviousDeclaration()) {
274 if (!Older->getParamDecl(p)->hasDefaultArg())
275 break;
276
277 OldParam = Older->getParamDecl(p);
278 }
279
280 Diag(OldParam->getLocation(), diag::note_previous_definition)
281 << OldParam->getDefaultArgRange();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000282 Invalid = true;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000283 } else if (OldParam->getDefaultArg()) {
284 // Merge the old default argument into the new parameter
285 NewParam->setDefaultArg(OldParam->getDefaultArg());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000286 } else if (NewParam->hasDefaultArg()) {
287 if (New->getDescribedFunctionTemplate()) {
288 // Paragraph 4, quoted above, only applies to non-template functions.
289 Diag(NewParam->getLocation(),
290 diag::err_param_default_argument_template_redecl)
291 << NewParam->getDefaultArgRange();
292 Diag(Old->getLocation(), diag::note_template_prev_declaration)
293 << false;
294 } else if (New->getDeclContext()->isDependentContext()) {
295 // C++ [dcl.fct.default]p6 (DR217):
296 // Default arguments for a member function of a class template shall
297 // be specified on the initial declaration of the member function
298 // within the class template.
299 //
300 // Reading the tea leaves a bit in DR217 and its reference to DR205
301 // leads me to the conclusion that one cannot add default function
302 // arguments for an out-of-line definition of a member function of a
303 // dependent type.
304 int WhichKind = 2;
305 if (CXXRecordDecl *Record
306 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
307 if (Record->getDescribedClassTemplate())
308 WhichKind = 0;
309 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
310 WhichKind = 1;
311 else
312 WhichKind = 2;
313 }
314
315 Diag(NewParam->getLocation(),
316 diag::err_param_default_argument_member_template_redecl)
317 << WhichKind
318 << NewParam->getDefaultArgRange();
319 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000320 }
321 }
322
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000323 if (CheckEquivalentExceptionSpec(
324 Old->getType()->getAsFunctionProtoType(), Old->getLocation(),
325 New->getType()->getAsFunctionProtoType(), New->getLocation())) {
326 Invalid = true;
327 }
328
Douglas Gregorcda9c672009-02-16 17:45:42 +0000329 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000330}
331
332/// CheckCXXDefaultArguments - Verify that the default arguments for a
333/// function declaration are well-formed according to C++
334/// [dcl.fct.default].
335void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
336 unsigned NumParams = FD->getNumParams();
337 unsigned p;
338
339 // Find first parameter with a default argument
340 for (p = 0; p < NumParams; ++p) {
341 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000342 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000343 break;
344 }
345
346 // C++ [dcl.fct.default]p4:
347 // In a given function declaration, all parameters
348 // subsequent to a parameter with a default argument shall
349 // have default arguments supplied in this or previous
350 // declarations. A default argument shall not be redefined
351 // by a later declaration (not even to the same value).
352 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000353 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000354 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000355 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000356 if (Param->isInvalidDecl())
357 /* We already complained about this parameter. */;
358 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000359 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000360 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000361 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000362 else
Mike Stump1eb44332009-09-09 15:08:12 +0000363 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000364 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Chris Lattner3d1cee32008-04-08 05:04:30 +0000366 LastMissingDefaultArg = p;
367 }
368 }
369
370 if (LastMissingDefaultArg > 0) {
371 // Some default arguments were missing. Clear out all of the
372 // default arguments up to (and including) the last missing
373 // default argument, so that we leave the function parameters
374 // in a semantically valid state.
375 for (p = 0; p <= LastMissingDefaultArg; ++p) {
376 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000377 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000378 if (!Param->hasUnparsedDefaultArg())
379 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000380 Param->setDefaultArg(0);
381 }
382 }
383 }
384}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000385
Douglas Gregorb48fe382008-10-31 09:07:45 +0000386/// isCurrentClassName - Determine whether the identifier II is the
387/// name of the class type currently being defined. In the case of
388/// nested classes, this will only return true if II is the name of
389/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000390bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
391 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000392 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000393 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000394 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000395 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
396 } else
397 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
398
399 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000400 return &II == CurDecl->getIdentifier();
401 else
402 return false;
403}
404
Mike Stump1eb44332009-09-09 15:08:12 +0000405/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000406///
407/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
408/// and returns NULL otherwise.
409CXXBaseSpecifier *
410Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
411 SourceRange SpecifierRange,
412 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000413 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000414 SourceLocation BaseLoc) {
415 // C++ [class.union]p1:
416 // A union shall not have base classes.
417 if (Class->isUnion()) {
418 Diag(Class->getLocation(), diag::err_base_clause_on_union)
419 << SpecifierRange;
420 return 0;
421 }
422
423 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000424 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000425 Class->getTagKind() == RecordDecl::TK_class,
426 Access, BaseType);
427
428 // Base specifiers must be record types.
429 if (!BaseType->isRecordType()) {
430 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
431 return 0;
432 }
433
434 // C++ [class.union]p1:
435 // A union shall not be used as a base class.
436 if (BaseType->isUnionType()) {
437 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
438 return 0;
439 }
440
441 // C++ [class.derived]p2:
442 // The class-name in a base-specifier shall not be an incompletely
443 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000444 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000445 PDiag(diag::err_incomplete_base_class)
446 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000447 return 0;
448
Eli Friedman1d954f62009-08-15 21:55:26 +0000449 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000450 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000451 assert(BaseDecl && "Record type has no declaration");
452 BaseDecl = BaseDecl->getDefinition(Context);
453 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000454 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
455 assert(CXXBaseDecl && "Base type is not a C++ type");
456 if (!CXXBaseDecl->isEmpty())
457 Class->setEmpty(false);
458 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor2943aed2009-03-03 04:44:36 +0000459 Class->setPolymorphic(true);
460
461 // C++ [dcl.init.aggr]p1:
462 // An aggregate is [...] a class with [...] no base classes [...].
463 Class->setAggregate(false);
464 Class->setPOD(false);
465
Anders Carlsson347ba892009-04-16 00:08:20 +0000466 if (Virtual) {
467 // C++ [class.ctor]p5:
468 // A constructor is trivial if its class has no virtual base classes.
469 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000470
471 // C++ [class.copy]p6:
472 // A copy constructor is trivial if its class has no virtual base classes.
473 Class->setHasTrivialCopyConstructor(false);
474
475 // C++ [class.copy]p11:
476 // A copy assignment operator is trivial if its class has no virtual
477 // base classes.
478 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000479
480 // C++0x [meta.unary.prop] is_empty:
481 // T is a class type, but not a union type, with ... no virtual base
482 // classes
483 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000484 } else {
485 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000486 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000487 // class have trivial constructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000488 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
489 Class->setHasTrivialConstructor(false);
490
491 // C++ [class.copy]p6:
492 // A copy constructor is trivial if all the direct base classes of its
493 // class have trivial copy constructors.
494 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
495 Class->setHasTrivialCopyConstructor(false);
496
497 // C++ [class.copy]p11:
498 // A copy assignment operator is trivial if all the direct base classes
499 // of its class have trivial copy assignment operators.
500 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
501 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000502 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000503
504 // C++ [class.ctor]p3:
505 // A destructor is trivial if all the direct base classes of its class
506 // have trivial destructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000507 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
508 Class->setHasTrivialDestructor(false);
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Douglas Gregor2943aed2009-03-03 04:44:36 +0000510 // Create the base specifier.
511 // FIXME: Allocate via ASTContext?
Mike Stump1eb44332009-09-09 15:08:12 +0000512 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
513 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000514 Access, BaseType);
515}
516
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000517/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
518/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000519/// example:
520/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000521/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000522Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000523Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000524 bool Virtual, AccessSpecifier Access,
525 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000526 if (!classdecl)
527 return true;
528
Douglas Gregor40808ce2009-03-09 23:48:35 +0000529 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000530 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000531 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000532 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
533 Virtual, Access,
534 BaseType, BaseLoc))
535 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Douglas Gregor2943aed2009-03-03 04:44:36 +0000537 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000538}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000539
Douglas Gregor2943aed2009-03-03 04:44:36 +0000540/// \brief Performs the actual work of attaching the given base class
541/// specifiers to a C++ class.
542bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
543 unsigned NumBases) {
544 if (NumBases == 0)
545 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000546
547 // Used to keep track of which base types we have already seen, so
548 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000549 // that the key is always the unqualified canonical type of the base
550 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000551 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
552
553 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000554 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000555 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000556 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000557 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000558 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor57c856b2008-10-23 18:13:27 +0000559 NewBaseType = NewBaseType.getUnqualifiedType();
560
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000561 if (KnownBaseTypes[NewBaseType]) {
562 // C++ [class.mi]p3:
563 // A class shall not be specified as a direct base class of a
564 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000565 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000566 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000567 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000568 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000569
570 // Delete the duplicate base class specifier; we're going to
571 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000572 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000573
574 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000575 } else {
576 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000577 KnownBaseTypes[NewBaseType] = Bases[idx];
578 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000579 }
580 }
581
582 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000583 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000584
585 // Delete the remaining (good) base class specifiers, since their
586 // data has been copied into the CXXRecordDecl.
587 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000588 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000589
590 return Invalid;
591}
592
593/// ActOnBaseSpecifiers - Attach the given base specifiers to the
594/// class, after checking whether there are any duplicate base
595/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000596void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000597 unsigned NumBases) {
598 if (!ClassDecl || !Bases || !NumBases)
599 return;
600
601 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000602 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000603 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000604}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000605
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000606//===----------------------------------------------------------------------===//
607// C++ class member Handling
608//===----------------------------------------------------------------------===//
609
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000610/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
611/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
612/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000613/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000614Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000615Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000616 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redle2b68332009-04-12 17:16:29 +0000617 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000618 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000619 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000620 Expr *BitWidth = static_cast<Expr*>(BW);
621 Expr *Init = static_cast<Expr*>(InitExpr);
622 SourceLocation Loc = D.getIdentifierLoc();
623
Sebastian Redl669d5d72008-11-14 23:42:31 +0000624 bool isFunc = D.isFunctionDeclarator();
625
John McCall67d1a672009-08-06 02:15:43 +0000626 assert(!DS.isFriendSpecified());
627
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000628 // C++ 9.2p6: A member shall not be declared to have automatic storage
629 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000630 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
631 // data members and cannot be applied to names declared const or static,
632 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000633 switch (DS.getStorageClassSpec()) {
634 case DeclSpec::SCS_unspecified:
635 case DeclSpec::SCS_typedef:
636 case DeclSpec::SCS_static:
637 // FALL THROUGH.
638 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000639 case DeclSpec::SCS_mutable:
640 if (isFunc) {
641 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000642 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000643 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000644 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000645
Sebastian Redla11f42f2008-11-17 23:24:37 +0000646 // FIXME: It would be nicer if the keyword was ignored only for this
647 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000648 D.getMutableDeclSpec().ClearStorageClassSpecs();
649 } else {
650 QualType T = GetTypeForDeclarator(D, S);
651 diag::kind err = static_cast<diag::kind>(0);
652 if (T->isReferenceType())
653 err = diag::err_mutable_reference;
654 else if (T.isConstQualified())
655 err = diag::err_mutable_const;
656 if (err != 0) {
657 if (DS.getStorageClassSpecLoc().isValid())
658 Diag(DS.getStorageClassSpecLoc(), err);
659 else
660 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000661 // FIXME: It would be nicer if the keyword was ignored only for this
662 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000663 D.getMutableDeclSpec().ClearStorageClassSpecs();
664 }
665 }
666 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000667 default:
668 if (DS.getStorageClassSpecLoc().isValid())
669 Diag(DS.getStorageClassSpecLoc(),
670 diag::err_storageclass_invalid_for_member);
671 else
672 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
673 D.getMutableDeclSpec().ClearStorageClassSpecs();
674 }
675
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000676 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000677 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000678 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000679 // Check also for this case:
680 //
681 // typedef int f();
682 // f a;
683 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000684 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000685 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000686 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000687
Sebastian Redl669d5d72008-11-14 23:42:31 +0000688 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
689 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000690 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000691
692 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000693 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000694 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000695 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
696 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000697 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000698 } else {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000699 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
700 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000701 if (!Member) {
702 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000703 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000704 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000705
706 // Non-instance-fields can't have a bitfield.
707 if (BitWidth) {
708 if (Member->isInvalidDecl()) {
709 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000710 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000711 // C++ 9.6p3: A bit-field shall not be a static member.
712 // "static member 'A' cannot be a bit-field"
713 Diag(Loc, diag::err_static_not_bitfield)
714 << Name << BitWidth->getSourceRange();
715 } else if (isa<TypedefDecl>(Member)) {
716 // "typedef member 'x' cannot be a bit-field"
717 Diag(Loc, diag::err_typedef_not_bitfield)
718 << Name << BitWidth->getSourceRange();
719 } else {
720 // A function typedef ("typedef int f(); f a;").
721 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
722 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000723 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000724 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000725 }
Mike Stump1eb44332009-09-09 15:08:12 +0000726
Chris Lattner8b963ef2009-03-05 23:01:03 +0000727 DeleteExpr(BitWidth);
728 BitWidth = 0;
729 Member->setInvalidDecl();
730 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000731
732 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Douglas Gregor37b372b2009-08-20 22:52:58 +0000734 // If we have declared a member function template, set the access of the
735 // templated declaration as well.
736 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
737 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000738 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000739
Douglas Gregor10bd3682008-11-17 22:58:34 +0000740 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000741
Douglas Gregor021c3b32009-03-11 23:00:04 +0000742 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000743 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000744 if (Deleted) // FIXME: Source location is not very good.
745 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000746
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000747 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000748 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000749 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000750 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000751 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000752}
753
Douglas Gregor7ad83902008-11-05 04:29:56 +0000754/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000755Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000756Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000757 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000758 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000759 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000760 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000761 SourceLocation IdLoc,
762 SourceLocation LParenLoc,
763 ExprTy **Args, unsigned NumArgs,
764 SourceLocation *CommaLocs,
765 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000766 if (!ConstructorD)
767 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000769 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +0000770
771 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000772 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000773 if (!Constructor) {
774 // The user wrote a constructor initializer on a function that is
775 // not a C++ constructor. Ignore the error for now, because we may
776 // have more member initializers coming; we'll diagnose it just
777 // once in ActOnMemInitializers.
778 return true;
779 }
780
781 CXXRecordDecl *ClassDecl = Constructor->getParent();
782
783 // C++ [class.base.init]p2:
784 // Names in a mem-initializer-id are looked up in the scope of the
785 // constructor’s class and, if not found in that scope, are looked
786 // up in the scope containing the constructor’s
787 // definition. [Note: if the constructor’s class contains a member
788 // with the same name as a direct or virtual base class of the
789 // class, a mem-initializer-id naming the member or base class and
790 // composed of a single identifier refers to the class member. A
791 // mem-initializer-id for the hidden base class may be specified
792 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000793 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000794 // Look for a member, first.
795 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000796 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000797 = ClassDecl->lookup(MemberOrBase);
798 if (Result.first != Result.second)
799 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000800
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000801 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000802
Eli Friedman59c04372009-07-29 19:44:27 +0000803 if (Member)
804 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
805 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000806 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000807 // It didn't name a member, so see if it names a class.
Mike Stump1eb44332009-09-09 15:08:12 +0000808 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanian96174332009-07-01 19:21:19 +0000809 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000810 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000811 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
812 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000814 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000815
Eli Friedman59c04372009-07-29 19:44:27 +0000816 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
817 RParenLoc, ClassDecl);
818}
819
820Sema::MemInitResult
821Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
822 unsigned NumArgs, SourceLocation IdLoc,
823 SourceLocation RParenLoc) {
824 bool HasDependentArg = false;
825 for (unsigned i = 0; i < NumArgs; i++)
826 HasDependentArg |= Args[i]->isTypeDependent();
827
828 CXXConstructorDecl *C = 0;
829 QualType FieldType = Member->getType();
830 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
831 FieldType = Array->getElementType();
832 if (FieldType->isDependentType()) {
833 // Can't check init for dependent type.
Ted Kremenek6217b802009-07-29 21:53:49 +0000834 } else if (FieldType->getAs<RecordType>()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000835 if (!HasDependentArg) {
836 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
837
838 C = PerformInitializationByConstructor(FieldType,
839 MultiExprArg(*this,
840 (void**)Args,
841 NumArgs),
842 IdLoc,
843 SourceRange(IdLoc, RParenLoc),
844 Member->getDeclName(), IK_Direct,
845 ConstructorArgs);
846
847 if (C) {
848 // Take over the constructor arguments as our own.
849 NumArgs = ConstructorArgs.size();
850 Args = (Expr **)ConstructorArgs.take();
851 }
852 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +0000853 } else if (NumArgs != 1 && NumArgs != 0) {
Mike Stump1eb44332009-09-09 15:08:12 +0000854 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +0000855 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
856 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +0000857 Expr *NewExp;
858 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000859 if (FieldType->isReferenceType()) {
860 Diag(IdLoc, diag::err_null_intialized_reference_member)
861 << Member->getDeclName();
862 return Diag(Member->getLocation(), diag::note_declared_at);
863 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +0000864 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
865 NumArgs = 1;
866 }
867 else
868 NewExp = (Expr*)Args[0];
Eli Friedman59c04372009-07-29 19:44:27 +0000869 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
870 return true;
871 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +0000872 }
Eli Friedman59c04372009-07-29 19:44:27 +0000873 // FIXME: Perform direct initialization of the member.
Mike Stump1eb44332009-09-09 15:08:12 +0000874 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +0000875 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +0000876}
877
878Sema::MemInitResult
879Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
880 unsigned NumArgs, SourceLocation IdLoc,
881 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
882 bool HasDependentArg = false;
883 for (unsigned i = 0; i < NumArgs; i++)
884 HasDependentArg |= Args[i]->isTypeDependent();
885
886 if (!BaseType->isDependentType()) {
887 if (!BaseType->isRecordType())
888 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
889 << BaseType << SourceRange(IdLoc, RParenLoc);
890
891 // C++ [class.base.init]p2:
892 // [...] Unless the mem-initializer-id names a nonstatic data
893 // member of the constructor’s class or a direct or virtual base
894 // of that class, the mem-initializer is ill-formed. A
895 // mem-initializer-list can initialize a base class using any
896 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Eli Friedman59c04372009-07-29 19:44:27 +0000898 // First, check for a direct base class.
899 const CXXBaseSpecifier *DirectBaseSpec = 0;
900 for (CXXRecordDecl::base_class_const_iterator Base =
901 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +0000902 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
Eli Friedman59c04372009-07-29 19:44:27 +0000903 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
904 // We found a direct base of this type. That's what we're
905 // initializing.
906 DirectBaseSpec = &*Base;
907 break;
908 }
909 }
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Eli Friedman59c04372009-07-29 19:44:27 +0000911 // Check for a virtual base class.
912 // FIXME: We might be able to short-circuit this if we know in advance that
913 // there are no virtual bases.
914 const CXXBaseSpecifier *VirtualBaseSpec = 0;
915 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
916 // We haven't found a base yet; search the class hierarchy for a
917 // virtual base class.
918 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
919 /*DetectVirtual=*/false);
920 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000921 for (BasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +0000922 Path != Paths.end(); ++Path) {
923 if (Path->back().Base->isVirtual()) {
924 VirtualBaseSpec = Path->back().Base;
925 break;
926 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000927 }
928 }
929 }
Eli Friedman59c04372009-07-29 19:44:27 +0000930
931 // C++ [base.class.init]p2:
932 // If a mem-initializer-id is ambiguous because it designates both
933 // a direct non-virtual base class and an inherited virtual base
934 // class, the mem-initializer is ill-formed.
935 if (DirectBaseSpec && VirtualBaseSpec)
936 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
937 << BaseType << SourceRange(IdLoc, RParenLoc);
938 // C++ [base.class.init]p2:
939 // Unless the mem-initializer-id names a nonstatic data membeer of the
940 // constructor's class ot a direst or virtual base of that class, the
941 // mem-initializer is ill-formed.
942 if (!DirectBaseSpec && !VirtualBaseSpec)
943 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
944 << BaseType << ClassDecl->getNameAsCString()
945 << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000946 }
947
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +0000948 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +0000949 if (!BaseType->isDependentType() && !HasDependentArg) {
950 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
951 Context.getCanonicalType(BaseType));
Douglas Gregor39da0b82009-09-09 23:08:42 +0000952 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
953
954 C = PerformInitializationByConstructor(BaseType,
955 MultiExprArg(*this,
956 (void**)Args, NumArgs),
Mike Stump1eb44332009-09-09 15:08:12 +0000957 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000958 Name, IK_Direct,
959 ConstructorArgs);
960 if (C) {
961 // Take over the constructor arguments as our own.
962 NumArgs = ConstructorArgs.size();
963 Args = (Expr **)ConstructorArgs.take();
964 }
Eli Friedman59c04372009-07-29 19:44:27 +0000965 }
966
Mike Stump1eb44332009-09-09 15:08:12 +0000967 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +0000968 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000969}
970
Fariborz Jahanian87595e42009-07-23 23:32:59 +0000971void
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000972Sema::setBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
973 CXXBaseOrMemberInitializer **Initializers,
974 unsigned NumInitializers,
Mike Stump1eb44332009-09-09 15:08:12 +0000975 llvm::SmallVectorImpl<CXXBaseSpecifier *>& Bases,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000976 llvm::SmallVectorImpl<FieldDecl *>&Fields) {
977 // We need to build the initializer AST according to order of construction
978 // and not what user specified in the Initializers list.
979 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
980 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
981 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
982 bool HasDependentBaseInit = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000984 for (unsigned i = 0; i < NumInitializers; i++) {
985 CXXBaseOrMemberInitializer *Member = Initializers[i];
986 if (Member->isBaseInitializer()) {
987 if (Member->getBaseClass()->isDependentType())
988 HasDependentBaseInit = true;
989 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
990 } else {
991 AllBaseFields[Member->getMember()] = Member;
992 }
993 }
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000995 if (HasDependentBaseInit) {
996 // FIXME. This does not preserve the ordering of the initializers.
997 // Try (with -Wreorder)
998 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +0000999 // template<class X> struct B : A<X> {
1000 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001001 // int x1;
1002 // };
1003 // B<int> x;
1004 // On seeing one dependent type, we should essentially exit this routine
1005 // while preserving user-declared initializer list. When this routine is
1006 // called during instantiatiation process, this routine will rebuild the
1007 // oderdered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001009 // If we have a dependent base initialization, we can't determine the
1010 // association between initializers and bases; just dump the known
1011 // initializers into the list, and don't try to deal with other bases.
1012 for (unsigned i = 0; i < NumInitializers; i++) {
1013 CXXBaseOrMemberInitializer *Member = Initializers[i];
1014 if (Member->isBaseInitializer())
1015 AllToInit.push_back(Member);
1016 }
1017 } else {
1018 // Push virtual bases before others.
1019 for (CXXRecordDecl::base_class_iterator VBase =
1020 ClassDecl->vbases_begin(),
1021 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1022 if (VBase->getType()->isDependentType())
1023 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001024 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001025 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001026 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001027 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1028 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
1029 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1030 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001031 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001032 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001033 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001034 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001035 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1036 assert(VBaseDecl && "setBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001037 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
1038 if (!Ctor)
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001039 Bases.push_back(VBase);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001040 else
1041 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1042
Mike Stump1eb44332009-09-09 15:08:12 +00001043 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001044 new (Context) CXXBaseOrMemberInitializer(VBase->getType(), 0, 0,
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001045 Ctor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001046 SourceLocation(),
1047 SourceLocation());
1048 AllToInit.push_back(Member);
1049 }
1050 }
Mike Stump1eb44332009-09-09 15:08:12 +00001051
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001052 for (CXXRecordDecl::base_class_iterator Base =
1053 ClassDecl->bases_begin(),
1054 E = ClassDecl->bases_end(); Base != E; ++Base) {
1055 // Virtuals are in the virtual base list and already constructed.
1056 if (Base->isVirtual())
1057 continue;
1058 // Skip dependent types.
1059 if (Base->getType()->isDependentType())
1060 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001061 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001062 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001063 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001064 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1065 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
1066 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1067 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001068 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001069 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001070 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001071 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001072 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001073 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001074 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
1075 if (!Ctor)
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001076 Bases.push_back(Base);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001077 else
1078 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1079
Mike Stump1eb44332009-09-09 15:08:12 +00001080 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001081 new (Context) CXXBaseOrMemberInitializer(Base->getType(), 0, 0,
1082 BaseDecl->getDefaultConstructor(Context),
1083 SourceLocation(),
1084 SourceLocation());
1085 AllToInit.push_back(Member);
1086 }
1087 }
1088 }
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001090 // non-static data members.
1091 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1092 E = ClassDecl->field_end(); Field != E; ++Field) {
1093 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001094 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001095 Field->getType()->getAs<RecordType>()) {
1096 CXXRecordDecl *FieldClassDecl
1097 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001098 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001099 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1100 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1101 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1102 // set to the anonymous union data member used in the initializer
1103 // list.
1104 Value->setMember(*Field);
1105 Value->setAnonUnionMember(*FA);
1106 AllToInit.push_back(Value);
1107 break;
1108 }
1109 }
1110 }
1111 continue;
1112 }
1113 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001114 QualType FT = (*Field)->getType();
1115 if (const RecordType* RT = FT->getAs<RecordType>()) {
1116 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl());
1117 assert(FieldRecDecl && "setBaseOrMemberInitializers - BaseDecl null");
Mike Stump1eb44332009-09-09 15:08:12 +00001118 if (CXXConstructorDecl *Ctor =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001119 FieldRecDecl->getDefaultConstructor(Context))
1120 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
1121 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001122 AllToInit.push_back(Value);
1123 continue;
1124 }
Mike Stump1eb44332009-09-09 15:08:12 +00001125
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001126 QualType FT = Context.getBaseElementType((*Field)->getType());
1127 if (const RecordType* RT = FT->getAs<RecordType>()) {
1128 CXXConstructorDecl *Ctor =
1129 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
1130 if (!Ctor && !FT->isDependentType())
1131 Fields.push_back(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001132 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001133 new (Context) CXXBaseOrMemberInitializer((*Field), 0, 0,
1134 Ctor,
1135 SourceLocation(),
1136 SourceLocation());
1137 AllToInit.push_back(Member);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001138 if (Ctor)
1139 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001140 if (FT.isConstQualified() && (!Ctor || Ctor->isTrivial())) {
1141 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1142 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1143 Diag((*Field)->getLocation(), diag::note_declared_at);
1144 }
1145 }
1146 else if (FT->isReferenceType()) {
1147 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1148 << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getDeclName();
1149 Diag((*Field)->getLocation(), diag::note_declared_at);
1150 }
1151 else if (FT.isConstQualified()) {
1152 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1153 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1154 Diag((*Field)->getLocation(), diag::note_declared_at);
1155 }
1156 }
Mike Stump1eb44332009-09-09 15:08:12 +00001157
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001158 NumInitializers = AllToInit.size();
1159 if (NumInitializers > 0) {
1160 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1161 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1162 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001163
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001164 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1165 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1166 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1167 }
1168}
1169
1170void
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001171Sema::BuildBaseOrMemberInitializers(ASTContext &C,
1172 CXXConstructorDecl *Constructor,
1173 CXXBaseOrMemberInitializer **Initializers,
1174 unsigned NumInitializers
1175 ) {
1176 llvm::SmallVector<CXXBaseSpecifier *, 4>Bases;
1177 llvm::SmallVector<FieldDecl *, 4>Members;
Mike Stump1eb44332009-09-09 15:08:12 +00001178
1179 setBaseOrMemberInitializers(Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001180 Initializers, NumInitializers, Bases, Members);
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001181 for (unsigned int i = 0; i < Bases.size(); i++)
Mike Stump1eb44332009-09-09 15:08:12 +00001182 Diag(Bases[i]->getSourceRange().getBegin(),
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001183 diag::err_missing_default_constructor) << 0 << Bases[i]->getType();
1184 for (unsigned int i = 0; i < Members.size(); i++)
Mike Stump1eb44332009-09-09 15:08:12 +00001185 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor)
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001186 << 1 << Members[i]->getType();
1187}
1188
Eli Friedman6347f422009-07-21 19:28:10 +00001189static void *GetKeyForTopLevelField(FieldDecl *Field) {
1190 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001191 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001192 if (RT->getDecl()->isAnonymousStructOrUnion())
1193 return static_cast<void *>(RT->getDecl());
1194 }
1195 return static_cast<void *>(Field);
1196}
1197
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001198static void *GetKeyForBase(QualType BaseType) {
1199 if (const RecordType *RT = BaseType->getAs<RecordType>())
1200 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001202 assert(0 && "Unexpected base type!");
1203 return 0;
1204}
1205
Mike Stump1eb44332009-09-09 15:08:12 +00001206static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001207 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001208 // For fields injected into the class via declaration of an anonymous union,
1209 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001210 if (Member->isMemberInitializer()) {
1211 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001213 // After BuildBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001214 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001215 // in AnonUnionMember field.
1216 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1217 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001218 if (Field->getDeclContext()->isRecord()) {
1219 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1220 if (RD->isAnonymousStructOrUnion())
1221 return static_cast<void *>(RD);
1222 }
1223 return static_cast<void *>(Field);
1224 }
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001226 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001227}
1228
Mike Stump1eb44332009-09-09 15:08:12 +00001229void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001230 SourceLocation ColonLoc,
1231 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001232 if (!ConstructorDecl)
1233 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001234
1235 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001236
1237 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001238 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Anders Carlssona7b35212009-03-25 02:58:17 +00001240 if (!Constructor) {
1241 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1242 return;
1243 }
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001245 if (!Constructor->isDependentContext()) {
1246 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1247 bool err = false;
1248 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001249 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001250 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1251 void *KeyToMember = GetKeyForMember(Member);
1252 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1253 if (!PrevMember) {
1254 PrevMember = Member;
1255 continue;
1256 }
1257 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001258 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001259 diag::error_multiple_mem_initialization)
1260 << Field->getNameAsString();
1261 else {
1262 Type *BaseClass = Member->getBaseClass();
1263 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001264 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001265 diag::error_multiple_base_initialization)
1266 << BaseClass->getDesugaredType(true);
1267 }
1268 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1269 << 0;
1270 err = true;
1271 }
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001273 if (err)
1274 return;
1275 }
Mike Stump1eb44332009-09-09 15:08:12 +00001276
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001277 BuildBaseOrMemberInitializers(Context, Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001278 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001279 NumMemInits);
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001281 if (Constructor->isDependentContext())
1282 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001283
1284 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001285 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001286 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001287 Diagnostic::Ignored)
1288 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001290 // Also issue warning if order of ctor-initializer list does not match order
1291 // of 1) base class declarations and 2) order of non-static data members.
1292 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001294 CXXRecordDecl *ClassDecl
1295 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1296 // Push virtual bases before others.
1297 for (CXXRecordDecl::base_class_iterator VBase =
1298 ClassDecl->vbases_begin(),
1299 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001300 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001302 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1303 E = ClassDecl->bases_end(); Base != E; ++Base) {
1304 // Virtuals are alread in the virtual base list and are constructed
1305 // first.
1306 if (Base->isVirtual())
1307 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001308 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001309 }
Mike Stump1eb44332009-09-09 15:08:12 +00001310
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001311 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1312 E = ClassDecl->field_end(); Field != E; ++Field)
1313 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001315 int Last = AllBaseOrMembers.size();
1316 int curIndex = 0;
1317 CXXBaseOrMemberInitializer *PrevMember = 0;
1318 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001319 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001320 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1321 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001322
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001323 for (; curIndex < Last; curIndex++)
1324 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1325 break;
1326 if (curIndex == Last) {
1327 assert(PrevMember && "Member not in member list?!");
1328 // Initializer as specified in ctor-initializer list is out of order.
1329 // Issue a warning diagnostic.
1330 if (PrevMember->isBaseInitializer()) {
1331 // Diagnostics is for an initialized base class.
1332 Type *BaseClass = PrevMember->getBaseClass();
1333 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001334 diag::warn_base_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001335 << BaseClass->getDesugaredType(true);
1336 } else {
1337 FieldDecl *Field = PrevMember->getMember();
1338 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001339 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001340 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001341 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001342 // Also the note!
1343 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001344 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001345 diag::note_fieldorbase_initialized_here) << 0
1346 << Field->getNameAsString();
1347 else {
1348 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001349 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001350 diag::note_fieldorbase_initialized_here) << 1
1351 << BaseClass->getDesugaredType(true);
1352 }
1353 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001354 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001355 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001356 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001357 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001358 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001359}
1360
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001361void
1362Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) {
1363 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext());
1364 llvm::SmallVector<uintptr_t, 32> AllToDestruct;
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001366 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1367 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1368 if (VBase->getType()->isDependentType())
1369 continue;
1370 // Skip over virtual bases which have trivial destructors.
1371 CXXRecordDecl *BaseClassDecl
1372 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1373 if (BaseClassDecl->hasTrivialDestructor())
1374 continue;
1375 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001376 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001377 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001378
1379 uintptr_t Member =
1380 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001381 | CXXDestructorDecl::VBASE;
1382 AllToDestruct.push_back(Member);
1383 }
1384 for (CXXRecordDecl::base_class_iterator Base =
1385 ClassDecl->bases_begin(),
1386 E = ClassDecl->bases_end(); Base != E; ++Base) {
1387 if (Base->isVirtual())
1388 continue;
1389 if (Base->getType()->isDependentType())
1390 continue;
1391 // Skip over virtual bases which have trivial destructors.
1392 CXXRecordDecl *BaseClassDecl
1393 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1394 if (BaseClassDecl->hasTrivialDestructor())
1395 continue;
1396 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001397 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001398 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001399 uintptr_t Member =
1400 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001401 | CXXDestructorDecl::DRCTNONVBASE;
1402 AllToDestruct.push_back(Member);
1403 }
Mike Stump1eb44332009-09-09 15:08:12 +00001404
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001405 // non-static data members.
1406 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1407 E = ClassDecl->field_end(); Field != E; ++Field) {
1408 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001409
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001410 if (const RecordType* RT = FieldType->getAs<RecordType>()) {
1411 // Skip over virtual bases which have trivial destructors.
1412 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1413 if (FieldClassDecl->hasTrivialDestructor())
1414 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001415 if (const CXXDestructorDecl *Dtor =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001416 FieldClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001417 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001418 const_cast<CXXDestructorDecl*>(Dtor));
1419 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field);
1420 AllToDestruct.push_back(Member);
1421 }
1422 }
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001424 unsigned NumDestructions = AllToDestruct.size();
1425 if (NumDestructions > 0) {
1426 Destructor->setNumBaseOrMemberDestructions(NumDestructions);
Mike Stump1eb44332009-09-09 15:08:12 +00001427 uintptr_t *BaseOrMemberDestructions =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001428 new (Context) uintptr_t [NumDestructions];
1429 // Insert in reverse order.
1430 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx)
1431 BaseOrMemberDestructions[i++] = AllToDestruct[Idx];
1432 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions);
1433 }
1434}
1435
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001436void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001437 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001438 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001440 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001441
1442 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001443 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001444 BuildBaseOrMemberInitializers(Context,
1445 Constructor,
1446 (CXXBaseOrMemberInitializer **)0, 0);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001447}
1448
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001449namespace {
1450 /// PureVirtualMethodCollector - traverses a class and its superclasses
1451 /// and determines if it has any pure virtual methods.
1452 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1453 ASTContext &Context;
1454
Sebastian Redldfe292d2009-03-22 21:28:55 +00001455 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001456 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001457
1458 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001459 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001461 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001463 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001464 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001465 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001467 MethodList List;
1468 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001470 // Copy the temporary list to methods, and make sure to ignore any
1471 // null entries.
1472 for (size_t i = 0, e = List.size(); i != e; ++i) {
1473 if (List[i])
1474 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001475 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001476 }
Mike Stump1eb44332009-09-09 15:08:12 +00001477
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001478 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001479
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001480 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1481 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001482 };
Mike Stump1eb44332009-09-09 15:08:12 +00001483
1484 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001485 MethodList& Methods) {
1486 // First, collect the pure virtual methods for the base classes.
1487 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1488 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001489 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001490 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001491 if (BaseDecl && BaseDecl->isAbstract())
1492 Collect(BaseDecl, Methods);
1493 }
1494 }
Mike Stump1eb44332009-09-09 15:08:12 +00001495
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001496 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001497 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001499 MethodSetTy OverriddenMethods;
1500 size_t MethodsSize = Methods.size();
1501
Mike Stump1eb44332009-09-09 15:08:12 +00001502 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001503 i != e; ++i) {
1504 // Traverse the record, looking for methods.
1505 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001506 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001507 if (MD->isPure()) {
1508 Methods.push_back(MD);
1509 continue;
1510 }
Mike Stump1eb44332009-09-09 15:08:12 +00001511
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001512 // Otherwise, record all the overridden methods in our set.
1513 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1514 E = MD->end_overridden_methods(); I != E; ++I) {
1515 // Keep track of the overridden methods.
1516 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001517 }
1518 }
1519 }
Mike Stump1eb44332009-09-09 15:08:12 +00001520
1521 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001522 // overridden.
1523 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1524 if (OverriddenMethods.count(Methods[i]))
1525 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001526 }
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001528 }
1529}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001530
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001531
Mike Stump1eb44332009-09-09 15:08:12 +00001532bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001533 unsigned DiagID, AbstractDiagSelID SelID,
1534 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001535 if (SelID == -1)
1536 return RequireNonAbstractType(Loc, T,
1537 PDiag(DiagID), CurrentRD);
1538 else
1539 return RequireNonAbstractType(Loc, T,
1540 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001541}
1542
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001543bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1544 const PartialDiagnostic &PD,
1545 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001546 if (!getLangOptions().CPlusPlus)
1547 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001548
Anders Carlsson11f21a02009-03-23 19:10:31 +00001549 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001550 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001551 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Ted Kremenek6217b802009-07-29 21:53:49 +00001553 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001554 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001555 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001556 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001558 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001559 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001560 }
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Ted Kremenek6217b802009-07-29 21:53:49 +00001562 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001563 if (!RT)
1564 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001565
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001566 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1567 if (!RD)
1568 return false;
1569
Anders Carlssone65a3c82009-03-24 17:23:42 +00001570 if (CurrentRD && CurrentRD != RD)
1571 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001573 if (!RD->isAbstract())
1574 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001576 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001578 // Check if we've already emitted the list of pure virtual functions for this
1579 // class.
1580 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1581 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001583 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001584
1585 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001586 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1587 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001588
1589 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001590 MD->getDeclName();
1591 }
1592
1593 if (!PureVirtualClassDiagSet)
1594 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1595 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001597 return true;
1598}
1599
Anders Carlsson8211eff2009-03-24 01:19:16 +00001600namespace {
Mike Stump1eb44332009-09-09 15:08:12 +00001601 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001602 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1603 Sema &SemaRef;
1604 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Anders Carlssone65a3c82009-03-24 17:23:42 +00001606 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001607 bool Invalid = false;
1608
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001609 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1610 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001611 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001612
Anders Carlsson8211eff2009-03-24 01:19:16 +00001613 return Invalid;
1614 }
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Anders Carlssone65a3c82009-03-24 17:23:42 +00001616 public:
1617 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1618 : SemaRef(SemaRef), AbstractClass(ac) {
1619 Visit(SemaRef.Context.getTranslationUnitDecl());
1620 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001621
Anders Carlssone65a3c82009-03-24 17:23:42 +00001622 bool VisitFunctionDecl(const FunctionDecl *FD) {
1623 if (FD->isThisDeclarationADefinition()) {
1624 // No need to do the check if we're in a definition, because it requires
1625 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00001626 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001627 return VisitDeclContext(FD);
1628 }
Mike Stump1eb44332009-09-09 15:08:12 +00001629
Anders Carlssone65a3c82009-03-24 17:23:42 +00001630 // Check the return type.
1631 QualType RTy = FD->getType()->getAsFunctionType()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001632 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00001633 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1634 diag::err_abstract_type_in_decl,
1635 Sema::AbstractReturnType,
1636 AbstractClass);
1637
Mike Stump1eb44332009-09-09 15:08:12 +00001638 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001639 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001640 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001641 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001642 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001643 VD->getOriginalType(),
1644 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001645 Sema::AbstractParamType,
1646 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001647 }
1648
1649 return Invalid;
1650 }
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Anders Carlssone65a3c82009-03-24 17:23:42 +00001652 bool VisitDecl(const Decl* D) {
1653 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1654 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Anders Carlssone65a3c82009-03-24 17:23:42 +00001656 return false;
1657 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001658 };
1659}
1660
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001661void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001662 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001663 SourceLocation LBrac,
1664 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001665 if (!TagDecl)
1666 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Douglas Gregor42af25f2009-05-11 19:58:34 +00001668 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001669 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001670 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00001671 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001672
Chris Lattnerb28317a2009-03-28 19:18:32 +00001673 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001674 if (!RD->isAbstract()) {
1675 // Collect all the pure virtual methods and see if this is an abstract
1676 // class after all.
1677 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001678 if (!Collector.empty())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001679 RD->setAbstract(true);
1680 }
Mike Stump1eb44332009-09-09 15:08:12 +00001681
1682 if (RD->isAbstract())
Anders Carlssone65a3c82009-03-24 17:23:42 +00001683 AbstractClassUsageDiagnoser(*this, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Douglas Gregor42af25f2009-05-11 19:58:34 +00001685 if (!RD->isDependentType())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001686 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001687}
1688
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001689/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1690/// special functions, such as the default constructor, copy
1691/// constructor, or destructor, to the given C++ class (C++
1692/// [special]p1). This routine can only be executed just before the
1693/// definition of the class is complete.
1694void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00001695 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00001696 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001697
Sebastian Redl465226e2009-05-27 22:11:52 +00001698 // FIXME: Implicit declarations have exception specifications, which are
1699 // the union of the specifications of the implicitly called functions.
1700
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001701 if (!ClassDecl->hasUserDeclaredConstructor()) {
1702 // C++ [class.ctor]p5:
1703 // A default constructor for a class X is a constructor of class X
1704 // that can be called without an argument. If there is no
1705 // user-declared constructor for class X, a default constructor is
1706 // implicitly declared. An implicitly-declared default constructor
1707 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001708 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001709 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00001710 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001711 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001712 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001713 Context.getFunctionType(Context.VoidTy,
1714 0, 0, false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001715 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001716 /*isExplicit=*/false,
1717 /*isInline=*/true,
1718 /*isImplicitlyDeclared=*/true);
1719 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001720 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001721 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001722 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001723 }
1724
1725 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1726 // C++ [class.copy]p4:
1727 // If the class definition does not explicitly declare a copy
1728 // constructor, one is declared implicitly.
1729
1730 // C++ [class.copy]p5:
1731 // The implicitly-declared copy constructor for a class X will
1732 // have the form
1733 //
1734 // X::X(const X&)
1735 //
1736 // if
1737 bool HasConstCopyConstructor = true;
1738
1739 // -- each direct or virtual base class B of X has a copy
1740 // constructor whose first parameter is of type const B& or
1741 // const volatile B&, and
1742 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1743 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1744 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00001745 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001746 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001747 = BaseClassDecl->hasConstCopyConstructor(Context);
1748 }
1749
1750 // -- for all the nonstatic data members of X that are of a
1751 // class type M (or array thereof), each such class type
1752 // has a copy constructor whose first parameter is of type
1753 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001754 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1755 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001756 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001757 QualType FieldType = (*Field)->getType();
1758 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1759 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001760 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001761 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001762 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001763 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001764 = FieldClassDecl->hasConstCopyConstructor(Context);
1765 }
1766 }
1767
Sebastian Redl64b45f72009-01-05 20:52:13 +00001768 // Otherwise, the implicitly declared copy constructor will have
1769 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001770 //
1771 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00001772 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001773 if (HasConstCopyConstructor)
1774 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001775 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001776
Sebastian Redl64b45f72009-01-05 20:52:13 +00001777 // An implicitly-declared copy constructor is an inline public
1778 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001779 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001780 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001781 CXXConstructorDecl *CopyConstructor
1782 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001783 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001784 Context.getFunctionType(Context.VoidTy,
1785 &ArgType, 1,
1786 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001787 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001788 /*isExplicit=*/false,
1789 /*isInline=*/true,
1790 /*isImplicitlyDeclared=*/true);
1791 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001792 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001793 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001794
1795 // Add the parameter to the constructor.
1796 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1797 ClassDecl->getLocation(),
1798 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001799 ArgType, /*DInfo=*/0,
1800 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00001801 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001802 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001803 }
1804
Sebastian Redl64b45f72009-01-05 20:52:13 +00001805 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1806 // Note: The following rules are largely analoguous to the copy
1807 // constructor rules. Note that virtual bases are not taken into account
1808 // for determining the argument type of the operator. Note also that
1809 // operators taking an object instead of a reference are allowed.
1810 //
1811 // C++ [class.copy]p10:
1812 // If the class definition does not explicitly declare a copy
1813 // assignment operator, one is declared implicitly.
1814 // The implicitly-defined copy assignment operator for a class X
1815 // will have the form
1816 //
1817 // X& X::operator=(const X&)
1818 //
1819 // if
1820 bool HasConstCopyAssignment = true;
1821
1822 // -- each direct base class B of X has a copy assignment operator
1823 // whose parameter is of type const B&, const volatile B& or B,
1824 // and
1825 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1826 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1827 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00001828 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001829 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001830 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001831 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001832 }
1833
1834 // -- for all the nonstatic data members of X that are of a class
1835 // type M (or array thereof), each such class type has a copy
1836 // assignment operator whose parameter is of type const M&,
1837 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001838 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1839 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001840 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00001841 QualType FieldType = (*Field)->getType();
1842 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1843 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001844 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00001845 const CXXRecordDecl *FieldClassDecl
1846 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001847 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00001848 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001849 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001850 }
1851 }
1852
1853 // Otherwise, the implicitly declared copy assignment operator will
1854 // have the form
1855 //
1856 // X& X::operator=(X&)
1857 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001858 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001859 if (HasConstCopyAssignment)
1860 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001861 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001862
1863 // An implicitly-declared copy assignment operator is an inline public
1864 // member of its class.
1865 DeclarationName Name =
1866 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1867 CXXMethodDecl *CopyAssignment =
1868 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1869 Context.getFunctionType(RetType, &ArgType, 1,
1870 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001871 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001872 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001873 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001874 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001875 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001876
1877 // Add the parameter to the operator.
1878 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1879 ClassDecl->getLocation(),
1880 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001881 ArgType, /*DInfo=*/0,
1882 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00001883 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001884
1885 // Don't call addedAssignmentOperator. There is no way to distinguish an
1886 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001887 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001888 }
1889
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001890 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001891 // C++ [class.dtor]p2:
1892 // If a class has no user-declared destructor, a destructor is
1893 // declared implicitly. An implicitly-declared destructor is an
1894 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001895 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001896 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00001897 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00001898 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001899 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00001900 Context.getFunctionType(Context.VoidTy,
1901 0, 0, false, 0),
1902 /*isInline=*/true,
1903 /*isImplicitlyDeclared=*/true);
1904 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001905 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001906 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001907 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001908 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001909}
1910
Douglas Gregor6569d682009-05-27 23:11:45 +00001911void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00001912 Decl *D = TemplateD.getAs<Decl>();
1913 if (!D)
1914 return;
1915
1916 TemplateParameterList *Params = 0;
1917 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
1918 Params = Template->getTemplateParameters();
1919 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1920 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
1921 Params = PartialSpec->getTemplateParameters();
1922 else
Douglas Gregor6569d682009-05-27 23:11:45 +00001923 return;
1924
Douglas Gregor6569d682009-05-27 23:11:45 +00001925 for (TemplateParameterList::iterator Param = Params->begin(),
1926 ParamEnd = Params->end();
1927 Param != ParamEnd; ++Param) {
1928 NamedDecl *Named = cast<NamedDecl>(*Param);
1929 if (Named->getDeclName()) {
1930 S->AddDecl(DeclPtrTy::make(Named));
1931 IdResolver.AddDecl(Named);
1932 }
1933 }
1934}
1935
Douglas Gregor72b505b2008-12-16 21:30:33 +00001936/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1937/// parsing a top-level (non-nested) C++ class, and we are now
1938/// parsing those parts of the given Method declaration that could
1939/// not be parsed earlier (C++ [class.mem]p2), such as default
1940/// arguments. This action should enter the scope of the given
1941/// Method declaration as if we had just parsed the qualified method
1942/// name. However, it should not bring the parameters into scope;
1943/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001944void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001945 if (!MethodD)
1946 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001948 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Douglas Gregor72b505b2008-12-16 21:30:33 +00001950 CXXScopeSpec SS;
Chris Lattnerb28317a2009-03-28 19:18:32 +00001951 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001952 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00001953 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1954 SS.setScopeRep(
1955 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001956 ActOnCXXEnterDeclaratorScope(S, SS);
1957}
1958
1959/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1960/// C++ method declaration. We're (re-)introducing the given
1961/// function parameter into scope for use in parsing later parts of
1962/// the method declaration. For example, we could see an
1963/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001964void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001965 if (!ParamD)
1966 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Chris Lattnerb28317a2009-03-28 19:18:32 +00001968 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00001969
1970 // If this parameter has an unparsed default argument, clear it out
1971 // to make way for the parsed default argument.
1972 if (Param->hasUnparsedDefaultArg())
1973 Param->setDefaultArg(0);
1974
Chris Lattnerb28317a2009-03-28 19:18:32 +00001975 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001976 if (Param->getDeclName())
1977 IdResolver.AddDecl(Param);
1978}
1979
1980/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1981/// processing the delayed method declaration for Method. The method
1982/// declaration is now considered finished. There may be a separate
1983/// ActOnStartOfFunctionDef action later (not necessarily
1984/// immediately!) for this method, if it was also defined inside the
1985/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001986void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001987 if (!MethodD)
1988 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001990 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Chris Lattnerb28317a2009-03-28 19:18:32 +00001992 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00001993 CXXScopeSpec SS;
Mike Stump1eb44332009-09-09 15:08:12 +00001994 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00001995 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1996 SS.setScopeRep(
1997 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001998 ActOnCXXExitDeclaratorScope(S, SS);
1999
2000 // Now that we have our default arguments, check the constructor
2001 // again. It could produce additional diagnostics or affect whether
2002 // the class has implicitly-declared destructors, among other
2003 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00002004 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2005 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002006
2007 // Check the default arguments, which we may have added.
2008 if (!Method->isInvalidDecl())
2009 CheckCXXDefaultArguments(Method);
2010}
2011
Douglas Gregor42a552f2008-11-05 20:51:48 +00002012/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00002013/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00002014/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002015/// emit diagnostics and set the invalid bit to true. In any case, the type
2016/// will be updated to reflect a well-formed type for the constructor and
2017/// returned.
2018QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2019 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002020 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002021
2022 // C++ [class.ctor]p3:
2023 // A constructor shall not be virtual (10.3) or static (9.4). A
2024 // constructor can be invoked for a const, volatile or const
2025 // volatile object. A constructor shall not be declared const,
2026 // volatile, or const volatile (9.3.2).
2027 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00002028 if (!D.isInvalidType())
2029 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2030 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2031 << SourceRange(D.getIdentifierLoc());
2032 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002033 }
2034 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002035 if (!D.isInvalidType())
2036 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2037 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2038 << SourceRange(D.getIdentifierLoc());
2039 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002040 SC = FunctionDecl::None;
2041 }
Mike Stump1eb44332009-09-09 15:08:12 +00002042
Chris Lattner65401802009-04-25 08:28:21 +00002043 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2044 if (FTI.TypeQuals != 0) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002045 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002046 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2047 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002048 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002049 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2050 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002051 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002052 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2053 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002054 }
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Douglas Gregor42a552f2008-11-05 20:51:48 +00002056 // Rebuild the function type "R" without any type qualifiers (in
2057 // case any of the errors above fired) and with "void" as the
2058 // return type, since constructors don't have return types. We
2059 // *always* have to do this, because GetTypeForDeclarator will
2060 // put in a result type of "int" when none was specified.
Douglas Gregor72564e72009-02-26 23:50:07 +00002061 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Chris Lattner65401802009-04-25 08:28:21 +00002062 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2063 Proto->getNumArgs(),
2064 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002065}
2066
Douglas Gregor72b505b2008-12-16 21:30:33 +00002067/// CheckConstructor - Checks a fully-formed constructor for
2068/// well-formedness, issuing any diagnostics required. Returns true if
2069/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002070void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002071 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002072 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2073 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002074 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002075
2076 // C++ [class.copy]p3:
2077 // A declaration of a constructor for a class X is ill-formed if
2078 // its first parameter is of type (optionally cv-qualified) X and
2079 // either there are no other parameters or else all other
2080 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002081 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002082 ((Constructor->getNumParams() == 1) ||
2083 (Constructor->getNumParams() > 1 &&
Anders Carlssonae0b4e72009-06-06 04:14:07 +00002084 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002085 QualType ParamType = Constructor->getParamDecl(0)->getType();
2086 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2087 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002088 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2089 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002090 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattner6e475012009-04-25 08:35:12 +00002091 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002092 }
2093 }
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Douglas Gregor72b505b2008-12-16 21:30:33 +00002095 // Notify the class that we've added a constructor.
2096 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002097}
2098
Mike Stump1eb44332009-09-09 15:08:12 +00002099static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002100FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2101 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2102 FTI.ArgInfo[0].Param &&
2103 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2104}
2105
Douglas Gregor42a552f2008-11-05 20:51:48 +00002106/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2107/// the well-formednes of the destructor declarator @p D with type @p
2108/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002109/// emit diagnostics and set the declarator to invalid. Even if this happens,
2110/// will be updated to reflect a well-formed type for the destructor and
2111/// returned.
2112QualType Sema::CheckDestructorDeclarator(Declarator &D,
2113 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002114 // C++ [class.dtor]p1:
2115 // [...] A typedef-name that names a class is a class-name
2116 // (7.1.3); however, a typedef-name that names a class shall not
2117 // be used as the identifier in the declarator for a destructor
2118 // declaration.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002119 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType());
Chris Lattner65401802009-04-25 08:28:21 +00002120 if (isa<TypedefType>(DeclaratorType)) {
2121 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002122 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002123 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002124 }
2125
2126 // C++ [class.dtor]p2:
2127 // A destructor is used to destroy objects of its class type. A
2128 // destructor takes no parameters, and no return type can be
2129 // specified for it (not even void). The address of a destructor
2130 // shall not be taken. A destructor shall not be static. A
2131 // destructor can be invoked for a const, volatile or const
2132 // volatile object. A destructor shall not be declared const,
2133 // volatile or const volatile (9.3.2).
2134 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002135 if (!D.isInvalidType())
2136 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2137 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2138 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002139 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002140 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002141 }
Chris Lattner65401802009-04-25 08:28:21 +00002142 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002143 // Destructors don't have return types, but the parser will
2144 // happily parse something like:
2145 //
2146 // class X {
2147 // float ~X();
2148 // };
2149 //
2150 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002151 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2152 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2153 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002154 }
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Chris Lattner65401802009-04-25 08:28:21 +00002156 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2157 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002158 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002159 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2160 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002161 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002162 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2163 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002164 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002165 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2166 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002167 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002168 }
2169
2170 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002171 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002172 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2173
2174 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002175 FTI.freeArgs();
2176 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002177 }
2178
Mike Stump1eb44332009-09-09 15:08:12 +00002179 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002180 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002181 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002182 D.setInvalidType();
2183 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002184
2185 // Rebuild the function type "R" without any type qualifiers or
2186 // parameters (in case any of the errors above fired) and with
2187 // "void" as the return type, since destructors don't have return
2188 // types. We *always* have to do this, because GetTypeForDeclarator
2189 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002190 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002191}
2192
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002193/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2194/// well-formednes of the conversion function declarator @p D with
2195/// type @p R. If there are any errors in the declarator, this routine
2196/// will emit diagnostics and return true. Otherwise, it will return
2197/// false. Either way, the type @p R will be updated to reflect a
2198/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002199void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002200 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002201 // C++ [class.conv.fct]p1:
2202 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002203 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002204 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002205 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002206 if (!D.isInvalidType())
2207 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2208 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2209 << SourceRange(D.getIdentifierLoc());
2210 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002211 SC = FunctionDecl::None;
2212 }
Chris Lattner6e475012009-04-25 08:35:12 +00002213 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002214 // Conversion functions don't have return types, but the parser will
2215 // happily parse something like:
2216 //
2217 // class X {
2218 // float operator bool();
2219 // };
2220 //
2221 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002222 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2223 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2224 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002225 }
2226
2227 // Make sure we don't have any parameters.
Douglas Gregor72564e72009-02-26 23:50:07 +00002228 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002229 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2230
2231 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002232 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002233 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002234 }
2235
Mike Stump1eb44332009-09-09 15:08:12 +00002236 // Make sure the conversion function isn't variadic.
Chris Lattner6e475012009-04-25 08:35:12 +00002237 if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002238 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002239 D.setInvalidType();
2240 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002241
2242 // C++ [class.conv.fct]p4:
2243 // The conversion-type-id shall not represent a function type nor
2244 // an array type.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002245 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002246 if (ConvType->isArrayType()) {
2247 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2248 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002249 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002250 } else if (ConvType->isFunctionType()) {
2251 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2252 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002253 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002254 }
2255
2256 // Rebuild the function type "R" without any parameters (in case any
2257 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002258 // return type.
2259 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor72564e72009-02-26 23:50:07 +00002260 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002261
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002262 // C++0x explicit conversion operators.
2263 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002264 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002265 diag::warn_explicit_conversion_functions)
2266 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002267}
2268
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002269/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2270/// the declaration of the given C++ conversion function. This routine
2271/// is responsible for recording the conversion function in the C++
2272/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002273Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002274 assert(Conversion && "Expected to receive a conversion function declaration");
2275
Douglas Gregor9d350972008-12-12 08:25:50 +00002276 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002277
2278 // Make sure we aren't redeclaring the conversion function.
2279 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002280
2281 // C++ [class.conv.fct]p1:
2282 // [...] A conversion function is never used to convert a
2283 // (possibly cv-qualified) object to the (possibly cv-qualified)
2284 // same object type (or a reference to it), to a (possibly
2285 // cv-qualified) base class of that type (or a reference to it),
2286 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002287 // FIXME: Suppress this warning if the conversion function ends up being a
2288 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002289 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002290 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002291 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002292 ConvType = ConvTypeRef->getPointeeType();
2293 if (ConvType->isRecordType()) {
2294 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2295 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002296 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002297 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002298 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002299 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002300 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002301 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002302 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002303 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002304 }
2305
Douglas Gregor70316a02008-12-26 15:00:45 +00002306 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002307 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002308 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002309 = Conversion->getDescribedFunctionTemplate())
2310 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor70316a02008-12-26 15:00:45 +00002311 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00002312 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor70316a02008-12-26 15:00:45 +00002313 Conv = Conversions->function_begin(),
2314 ConvEnd = Conversions->function_end();
2315 Conv != ConvEnd; ++Conv) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002316 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor70316a02008-12-26 15:00:45 +00002317 *Conv = Conversion;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002318 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002319 }
2320 }
2321 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002322 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002323 = Conversion->getDescribedFunctionTemplate())
2324 ClassDecl->addConversionFunction(Context, ConversionTemplate);
2325 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Douglas Gregor70316a02008-12-26 15:00:45 +00002326 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002327
Chris Lattnerb28317a2009-03-28 19:18:32 +00002328 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002329}
2330
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002331//===----------------------------------------------------------------------===//
2332// Namespace Handling
2333//===----------------------------------------------------------------------===//
2334
2335/// ActOnStartNamespaceDef - This is called at the start of a namespace
2336/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002337Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2338 SourceLocation IdentLoc,
2339 IdentifierInfo *II,
2340 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002341 NamespaceDecl *Namespc =
2342 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2343 Namespc->setLBracLoc(LBrace);
2344
2345 Scope *DeclRegionScope = NamespcScope->getParent();
2346
2347 if (II) {
2348 // C++ [namespace.def]p2:
2349 // The identifier in an original-namespace-definition shall not have been
2350 // previously defined in the declarative region in which the
2351 // original-namespace-definition appears. The identifier in an
2352 // original-namespace-definition is the name of the namespace. Subsequently
2353 // in that declarative region, it is treated as an original-namespace-name.
2354
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002355 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
2356 true);
Mike Stump1eb44332009-09-09 15:08:12 +00002357
Douglas Gregor44b43212008-12-11 16:49:14 +00002358 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2359 // This is an extended namespace definition.
2360 // Attach this namespace decl to the chain of extended namespace
2361 // definitions.
2362 OrigNS->setNextNamespace(Namespc);
2363 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002364
Mike Stump1eb44332009-09-09 15:08:12 +00002365 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002366 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002367 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002368 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002369 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002370 } else if (PrevDecl) {
2371 // This is an invalid name redefinition.
2372 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2373 << Namespc->getDeclName();
2374 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2375 Namespc->setInvalidDecl();
2376 // Continue on to push Namespc as current DeclContext and return it.
Mike Stump1eb44332009-09-09 15:08:12 +00002377 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002378
2379 PushOnScopeChains(Namespc, DeclRegionScope);
2380 } else {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002381 // FIXME: Handle anonymous namespaces
2382 }
2383
2384 // Although we could have an invalid decl (i.e. the namespace name is a
2385 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002386 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2387 // for the namespace has the declarations that showed up in that particular
2388 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002389 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002390 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002391}
2392
2393/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2394/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002395void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2396 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002397 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2398 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2399 Namespc->setRBracLoc(RBrace);
2400 PopDeclContext();
2401}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002402
Chris Lattnerb28317a2009-03-28 19:18:32 +00002403Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2404 SourceLocation UsingLoc,
2405 SourceLocation NamespcLoc,
2406 const CXXScopeSpec &SS,
2407 SourceLocation IdentLoc,
2408 IdentifierInfo *NamespcName,
2409 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002410 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2411 assert(NamespcName && "Invalid NamespcName.");
2412 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002413 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002414
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002415 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002416
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002417 // Lookup namespace name.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002418 LookupResult R = LookupParsedName(S, &SS, NamespcName,
2419 LookupNamespaceName, false);
2420 if (R.isAmbiguous()) {
2421 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002422 return DeclPtrTy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002423 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002424 if (NamedDecl *NS = R) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002425 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002426 // C++ [namespace.udir]p1:
2427 // A using-directive specifies that the names in the nominated
2428 // namespace can be used in the scope in which the
2429 // using-directive appears after the using-directive. During
2430 // unqualified name lookup (3.4.1), the names appear as if they
2431 // were declared in the nearest enclosing namespace which
2432 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002433 // namespace. [Note: in this context, "contains" means "contains
2434 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002435
2436 // Find enclosing context containing both using-directive and
2437 // nominated namespace.
2438 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2439 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2440 CommonAncestor = CommonAncestor->getParent();
2441
Mike Stump1eb44332009-09-09 15:08:12 +00002442 UDir = UsingDirectiveDecl::Create(Context,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002443 CurContext, UsingLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002444 NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002445 SS.getRange(),
2446 (NestedNameSpecifier *)SS.getScopeRep(),
2447 IdentLoc,
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002448 cast<NamespaceDecl>(NS),
2449 CommonAncestor);
2450 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002451 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002452 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002453 }
2454
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002455 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002456 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002457 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002458}
2459
2460void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2461 // If scope has associated entity, then using directive is at namespace
2462 // or translation unit scope. We add UsingDirectiveDecls, into
2463 // it's lookup structure.
2464 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002465 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002466 else
2467 // Otherwise it is block-sope. using-directives will affect lookup
2468 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002469 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002470}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002471
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002472
2473Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002474 AccessSpecifier AS,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002475 SourceLocation UsingLoc,
2476 const CXXScopeSpec &SS,
2477 SourceLocation IdentLoc,
2478 IdentifierInfo *TargetName,
2479 OverloadedOperatorKind Op,
2480 AttributeList *AttrList,
2481 bool IsTypeName) {
Eli Friedman5d39dee2009-06-27 05:59:59 +00002482 assert((TargetName || Op) && "Invalid TargetName.");
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002483 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002484
Anders Carlsson0c6139d2009-06-27 00:27:47 +00002485 DeclarationName Name;
2486 if (TargetName)
2487 Name = TargetName;
2488 else
2489 Name = Context.DeclarationNames.getCXXOperatorName(Op);
Mike Stump1eb44332009-09-09 15:08:12 +00002490
2491 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS, IdentLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00002492 Name, AttrList, IsTypeName);
Anders Carlsson595adc12009-08-29 19:54:19 +00002493 if (UD) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00002494 PushOnScopeChains(UD, S);
Anders Carlsson595adc12009-08-29 19:54:19 +00002495 UD->setAccess(AS);
2496 }
Mike Stump1eb44332009-09-09 15:08:12 +00002497
Anders Carlssonc72160b2009-08-28 05:40:36 +00002498 return DeclPtrTy::make(UD);
2499}
2500
2501NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2502 const CXXScopeSpec &SS,
2503 SourceLocation IdentLoc,
2504 DeclarationName Name,
2505 AttributeList *AttrList,
2506 bool IsTypeName) {
2507 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2508 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00002509
Anders Carlsson550b14b2009-08-28 05:49:21 +00002510 // FIXME: We ignore attributes for now.
2511 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00002512
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002513 if (SS.isEmpty()) {
2514 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002515 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002516 }
Mike Stump1eb44332009-09-09 15:08:12 +00002517
2518 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002519 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2520
Anders Carlsson550b14b2009-08-28 05:49:21 +00002521 if (isUnknownSpecialization(SS)) {
2522 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2523 SS.getRange(), NNS,
2524 IdentLoc, Name, IsTypeName);
2525 }
Mike Stump1eb44332009-09-09 15:08:12 +00002526
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002527 DeclContext *LookupContext = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002528
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002529 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2530 // C++0x N2914 [namespace.udecl]p3:
2531 // A using-declaration used as a member-declaration shall refer to a member
2532 // of a base class of the class being defined, shall refer to a member of an
2533 // anonymous union that is a member of a base class of the class being
Mike Stump1eb44332009-09-09 15:08:12 +00002534 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002535 // a member of a base class of the class being defined.
2536 const Type *Ty = NNS->getAsType();
2537 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) {
2538 Diag(SS.getRange().getBegin(),
2539 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2540 << NNS << RD->getDeclName();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002541 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002542 }
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002543
2544 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0));
2545 LookupContext = BaseTy->getAs<RecordType>()->getDecl();
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002546 } else {
2547 // C++0x N2914 [namespace.udecl]p8:
2548 // A using-declaration for a class member shall be a member-declaration.
2549 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002550 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002551 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002552 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002553 }
Mike Stump1eb44332009-09-09 15:08:12 +00002554
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002555 // C++0x N2914 [namespace.udecl]p9:
2556 // In a using-declaration, a prefix :: refers to the global namespace.
2557 if (NNS->getKind() == NestedNameSpecifier::Global)
2558 LookupContext = Context.getTranslationUnitDecl();
2559 else
2560 LookupContext = NNS->getAsNamespace();
2561 }
2562
2563
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002564 // Lookup target name.
Mike Stump1eb44332009-09-09 15:08:12 +00002565 LookupResult R = LookupQualifiedName(LookupContext,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002566 Name, LookupOrdinaryName);
Mike Stump1eb44332009-09-09 15:08:12 +00002567
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002568 if (!R) {
Anders Carlsson05180af2009-08-30 00:58:45 +00002569 DiagnoseMissingMember(IdentLoc, Name, NNS, SS.getRange());
Anders Carlssonc72160b2009-08-28 05:40:36 +00002570 return 0;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002571 }
2572
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002573 NamedDecl *ND = R.getAsDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002574
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002575 if (IsTypeName && !isa<TypeDecl>(ND)) {
2576 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002577 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002578 }
2579
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002580 // C++0x N2914 [namespace.udecl]p6:
2581 // A using-declaration shall not name a namespace.
2582 if (isa<NamespaceDecl>(ND)) {
2583 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2584 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002585 return 0;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002586 }
Mike Stump1eb44332009-09-09 15:08:12 +00002587
Anders Carlssonc72160b2009-08-28 05:40:36 +00002588 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2589 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002590}
2591
Anders Carlsson81c85c42009-03-28 23:53:49 +00002592/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2593/// is a namespace alias, returns the namespace it points to.
2594static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2595 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2596 return AD->getNamespace();
2597 return dyn_cast_or_null<NamespaceDecl>(D);
2598}
2599
Mike Stump1eb44332009-09-09 15:08:12 +00002600Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002601 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002602 SourceLocation AliasLoc,
2603 IdentifierInfo *Alias,
2604 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002605 SourceLocation IdentLoc,
2606 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00002607
Anders Carlsson81c85c42009-03-28 23:53:49 +00002608 // Lookup the namespace name.
2609 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
2610
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002611 // Check if we have a previous declaration with the same name.
Anders Carlssondd729fc2009-03-28 23:49:35 +00002612 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00002613 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002614 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00002615 // namespace, so don't create a new one.
2616 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
2617 return DeclPtrTy();
2618 }
Mike Stump1eb44332009-09-09 15:08:12 +00002619
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002620 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2621 diag::err_redefinition_different_kind;
2622 Diag(AliasLoc, DiagID) << Alias;
2623 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002624 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002625 }
2626
Anders Carlsson5721c682009-03-28 06:42:02 +00002627 if (R.isAmbiguous()) {
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002628 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002629 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002630 }
Mike Stump1eb44332009-09-09 15:08:12 +00002631
Anders Carlsson5721c682009-03-28 06:42:02 +00002632 if (!R) {
2633 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00002634 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002635 }
Mike Stump1eb44332009-09-09 15:08:12 +00002636
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002637 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00002638 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2639 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00002640 (NestedNameSpecifier *)SS.getScopeRep(),
Anders Carlsson68771c72009-03-28 22:58:02 +00002641 IdentLoc, R);
Mike Stump1eb44332009-09-09 15:08:12 +00002642
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002643 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00002644 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00002645}
2646
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002647void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2648 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00002649 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2650 !Constructor->isUsed()) &&
2651 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00002652
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002653 CXXRecordDecl *ClassDecl
2654 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002655 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Mike Stump1eb44332009-09-09 15:08:12 +00002656 // Before the implicitly-declared default constructor for a class is
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002657 // implicitly defined, all the implicitly-declared default constructors
2658 // for its base class and its non-static data members shall have been
2659 // implicitly defined.
2660 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002661 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2662 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002663 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002664 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002665 if (!BaseClassDecl->hasTrivialConstructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002666 if (CXXConstructorDecl *BaseCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002667 BaseClassDecl->getDefaultConstructor(Context))
2668 MarkDeclarationReferenced(CurrentLocation, BaseCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002669 else {
Mike Stump1eb44332009-09-09 15:08:12 +00002670 Diag(CurrentLocation, diag::err_defining_default_ctor)
2671 << Context.getTagDeclType(ClassDecl) << 1
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002672 << Context.getTagDeclType(BaseClassDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002673 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002674 << Context.getTagDeclType(BaseClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002675 err = true;
2676 }
2677 }
2678 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002679 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2680 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002681 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2682 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2683 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002684 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002685 CXXRecordDecl *FieldClassDecl
2686 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Duncan Sands6887e632009-06-25 09:03:06 +00002687 if (!FieldClassDecl->hasTrivialConstructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002688 if (CXXConstructorDecl *FieldCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002689 FieldClassDecl->getDefaultConstructor(Context))
2690 MarkDeclarationReferenced(CurrentLocation, FieldCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002691 else {
Mike Stump1eb44332009-09-09 15:08:12 +00002692 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002693 << Context.getTagDeclType(ClassDecl) << 0 <<
2694 Context.getTagDeclType(FieldClassDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002695 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002696 << Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002697 err = true;
2698 }
2699 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002700 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002701 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00002702 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002703 Diag((*Field)->getLocation(), diag::note_declared_at);
2704 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002705 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002706 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00002707 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002708 Diag((*Field)->getLocation(), diag::note_declared_at);
2709 err = true;
2710 }
2711 }
2712 if (!err)
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00002713 Constructor->setUsed();
2714 else
2715 Constructor->setInvalidDecl();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002716}
2717
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002718void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00002719 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002720 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2721 "DefineImplicitDestructor - call it for implicit default dtor");
Mike Stump1eb44332009-09-09 15:08:12 +00002722
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002723 CXXRecordDecl *ClassDecl
2724 = cast<CXXRecordDecl>(Destructor->getDeclContext());
2725 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2726 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00002727 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002728 // implicitly defined, all the implicitly-declared default destructors
2729 // for its base class and its non-static data members shall have been
2730 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002731 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2732 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002733 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002734 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002735 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002736 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002737 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2738 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2739 else
Mike Stump1eb44332009-09-09 15:08:12 +00002740 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002741 "DefineImplicitDestructor - missing dtor in a base class");
2742 }
2743 }
Mike Stump1eb44332009-09-09 15:08:12 +00002744
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002745 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2746 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002747 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2748 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2749 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002750 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002751 CXXRecordDecl *FieldClassDecl
2752 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2753 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002754 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002755 const_cast<CXXDestructorDecl*>(
2756 FieldClassDecl->getDestructor(Context)))
2757 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
2758 else
Mike Stump1eb44332009-09-09 15:08:12 +00002759 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002760 "DefineImplicitDestructor - missing dtor in class of a data member");
2761 }
2762 }
2763 }
2764 Destructor->setUsed();
2765}
2766
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002767void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
2768 CXXMethodDecl *MethodDecl) {
2769 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
2770 MethodDecl->getOverloadedOperator() == OO_Equal &&
2771 !MethodDecl->isUsed()) &&
2772 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00002773
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002774 CXXRecordDecl *ClassDecl
2775 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002776
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00002777 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002778 // Before the implicitly-declared copy assignment operator for a class is
2779 // implicitly defined, all implicitly-declared copy assignment operators
2780 // for its direct base classes and its nonstatic data members shall have
2781 // been implicitly defined.
2782 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002783 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2784 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002785 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002786 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002787 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002788 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
2789 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
2790 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002791 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2792 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002793 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2794 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2795 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002796 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002797 CXXRecordDecl *FieldClassDecl
2798 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002799 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002800 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
2801 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002802 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002803 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00002804 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
2805 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002806 Diag(CurrentLocation, diag::note_first_required_here);
2807 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002808 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002809 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00002810 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
2811 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002812 Diag(CurrentLocation, diag::note_first_required_here);
2813 err = true;
2814 }
2815 }
2816 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00002817 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002818}
2819
2820CXXMethodDecl *
2821Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
2822 CXXRecordDecl *ClassDecl) {
2823 QualType LHSType = Context.getTypeDeclType(ClassDecl);
2824 QualType RHSType(LHSType);
2825 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00002826 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002827 // operator = (B&).
2828 if (ParmDecl->getType().isConstQualified())
2829 RHSType.addConst();
2830 if (ParmDecl->getType().isVolatileQualified())
2831 RHSType.addVolatile();
Mike Stump1eb44332009-09-09 15:08:12 +00002832 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
2833 LHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002834 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00002835 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
2836 RHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002837 SourceLocation()));
2838 Expr *Args[2] = { &*LHS, &*RHS };
2839 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00002840 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002841 CandidateSet);
2842 OverloadCandidateSet::iterator Best;
Mike Stump1eb44332009-09-09 15:08:12 +00002843 if (BestViableFunction(CandidateSet,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002844 ClassDecl->getLocation(), Best) == OR_Success)
2845 return cast<CXXMethodDecl>(Best->Function);
2846 assert(false &&
2847 "getAssignOperatorMethod - copy assignment operator method not found");
2848 return 0;
2849}
2850
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002851void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2852 CXXConstructorDecl *CopyConstructor,
2853 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00002854 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002855 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
2856 !CopyConstructor->isUsed()) &&
2857 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00002858
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002859 CXXRecordDecl *ClassDecl
2860 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
2861 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002862 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00002863 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002864 // implicitly defined, all the implicitly-declared copy constructors
2865 // for its base class and its non-static data members shall have been
2866 // implicitly defined.
2867 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2868 Base != ClassDecl->bases_end(); ++Base) {
2869 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002870 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002871 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002872 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002873 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002874 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002875 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2876 FieldEnd = ClassDecl->field_end();
2877 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002878 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2879 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2880 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002881 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002882 CXXRecordDecl *FieldClassDecl
2883 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002884 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002885 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002886 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002887 }
2888 }
2889 CopyConstructor->setUsed();
2890}
2891
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002892Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00002893Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00002894 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002895 MultiExprArg ExprArgs) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002896 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002897
Douglas Gregor39da0b82009-09-09 23:08:42 +00002898 // C++ [class.copy]p15:
2899 // Whenever a temporary class object is copied using a copy constructor, and
2900 // this object and the copy have the same cv-unqualified type, an
2901 // implementation is permitted to treat the original and the copy as two
2902 // different ways of referring to the same object and not perform a copy at
2903 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00002904
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002905 // FIXME: Is this enough?
Douglas Gregor39da0b82009-09-09 23:08:42 +00002906 if (Constructor->isCopyConstructor(Context)) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00002907 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002908 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2909 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00002910 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2911 if (ICE->getCastKind() == CastExpr::CK_NoOp)
2912 E = ICE->getSubExpr();
2913
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002914 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
2915 Elidable = true;
2916 }
Mike Stump1eb44332009-09-09 15:08:12 +00002917
2918 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002919 Elidable, move(ExprArgs));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002920}
2921
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002922/// BuildCXXConstructExpr - Creates a complete call to a constructor,
2923/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002924Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00002925Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2926 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002927 MultiExprArg ExprArgs) {
2928 unsigned NumExprs = ExprArgs.size();
2929 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00002930
Douglas Gregor39da0b82009-09-09 23:08:42 +00002931 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
2932 Elidable, Exprs, NumExprs));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002933}
2934
Anders Carlssone7624a72009-08-27 05:08:22 +00002935Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00002936Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
2937 QualType Ty,
2938 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00002939 MultiExprArg Args,
2940 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002941 unsigned NumExprs = Args.size();
2942 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00002943
Douglas Gregor39da0b82009-09-09 23:08:42 +00002944 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
2945 TyBeginLoc, Exprs,
2946 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00002947}
2948
2949
Mike Stump1eb44332009-09-09 15:08:12 +00002950bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002951 CXXConstructorDecl *Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00002952 QualType DeclInitType,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002953 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002954 OwningExprResult TempResult =
2955 BuildCXXConstructExpr(VD->getLocation(), DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002956 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00002957 if (TempResult.isInvalid())
2958 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002959
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002960 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002961 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +00002962 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor78d15832009-05-26 18:54:04 +00002963 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00002964
Anders Carlssonfe2de492009-08-25 05:18:00 +00002965 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00002966}
2967
Mike Stump1eb44332009-09-09 15:08:12 +00002968void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002969 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00002970 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002971 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00002972 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002973 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002974 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002975}
2976
Mike Stump1eb44332009-09-09 15:08:12 +00002977/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002978/// ActOnDeclarator, when a C++ direct initializer is present.
2979/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00002980void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
2981 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00002982 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002983 SourceLocation *CommaLocs,
2984 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00002985 unsigned NumExprs = Exprs.size();
2986 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00002987 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002988
2989 // If there is no declaration, there was an error parsing it. Just ignore
2990 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002991 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002992 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002993
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002994 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2995 if (!VDecl) {
2996 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
2997 RealDecl->setInvalidDecl();
2998 return;
2999 }
3000
Douglas Gregor83ddad32009-08-26 21:14:46 +00003001 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003002 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003003 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3004 //
3005 // Clients that want to distinguish between the two forms, can check for
3006 // direct initializer using VarDecl::hasCXXDirectInitializer().
3007 // A major benefit is that clients that don't particularly care about which
3008 // exactly form was it (like the CodeGen) can handle both cases without
3009 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003010
Douglas Gregor83ddad32009-08-26 21:14:46 +00003011 // If either the declaration has a dependent type or if any of the expressions
3012 // is type-dependent, we represent the initialization via a ParenListExpr for
3013 // later use during template instantiation.
3014 if (VDecl->getType()->isDependentType() ||
3015 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3016 // Let clients know that initialization was done with a direct initializer.
3017 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003018
Douglas Gregor83ddad32009-08-26 21:14:46 +00003019 // Store the initialization expressions as a ParenListExpr.
3020 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003021 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003022 new (Context) ParenListExpr(Context, LParenLoc,
3023 (Expr **)Exprs.release(),
3024 NumExprs, RParenLoc));
3025 return;
3026 }
Mike Stump1eb44332009-09-09 15:08:12 +00003027
Douglas Gregor83ddad32009-08-26 21:14:46 +00003028
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003029 // C++ 8.5p11:
3030 // The form of initialization (using parentheses or '=') is generally
3031 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003032 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003033 QualType DeclInitType = VDecl->getType();
3034 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
3035 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003036
Douglas Gregor615c5d42009-03-24 16:43:20 +00003037 // FIXME: This isn't the right place to complete the type.
3038 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3039 diag::err_typecheck_decl_incomplete_type)) {
3040 VDecl->setInvalidDecl();
3041 return;
3042 }
3043
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003044 if (VDecl->getType()->isRecordType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003045 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3046
Douglas Gregor18fe5682008-11-03 20:45:27 +00003047 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00003048 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003049 move(Exprs),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003050 VDecl->getLocation(),
3051 SourceRange(VDecl->getLocation(),
3052 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003053 VDecl->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +00003054 IK_Direct,
3055 ConstructorArgs);
Sebastian Redlf53597f2009-03-15 17:47:39 +00003056 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00003057 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00003058 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00003059 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003060 if (InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003061 move_arg(ConstructorArgs)))
Anders Carlssonfe2de492009-08-25 05:18:00 +00003062 RealDecl->setInvalidDecl();
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003063 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00003064 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003065 return;
3066 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003067
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003068 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003069 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3070 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003071 RealDecl->setInvalidDecl();
3072 return;
3073 }
3074
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003075 // Let clients know that initialization was done with a direct initializer.
3076 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003077
3078 assert(NumExprs == 1 && "Expected 1 expression");
3079 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00003080 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3081 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003082}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003083
Douglas Gregor39da0b82009-09-09 23:08:42 +00003084/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3085/// may occur as part of direct-initialization or copy-initialization.
3086///
3087/// \param ClassType the type of the object being initialized, which must have
3088/// class type.
3089///
3090/// \param ArgsPtr the arguments provided to initialize the object
3091///
3092/// \param Loc the source location where the initialization occurs
3093///
3094/// \param Range the source range that covers the entire initialization
3095///
3096/// \param InitEntity the name of the entity being initialized, if known
3097///
3098/// \param Kind the type of initialization being performed
3099///
3100/// \param ConvertedArgs a vector that will be filled in with the
3101/// appropriately-converted arguments to the constructor (if initialization
3102/// succeeded).
3103///
3104/// \returns the constructor used to initialize the object, if successful.
3105/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003106CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003107Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003108 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003109 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003110 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003111 InitializationKind Kind,
3112 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003113 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregor18fe5682008-11-03 20:45:27 +00003114 assert(ClassRec && "Can only initialize a class type here");
Douglas Gregor39da0b82009-09-09 23:08:42 +00003115 Expr **Args = (Expr **)ArgsPtr.get();
3116 unsigned NumArgs = ArgsPtr.size();
3117
Mike Stump1eb44332009-09-09 15:08:12 +00003118 // C++ [dcl.init]p14:
Douglas Gregor18fe5682008-11-03 20:45:27 +00003119 // If the initialization is direct-initialization, or if it is
3120 // copy-initialization where the cv-unqualified version of the
3121 // source type is the same class as, or a derived class of, the
3122 // class of the destination, constructors are considered. The
3123 // applicable constructors are enumerated (13.3.1.3), and the
3124 // best one is chosen through overload resolution (13.3). The
3125 // constructor so selected is called to initialize the object,
3126 // with the initializer expression(s) as its argument(s). If no
3127 // constructor applies, or the overload resolution is ambiguous,
3128 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003129 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3130 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003131
3132 // Add constructors to the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00003133 DeclarationName ConstructorName
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003134 = Context.DeclarationNames.getCXXConstructorName(
3135 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003136 DeclContext::lookup_const_iterator Con, ConEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003137 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003138 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00003139 // Find the constructor (which may be a template).
3140 CXXConstructorDecl *Constructor = 0;
3141 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3142 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003143 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003144 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3145 else
3146 Constructor = cast<CXXConstructorDecl>(*Con);
3147
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003148 if ((Kind == IK_Direct) ||
Mike Stump1eb44332009-09-09 15:08:12 +00003149 (Kind == IK_Copy &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00003150 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregordec06662009-08-21 18:42:58 +00003151 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
3152 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003153 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
Douglas Gregordec06662009-08-21 18:42:58 +00003154 Args, NumArgs, CandidateSet);
3155 else
3156 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3157 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003158 }
3159
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003160 // FIXME: When we decide not to synthesize the implicitly-declared
3161 // constructors, we'll need to make them appear here.
3162
Douglas Gregor18fe5682008-11-03 20:45:27 +00003163 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003164 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00003165 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00003166 // We found a constructor. Break out so that we can convert the arguments
3167 // appropriately.
3168 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003169
Douglas Gregor18fe5682008-11-03 20:45:27 +00003170 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003171 if (InitEntity)
3172 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003173 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00003174 else
3175 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003176 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00003177 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00003178 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003179
Douglas Gregor18fe5682008-11-03 20:45:27 +00003180 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003181 if (InitEntity)
3182 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3183 else
3184 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003185 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3186 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003187
3188 case OR_Deleted:
3189 if (InitEntity)
3190 Diag(Loc, diag::err_ovl_deleted_init)
3191 << Best->Function->isDeleted()
3192 << InitEntity << Range;
3193 else
3194 Diag(Loc, diag::err_ovl_deleted_init)
3195 << Best->Function->isDeleted()
3196 << InitEntity << Range;
3197 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3198 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003199 }
Mike Stump1eb44332009-09-09 15:08:12 +00003200
Douglas Gregor39da0b82009-09-09 23:08:42 +00003201 // Convert the arguments, fill in default arguments, etc.
3202 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3203 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3204 return 0;
3205
3206 return Constructor;
3207}
3208
3209/// \brief Given a constructor and the set of arguments provided for the
3210/// constructor, convert the arguments and add any required default arguments
3211/// to form a proper call to this constructor.
3212///
3213/// \returns true if an error occurred, false otherwise.
3214bool
3215Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3216 MultiExprArg ArgsPtr,
3217 SourceLocation Loc,
3218 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3219 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3220 unsigned NumArgs = ArgsPtr.size();
3221 Expr **Args = (Expr **)ArgsPtr.get();
3222
3223 const FunctionProtoType *Proto
3224 = Constructor->getType()->getAs<FunctionProtoType>();
3225 assert(Proto && "Constructor without a prototype?");
3226 unsigned NumArgsInProto = Proto->getNumArgs();
3227 unsigned NumArgsToCheck = NumArgs;
3228
3229 // If too few arguments are available, we'll fill in the rest with defaults.
3230 if (NumArgs < NumArgsInProto) {
3231 NumArgsToCheck = NumArgsInProto;
3232 ConvertedArgs.reserve(NumArgsInProto);
3233 } else {
3234 ConvertedArgs.reserve(NumArgs);
3235 if (NumArgs > NumArgsInProto)
3236 NumArgsToCheck = NumArgsInProto;
3237 }
3238
3239 // Convert arguments
3240 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3241 QualType ProtoArgType = Proto->getArgType(i);
3242
3243 Expr *Arg;
3244 if (i < NumArgs) {
3245 Arg = Args[i];
3246
3247 // Pass the argument.
3248 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3249 return true;
3250
3251 Args[i] = 0;
3252 } else {
3253 ParmVarDecl *Param = Constructor->getParamDecl(i);
3254
3255 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3256 if (DefArg.isInvalid())
3257 return true;
3258
3259 Arg = DefArg.takeAs<Expr>();
3260 }
3261
3262 ConvertedArgs.push_back(Arg);
3263 }
3264
3265 // If this is a variadic call, handle args passed through "...".
3266 if (Proto->isVariadic()) {
3267 // Promote the arguments (C99 6.5.2.2p7).
3268 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3269 Expr *Arg = Args[i];
3270 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3271 return true;
3272
3273 ConvertedArgs.push_back(Arg);
3274 Args[i] = 0;
3275 }
3276 }
3277
3278 return false;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003279}
3280
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003281/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3282/// determine whether they are reference-related,
3283/// reference-compatible, reference-compatible with added
3284/// qualification, or incompatible, for use in C++ initialization by
3285/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3286/// type, and the first type (T1) is the pointee type of the reference
3287/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00003288Sema::ReferenceCompareResult
3289Sema::CompareReferenceRelationship(QualType T1, QualType T2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003290 bool& DerivedToBase) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003291 assert(!T1->isReferenceType() &&
3292 "T1 must be the pointee type of the reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003293 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
3294
3295 T1 = Context.getCanonicalType(T1);
3296 T2 = Context.getCanonicalType(T2);
3297 QualType UnqualT1 = T1.getUnqualifiedType();
3298 QualType UnqualT2 = T2.getUnqualifiedType();
3299
3300 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003301 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00003302 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003303 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003304 if (UnqualT1 == UnqualT2)
3305 DerivedToBase = false;
3306 else if (IsDerivedFrom(UnqualT2, UnqualT1))
3307 DerivedToBase = true;
3308 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003309 return Ref_Incompatible;
3310
3311 // At this point, we know that T1 and T2 are reference-related (at
3312 // least).
3313
3314 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003315 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003316 // reference-related to T2 and cv1 is the same cv-qualification
3317 // as, or greater cv-qualification than, cv2. For purposes of
3318 // overload resolution, cases for which cv1 is greater
3319 // cv-qualification than cv2 are identified as
3320 // reference-compatible with added qualification (see 13.3.3.2).
3321 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3322 return Ref_Compatible;
3323 else if (T1.isMoreQualifiedThan(T2))
3324 return Ref_Compatible_With_Added_Qualification;
3325 else
3326 return Ref_Related;
3327}
3328
3329/// CheckReferenceInit - Check the initialization of a reference
3330/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3331/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00003332/// list), and DeclType is the type of the declaration. When ICS is
3333/// non-null, this routine will compute the implicit conversion
3334/// sequence according to C++ [over.ics.ref] and will not produce any
3335/// diagnostics; when ICS is null, it will emit diagnostics when any
3336/// errors are found. Either way, a return value of true indicates
3337/// that there was a failure, a return value of false indicates that
3338/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00003339///
3340/// When @p SuppressUserConversions, user-defined conversions are
3341/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003342/// When @p AllowExplicit, we also permit explicit user-defined
3343/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00003344/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00003345bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003346Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003347 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00003348 bool AllowExplicit, bool ForceRValue,
3349 ImplicitConversionSequence *ICS) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003350 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3351
Ted Kremenek6217b802009-07-29 21:53:49 +00003352 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003353 QualType T2 = Init->getType();
3354
Douglas Gregor904eed32008-11-10 20:40:00 +00003355 // If the initializer is the address of an overloaded function, try
3356 // to resolve the overloaded function. If all goes well, T2 is the
3357 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00003358 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00003359 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003360 ICS != 0);
3361 if (Fn) {
3362 // Since we're performing this reference-initialization for
3363 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003364 if (!ICS) {
3365 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
3366 return true;
3367
Douglas Gregor904eed32008-11-10 20:40:00 +00003368 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003369 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003370
3371 T2 = Fn->getType();
3372 }
3373 }
3374
Douglas Gregor15da57e2008-10-29 02:00:59 +00003375 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003376 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00003377 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00003378 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3379 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003380 ReferenceCompareResult RefRelationship
Douglas Gregor15da57e2008-10-29 02:00:59 +00003381 = CompareReferenceRelationship(T1, T2, DerivedToBase);
3382
3383 // Most paths end in a failed conversion.
3384 if (ICS)
3385 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003386
3387 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00003388 // A reference to type "cv1 T1" is initialized by an expression
3389 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003390
3391 // -- If the initializer expression
3392
Sebastian Redla9845802009-03-29 15:27:50 +00003393 // Rvalue references cannot bind to lvalues (N2812).
3394 // There is absolutely no situation where they can. In particular, note that
3395 // this is ill-formed, even if B has a user-defined conversion to A&&:
3396 // B b;
3397 // A&& r = b;
3398 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3399 if (!ICS)
3400 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
3401 << Init->getSourceRange();
3402 return true;
3403 }
3404
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003405 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00003406 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3407 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00003408 //
3409 // Note that the bit-field check is skipped if we are just computing
3410 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003411 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003412 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003413 BindsDirectly = true;
3414
Douglas Gregor15da57e2008-10-29 02:00:59 +00003415 if (ICS) {
3416 // C++ [over.ics.ref]p1:
3417 // When a parameter of reference type binds directly (8.5.3)
3418 // to an argument expression, the implicit conversion sequence
3419 // is the identity conversion, unless the argument expression
3420 // has a type that is a derived class of the parameter type,
3421 // in which case the implicit conversion sequence is a
3422 // derived-to-base Conversion (13.3.3.1).
3423 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3424 ICS->Standard.First = ICK_Identity;
3425 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3426 ICS->Standard.Third = ICK_Identity;
3427 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3428 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003429 ICS->Standard.ReferenceBinding = true;
3430 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003431 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00003432 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003433
3434 // Nothing more to do: the inaccessibility/ambiguity check for
3435 // derived-to-base conversions is suppressed when we're
3436 // computing the implicit conversion sequence (C++
3437 // [over.best.ics]p2).
3438 return false;
3439 } else {
3440 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00003441 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3442 if (DerivedToBase)
3443 CK = CastExpr::CK_DerivedToBase;
3444 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003445 }
3446 }
3447
3448 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00003449 // implicitly converted to an lvalue of type "cv3 T3,"
3450 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003451 // 92) (this conversion is selected by enumerating the
3452 // applicable conversion functions (13.3.1.6) and choosing
3453 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00003454 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
3455 !RequireCompleteType(SourceLocation(), T2, 0)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003456 // FIXME: Look for conversions in base classes!
Mike Stump1eb44332009-09-09 15:08:12 +00003457 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003458 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003459
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003460 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003461 OverloadedFunctionDecl *Conversions
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003462 = T2RecordDecl->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00003463 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003464 = Conversions->function_begin();
3465 Func != Conversions->function_end(); ++Func) {
Mike Stump1eb44332009-09-09 15:08:12 +00003466 FunctionTemplateDecl *ConvTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003467 = dyn_cast<FunctionTemplateDecl>(*Func);
3468 CXXConversionDecl *Conv;
3469 if (ConvTemplate)
3470 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3471 else
3472 Conv = cast<CXXConversionDecl>(*Func);
Sebastian Redldfe292d2009-03-22 21:28:55 +00003473
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003474 // If the conversion function doesn't return a reference type,
3475 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003476 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003477 (AllowExplicit || !Conv->isExplicit())) {
3478 if (ConvTemplate)
Mike Stump1eb44332009-09-09 15:08:12 +00003479 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003480 CandidateSet);
3481 else
3482 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3483 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003484 }
3485
3486 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003487 switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003488 case OR_Success:
3489 // This is a direct binding.
3490 BindsDirectly = true;
3491
3492 if (ICS) {
3493 // C++ [over.ics.ref]p1:
3494 //
3495 // [...] If the parameter binds directly to the result of
3496 // applying a conversion function to the argument
3497 // expression, the implicit conversion sequence is a
3498 // user-defined conversion sequence (13.3.3.1.2), with the
3499 // second standard conversion sequence either an identity
3500 // conversion or, if the conversion function returns an
3501 // entity of a type that is a derived class of the parameter
3502 // type, a derived-to-base Conversion.
3503 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3504 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3505 ICS->UserDefined.After = Best->FinalConversion;
3506 ICS->UserDefined.ConversionFunction = Best->Function;
3507 assert(ICS->UserDefined.After.ReferenceBinding &&
3508 ICS->UserDefined.After.DirectBinding &&
3509 "Expected a direct reference binding!");
3510 return false;
3511 } else {
3512 // Perform the conversion.
Mike Stump390b4cc2009-05-16 07:39:55 +00003513 // FIXME: Binding to a subobject of the lvalue is going to require more
3514 // AST annotation than this.
Anders Carlsson3503d042009-07-31 01:23:52 +00003515 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003516 }
3517 break;
3518
3519 case OR_Ambiguous:
3520 assert(false && "Ambiguous reference binding conversions not implemented.");
3521 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003522
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003523 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003524 case OR_Deleted:
3525 // There was no suitable conversion, or we found a deleted
3526 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003527 break;
3528 }
3529 }
Mike Stump1eb44332009-09-09 15:08:12 +00003530
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003531 if (BindsDirectly) {
3532 // C++ [dcl.init.ref]p4:
3533 // [...] In all cases where the reference-related or
3534 // reference-compatible relationship of two types is used to
3535 // establish the validity of a reference binding, and T1 is a
3536 // base class of T2, a program that necessitates such a binding
3537 // is ill-formed if T1 is an inaccessible (clause 11) or
3538 // ambiguous (10.2) base class of T2.
3539 //
3540 // Note that we only check this condition when we're allowed to
3541 // complain about errors, because we should not be checking for
3542 // ambiguity (or inaccessibility) unless the reference binding
3543 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00003544 if (DerivedToBase)
3545 return CheckDerivedToBaseConversion(T2, T1,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003546 Init->getSourceRange().getBegin(),
3547 Init->getSourceRange());
3548 else
3549 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003550 }
3551
3552 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00003553 // type (i.e., cv1 shall be const), or the reference shall be an
3554 // rvalue reference and the initializer expression shall be an rvalue.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003555 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00003556 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003557 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003558 diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00003559 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3560 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003561 return true;
3562 }
3563
3564 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00003565 // class type, and "cv1 T1" is reference-compatible with
3566 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003567 // following ways (the choice is implementation-defined):
3568 //
3569 // -- The reference is bound to the object represented by
3570 // the rvalue (see 3.10) or to a sub-object within that
3571 // object.
3572 //
Eli Friedman33a31382009-08-05 19:21:58 +00003573 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003574 // a constructor is called to copy the entire rvalue
3575 // object into the temporary. The reference is bound to
3576 // the temporary or to a sub-object within the
3577 // temporary.
3578 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003579 // The constructor that would be used to make the copy
3580 // shall be callable whether or not the copy is actually
3581 // done.
3582 //
Sebastian Redla9845802009-03-29 15:27:50 +00003583 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003584 // freedom, so we will always take the first option and never build
3585 // a temporary in this case. FIXME: We will, however, have to check
3586 // for the presence of a copy constructor in C++98/03 mode.
3587 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003588 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3589 if (ICS) {
3590 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3591 ICS->Standard.First = ICK_Identity;
3592 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3593 ICS->Standard.Third = ICK_Identity;
3594 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3595 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003596 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003597 ICS->Standard.DirectBinding = false;
3598 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00003599 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003600 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003601 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3602 if (DerivedToBase)
3603 CK = CastExpr::CK_DerivedToBase;
3604 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003605 }
3606 return false;
3607 }
3608
Eli Friedman33a31382009-08-05 19:21:58 +00003609 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003610 // initialized from the initializer expression using the
3611 // rules for a non-reference copy initialization (8.5). The
3612 // reference is then bound to the temporary. If T1 is
3613 // reference-related to T2, cv1 must be the same
3614 // cv-qualification as, or greater cv-qualification than,
3615 // cv2; otherwise, the program is ill-formed.
3616 if (RefRelationship == Ref_Related) {
3617 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3618 // we would be reference-compatible or reference-compatible with
3619 // added qualification. But that wasn't the case, so the reference
3620 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003621 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003622 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003623 diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00003624 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3625 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003626 return true;
3627 }
3628
Douglas Gregor734d9862009-01-30 23:27:23 +00003629 // If at least one of the types is a class type, the types are not
3630 // related, and we aren't allowed any user conversions, the
3631 // reference binding fails. This case is important for breaking
3632 // recursion, since TryImplicitConversion below will attempt to
3633 // create a temporary through the use of a copy constructor.
3634 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3635 (T1->isRecordType() || T2->isRecordType())) {
3636 if (!ICS)
3637 Diag(Init->getSourceRange().getBegin(),
3638 diag::err_typecheck_convert_incompatible)
3639 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3640 return true;
3641 }
3642
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003643 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003644 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00003645 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003646 //
Sebastian Redla9845802009-03-29 15:27:50 +00003647 // When a parameter of reference type is not bound directly to
3648 // an argument expression, the conversion sequence is the one
3649 // required to convert the argument expression to the
3650 // underlying type of the reference according to
3651 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3652 // to copy-initializing a temporary of the underlying type with
3653 // the argument expression. Any difference in top-level
3654 // cv-qualification is subsumed by the initialization itself
3655 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003656 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
3657 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00003658 /*ForceRValue=*/false,
3659 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003660
Sebastian Redla9845802009-03-29 15:27:50 +00003661 // Of course, that's still a reference binding.
3662 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3663 ICS->Standard.ReferenceBinding = true;
3664 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003665 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00003666 ImplicitConversionSequence::UserDefinedConversion) {
3667 ICS->UserDefined.After.ReferenceBinding = true;
3668 ICS->UserDefined.After.RRefBinding = isRValRef;
3669 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00003670 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3671 } else {
Douglas Gregor45920e82008-12-19 17:40:08 +00003672 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor15da57e2008-10-29 02:00:59 +00003673 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003674}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003675
3676/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3677/// of this overloaded operator is well-formed. If so, returns false;
3678/// otherwise, emits appropriate diagnostics and returns true.
3679bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003680 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003681 "Expected an overloaded operator declaration");
3682
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003683 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
3684
Mike Stump1eb44332009-09-09 15:08:12 +00003685 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003686 // The allocation and deallocation functions, operator new,
3687 // operator new[], operator delete and operator delete[], are
3688 // described completely in 3.7.3. The attributes and restrictions
3689 // found in the rest of this subclause do not apply to them unless
3690 // explicitly stated in 3.7.3.
Mike Stump390b4cc2009-05-16 07:39:55 +00003691 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003692 if (Op == OO_New || Op == OO_Array_New ||
3693 Op == OO_Delete || Op == OO_Array_Delete)
3694 return false;
3695
3696 // C++ [over.oper]p6:
3697 // An operator function shall either be a non-static member
3698 // function or be a non-member function and have at least one
3699 // parameter whose type is a class, a reference to a class, an
3700 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003701 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
3702 if (MethodDecl->isStatic())
3703 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003704 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003705 } else {
3706 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003707 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
3708 ParamEnd = FnDecl->param_end();
3709 Param != ParamEnd; ++Param) {
3710 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00003711 if (ParamType->isDependentType() || ParamType->isRecordType() ||
3712 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003713 ClassOrEnumParam = true;
3714 break;
3715 }
3716 }
3717
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003718 if (!ClassOrEnumParam)
3719 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003720 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003721 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003722 }
3723
3724 // C++ [over.oper]p8:
3725 // An operator function cannot have default arguments (8.3.6),
3726 // except where explicitly stated below.
3727 //
Mike Stump1eb44332009-09-09 15:08:12 +00003728 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003729 // (C++ [over.call]p1).
3730 if (Op != OO_Call) {
3731 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
3732 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00003733 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00003734 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00003735 diag::err_operator_overload_default_arg)
3736 << FnDecl->getDeclName();
3737 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003738 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003739 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003740 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003741 }
3742 }
3743
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003744 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
3745 { false, false, false }
3746#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3747 , { Unary, Binary, MemberOnly }
3748#include "clang/Basic/OperatorKinds.def"
3749 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003750
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003751 bool CanBeUnaryOperator = OperatorUses[Op][0];
3752 bool CanBeBinaryOperator = OperatorUses[Op][1];
3753 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003754
3755 // C++ [over.oper]p8:
3756 // [...] Operator functions cannot have more or fewer parameters
3757 // than the number required for the corresponding operator, as
3758 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00003759 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003760 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003761 if (Op != OO_Call &&
3762 ((NumParams == 1 && !CanBeUnaryOperator) ||
3763 (NumParams == 2 && !CanBeBinaryOperator) ||
3764 (NumParams < 1) || (NumParams > 2))) {
3765 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00003766 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003767 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00003768 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003769 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00003770 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003771 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00003772 assert(CanBeBinaryOperator &&
3773 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00003774 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003775 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003776
Chris Lattner416e46f2008-11-21 07:57:12 +00003777 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003778 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003779 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003780
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003781 // Overloaded operators other than operator() cannot be variadic.
3782 if (Op != OO_Call &&
Douglas Gregor72564e72009-02-26 23:50:07 +00003783 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003784 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003785 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003786 }
3787
3788 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003789 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
3790 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003791 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003792 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003793 }
3794
3795 // C++ [over.inc]p1:
3796 // The user-defined function called operator++ implements the
3797 // prefix and postfix ++ operator. If this function is a member
3798 // function with no parameters, or a non-member function with one
3799 // parameter of class or enumeration type, it defines the prefix
3800 // increment operator ++ for objects of that type. If the function
3801 // is a member function with one parameter (which shall be of type
3802 // int) or a non-member function with two parameters (the second
3803 // of which shall be of type int), it defines the postfix
3804 // increment operator ++ for objects of that type.
3805 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
3806 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
3807 bool ParamIsInt = false;
3808 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
3809 ParamIsInt = BT->getKind() == BuiltinType::Int;
3810
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00003811 if (!ParamIsInt)
3812 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003813 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00003814 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003815 }
3816
Sebastian Redl64b45f72009-01-05 20:52:13 +00003817 // Notify the class if it got an assignment operator.
3818 if (Op == OO_Equal) {
3819 // Would have returned earlier otherwise.
3820 assert(isa<CXXMethodDecl>(FnDecl) &&
3821 "Overloaded = not member, but not filtered.");
3822 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Fariborz Jahanianad258832009-08-13 21:09:41 +00003823 Method->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003824 Method->getParent()->addedAssignmentOperator(Context, Method);
3825 }
3826
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003827 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003828}
Chris Lattner5a003a42008-12-17 07:09:26 +00003829
Douglas Gregor074149e2009-01-05 19:45:36 +00003830/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
3831/// linkage specification, including the language and (if present)
3832/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
3833/// the location of the language string literal, which is provided
3834/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
3835/// the '{' brace. Otherwise, this linkage specification does not
3836/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003837Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
3838 SourceLocation ExternLoc,
3839 SourceLocation LangLoc,
3840 const char *Lang,
3841 unsigned StrSize,
3842 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00003843 LinkageSpecDecl::LanguageIDs Language;
3844 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3845 Language = LinkageSpecDecl::lang_c;
3846 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3847 Language = LinkageSpecDecl::lang_cxx;
3848 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00003849 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003850 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00003851 }
Mike Stump1eb44332009-09-09 15:08:12 +00003852
Chris Lattnercc98eac2008-12-17 07:13:27 +00003853 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00003854
Douglas Gregor074149e2009-01-05 19:45:36 +00003855 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00003856 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00003857 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003858 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00003859 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003860 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00003861}
3862
Douglas Gregor074149e2009-01-05 19:45:36 +00003863/// ActOnFinishLinkageSpecification - Completely the definition of
3864/// the C++ linkage specification LinkageSpec. If RBraceLoc is
3865/// valid, it's the position of the closing '}' brace in a linkage
3866/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003867Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
3868 DeclPtrTy LinkageSpec,
3869 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00003870 if (LinkageSpec)
3871 PopDeclContext();
3872 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00003873}
3874
Douglas Gregord308e622009-05-18 20:51:54 +00003875/// \brief Perform semantic analysis for the variable declaration that
3876/// occurs within a C++ catch clause, returning the newly-created
3877/// variable.
3878VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003879 DeclaratorInfo *DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00003880 IdentifierInfo *Name,
3881 SourceLocation Loc,
3882 SourceRange Range) {
3883 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003884
3885 // Arrays and functions decay.
3886 if (ExDeclType->isArrayType())
3887 ExDeclType = Context.getArrayDecayedType(ExDeclType);
3888 else if (ExDeclType->isFunctionType())
3889 ExDeclType = Context.getPointerType(ExDeclType);
3890
3891 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
3892 // The exception-declaration shall not denote a pointer or reference to an
3893 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003894 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00003895 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00003896 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003897 Invalid = true;
3898 }
Douglas Gregord308e622009-05-18 20:51:54 +00003899
Sebastian Redl4b07b292008-12-22 19:15:10 +00003900 QualType BaseType = ExDeclType;
3901 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003902 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00003903 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003904 BaseType = Ptr->getPointeeType();
3905 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003906 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00003907 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003908 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00003909 BaseType = Ref->getPointeeType();
3910 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003911 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003912 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003913 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00003914 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00003915 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003916
Mike Stump1eb44332009-09-09 15:08:12 +00003917 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00003918 RequireNonAbstractType(Loc, ExDeclType,
3919 diag::err_abstract_type_in_decl,
3920 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00003921 Invalid = true;
3922
Douglas Gregord308e622009-05-18 20:51:54 +00003923 // FIXME: Need to test for ability to copy-construct and destroy the
3924 // exception variable.
3925
Sebastian Redl8351da02008-12-22 21:35:02 +00003926 // FIXME: Need to check for abstract classes.
3927
Mike Stump1eb44332009-09-09 15:08:12 +00003928 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003929 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00003930
3931 if (Invalid)
3932 ExDecl->setInvalidDecl();
3933
3934 return ExDecl;
3935}
3936
3937/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
3938/// handler.
3939Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003940 DeclaratorInfo *DInfo = 0;
3941 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00003942
3943 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00003944 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003945 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003946 // The scope should be freshly made just for us. There is just no way
3947 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003948 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00003949 if (PrevDecl->isTemplateParameter()) {
3950 // Maybe we will complain about the shadowed template parameter.
3951 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003952 }
3953 }
3954
Chris Lattnereaaebc72009-04-25 08:06:05 +00003955 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003956 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
3957 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00003958 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003959 }
3960
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003961 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00003962 D.getIdentifier(),
3963 D.getIdentifierLoc(),
3964 D.getDeclSpec().getSourceRange());
3965
Chris Lattnereaaebc72009-04-25 08:06:05 +00003966 if (Invalid)
3967 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003968
Sebastian Redl4b07b292008-12-22 19:15:10 +00003969 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00003970 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00003971 PushOnScopeChains(ExDecl, S);
3972 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003973 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003974
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003975 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003976 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003977}
Anders Carlssonfb311762009-03-14 00:25:26 +00003978
Mike Stump1eb44332009-09-09 15:08:12 +00003979Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003980 ExprArg assertexpr,
3981 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00003982 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003983 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00003984 cast<StringLiteral>((Expr *)assertmessageexpr.get());
3985
Anders Carlssonc3082412009-03-14 00:33:21 +00003986 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
3987 llvm::APSInt Value(32);
3988 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
3989 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
3990 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003991 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00003992 }
Anders Carlssonfb311762009-03-14 00:25:26 +00003993
Anders Carlssonc3082412009-03-14 00:33:21 +00003994 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00003995 std::string str(AssertMessage->getStrData(),
Anders Carlssonc3082412009-03-14 00:33:21 +00003996 AssertMessage->getByteLength());
Mike Stump1eb44332009-09-09 15:08:12 +00003997 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson94b15fb2009-03-15 18:44:04 +00003998 << str << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00003999 }
4000 }
Mike Stump1eb44332009-09-09 15:08:12 +00004001
Anders Carlsson77d81422009-03-15 17:35:16 +00004002 assertexpr.release();
4003 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004004 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00004005 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00004006
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004007 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00004008 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00004009}
Sebastian Redl50de12f2009-03-24 22:27:57 +00004010
John McCall02cace72009-08-28 07:59:38 +00004011Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S,
John McCallbbbcdd92009-09-11 21:02:39 +00004012 const DeclSpec &DS) {
John McCall02cace72009-08-28 07:59:38 +00004013 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00004014
4015 assert(DS.isFriendSpecified());
4016 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4017
John McCall6b2becf2009-09-08 17:47:29 +00004018 // Try to convert the decl specifier to a type.
4019 bool invalid = false;
4020 QualType T = ConvertDeclSpecToType(DS, Loc, invalid);
4021 if (invalid) return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00004022
John McCall02cace72009-08-28 07:59:38 +00004023 // C++ [class.friend]p2:
4024 // An elaborated-type-specifier shall be used in a friend declaration
4025 // for a class.*
4026 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00004027 // This is one of the rare places in Clang where it's legitimate to
4028 // ask about the "spelling" of the type.
4029 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4030 // If we evaluated the type to a record type, suggest putting
4031 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00004032 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00004033 RecordDecl *RD = RT->getDecl();
4034
4035 std::string InsertionText = std::string(" ") + RD->getKindName();
4036
4037 Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type)
4038 << (RD->isUnion())
4039 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4040 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00004041 return DeclPtrTy();
4042 }else {
John McCall6b2becf2009-09-08 17:47:29 +00004043 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4044 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004045 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00004046 }
4047 }
4048
John McCallbbbcdd92009-09-11 21:02:39 +00004049 bool IsDefinition = false;
John McCall6b2becf2009-09-08 17:47:29 +00004050 FriendDecl::FriendUnion FU = T.getTypePtr();
4051
John McCallbbbcdd92009-09-11 21:02:39 +00004052 // We want to do a few things differently if the type was declared with
4053 // a tag: specifically, we want to use the associated RecordDecl as
4054 // the object of our friend declaration, and we want to disallow
4055 // class definitions.
John McCall6b2becf2009-09-08 17:47:29 +00004056 switch (DS.getTypeSpecType()) {
4057 default: break;
4058 case DeclSpec::TST_class:
4059 case DeclSpec::TST_struct:
4060 case DeclSpec::TST_union:
4061 CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep());
4062 if (RD) {
4063 IsDefinition |= RD->isDefinition();
4064 FU = RD;
4065 }
4066 break;
4067 }
John McCall02cace72009-08-28 07:59:38 +00004068
4069 // C++ [class.friend]p2: A class shall not be defined inside
4070 // a friend declaration.
4071 if (IsDefinition) {
4072 Diag(DS.getFriendSpecLoc(), diag::err_friend_decl_defines_class)
4073 << DS.getSourceRange();
4074 return DeclPtrTy();
4075 }
4076
4077 // C++98 [class.friend]p1: A friend of a class is a function
4078 // or class that is not a member of the class . . .
4079 // But that's a silly restriction which nobody implements for
4080 // inner classes, and C++0x removes it anyway, so we only report
4081 // this (as a warning) if we're being pedantic.
John McCall6b2becf2009-09-08 17:47:29 +00004082 if (!getLangOptions().CPlusPlus0x)
4083 if (const RecordType *RT = T->getAs<RecordType>())
4084 if (RT->getDecl()->getDeclContext() == CurContext)
4085 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCall02cace72009-08-28 07:59:38 +00004086
4087 FriendDecl *FD = FriendDecl::Create(Context, CurContext, Loc, FU,
4088 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00004089 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00004090 CurContext->addDecl(FD);
4091
4092 return DeclPtrTy::make(FD);
4093}
4094
John McCallbbbcdd92009-09-11 21:02:39 +00004095Sema::DeclPtrTy
4096Sema::ActOnFriendFunctionDecl(Scope *S,
4097 Declarator &D,
4098 bool IsDefinition,
4099 MultiTemplateParamsArg TemplateParams) {
4100 // FIXME: do something with template parameters
4101
John McCall02cace72009-08-28 07:59:38 +00004102 const DeclSpec &DS = D.getDeclSpec();
4103
4104 assert(DS.isFriendSpecified());
4105 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4106
4107 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004108 DeclaratorInfo *DInfo = 0;
John McCall02cace72009-08-28 07:59:38 +00004109 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall67d1a672009-08-06 02:15:43 +00004110
4111 // C++ [class.friend]p1
4112 // A friend of a class is a function or class....
4113 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00004114 // It *doesn't* see through dependent types, which is correct
4115 // according to [temp.arg.type]p3:
4116 // If a declaration acquires a function type through a
4117 // type dependent on a template-parameter and this causes
4118 // a declaration that does not use the syntactic form of a
4119 // function declarator to have a function type, the program
4120 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00004121 if (!T->isFunctionType()) {
4122 Diag(Loc, diag::err_unexpected_friend);
4123
4124 // It might be worthwhile to try to recover by creating an
4125 // appropriate declaration.
4126 return DeclPtrTy();
4127 }
4128
4129 // C++ [namespace.memdef]p3
4130 // - If a friend declaration in a non-local class first declares a
4131 // class or function, the friend class or function is a member
4132 // of the innermost enclosing namespace.
4133 // - The name of the friend is not found by simple name lookup
4134 // until a matching declaration is provided in that namespace
4135 // scope (either before or after the class declaration granting
4136 // friendship).
4137 // - If a friend function is called, its name may be found by the
4138 // name lookup that considers functions from namespaces and
4139 // classes associated with the types of the function arguments.
4140 // - When looking for a prior declaration of a class or a function
4141 // declared as a friend, scopes outside the innermost enclosing
4142 // namespace scope are not considered.
4143
John McCall02cace72009-08-28 07:59:38 +00004144 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4145 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00004146 assert(Name);
4147
4148 // The existing declaration we found.
4149 FunctionDecl *FD = NULL;
4150
4151 // The context we found the declaration in, or in which we should
4152 // create the declaration.
4153 DeclContext *DC;
4154
4155 // FIXME: handle local classes
4156
4157 // Recover from invalid scope qualifiers as if they just weren't there.
4158 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
4159 DC = computeDeclContext(ScopeQual);
4160
4161 // FIXME: handle dependent contexts
4162 if (!DC) return DeclPtrTy();
4163
4164 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
4165
4166 // If searching in that context implicitly found a declaration in
4167 // a different context, treat it like it wasn't found at all.
4168 // TODO: better diagnostics for this case. Suggesting the right
4169 // qualified scope would be nice...
4170 if (!Dec || Dec->getDeclContext() != DC) {
John McCall02cace72009-08-28 07:59:38 +00004171 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00004172 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4173 return DeclPtrTy();
4174 }
4175
4176 // C++ [class.friend]p1: A friend of a class is a function or
4177 // class that is not a member of the class . . .
4178 if (DC == CurContext)
4179 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4180
4181 FD = cast<FunctionDecl>(Dec);
4182
4183 // Otherwise walk out to the nearest namespace scope looking for matches.
4184 } else {
4185 // TODO: handle local class contexts.
4186
4187 DC = CurContext;
4188 while (true) {
4189 // Skip class contexts. If someone can cite chapter and verse
4190 // for this behavior, that would be nice --- it's what GCC and
4191 // EDG do, and it seems like a reasonable intent, but the spec
4192 // really only says that checks for unqualified existing
4193 // declarations should stop at the nearest enclosing namespace,
4194 // not that they should only consider the nearest enclosing
4195 // namespace.
4196 while (DC->isRecord()) DC = DC->getParent();
4197
4198 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
4199
4200 // TODO: decide what we think about using declarations.
4201 if (Dec) {
4202 FD = cast<FunctionDecl>(Dec);
4203 break;
4204 }
4205 if (DC->isFileContext()) break;
4206 DC = DC->getParent();
4207 }
4208
4209 // C++ [class.friend]p1: A friend of a class is a function or
4210 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00004211 // C++0x changes this for both friend types and functions.
4212 // Most C++ 98 compilers do seem to give an error here, so
4213 // we do, too.
4214 if (FD && DC == CurContext && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00004215 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4216 }
4217
John McCall3f9a8a62009-08-11 06:59:38 +00004218 bool Redeclaration = (FD != 0);
4219
4220 // If we found a match, create a friend function declaration with
4221 // that function as the previous declaration.
4222 if (Redeclaration) {
4223 // Create it in the semantic context of the original declaration.
4224 DC = FD->getDeclContext();
4225
John McCall67d1a672009-08-06 02:15:43 +00004226 // If we didn't find something matching the type exactly, create
4227 // a declaration. This declaration should only be findable via
4228 // argument-dependent lookup.
John McCall3f9a8a62009-08-11 06:59:38 +00004229 } else {
John McCall67d1a672009-08-06 02:15:43 +00004230 assert(DC->isFileContext());
4231
4232 // This implies that it has to be an operator or function.
John McCall02cace72009-08-28 07:59:38 +00004233 if (D.getKind() == Declarator::DK_Constructor ||
4234 D.getKind() == Declarator::DK_Destructor ||
4235 D.getKind() == Declarator::DK_Conversion) {
John McCall67d1a672009-08-06 02:15:43 +00004236 Diag(Loc, diag::err_introducing_special_friend) <<
John McCall02cace72009-08-28 07:59:38 +00004237 (D.getKind() == Declarator::DK_Constructor ? 0 :
4238 D.getKind() == Declarator::DK_Destructor ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00004239 return DeclPtrTy();
4240 }
John McCall67d1a672009-08-06 02:15:43 +00004241 }
4242
John McCall02cace72009-08-28 07:59:38 +00004243 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo,
John McCall3f9a8a62009-08-11 06:59:38 +00004244 /* PrevDecl = */ FD,
4245 MultiTemplateParamsArg(*this),
4246 IsDefinition,
4247 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00004248 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00004249
4250 assert(cast<FunctionDecl>(ND)->getPreviousDeclaration() == FD &&
4251 "lost reference to previous declaration");
4252
John McCall02cace72009-08-28 07:59:38 +00004253 FD = cast<FunctionDecl>(ND);
John McCall3f9a8a62009-08-11 06:59:38 +00004254
John McCall88232aa2009-08-18 00:00:49 +00004255 assert(FD->getDeclContext() == DC);
4256 assert(FD->getLexicalDeclContext() == CurContext);
4257
John McCallab88d972009-08-31 22:39:49 +00004258 // Add the function declaration to the appropriate lookup tables,
4259 // adjusting the redeclarations list as necessary. We don't
4260 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00004261 //
John McCallab88d972009-08-31 22:39:49 +00004262 // Also update the scope-based lookup if the target context's
4263 // lookup context is in lexical scope.
4264 if (!CurContext->isDependentContext()) {
4265 DC = DC->getLookupContext();
4266 DC->makeDeclVisibleInContext(FD, /* Recoverable=*/ false);
4267 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4268 PushOnScopeChains(FD, EnclosingScope, /*AddToContext=*/ false);
4269 }
John McCall02cace72009-08-28 07:59:38 +00004270
4271 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
4272 D.getIdentifierLoc(), FD,
4273 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00004274 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00004275 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00004276
4277 return DeclPtrTy::make(FD);
Anders Carlsson00338362009-05-11 22:55:49 +00004278}
4279
Chris Lattnerb28317a2009-03-28 19:18:32 +00004280void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004281 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004282
Chris Lattnerb28317a2009-03-28 19:18:32 +00004283 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00004284 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4285 if (!Fn) {
4286 Diag(DelLoc, diag::err_deleted_non_function);
4287 return;
4288 }
4289 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4290 Diag(DelLoc, diag::err_deleted_decl_not_first);
4291 Diag(Prev->getLocation(), diag::note_previous_declaration);
4292 // If the declaration wasn't the first, we delete the function anyway for
4293 // recovery.
4294 }
4295 Fn->setDeleted();
4296}
Sebastian Redl13e88542009-04-27 21:33:24 +00004297
4298static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4299 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4300 ++CI) {
4301 Stmt *SubStmt = *CI;
4302 if (!SubStmt)
4303 continue;
4304 if (isa<ReturnStmt>(SubStmt))
4305 Self.Diag(SubStmt->getSourceRange().getBegin(),
4306 diag::err_return_in_constructor_handler);
4307 if (!isa<Expr>(SubStmt))
4308 SearchForReturnInStmt(Self, SubStmt);
4309 }
4310}
4311
4312void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4313 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4314 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4315 SearchForReturnInStmt(*this, Handler);
4316 }
4317}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004318
Mike Stump1eb44332009-09-09 15:08:12 +00004319bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004320 const CXXMethodDecl *Old) {
4321 QualType NewTy = New->getType()->getAsFunctionType()->getResultType();
4322 QualType OldTy = Old->getType()->getAsFunctionType()->getResultType();
4323
4324 QualType CNewTy = Context.getCanonicalType(NewTy);
4325 QualType COldTy = Context.getCanonicalType(OldTy);
4326
Mike Stump1eb44332009-09-09 15:08:12 +00004327 if (CNewTy == COldTy &&
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004328 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
4329 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004330
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004331 // Check if the return types are covariant
4332 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004333
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004334 /// Both types must be pointers or references to classes.
4335 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4336 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4337 NewClassTy = NewPT->getPointeeType();
4338 OldClassTy = OldPT->getPointeeType();
4339 }
4340 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4341 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4342 NewClassTy = NewRT->getPointeeType();
4343 OldClassTy = OldRT->getPointeeType();
4344 }
4345 }
Mike Stump1eb44332009-09-09 15:08:12 +00004346
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004347 // The return types aren't either both pointers or references to a class type.
4348 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004349 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004350 diag::err_different_return_type_for_overriding_virtual_function)
4351 << New->getDeclName() << NewTy << OldTy;
4352 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00004353
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004354 return true;
4355 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004356
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004357 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
4358 // Check if the new class derives from the old class.
4359 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4360 Diag(New->getLocation(),
4361 diag::err_covariant_return_not_derived)
4362 << New->getDeclName() << NewTy << OldTy;
4363 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4364 return true;
4365 }
Mike Stump1eb44332009-09-09 15:08:12 +00004366
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004367 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00004368 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004369 diag::err_covariant_return_inaccessible_base,
4370 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4371 // FIXME: Should this point to the return type?
4372 New->getLocation(), SourceRange(), New->getDeclName())) {
4373 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4374 return true;
4375 }
4376 }
Mike Stump1eb44332009-09-09 15:08:12 +00004377
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004378 // The qualifiers of the return types must be the same.
4379 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
4380 Diag(New->getLocation(),
4381 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004382 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004383 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4384 return true;
4385 };
Mike Stump1eb44332009-09-09 15:08:12 +00004386
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004387
4388 // The new class type must have the same or less qualifiers as the old type.
4389 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4390 Diag(New->getLocation(),
4391 diag::err_covariant_return_type_class_type_more_qualified)
4392 << New->getDeclName() << NewTy << OldTy;
4393 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4394 return true;
4395 };
Mike Stump1eb44332009-09-09 15:08:12 +00004396
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004397 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004398}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004399
Sebastian Redl23c7d062009-07-07 20:29:57 +00004400bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
Mike Stump1eb44332009-09-09 15:08:12 +00004401 const CXXMethodDecl *Old) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00004402 return CheckExceptionSpecSubset(diag::err_override_exception_spec,
4403 diag::note_overridden_virtual_function,
4404 Old->getType()->getAsFunctionProtoType(),
4405 Old->getLocation(),
4406 New->getType()->getAsFunctionProtoType(),
4407 New->getLocation());
4408}
4409
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004410/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4411/// initializer for the declaration 'Dcl'.
4412/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4413/// static data member of class X, names should be looked up in the scope of
4414/// class X.
4415void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004416 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004417
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004418 Decl *D = Dcl.getAs<Decl>();
4419 // If there is no declaration, there was an error parsing it.
4420 if (D == 0)
4421 return;
4422
4423 // Check whether it is a declaration with a nested name specifier like
4424 // int foo::bar;
4425 if (!D->isOutOfLine())
4426 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004427
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004428 // C++ [basic.lookup.unqual]p13
4429 //
4430 // A name used in the definition of a static data member of class X
4431 // (after the qualified-id of the static member) is looked up as if the name
4432 // was used in a member function of X.
Mike Stump1eb44332009-09-09 15:08:12 +00004433
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004434 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004435 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004436}
4437
4438/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4439/// initializer for the declaration 'Dcl'.
4440void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004441 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004442
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004443 Decl *D = Dcl.getAs<Decl>();
4444 // If there is no declaration, there was an error parsing it.
4445 if (D == 0)
4446 return;
4447
4448 // Check whether it is a declaration with a nested name specifier like
4449 // int foo::bar;
4450 if (!D->isOutOfLine())
4451 return;
4452
4453 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004454 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004455}