blob: b3cef85d679d7631d0687e5bdb33f8c9b0bebde6 [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:
244 //
245 // For non-template functions, default arguments can be added in
246 // later declarations of a function in the same
247 // scope. Declarations in different scopes have completely
248 // distinct sets of default arguments. That is, declarations in
249 // inner scopes do not acquire default arguments from
250 // declarations in outer scopes, and vice versa. In a given
251 // function declaration, all parameters subsequent to a
252 // parameter with a default argument shall have default
253 // arguments supplied in this or previous declarations. A
254 // default argument shall not be redefined by a later
255 // declaration (not even to the same value).
256 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
257 ParmVarDecl *OldParam = Old->getParamDecl(p);
258 ParmVarDecl *NewParam = New->getParamDecl(p);
259
Mike Stump1eb44332009-09-09 15:08:12 +0000260 if (OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
261 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000262 diag::err_param_default_argument_redefinition)
263 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000264 Diag(OldParam->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000265 Invalid = true;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000266 } else if (OldParam->getDefaultArg()) {
267 // Merge the old default argument into the new parameter
268 NewParam->setDefaultArg(OldParam->getDefaultArg());
269 }
270 }
271
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000272 if (CheckEquivalentExceptionSpec(
273 Old->getType()->getAsFunctionProtoType(), Old->getLocation(),
274 New->getType()->getAsFunctionProtoType(), New->getLocation())) {
275 Invalid = true;
276 }
277
Douglas Gregorcda9c672009-02-16 17:45:42 +0000278 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000279}
280
281/// CheckCXXDefaultArguments - Verify that the default arguments for a
282/// function declaration are well-formed according to C++
283/// [dcl.fct.default].
284void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
285 unsigned NumParams = FD->getNumParams();
286 unsigned p;
287
288 // Find first parameter with a default argument
289 for (p = 0; p < NumParams; ++p) {
290 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000291 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000292 break;
293 }
294
295 // C++ [dcl.fct.default]p4:
296 // In a given function declaration, all parameters
297 // subsequent to a parameter with a default argument shall
298 // have default arguments supplied in this or previous
299 // declarations. A default argument shall not be redefined
300 // by a later declaration (not even to the same value).
301 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000302 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000303 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000304 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000305 if (Param->isInvalidDecl())
306 /* We already complained about this parameter. */;
307 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000308 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000309 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000310 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000311 else
Mike Stump1eb44332009-09-09 15:08:12 +0000312 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000313 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Chris Lattner3d1cee32008-04-08 05:04:30 +0000315 LastMissingDefaultArg = p;
316 }
317 }
318
319 if (LastMissingDefaultArg > 0) {
320 // Some default arguments were missing. Clear out all of the
321 // default arguments up to (and including) the last missing
322 // default argument, so that we leave the function parameters
323 // in a semantically valid state.
324 for (p = 0; p <= LastMissingDefaultArg; ++p) {
325 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000326 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000327 if (!Param->hasUnparsedDefaultArg())
328 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000329 Param->setDefaultArg(0);
330 }
331 }
332 }
333}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000334
Douglas Gregorb48fe382008-10-31 09:07:45 +0000335/// isCurrentClassName - Determine whether the identifier II is the
336/// name of the class type currently being defined. In the case of
337/// nested classes, this will only return true if II is the name of
338/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000339bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
340 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000341 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000342 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000343 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000344 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
345 } else
346 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
347
348 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000349 return &II == CurDecl->getIdentifier();
350 else
351 return false;
352}
353
Mike Stump1eb44332009-09-09 15:08:12 +0000354/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000355///
356/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
357/// and returns NULL otherwise.
358CXXBaseSpecifier *
359Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
360 SourceRange SpecifierRange,
361 bool Virtual, AccessSpecifier Access,
Mike Stump1eb44332009-09-09 15:08:12 +0000362 QualType BaseType,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000363 SourceLocation BaseLoc) {
364 // C++ [class.union]p1:
365 // A union shall not have base classes.
366 if (Class->isUnion()) {
367 Diag(Class->getLocation(), diag::err_base_clause_on_union)
368 << SpecifierRange;
369 return 0;
370 }
371
372 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +0000373 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000374 Class->getTagKind() == RecordDecl::TK_class,
375 Access, BaseType);
376
377 // Base specifiers must be record types.
378 if (!BaseType->isRecordType()) {
379 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
380 return 0;
381 }
382
383 // C++ [class.union]p1:
384 // A union shall not be used as a base class.
385 if (BaseType->isUnionType()) {
386 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
387 return 0;
388 }
389
390 // C++ [class.derived]p2:
391 // The class-name in a base-specifier shall not be an incompletely
392 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +0000393 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000394 PDiag(diag::err_incomplete_base_class)
395 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000396 return 0;
397
Eli Friedman1d954f62009-08-15 21:55:26 +0000398 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000399 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000400 assert(BaseDecl && "Record type has no declaration");
401 BaseDecl = BaseDecl->getDefinition(Context);
402 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000403 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
404 assert(CXXBaseDecl && "Base type is not a C++ type");
405 if (!CXXBaseDecl->isEmpty())
406 Class->setEmpty(false);
407 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor2943aed2009-03-03 04:44:36 +0000408 Class->setPolymorphic(true);
409
410 // C++ [dcl.init.aggr]p1:
411 // An aggregate is [...] a class with [...] no base classes [...].
412 Class->setAggregate(false);
413 Class->setPOD(false);
414
Anders Carlsson347ba892009-04-16 00:08:20 +0000415 if (Virtual) {
416 // C++ [class.ctor]p5:
417 // A constructor is trivial if its class has no virtual base classes.
418 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000419
420 // C++ [class.copy]p6:
421 // A copy constructor is trivial if its class has no virtual base classes.
422 Class->setHasTrivialCopyConstructor(false);
423
424 // C++ [class.copy]p11:
425 // A copy assignment operator is trivial if its class has no virtual
426 // base classes.
427 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000428
429 // C++0x [meta.unary.prop] is_empty:
430 // T is a class type, but not a union type, with ... no virtual base
431 // classes
432 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000433 } else {
434 // C++ [class.ctor]p5:
Mike Stump1eb44332009-09-09 15:08:12 +0000435 // A constructor is trivial if all the direct base classes of its
Anders Carlsson347ba892009-04-16 00:08:20 +0000436 // class have trivial constructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000437 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
438 Class->setHasTrivialConstructor(false);
439
440 // C++ [class.copy]p6:
441 // A copy constructor is trivial if all the direct base classes of its
442 // class have trivial copy constructors.
443 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
444 Class->setHasTrivialCopyConstructor(false);
445
446 // C++ [class.copy]p11:
447 // A copy assignment operator is trivial if all the direct base classes
448 // of its class have trivial copy assignment operators.
449 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
450 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000451 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000452
453 // C++ [class.ctor]p3:
454 // A destructor is trivial if all the direct base classes of its class
455 // have trivial destructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000456 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
457 Class->setHasTrivialDestructor(false);
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Douglas Gregor2943aed2009-03-03 04:44:36 +0000459 // Create the base specifier.
460 // FIXME: Allocate via ASTContext?
Mike Stump1eb44332009-09-09 15:08:12 +0000461 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
462 Class->getTagKind() == RecordDecl::TK_class,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000463 Access, BaseType);
464}
465
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000466/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
467/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +0000468/// example:
469/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000470/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump1eb44332009-09-09 15:08:12 +0000471Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000472Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000473 bool Virtual, AccessSpecifier Access,
474 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000475 if (!classdecl)
476 return true;
477
Douglas Gregor40808ce2009-03-09 23:48:35 +0000478 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000479 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000480 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000481 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
482 Virtual, Access,
483 BaseType, BaseLoc))
484 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Douglas Gregor2943aed2009-03-03 04:44:36 +0000486 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000487}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000488
Douglas Gregor2943aed2009-03-03 04:44:36 +0000489/// \brief Performs the actual work of attaching the given base class
490/// specifiers to a C++ class.
491bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
492 unsigned NumBases) {
493 if (NumBases == 0)
494 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000495
496 // Used to keep track of which base types we have already seen, so
497 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000498 // that the key is always the unqualified canonical type of the base
499 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000500 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
501
502 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000503 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000504 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000505 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +0000506 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000507 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor57c856b2008-10-23 18:13:27 +0000508 NewBaseType = NewBaseType.getUnqualifiedType();
509
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000510 if (KnownBaseTypes[NewBaseType]) {
511 // C++ [class.mi]p3:
512 // A class shall not be specified as a direct base class of a
513 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000514 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000515 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000516 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000517 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000518
519 // Delete the duplicate base class specifier; we're going to
520 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000521 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000522
523 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000524 } else {
525 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000526 KnownBaseTypes[NewBaseType] = Bases[idx];
527 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000528 }
529 }
530
531 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000532 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000533
534 // Delete the remaining (good) base class specifiers, since their
535 // data has been copied into the CXXRecordDecl.
536 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000537 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000538
539 return Invalid;
540}
541
542/// ActOnBaseSpecifiers - Attach the given base specifiers to the
543/// class, after checking whether there are any duplicate base
544/// classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000545void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000546 unsigned NumBases) {
547 if (!ClassDecl || !Bases || !NumBases)
548 return;
549
550 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000551 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000552 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000553}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000554
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000555//===----------------------------------------------------------------------===//
556// C++ class member Handling
557//===----------------------------------------------------------------------===//
558
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000559/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
560/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
561/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000562/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000563Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000564Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000565 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redle2b68332009-04-12 17:16:29 +0000566 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000567 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000568 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000569 Expr *BitWidth = static_cast<Expr*>(BW);
570 Expr *Init = static_cast<Expr*>(InitExpr);
571 SourceLocation Loc = D.getIdentifierLoc();
572
Sebastian Redl669d5d72008-11-14 23:42:31 +0000573 bool isFunc = D.isFunctionDeclarator();
574
John McCall67d1a672009-08-06 02:15:43 +0000575 assert(!DS.isFriendSpecified());
576
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000577 // C++ 9.2p6: A member shall not be declared to have automatic storage
578 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000579 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
580 // data members and cannot be applied to names declared const or static,
581 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000582 switch (DS.getStorageClassSpec()) {
583 case DeclSpec::SCS_unspecified:
584 case DeclSpec::SCS_typedef:
585 case DeclSpec::SCS_static:
586 // FALL THROUGH.
587 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000588 case DeclSpec::SCS_mutable:
589 if (isFunc) {
590 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000591 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000592 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000593 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +0000594
Sebastian Redla11f42f2008-11-17 23:24:37 +0000595 // FIXME: It would be nicer if the keyword was ignored only for this
596 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000597 D.getMutableDeclSpec().ClearStorageClassSpecs();
598 } else {
599 QualType T = GetTypeForDeclarator(D, S);
600 diag::kind err = static_cast<diag::kind>(0);
601 if (T->isReferenceType())
602 err = diag::err_mutable_reference;
603 else if (T.isConstQualified())
604 err = diag::err_mutable_const;
605 if (err != 0) {
606 if (DS.getStorageClassSpecLoc().isValid())
607 Diag(DS.getStorageClassSpecLoc(), err);
608 else
609 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000610 // FIXME: It would be nicer if the keyword was ignored only for this
611 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000612 D.getMutableDeclSpec().ClearStorageClassSpecs();
613 }
614 }
615 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000616 default:
617 if (DS.getStorageClassSpecLoc().isValid())
618 Diag(DS.getStorageClassSpecLoc(),
619 diag::err_storageclass_invalid_for_member);
620 else
621 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
622 D.getMutableDeclSpec().ClearStorageClassSpecs();
623 }
624
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000625 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000626 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000627 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000628 // Check also for this case:
629 //
630 // typedef int f();
631 // f a;
632 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000633 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000634 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000635 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000636
Sebastian Redl669d5d72008-11-14 23:42:31 +0000637 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
638 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000639 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000640
641 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000642 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000643 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000644 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
645 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000646 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000647 } else {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000648 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
649 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000650 if (!Member) {
651 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000652 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000653 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000654
655 // Non-instance-fields can't have a bitfield.
656 if (BitWidth) {
657 if (Member->isInvalidDecl()) {
658 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000659 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000660 // C++ 9.6p3: A bit-field shall not be a static member.
661 // "static member 'A' cannot be a bit-field"
662 Diag(Loc, diag::err_static_not_bitfield)
663 << Name << BitWidth->getSourceRange();
664 } else if (isa<TypedefDecl>(Member)) {
665 // "typedef member 'x' cannot be a bit-field"
666 Diag(Loc, diag::err_typedef_not_bitfield)
667 << Name << BitWidth->getSourceRange();
668 } else {
669 // A function typedef ("typedef int f(); f a;").
670 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
671 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +0000672 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000673 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000674 }
Mike Stump1eb44332009-09-09 15:08:12 +0000675
Chris Lattner8b963ef2009-03-05 23:01:03 +0000676 DeleteExpr(BitWidth);
677 BitWidth = 0;
678 Member->setInvalidDecl();
679 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000680
681 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Douglas Gregor37b372b2009-08-20 22:52:58 +0000683 // If we have declared a member function template, set the access of the
684 // templated declaration as well.
685 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
686 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000687 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000688
Douglas Gregor10bd3682008-11-17 22:58:34 +0000689 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000690
Douglas Gregor021c3b32009-03-11 23:00:04 +0000691 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000692 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000693 if (Deleted) // FIXME: Source location is not very good.
694 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000695
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000696 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000697 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000698 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000699 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000700 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000701}
702
Douglas Gregor7ad83902008-11-05 04:29:56 +0000703/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump1eb44332009-09-09 15:08:12 +0000704Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000705Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000706 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000707 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000708 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000709 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000710 SourceLocation IdLoc,
711 SourceLocation LParenLoc,
712 ExprTy **Args, unsigned NumArgs,
713 SourceLocation *CommaLocs,
714 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000715 if (!ConstructorD)
716 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000718 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +0000719
720 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000721 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000722 if (!Constructor) {
723 // The user wrote a constructor initializer on a function that is
724 // not a C++ constructor. Ignore the error for now, because we may
725 // have more member initializers coming; we'll diagnose it just
726 // once in ActOnMemInitializers.
727 return true;
728 }
729
730 CXXRecordDecl *ClassDecl = Constructor->getParent();
731
732 // C++ [class.base.init]p2:
733 // Names in a mem-initializer-id are looked up in the scope of the
734 // constructor’s class and, if not found in that scope, are looked
735 // up in the scope containing the constructor’s
736 // definition. [Note: if the constructor’s class contains a member
737 // with the same name as a direct or virtual base class of the
738 // class, a mem-initializer-id naming the member or base class and
739 // composed of a single identifier refers to the class member. A
740 // mem-initializer-id for the hidden base class may be specified
741 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000742 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000743 // Look for a member, first.
744 FieldDecl *Member = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000745 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000746 = ClassDecl->lookup(MemberOrBase);
747 if (Result.first != Result.second)
748 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000749
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000750 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000751
Eli Friedman59c04372009-07-29 19:44:27 +0000752 if (Member)
753 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
754 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000755 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000756 // It didn't name a member, so see if it names a class.
Mike Stump1eb44332009-09-09 15:08:12 +0000757 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
Fariborz Jahanian96174332009-07-01 19:21:19 +0000758 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000759 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000760 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
761 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000763 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000764
Eli Friedman59c04372009-07-29 19:44:27 +0000765 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
766 RParenLoc, ClassDecl);
767}
768
769Sema::MemInitResult
770Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
771 unsigned NumArgs, SourceLocation IdLoc,
772 SourceLocation RParenLoc) {
773 bool HasDependentArg = false;
774 for (unsigned i = 0; i < NumArgs; i++)
775 HasDependentArg |= Args[i]->isTypeDependent();
776
777 CXXConstructorDecl *C = 0;
778 QualType FieldType = Member->getType();
779 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
780 FieldType = Array->getElementType();
781 if (FieldType->isDependentType()) {
782 // Can't check init for dependent type.
Ted Kremenek6217b802009-07-29 21:53:49 +0000783 } else if (FieldType->getAs<RecordType>()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +0000784 if (!HasDependentArg) {
785 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
786
787 C = PerformInitializationByConstructor(FieldType,
788 MultiExprArg(*this,
789 (void**)Args,
790 NumArgs),
791 IdLoc,
792 SourceRange(IdLoc, RParenLoc),
793 Member->getDeclName(), IK_Direct,
794 ConstructorArgs);
795
796 if (C) {
797 // Take over the constructor arguments as our own.
798 NumArgs = ConstructorArgs.size();
799 Args = (Expr **)ConstructorArgs.take();
800 }
801 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +0000802 } else if (NumArgs != 1 && NumArgs != 0) {
Mike Stump1eb44332009-09-09 15:08:12 +0000803 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +0000804 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
805 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +0000806 Expr *NewExp;
807 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000808 if (FieldType->isReferenceType()) {
809 Diag(IdLoc, diag::err_null_intialized_reference_member)
810 << Member->getDeclName();
811 return Diag(Member->getLocation(), diag::note_declared_at);
812 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +0000813 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
814 NumArgs = 1;
815 }
816 else
817 NewExp = (Expr*)Args[0];
Eli Friedman59c04372009-07-29 19:44:27 +0000818 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
819 return true;
820 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +0000821 }
Eli Friedman59c04372009-07-29 19:44:27 +0000822 // FIXME: Perform direct initialization of the member.
Mike Stump1eb44332009-09-09 15:08:12 +0000823 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +0000824 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +0000825}
826
827Sema::MemInitResult
828Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
829 unsigned NumArgs, SourceLocation IdLoc,
830 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
831 bool HasDependentArg = false;
832 for (unsigned i = 0; i < NumArgs; i++)
833 HasDependentArg |= Args[i]->isTypeDependent();
834
835 if (!BaseType->isDependentType()) {
836 if (!BaseType->isRecordType())
837 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
838 << BaseType << SourceRange(IdLoc, RParenLoc);
839
840 // C++ [class.base.init]p2:
841 // [...] Unless the mem-initializer-id names a nonstatic data
842 // member of the constructor’s class or a direct or virtual base
843 // of that class, the mem-initializer is ill-formed. A
844 // mem-initializer-list can initialize a base class using any
845 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +0000846
Eli Friedman59c04372009-07-29 19:44:27 +0000847 // First, check for a direct base class.
848 const CXXBaseSpecifier *DirectBaseSpec = 0;
849 for (CXXRecordDecl::base_class_const_iterator Base =
850 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +0000851 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
Eli Friedman59c04372009-07-29 19:44:27 +0000852 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
853 // We found a direct base of this type. That's what we're
854 // initializing.
855 DirectBaseSpec = &*Base;
856 break;
857 }
858 }
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Eli Friedman59c04372009-07-29 19:44:27 +0000860 // Check for a virtual base class.
861 // FIXME: We might be able to short-circuit this if we know in advance that
862 // there are no virtual bases.
863 const CXXBaseSpecifier *VirtualBaseSpec = 0;
864 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
865 // We haven't found a base yet; search the class hierarchy for a
866 // virtual base class.
867 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
868 /*DetectVirtual=*/false);
869 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000870 for (BasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +0000871 Path != Paths.end(); ++Path) {
872 if (Path->back().Base->isVirtual()) {
873 VirtualBaseSpec = Path->back().Base;
874 break;
875 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000876 }
877 }
878 }
Eli Friedman59c04372009-07-29 19:44:27 +0000879
880 // C++ [base.class.init]p2:
881 // If a mem-initializer-id is ambiguous because it designates both
882 // a direct non-virtual base class and an inherited virtual base
883 // class, the mem-initializer is ill-formed.
884 if (DirectBaseSpec && VirtualBaseSpec)
885 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
886 << BaseType << SourceRange(IdLoc, RParenLoc);
887 // C++ [base.class.init]p2:
888 // Unless the mem-initializer-id names a nonstatic data membeer of the
889 // constructor's class ot a direst or virtual base of that class, the
890 // mem-initializer is ill-formed.
891 if (!DirectBaseSpec && !VirtualBaseSpec)
892 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
893 << BaseType << ClassDecl->getNameAsCString()
894 << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000895 }
896
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +0000897 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +0000898 if (!BaseType->isDependentType() && !HasDependentArg) {
899 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
900 Context.getCanonicalType(BaseType));
Douglas Gregor39da0b82009-09-09 23:08:42 +0000901 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
902
903 C = PerformInitializationByConstructor(BaseType,
904 MultiExprArg(*this,
905 (void**)Args, NumArgs),
Mike Stump1eb44332009-09-09 15:08:12 +0000906 IdLoc, SourceRange(IdLoc, RParenLoc),
Douglas Gregor39da0b82009-09-09 23:08:42 +0000907 Name, IK_Direct,
908 ConstructorArgs);
909 if (C) {
910 // Take over the constructor arguments as our own.
911 NumArgs = ConstructorArgs.size();
912 Args = (Expr **)ConstructorArgs.take();
913 }
Eli Friedman59c04372009-07-29 19:44:27 +0000914 }
915
Mike Stump1eb44332009-09-09 15:08:12 +0000916 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +0000917 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000918}
919
Fariborz Jahanian87595e42009-07-23 23:32:59 +0000920void
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000921Sema::setBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
922 CXXBaseOrMemberInitializer **Initializers,
923 unsigned NumInitializers,
Mike Stump1eb44332009-09-09 15:08:12 +0000924 llvm::SmallVectorImpl<CXXBaseSpecifier *>& Bases,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000925 llvm::SmallVectorImpl<FieldDecl *>&Fields) {
926 // We need to build the initializer AST according to order of construction
927 // and not what user specified in the Initializers list.
928 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
929 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
930 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
931 bool HasDependentBaseInit = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000933 for (unsigned i = 0; i < NumInitializers; i++) {
934 CXXBaseOrMemberInitializer *Member = Initializers[i];
935 if (Member->isBaseInitializer()) {
936 if (Member->getBaseClass()->isDependentType())
937 HasDependentBaseInit = true;
938 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
939 } else {
940 AllBaseFields[Member->getMember()] = Member;
941 }
942 }
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000944 if (HasDependentBaseInit) {
945 // FIXME. This does not preserve the ordering of the initializers.
946 // Try (with -Wreorder)
947 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +0000948 // template<class X> struct B : A<X> {
949 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000950 // int x1;
951 // };
952 // B<int> x;
953 // On seeing one dependent type, we should essentially exit this routine
954 // while preserving user-declared initializer list. When this routine is
955 // called during instantiatiation process, this routine will rebuild the
956 // oderdered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000958 // If we have a dependent base initialization, we can't determine the
959 // association between initializers and bases; just dump the known
960 // initializers into the list, and don't try to deal with other bases.
961 for (unsigned i = 0; i < NumInitializers; i++) {
962 CXXBaseOrMemberInitializer *Member = Initializers[i];
963 if (Member->isBaseInitializer())
964 AllToInit.push_back(Member);
965 }
966 } else {
967 // Push virtual bases before others.
968 for (CXXRecordDecl::base_class_iterator VBase =
969 ClassDecl->vbases_begin(),
970 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
971 if (VBase->getType()->isDependentType())
972 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000973 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +0000974 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000975 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +0000976 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
977 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
978 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
979 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000980 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +0000981 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000982 else {
Mike Stump1eb44332009-09-09 15:08:12 +0000983 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000984 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
985 assert(VBaseDecl && "setBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +0000986 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
987 if (!Ctor)
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000988 Bases.push_back(VBase);
Fariborz Jahanian9d436202009-09-03 21:32:41 +0000989 else
990 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
991
Mike Stump1eb44332009-09-09 15:08:12 +0000992 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000993 new (Context) CXXBaseOrMemberInitializer(VBase->getType(), 0, 0,
Fariborz Jahanian9d436202009-09-03 21:32:41 +0000994 Ctor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000995 SourceLocation(),
996 SourceLocation());
997 AllToInit.push_back(Member);
998 }
999 }
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001001 for (CXXRecordDecl::base_class_iterator Base =
1002 ClassDecl->bases_begin(),
1003 E = ClassDecl->bases_end(); Base != E; ++Base) {
1004 // Virtuals are in the virtual base list and already constructed.
1005 if (Base->isVirtual())
1006 continue;
1007 // Skip dependent types.
1008 if (Base->getType()->isDependentType())
1009 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001010 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001011 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001012 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001013 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1014 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
1015 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
1016 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001017 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001018 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001019 else {
Mike Stump1eb44332009-09-09 15:08:12 +00001020 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001021 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001022 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001023 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
1024 if (!Ctor)
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001025 Bases.push_back(Base);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001026 else
1027 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1028
Mike Stump1eb44332009-09-09 15:08:12 +00001029 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001030 new (Context) CXXBaseOrMemberInitializer(Base->getType(), 0, 0,
1031 BaseDecl->getDefaultConstructor(Context),
1032 SourceLocation(),
1033 SourceLocation());
1034 AllToInit.push_back(Member);
1035 }
1036 }
1037 }
Mike Stump1eb44332009-09-09 15:08:12 +00001038
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001039 // non-static data members.
1040 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1041 E = ClassDecl->field_end(); Field != E; ++Field) {
1042 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001043 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001044 Field->getType()->getAs<RecordType>()) {
1045 CXXRecordDecl *FieldClassDecl
1046 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001047 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001048 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1049 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1050 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1051 // set to the anonymous union data member used in the initializer
1052 // list.
1053 Value->setMember(*Field);
1054 Value->setAnonUnionMember(*FA);
1055 AllToInit.push_back(Value);
1056 break;
1057 }
1058 }
1059 }
1060 continue;
1061 }
1062 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001063 QualType FT = (*Field)->getType();
1064 if (const RecordType* RT = FT->getAs<RecordType>()) {
1065 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl());
1066 assert(FieldRecDecl && "setBaseOrMemberInitializers - BaseDecl null");
Mike Stump1eb44332009-09-09 15:08:12 +00001067 if (CXXConstructorDecl *Ctor =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001068 FieldRecDecl->getDefaultConstructor(Context))
1069 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
1070 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001071 AllToInit.push_back(Value);
1072 continue;
1073 }
Mike Stump1eb44332009-09-09 15:08:12 +00001074
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001075 QualType FT = Context.getBaseElementType((*Field)->getType());
1076 if (const RecordType* RT = FT->getAs<RecordType>()) {
1077 CXXConstructorDecl *Ctor =
1078 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
1079 if (!Ctor && !FT->isDependentType())
1080 Fields.push_back(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001081 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001082 new (Context) CXXBaseOrMemberInitializer((*Field), 0, 0,
1083 Ctor,
1084 SourceLocation(),
1085 SourceLocation());
1086 AllToInit.push_back(Member);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001087 if (Ctor)
1088 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001089 if (FT.isConstQualified() && (!Ctor || Ctor->isTrivial())) {
1090 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1091 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1092 Diag((*Field)->getLocation(), diag::note_declared_at);
1093 }
1094 }
1095 else if (FT->isReferenceType()) {
1096 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1097 << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getDeclName();
1098 Diag((*Field)->getLocation(), diag::note_declared_at);
1099 }
1100 else if (FT.isConstQualified()) {
1101 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1102 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1103 Diag((*Field)->getLocation(), diag::note_declared_at);
1104 }
1105 }
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001107 NumInitializers = AllToInit.size();
1108 if (NumInitializers > 0) {
1109 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1110 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1111 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001113 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1114 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1115 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1116 }
1117}
1118
1119void
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001120Sema::BuildBaseOrMemberInitializers(ASTContext &C,
1121 CXXConstructorDecl *Constructor,
1122 CXXBaseOrMemberInitializer **Initializers,
1123 unsigned NumInitializers
1124 ) {
1125 llvm::SmallVector<CXXBaseSpecifier *, 4>Bases;
1126 llvm::SmallVector<FieldDecl *, 4>Members;
Mike Stump1eb44332009-09-09 15:08:12 +00001127
1128 setBaseOrMemberInitializers(Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001129 Initializers, NumInitializers, Bases, Members);
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001130 for (unsigned int i = 0; i < Bases.size(); i++)
Mike Stump1eb44332009-09-09 15:08:12 +00001131 Diag(Bases[i]->getSourceRange().getBegin(),
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001132 diag::err_missing_default_constructor) << 0 << Bases[i]->getType();
1133 for (unsigned int i = 0; i < Members.size(); i++)
Mike Stump1eb44332009-09-09 15:08:12 +00001134 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor)
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001135 << 1 << Members[i]->getType();
1136}
1137
Eli Friedman6347f422009-07-21 19:28:10 +00001138static void *GetKeyForTopLevelField(FieldDecl *Field) {
1139 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001140 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001141 if (RT->getDecl()->isAnonymousStructOrUnion())
1142 return static_cast<void *>(RT->getDecl());
1143 }
1144 return static_cast<void *>(Field);
1145}
1146
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001147static void *GetKeyForBase(QualType BaseType) {
1148 if (const RecordType *RT = BaseType->getAs<RecordType>())
1149 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001151 assert(0 && "Unexpected base type!");
1152 return 0;
1153}
1154
Mike Stump1eb44332009-09-09 15:08:12 +00001155static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001156 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001157 // For fields injected into the class via declaration of an anonymous union,
1158 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001159 if (Member->isMemberInitializer()) {
1160 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001162 // After BuildBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001163 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001164 // in AnonUnionMember field.
1165 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1166 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001167 if (Field->getDeclContext()->isRecord()) {
1168 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1169 if (RD->isAnonymousStructOrUnion())
1170 return static_cast<void *>(RD);
1171 }
1172 return static_cast<void *>(Field);
1173 }
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001175 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001176}
1177
Mike Stump1eb44332009-09-09 15:08:12 +00001178void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001179 SourceLocation ColonLoc,
1180 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001181 if (!ConstructorDecl)
1182 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001183
1184 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001185
1186 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001187 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Anders Carlssona7b35212009-03-25 02:58:17 +00001189 if (!Constructor) {
1190 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1191 return;
1192 }
Mike Stump1eb44332009-09-09 15:08:12 +00001193
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001194 if (!Constructor->isDependentContext()) {
1195 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1196 bool err = false;
1197 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001198 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001199 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1200 void *KeyToMember = GetKeyForMember(Member);
1201 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1202 if (!PrevMember) {
1203 PrevMember = Member;
1204 continue;
1205 }
1206 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001207 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001208 diag::error_multiple_mem_initialization)
1209 << Field->getNameAsString();
1210 else {
1211 Type *BaseClass = Member->getBaseClass();
1212 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001213 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001214 diag::error_multiple_base_initialization)
1215 << BaseClass->getDesugaredType(true);
1216 }
1217 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1218 << 0;
1219 err = true;
1220 }
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001222 if (err)
1223 return;
1224 }
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001226 BuildBaseOrMemberInitializers(Context, Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001227 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001228 NumMemInits);
Mike Stump1eb44332009-09-09 15:08:12 +00001229
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001230 if (Constructor->isDependentContext())
1231 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001232
1233 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001234 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001235 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001236 Diagnostic::Ignored)
1237 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001239 // Also issue warning if order of ctor-initializer list does not match order
1240 // of 1) base class declarations and 2) order of non-static data members.
1241 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001242
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001243 CXXRecordDecl *ClassDecl
1244 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1245 // Push virtual bases before others.
1246 for (CXXRecordDecl::base_class_iterator VBase =
1247 ClassDecl->vbases_begin(),
1248 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001249 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001250
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001251 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1252 E = ClassDecl->bases_end(); Base != E; ++Base) {
1253 // Virtuals are alread in the virtual base list and are constructed
1254 // first.
1255 if (Base->isVirtual())
1256 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001257 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001258 }
Mike Stump1eb44332009-09-09 15:08:12 +00001259
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001260 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1261 E = ClassDecl->field_end(); Field != E; ++Field)
1262 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001264 int Last = AllBaseOrMembers.size();
1265 int curIndex = 0;
1266 CXXBaseOrMemberInitializer *PrevMember = 0;
1267 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001268 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001269 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1270 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001271
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001272 for (; curIndex < Last; curIndex++)
1273 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1274 break;
1275 if (curIndex == Last) {
1276 assert(PrevMember && "Member not in member list?!");
1277 // Initializer as specified in ctor-initializer list is out of order.
1278 // Issue a warning diagnostic.
1279 if (PrevMember->isBaseInitializer()) {
1280 // Diagnostics is for an initialized base class.
1281 Type *BaseClass = PrevMember->getBaseClass();
1282 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001283 diag::warn_base_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001284 << BaseClass->getDesugaredType(true);
1285 } else {
1286 FieldDecl *Field = PrevMember->getMember();
1287 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001288 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001289 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001290 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001291 // Also the note!
1292 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001293 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001294 diag::note_fieldorbase_initialized_here) << 0
1295 << Field->getNameAsString();
1296 else {
1297 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001298 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001299 diag::note_fieldorbase_initialized_here) << 1
1300 << BaseClass->getDesugaredType(true);
1301 }
1302 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001303 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001304 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001305 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001306 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001307 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001308}
1309
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001310void
1311Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) {
1312 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext());
1313 llvm::SmallVector<uintptr_t, 32> AllToDestruct;
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001315 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1316 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1317 if (VBase->getType()->isDependentType())
1318 continue;
1319 // Skip over virtual bases which have trivial destructors.
1320 CXXRecordDecl *BaseClassDecl
1321 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1322 if (BaseClassDecl->hasTrivialDestructor())
1323 continue;
1324 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001325 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001326 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001327
1328 uintptr_t Member =
1329 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001330 | CXXDestructorDecl::VBASE;
1331 AllToDestruct.push_back(Member);
1332 }
1333 for (CXXRecordDecl::base_class_iterator Base =
1334 ClassDecl->bases_begin(),
1335 E = ClassDecl->bases_end(); Base != E; ++Base) {
1336 if (Base->isVirtual())
1337 continue;
1338 if (Base->getType()->isDependentType())
1339 continue;
1340 // Skip over virtual bases which have trivial destructors.
1341 CXXRecordDecl *BaseClassDecl
1342 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1343 if (BaseClassDecl->hasTrivialDestructor())
1344 continue;
1345 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001346 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001347 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001348 uintptr_t Member =
1349 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001350 | CXXDestructorDecl::DRCTNONVBASE;
1351 AllToDestruct.push_back(Member);
1352 }
Mike Stump1eb44332009-09-09 15:08:12 +00001353
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001354 // non-static data members.
1355 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1356 E = ClassDecl->field_end(); Field != E; ++Field) {
1357 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001358
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001359 if (const RecordType* RT = FieldType->getAs<RecordType>()) {
1360 // Skip over virtual bases which have trivial destructors.
1361 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1362 if (FieldClassDecl->hasTrivialDestructor())
1363 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001364 if (const CXXDestructorDecl *Dtor =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001365 FieldClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001366 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001367 const_cast<CXXDestructorDecl*>(Dtor));
1368 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field);
1369 AllToDestruct.push_back(Member);
1370 }
1371 }
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001373 unsigned NumDestructions = AllToDestruct.size();
1374 if (NumDestructions > 0) {
1375 Destructor->setNumBaseOrMemberDestructions(NumDestructions);
Mike Stump1eb44332009-09-09 15:08:12 +00001376 uintptr_t *BaseOrMemberDestructions =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001377 new (Context) uintptr_t [NumDestructions];
1378 // Insert in reverse order.
1379 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx)
1380 BaseOrMemberDestructions[i++] = AllToDestruct[Idx];
1381 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions);
1382 }
1383}
1384
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001385void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001386 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001387 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001389 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001390
1391 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001392 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001393 BuildBaseOrMemberInitializers(Context,
1394 Constructor,
1395 (CXXBaseOrMemberInitializer **)0, 0);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001396}
1397
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001398namespace {
1399 /// PureVirtualMethodCollector - traverses a class and its superclasses
1400 /// and determines if it has any pure virtual methods.
1401 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1402 ASTContext &Context;
1403
Sebastian Redldfe292d2009-03-22 21:28:55 +00001404 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001405 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001406
1407 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001408 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001409
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001410 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001412 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001413 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001414 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001415
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001416 MethodList List;
1417 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001419 // Copy the temporary list to methods, and make sure to ignore any
1420 // null entries.
1421 for (size_t i = 0, e = List.size(); i != e; ++i) {
1422 if (List[i])
1423 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001424 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001425 }
Mike Stump1eb44332009-09-09 15:08:12 +00001426
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001427 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001429 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1430 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001431 };
Mike Stump1eb44332009-09-09 15:08:12 +00001432
1433 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001434 MethodList& Methods) {
1435 // First, collect the pure virtual methods for the base classes.
1436 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1437 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001438 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001439 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001440 if (BaseDecl && BaseDecl->isAbstract())
1441 Collect(BaseDecl, Methods);
1442 }
1443 }
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001445 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001446 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001448 MethodSetTy OverriddenMethods;
1449 size_t MethodsSize = Methods.size();
1450
Mike Stump1eb44332009-09-09 15:08:12 +00001451 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001452 i != e; ++i) {
1453 // Traverse the record, looking for methods.
1454 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001455 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001456 if (MD->isPure()) {
1457 Methods.push_back(MD);
1458 continue;
1459 }
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001461 // Otherwise, record all the overridden methods in our set.
1462 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1463 E = MD->end_overridden_methods(); I != E; ++I) {
1464 // Keep track of the overridden methods.
1465 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001466 }
1467 }
1468 }
Mike Stump1eb44332009-09-09 15:08:12 +00001469
1470 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001471 // overridden.
1472 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1473 if (OverriddenMethods.count(Methods[i]))
1474 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001475 }
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001477 }
1478}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001479
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001480
Mike Stump1eb44332009-09-09 15:08:12 +00001481bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001482 unsigned DiagID, AbstractDiagSelID SelID,
1483 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001484 if (SelID == -1)
1485 return RequireNonAbstractType(Loc, T,
1486 PDiag(DiagID), CurrentRD);
1487 else
1488 return RequireNonAbstractType(Loc, T,
1489 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001490}
1491
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001492bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1493 const PartialDiagnostic &PD,
1494 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001495 if (!getLangOptions().CPlusPlus)
1496 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Anders Carlsson11f21a02009-03-23 19:10:31 +00001498 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001499 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001500 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Ted Kremenek6217b802009-07-29 21:53:49 +00001502 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001503 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001504 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001505 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001507 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001508 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001509 }
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Ted Kremenek6217b802009-07-29 21:53:49 +00001511 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001512 if (!RT)
1513 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001515 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1516 if (!RD)
1517 return false;
1518
Anders Carlssone65a3c82009-03-24 17:23:42 +00001519 if (CurrentRD && CurrentRD != RD)
1520 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001522 if (!RD->isAbstract())
1523 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001524
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001525 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001527 // Check if we've already emitted the list of pure virtual functions for this
1528 // class.
1529 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1530 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001532 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001533
1534 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001535 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1536 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001537
1538 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001539 MD->getDeclName();
1540 }
1541
1542 if (!PureVirtualClassDiagSet)
1543 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1544 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001546 return true;
1547}
1548
Anders Carlsson8211eff2009-03-24 01:19:16 +00001549namespace {
Mike Stump1eb44332009-09-09 15:08:12 +00001550 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001551 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1552 Sema &SemaRef;
1553 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Anders Carlssone65a3c82009-03-24 17:23:42 +00001555 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001556 bool Invalid = false;
1557
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001558 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1559 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001560 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001561
Anders Carlsson8211eff2009-03-24 01:19:16 +00001562 return Invalid;
1563 }
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Anders Carlssone65a3c82009-03-24 17:23:42 +00001565 public:
1566 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1567 : SemaRef(SemaRef), AbstractClass(ac) {
1568 Visit(SemaRef.Context.getTranslationUnitDecl());
1569 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001570
Anders Carlssone65a3c82009-03-24 17:23:42 +00001571 bool VisitFunctionDecl(const FunctionDecl *FD) {
1572 if (FD->isThisDeclarationADefinition()) {
1573 // No need to do the check if we're in a definition, because it requires
1574 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00001575 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001576 return VisitDeclContext(FD);
1577 }
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Anders Carlssone65a3c82009-03-24 17:23:42 +00001579 // Check the return type.
1580 QualType RTy = FD->getType()->getAsFunctionType()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001581 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00001582 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1583 diag::err_abstract_type_in_decl,
1584 Sema::AbstractReturnType,
1585 AbstractClass);
1586
Mike Stump1eb44332009-09-09 15:08:12 +00001587 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001588 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001589 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001590 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001591 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001592 VD->getOriginalType(),
1593 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001594 Sema::AbstractParamType,
1595 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001596 }
1597
1598 return Invalid;
1599 }
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Anders Carlssone65a3c82009-03-24 17:23:42 +00001601 bool VisitDecl(const Decl* D) {
1602 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1603 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Anders Carlssone65a3c82009-03-24 17:23:42 +00001605 return false;
1606 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001607 };
1608}
1609
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001610void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001611 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001612 SourceLocation LBrac,
1613 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001614 if (!TagDecl)
1615 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Douglas Gregor42af25f2009-05-11 19:58:34 +00001617 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001618 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001619 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00001620 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001621
Chris Lattnerb28317a2009-03-28 19:18:32 +00001622 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001623 if (!RD->isAbstract()) {
1624 // Collect all the pure virtual methods and see if this is an abstract
1625 // class after all.
1626 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001627 if (!Collector.empty())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001628 RD->setAbstract(true);
1629 }
Mike Stump1eb44332009-09-09 15:08:12 +00001630
1631 if (RD->isAbstract())
Anders Carlssone65a3c82009-03-24 17:23:42 +00001632 AbstractClassUsageDiagnoser(*this, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Douglas Gregor42af25f2009-05-11 19:58:34 +00001634 if (!RD->isDependentType())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001635 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001636}
1637
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001638/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1639/// special functions, such as the default constructor, copy
1640/// constructor, or destructor, to the given C++ class (C++
1641/// [special]p1). This routine can only be executed just before the
1642/// definition of the class is complete.
1643void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00001644 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00001645 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001646
Sebastian Redl465226e2009-05-27 22:11:52 +00001647 // FIXME: Implicit declarations have exception specifications, which are
1648 // the union of the specifications of the implicitly called functions.
1649
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001650 if (!ClassDecl->hasUserDeclaredConstructor()) {
1651 // C++ [class.ctor]p5:
1652 // A default constructor for a class X is a constructor of class X
1653 // that can be called without an argument. If there is no
1654 // user-declared constructor for class X, a default constructor is
1655 // implicitly declared. An implicitly-declared default constructor
1656 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001657 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001658 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00001659 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001660 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001661 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001662 Context.getFunctionType(Context.VoidTy,
1663 0, 0, false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001664 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001665 /*isExplicit=*/false,
1666 /*isInline=*/true,
1667 /*isImplicitlyDeclared=*/true);
1668 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001669 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001670 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001671 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001672 }
1673
1674 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1675 // C++ [class.copy]p4:
1676 // If the class definition does not explicitly declare a copy
1677 // constructor, one is declared implicitly.
1678
1679 // C++ [class.copy]p5:
1680 // The implicitly-declared copy constructor for a class X will
1681 // have the form
1682 //
1683 // X::X(const X&)
1684 //
1685 // if
1686 bool HasConstCopyConstructor = true;
1687
1688 // -- each direct or virtual base class B of X has a copy
1689 // constructor whose first parameter is of type const B& or
1690 // const volatile B&, and
1691 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1692 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1693 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00001694 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001695 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001696 = BaseClassDecl->hasConstCopyConstructor(Context);
1697 }
1698
1699 // -- for all the nonstatic data members of X that are of a
1700 // class type M (or array thereof), each such class type
1701 // has a copy constructor whose first parameter is of type
1702 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001703 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1704 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001705 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001706 QualType FieldType = (*Field)->getType();
1707 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1708 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001709 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001710 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001711 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001712 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001713 = FieldClassDecl->hasConstCopyConstructor(Context);
1714 }
1715 }
1716
Sebastian Redl64b45f72009-01-05 20:52:13 +00001717 // Otherwise, the implicitly declared copy constructor will have
1718 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001719 //
1720 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00001721 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001722 if (HasConstCopyConstructor)
1723 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001724 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001725
Sebastian Redl64b45f72009-01-05 20:52:13 +00001726 // An implicitly-declared copy constructor is an inline public
1727 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001728 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001729 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001730 CXXConstructorDecl *CopyConstructor
1731 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001732 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001733 Context.getFunctionType(Context.VoidTy,
1734 &ArgType, 1,
1735 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001736 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001737 /*isExplicit=*/false,
1738 /*isInline=*/true,
1739 /*isImplicitlyDeclared=*/true);
1740 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001741 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001742 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001743
1744 // Add the parameter to the constructor.
1745 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1746 ClassDecl->getLocation(),
1747 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001748 ArgType, /*DInfo=*/0,
1749 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00001750 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001751 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001752 }
1753
Sebastian Redl64b45f72009-01-05 20:52:13 +00001754 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1755 // Note: The following rules are largely analoguous to the copy
1756 // constructor rules. Note that virtual bases are not taken into account
1757 // for determining the argument type of the operator. Note also that
1758 // operators taking an object instead of a reference are allowed.
1759 //
1760 // C++ [class.copy]p10:
1761 // If the class definition does not explicitly declare a copy
1762 // assignment operator, one is declared implicitly.
1763 // The implicitly-defined copy assignment operator for a class X
1764 // will have the form
1765 //
1766 // X& X::operator=(const X&)
1767 //
1768 // if
1769 bool HasConstCopyAssignment = true;
1770
1771 // -- each direct base class B of X has a copy assignment operator
1772 // whose parameter is of type const B&, const volatile B& or B,
1773 // and
1774 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1775 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1776 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00001777 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001778 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001779 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001780 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001781 }
1782
1783 // -- for all the nonstatic data members of X that are of a class
1784 // type M (or array thereof), each such class type has a copy
1785 // assignment operator whose parameter is of type const M&,
1786 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001787 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1788 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001789 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00001790 QualType FieldType = (*Field)->getType();
1791 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1792 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001793 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00001794 const CXXRecordDecl *FieldClassDecl
1795 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001796 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00001797 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001798 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001799 }
1800 }
1801
1802 // Otherwise, the implicitly declared copy assignment operator will
1803 // have the form
1804 //
1805 // X& X::operator=(X&)
1806 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001807 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001808 if (HasConstCopyAssignment)
1809 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001810 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001811
1812 // An implicitly-declared copy assignment operator is an inline public
1813 // member of its class.
1814 DeclarationName Name =
1815 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1816 CXXMethodDecl *CopyAssignment =
1817 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1818 Context.getFunctionType(RetType, &ArgType, 1,
1819 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001820 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001821 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001822 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001823 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001824 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001825
1826 // Add the parameter to the operator.
1827 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1828 ClassDecl->getLocation(),
1829 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001830 ArgType, /*DInfo=*/0,
1831 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00001832 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001833
1834 // Don't call addedAssignmentOperator. There is no way to distinguish an
1835 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001836 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001837 }
1838
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001839 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001840 // C++ [class.dtor]p2:
1841 // If a class has no user-declared destructor, a destructor is
1842 // declared implicitly. An implicitly-declared destructor is an
1843 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001844 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001845 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00001846 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00001847 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001848 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00001849 Context.getFunctionType(Context.VoidTy,
1850 0, 0, false, 0),
1851 /*isInline=*/true,
1852 /*isImplicitlyDeclared=*/true);
1853 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001854 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001855 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001856 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001857 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001858}
1859
Douglas Gregor6569d682009-05-27 23:11:45 +00001860void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00001861 Decl *D = TemplateD.getAs<Decl>();
1862 if (!D)
1863 return;
1864
1865 TemplateParameterList *Params = 0;
1866 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
1867 Params = Template->getTemplateParameters();
1868 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
1869 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
1870 Params = PartialSpec->getTemplateParameters();
1871 else
Douglas Gregor6569d682009-05-27 23:11:45 +00001872 return;
1873
Douglas Gregor6569d682009-05-27 23:11:45 +00001874 for (TemplateParameterList::iterator Param = Params->begin(),
1875 ParamEnd = Params->end();
1876 Param != ParamEnd; ++Param) {
1877 NamedDecl *Named = cast<NamedDecl>(*Param);
1878 if (Named->getDeclName()) {
1879 S->AddDecl(DeclPtrTy::make(Named));
1880 IdResolver.AddDecl(Named);
1881 }
1882 }
1883}
1884
Douglas Gregor72b505b2008-12-16 21:30:33 +00001885/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1886/// parsing a top-level (non-nested) C++ class, and we are now
1887/// parsing those parts of the given Method declaration that could
1888/// not be parsed earlier (C++ [class.mem]p2), such as default
1889/// arguments. This action should enter the scope of the given
1890/// Method declaration as if we had just parsed the qualified method
1891/// name. However, it should not bring the parameters into scope;
1892/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001893void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001894 if (!MethodD)
1895 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001897 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00001898
Douglas Gregor72b505b2008-12-16 21:30:33 +00001899 CXXScopeSpec SS;
Chris Lattnerb28317a2009-03-28 19:18:32 +00001900 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001901 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00001902 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1903 SS.setScopeRep(
1904 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001905 ActOnCXXEnterDeclaratorScope(S, SS);
1906}
1907
1908/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1909/// C++ method declaration. We're (re-)introducing the given
1910/// function parameter into scope for use in parsing later parts of
1911/// the method declaration. For example, we could see an
1912/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001913void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001914 if (!ParamD)
1915 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Chris Lattnerb28317a2009-03-28 19:18:32 +00001917 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00001918
1919 // If this parameter has an unparsed default argument, clear it out
1920 // to make way for the parsed default argument.
1921 if (Param->hasUnparsedDefaultArg())
1922 Param->setDefaultArg(0);
1923
Chris Lattnerb28317a2009-03-28 19:18:32 +00001924 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001925 if (Param->getDeclName())
1926 IdResolver.AddDecl(Param);
1927}
1928
1929/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1930/// processing the delayed method declaration for Method. The method
1931/// declaration is now considered finished. There may be a separate
1932/// ActOnStartOfFunctionDef action later (not necessarily
1933/// immediately!) for this method, if it was also defined inside the
1934/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001935void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001936 if (!MethodD)
1937 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001938
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001939 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Chris Lattnerb28317a2009-03-28 19:18:32 +00001941 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00001942 CXXScopeSpec SS;
Mike Stump1eb44332009-09-09 15:08:12 +00001943 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00001944 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1945 SS.setScopeRep(
1946 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001947 ActOnCXXExitDeclaratorScope(S, SS);
1948
1949 // Now that we have our default arguments, check the constructor
1950 // again. It could produce additional diagnostics or affect whether
1951 // the class has implicitly-declared destructors, among other
1952 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00001953 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
1954 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00001955
1956 // Check the default arguments, which we may have added.
1957 if (!Method->isInvalidDecl())
1958 CheckCXXDefaultArguments(Method);
1959}
1960
Douglas Gregor42a552f2008-11-05 20:51:48 +00001961/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00001962/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00001963/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00001964/// emit diagnostics and set the invalid bit to true. In any case, the type
1965/// will be updated to reflect a well-formed type for the constructor and
1966/// returned.
1967QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
1968 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001969 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001970
1971 // C++ [class.ctor]p3:
1972 // A constructor shall not be virtual (10.3) or static (9.4). A
1973 // constructor can be invoked for a const, volatile or const
1974 // volatile object. A constructor shall not be declared const,
1975 // volatile, or const volatile (9.3.2).
1976 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00001977 if (!D.isInvalidType())
1978 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1979 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1980 << SourceRange(D.getIdentifierLoc());
1981 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001982 }
1983 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00001984 if (!D.isInvalidType())
1985 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1986 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1987 << SourceRange(D.getIdentifierLoc());
1988 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001989 SC = FunctionDecl::None;
1990 }
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Chris Lattner65401802009-04-25 08:28:21 +00001992 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1993 if (FTI.TypeQuals != 0) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001994 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001995 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1996 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001997 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001998 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1999 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002000 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002001 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2002 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002003 }
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Douglas Gregor42a552f2008-11-05 20:51:48 +00002005 // Rebuild the function type "R" without any type qualifiers (in
2006 // case any of the errors above fired) and with "void" as the
2007 // return type, since constructors don't have return types. We
2008 // *always* have to do this, because GetTypeForDeclarator will
2009 // put in a result type of "int" when none was specified.
Douglas Gregor72564e72009-02-26 23:50:07 +00002010 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Chris Lattner65401802009-04-25 08:28:21 +00002011 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2012 Proto->getNumArgs(),
2013 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002014}
2015
Douglas Gregor72b505b2008-12-16 21:30:33 +00002016/// CheckConstructor - Checks a fully-formed constructor for
2017/// well-formedness, issuing any diagnostics required. Returns true if
2018/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00002019void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00002020 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00002021 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2022 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00002023 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002024
2025 // C++ [class.copy]p3:
2026 // A declaration of a constructor for a class X is ill-formed if
2027 // its first parameter is of type (optionally cv-qualified) X and
2028 // either there are no other parameters or else all other
2029 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00002030 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002031 ((Constructor->getNumParams() == 1) ||
2032 (Constructor->getNumParams() > 1 &&
Anders Carlssonae0b4e72009-06-06 04:14:07 +00002033 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002034 QualType ParamType = Constructor->getParamDecl(0)->getType();
2035 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2036 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002037 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2038 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002039 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattner6e475012009-04-25 08:35:12 +00002040 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002041 }
2042 }
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Douglas Gregor72b505b2008-12-16 21:30:33 +00002044 // Notify the class that we've added a constructor.
2045 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002046}
2047
Mike Stump1eb44332009-09-09 15:08:12 +00002048static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002049FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2050 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2051 FTI.ArgInfo[0].Param &&
2052 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2053}
2054
Douglas Gregor42a552f2008-11-05 20:51:48 +00002055/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2056/// the well-formednes of the destructor declarator @p D with type @p
2057/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002058/// emit diagnostics and set the declarator to invalid. Even if this happens,
2059/// will be updated to reflect a well-formed type for the destructor and
2060/// returned.
2061QualType Sema::CheckDestructorDeclarator(Declarator &D,
2062 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002063 // C++ [class.dtor]p1:
2064 // [...] A typedef-name that names a class is a class-name
2065 // (7.1.3); however, a typedef-name that names a class shall not
2066 // be used as the identifier in the declarator for a destructor
2067 // declaration.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002068 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType());
Chris Lattner65401802009-04-25 08:28:21 +00002069 if (isa<TypedefType>(DeclaratorType)) {
2070 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002071 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002072 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002073 }
2074
2075 // C++ [class.dtor]p2:
2076 // A destructor is used to destroy objects of its class type. A
2077 // destructor takes no parameters, and no return type can be
2078 // specified for it (not even void). The address of a destructor
2079 // shall not be taken. A destructor shall not be static. A
2080 // destructor can be invoked for a const, volatile or const
2081 // volatile object. A destructor shall not be declared const,
2082 // volatile or const volatile (9.3.2).
2083 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002084 if (!D.isInvalidType())
2085 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2086 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2087 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002088 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002089 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002090 }
Chris Lattner65401802009-04-25 08:28:21 +00002091 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002092 // Destructors don't have return types, but the parser will
2093 // happily parse something like:
2094 //
2095 // class X {
2096 // float ~X();
2097 // };
2098 //
2099 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002100 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2101 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2102 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002103 }
Mike Stump1eb44332009-09-09 15:08:12 +00002104
Chris Lattner65401802009-04-25 08:28:21 +00002105 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2106 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002107 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002108 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2109 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002110 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002111 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2112 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002113 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002114 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2115 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002116 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002117 }
2118
2119 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002120 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002121 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2122
2123 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002124 FTI.freeArgs();
2125 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002126 }
2127
Mike Stump1eb44332009-09-09 15:08:12 +00002128 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002129 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002130 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002131 D.setInvalidType();
2132 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002133
2134 // Rebuild the function type "R" without any type qualifiers or
2135 // parameters (in case any of the errors above fired) and with
2136 // "void" as the return type, since destructors don't have return
2137 // types. We *always* have to do this, because GetTypeForDeclarator
2138 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002139 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002140}
2141
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002142/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2143/// well-formednes of the conversion function declarator @p D with
2144/// type @p R. If there are any errors in the declarator, this routine
2145/// will emit diagnostics and return true. Otherwise, it will return
2146/// false. Either way, the type @p R will be updated to reflect a
2147/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002148void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002149 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002150 // C++ [class.conv.fct]p1:
2151 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002152 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002153 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002154 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002155 if (!D.isInvalidType())
2156 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2157 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2158 << SourceRange(D.getIdentifierLoc());
2159 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002160 SC = FunctionDecl::None;
2161 }
Chris Lattner6e475012009-04-25 08:35:12 +00002162 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002163 // Conversion functions don't have return types, but the parser will
2164 // happily parse something like:
2165 //
2166 // class X {
2167 // float operator bool();
2168 // };
2169 //
2170 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002171 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2172 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2173 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002174 }
2175
2176 // Make sure we don't have any parameters.
Douglas Gregor72564e72009-02-26 23:50:07 +00002177 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002178 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2179
2180 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002181 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002182 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002183 }
2184
Mike Stump1eb44332009-09-09 15:08:12 +00002185 // Make sure the conversion function isn't variadic.
Chris Lattner6e475012009-04-25 08:35:12 +00002186 if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002187 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002188 D.setInvalidType();
2189 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002190
2191 // C++ [class.conv.fct]p4:
2192 // The conversion-type-id shall not represent a function type nor
2193 // an array type.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002194 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002195 if (ConvType->isArrayType()) {
2196 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2197 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002198 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002199 } else if (ConvType->isFunctionType()) {
2200 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2201 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002202 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002203 }
2204
2205 // Rebuild the function type "R" without any parameters (in case any
2206 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002207 // return type.
2208 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor72564e72009-02-26 23:50:07 +00002209 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002210
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002211 // C++0x explicit conversion operators.
2212 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002213 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002214 diag::warn_explicit_conversion_functions)
2215 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002216}
2217
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002218/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2219/// the declaration of the given C++ conversion function. This routine
2220/// is responsible for recording the conversion function in the C++
2221/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002222Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002223 assert(Conversion && "Expected to receive a conversion function declaration");
2224
Douglas Gregor9d350972008-12-12 08:25:50 +00002225 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002226
2227 // Make sure we aren't redeclaring the conversion function.
2228 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002229
2230 // C++ [class.conv.fct]p1:
2231 // [...] A conversion function is never used to convert a
2232 // (possibly cv-qualified) object to the (possibly cv-qualified)
2233 // same object type (or a reference to it), to a (possibly
2234 // cv-qualified) base class of that type (or a reference to it),
2235 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002236 // FIXME: Suppress this warning if the conversion function ends up being a
2237 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002238 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002239 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002240 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002241 ConvType = ConvTypeRef->getPointeeType();
2242 if (ConvType->isRecordType()) {
2243 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2244 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002245 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002246 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002247 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002248 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002249 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002250 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002251 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002252 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002253 }
2254
Douglas Gregor70316a02008-12-26 15:00:45 +00002255 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002256 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002257 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002258 = Conversion->getDescribedFunctionTemplate())
2259 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor70316a02008-12-26 15:00:45 +00002260 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00002261 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor70316a02008-12-26 15:00:45 +00002262 Conv = Conversions->function_begin(),
2263 ConvEnd = Conversions->function_end();
2264 Conv != ConvEnd; ++Conv) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002265 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor70316a02008-12-26 15:00:45 +00002266 *Conv = Conversion;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002267 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002268 }
2269 }
2270 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002271 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002272 = Conversion->getDescribedFunctionTemplate())
2273 ClassDecl->addConversionFunction(Context, ConversionTemplate);
2274 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Douglas Gregor70316a02008-12-26 15:00:45 +00002275 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002276
Chris Lattnerb28317a2009-03-28 19:18:32 +00002277 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002278}
2279
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002280//===----------------------------------------------------------------------===//
2281// Namespace Handling
2282//===----------------------------------------------------------------------===//
2283
2284/// ActOnStartNamespaceDef - This is called at the start of a namespace
2285/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002286Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2287 SourceLocation IdentLoc,
2288 IdentifierInfo *II,
2289 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002290 NamespaceDecl *Namespc =
2291 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2292 Namespc->setLBracLoc(LBrace);
2293
2294 Scope *DeclRegionScope = NamespcScope->getParent();
2295
2296 if (II) {
2297 // C++ [namespace.def]p2:
2298 // The identifier in an original-namespace-definition shall not have been
2299 // previously defined in the declarative region in which the
2300 // original-namespace-definition appears. The identifier in an
2301 // original-namespace-definition is the name of the namespace. Subsequently
2302 // in that declarative region, it is treated as an original-namespace-name.
2303
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002304 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
2305 true);
Mike Stump1eb44332009-09-09 15:08:12 +00002306
Douglas Gregor44b43212008-12-11 16:49:14 +00002307 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2308 // This is an extended namespace definition.
2309 // Attach this namespace decl to the chain of extended namespace
2310 // definitions.
2311 OrigNS->setNextNamespace(Namespc);
2312 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002313
Mike Stump1eb44332009-09-09 15:08:12 +00002314 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002315 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002316 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002317 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002318 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002319 } else if (PrevDecl) {
2320 // This is an invalid name redefinition.
2321 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2322 << Namespc->getDeclName();
2323 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2324 Namespc->setInvalidDecl();
2325 // Continue on to push Namespc as current DeclContext and return it.
Mike Stump1eb44332009-09-09 15:08:12 +00002326 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002327
2328 PushOnScopeChains(Namespc, DeclRegionScope);
2329 } else {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002330 // FIXME: Handle anonymous namespaces
2331 }
2332
2333 // Although we could have an invalid decl (i.e. the namespace name is a
2334 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002335 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2336 // for the namespace has the declarations that showed up in that particular
2337 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002338 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002339 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002340}
2341
2342/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2343/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002344void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2345 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002346 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2347 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2348 Namespc->setRBracLoc(RBrace);
2349 PopDeclContext();
2350}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002351
Chris Lattnerb28317a2009-03-28 19:18:32 +00002352Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2353 SourceLocation UsingLoc,
2354 SourceLocation NamespcLoc,
2355 const CXXScopeSpec &SS,
2356 SourceLocation IdentLoc,
2357 IdentifierInfo *NamespcName,
2358 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002359 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2360 assert(NamespcName && "Invalid NamespcName.");
2361 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002362 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002363
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002364 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002365
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002366 // Lookup namespace name.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002367 LookupResult R = LookupParsedName(S, &SS, NamespcName,
2368 LookupNamespaceName, false);
2369 if (R.isAmbiguous()) {
2370 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002371 return DeclPtrTy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002372 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002373 if (NamedDecl *NS = R) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002374 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002375 // C++ [namespace.udir]p1:
2376 // A using-directive specifies that the names in the nominated
2377 // namespace can be used in the scope in which the
2378 // using-directive appears after the using-directive. During
2379 // unqualified name lookup (3.4.1), the names appear as if they
2380 // were declared in the nearest enclosing namespace which
2381 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002382 // namespace. [Note: in this context, "contains" means "contains
2383 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002384
2385 // Find enclosing context containing both using-directive and
2386 // nominated namespace.
2387 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2388 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2389 CommonAncestor = CommonAncestor->getParent();
2390
Mike Stump1eb44332009-09-09 15:08:12 +00002391 UDir = UsingDirectiveDecl::Create(Context,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002392 CurContext, UsingLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002393 NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002394 SS.getRange(),
2395 (NestedNameSpecifier *)SS.getScopeRep(),
2396 IdentLoc,
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002397 cast<NamespaceDecl>(NS),
2398 CommonAncestor);
2399 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002400 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002401 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002402 }
2403
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002404 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002405 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002406 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002407}
2408
2409void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2410 // If scope has associated entity, then using directive is at namespace
2411 // or translation unit scope. We add UsingDirectiveDecls, into
2412 // it's lookup structure.
2413 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002414 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002415 else
2416 // Otherwise it is block-sope. using-directives will affect lookup
2417 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002418 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002419}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002420
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002421
2422Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002423 AccessSpecifier AS,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002424 SourceLocation UsingLoc,
2425 const CXXScopeSpec &SS,
2426 SourceLocation IdentLoc,
2427 IdentifierInfo *TargetName,
2428 OverloadedOperatorKind Op,
2429 AttributeList *AttrList,
2430 bool IsTypeName) {
Eli Friedman5d39dee2009-06-27 05:59:59 +00002431 assert((TargetName || Op) && "Invalid TargetName.");
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002432 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002433
Anders Carlsson0c6139d2009-06-27 00:27:47 +00002434 DeclarationName Name;
2435 if (TargetName)
2436 Name = TargetName;
2437 else
2438 Name = Context.DeclarationNames.getCXXOperatorName(Op);
Mike Stump1eb44332009-09-09 15:08:12 +00002439
2440 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS, IdentLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00002441 Name, AttrList, IsTypeName);
Anders Carlsson595adc12009-08-29 19:54:19 +00002442 if (UD) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00002443 PushOnScopeChains(UD, S);
Anders Carlsson595adc12009-08-29 19:54:19 +00002444 UD->setAccess(AS);
2445 }
Mike Stump1eb44332009-09-09 15:08:12 +00002446
Anders Carlssonc72160b2009-08-28 05:40:36 +00002447 return DeclPtrTy::make(UD);
2448}
2449
2450NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2451 const CXXScopeSpec &SS,
2452 SourceLocation IdentLoc,
2453 DeclarationName Name,
2454 AttributeList *AttrList,
2455 bool IsTypeName) {
2456 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2457 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00002458
Anders Carlsson550b14b2009-08-28 05:49:21 +00002459 // FIXME: We ignore attributes for now.
2460 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00002461
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002462 if (SS.isEmpty()) {
2463 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002464 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002465 }
Mike Stump1eb44332009-09-09 15:08:12 +00002466
2467 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002468 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2469
Anders Carlsson550b14b2009-08-28 05:49:21 +00002470 if (isUnknownSpecialization(SS)) {
2471 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2472 SS.getRange(), NNS,
2473 IdentLoc, Name, IsTypeName);
2474 }
Mike Stump1eb44332009-09-09 15:08:12 +00002475
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002476 DeclContext *LookupContext = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002477
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002478 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2479 // C++0x N2914 [namespace.udecl]p3:
2480 // A using-declaration used as a member-declaration shall refer to a member
2481 // of a base class of the class being defined, shall refer to a member of an
2482 // anonymous union that is a member of a base class of the class being
Mike Stump1eb44332009-09-09 15:08:12 +00002483 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002484 // a member of a base class of the class being defined.
2485 const Type *Ty = NNS->getAsType();
2486 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) {
2487 Diag(SS.getRange().getBegin(),
2488 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2489 << NNS << RD->getDeclName();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002490 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002491 }
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002492
2493 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0));
2494 LookupContext = BaseTy->getAs<RecordType>()->getDecl();
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002495 } else {
2496 // C++0x N2914 [namespace.udecl]p8:
2497 // A using-declaration for a class member shall be a member-declaration.
2498 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002499 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002500 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002501 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002502 }
Mike Stump1eb44332009-09-09 15:08:12 +00002503
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002504 // C++0x N2914 [namespace.udecl]p9:
2505 // In a using-declaration, a prefix :: refers to the global namespace.
2506 if (NNS->getKind() == NestedNameSpecifier::Global)
2507 LookupContext = Context.getTranslationUnitDecl();
2508 else
2509 LookupContext = NNS->getAsNamespace();
2510 }
2511
2512
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002513 // Lookup target name.
Mike Stump1eb44332009-09-09 15:08:12 +00002514 LookupResult R = LookupQualifiedName(LookupContext,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002515 Name, LookupOrdinaryName);
Mike Stump1eb44332009-09-09 15:08:12 +00002516
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002517 if (!R) {
Anders Carlsson05180af2009-08-30 00:58:45 +00002518 DiagnoseMissingMember(IdentLoc, Name, NNS, SS.getRange());
Anders Carlssonc72160b2009-08-28 05:40:36 +00002519 return 0;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002520 }
2521
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002522 NamedDecl *ND = R.getAsDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002523
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002524 if (IsTypeName && !isa<TypeDecl>(ND)) {
2525 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002526 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002527 }
2528
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002529 // C++0x N2914 [namespace.udecl]p6:
2530 // A using-declaration shall not name a namespace.
2531 if (isa<NamespaceDecl>(ND)) {
2532 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2533 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002534 return 0;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002535 }
Mike Stump1eb44332009-09-09 15:08:12 +00002536
Anders Carlssonc72160b2009-08-28 05:40:36 +00002537 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2538 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002539}
2540
Anders Carlsson81c85c42009-03-28 23:53:49 +00002541/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2542/// is a namespace alias, returns the namespace it points to.
2543static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2544 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2545 return AD->getNamespace();
2546 return dyn_cast_or_null<NamespaceDecl>(D);
2547}
2548
Mike Stump1eb44332009-09-09 15:08:12 +00002549Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002550 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002551 SourceLocation AliasLoc,
2552 IdentifierInfo *Alias,
2553 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002554 SourceLocation IdentLoc,
2555 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00002556
Anders Carlsson81c85c42009-03-28 23:53:49 +00002557 // Lookup the namespace name.
2558 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
2559
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002560 // Check if we have a previous declaration with the same name.
Anders Carlssondd729fc2009-03-28 23:49:35 +00002561 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00002562 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002563 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00002564 // namespace, so don't create a new one.
2565 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
2566 return DeclPtrTy();
2567 }
Mike Stump1eb44332009-09-09 15:08:12 +00002568
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002569 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2570 diag::err_redefinition_different_kind;
2571 Diag(AliasLoc, DiagID) << Alias;
2572 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002573 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002574 }
2575
Anders Carlsson5721c682009-03-28 06:42:02 +00002576 if (R.isAmbiguous()) {
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002577 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002578 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002579 }
Mike Stump1eb44332009-09-09 15:08:12 +00002580
Anders Carlsson5721c682009-03-28 06:42:02 +00002581 if (!R) {
2582 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00002583 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002584 }
Mike Stump1eb44332009-09-09 15:08:12 +00002585
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002586 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00002587 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2588 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00002589 (NestedNameSpecifier *)SS.getScopeRep(),
Anders Carlsson68771c72009-03-28 22:58:02 +00002590 IdentLoc, R);
Mike Stump1eb44332009-09-09 15:08:12 +00002591
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002592 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00002593 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00002594}
2595
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002596void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2597 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00002598 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2599 !Constructor->isUsed()) &&
2600 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00002601
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002602 CXXRecordDecl *ClassDecl
2603 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002604 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Mike Stump1eb44332009-09-09 15:08:12 +00002605 // Before the implicitly-declared default constructor for a class is
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002606 // implicitly defined, all the implicitly-declared default constructors
2607 // for its base class and its non-static data members shall have been
2608 // implicitly defined.
2609 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002610 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2611 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002612 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002613 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002614 if (!BaseClassDecl->hasTrivialConstructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002615 if (CXXConstructorDecl *BaseCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002616 BaseClassDecl->getDefaultConstructor(Context))
2617 MarkDeclarationReferenced(CurrentLocation, BaseCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002618 else {
Mike Stump1eb44332009-09-09 15:08:12 +00002619 Diag(CurrentLocation, diag::err_defining_default_ctor)
2620 << Context.getTagDeclType(ClassDecl) << 1
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002621 << Context.getTagDeclType(BaseClassDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002622 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002623 << Context.getTagDeclType(BaseClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002624 err = true;
2625 }
2626 }
2627 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002628 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2629 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002630 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2631 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2632 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002633 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002634 CXXRecordDecl *FieldClassDecl
2635 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Duncan Sands6887e632009-06-25 09:03:06 +00002636 if (!FieldClassDecl->hasTrivialConstructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002637 if (CXXConstructorDecl *FieldCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002638 FieldClassDecl->getDefaultConstructor(Context))
2639 MarkDeclarationReferenced(CurrentLocation, FieldCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002640 else {
Mike Stump1eb44332009-09-09 15:08:12 +00002641 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002642 << Context.getTagDeclType(ClassDecl) << 0 <<
2643 Context.getTagDeclType(FieldClassDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002644 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002645 << Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002646 err = true;
2647 }
2648 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002649 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002650 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00002651 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002652 Diag((*Field)->getLocation(), diag::note_declared_at);
2653 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002654 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002655 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00002656 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002657 Diag((*Field)->getLocation(), diag::note_declared_at);
2658 err = true;
2659 }
2660 }
2661 if (!err)
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00002662 Constructor->setUsed();
2663 else
2664 Constructor->setInvalidDecl();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002665}
2666
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002667void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00002668 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002669 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2670 "DefineImplicitDestructor - call it for implicit default dtor");
Mike Stump1eb44332009-09-09 15:08:12 +00002671
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002672 CXXRecordDecl *ClassDecl
2673 = cast<CXXRecordDecl>(Destructor->getDeclContext());
2674 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2675 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00002676 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002677 // implicitly defined, all the implicitly-declared default destructors
2678 // for its base class and its non-static data members shall have been
2679 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002680 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2681 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002682 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002683 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002684 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002685 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002686 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2687 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2688 else
Mike Stump1eb44332009-09-09 15:08:12 +00002689 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002690 "DefineImplicitDestructor - missing dtor in a base class");
2691 }
2692 }
Mike Stump1eb44332009-09-09 15:08:12 +00002693
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002694 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2695 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002696 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2697 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2698 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002699 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002700 CXXRecordDecl *FieldClassDecl
2701 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2702 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002703 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002704 const_cast<CXXDestructorDecl*>(
2705 FieldClassDecl->getDestructor(Context)))
2706 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
2707 else
Mike Stump1eb44332009-09-09 15:08:12 +00002708 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002709 "DefineImplicitDestructor - missing dtor in class of a data member");
2710 }
2711 }
2712 }
2713 Destructor->setUsed();
2714}
2715
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002716void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
2717 CXXMethodDecl *MethodDecl) {
2718 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
2719 MethodDecl->getOverloadedOperator() == OO_Equal &&
2720 !MethodDecl->isUsed()) &&
2721 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00002722
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002723 CXXRecordDecl *ClassDecl
2724 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002725
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00002726 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002727 // Before the implicitly-declared copy assignment operator for a class is
2728 // implicitly defined, all implicitly-declared copy assignment operators
2729 // for its direct base classes and its nonstatic data members shall have
2730 // been implicitly defined.
2731 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002732 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2733 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002734 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002735 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002736 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002737 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
2738 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
2739 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002740 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2741 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002742 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2743 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2744 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002745 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002746 CXXRecordDecl *FieldClassDecl
2747 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002748 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002749 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
2750 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002751 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002752 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00002753 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
2754 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002755 Diag(CurrentLocation, diag::note_first_required_here);
2756 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002757 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002758 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00002759 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
2760 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002761 Diag(CurrentLocation, diag::note_first_required_here);
2762 err = true;
2763 }
2764 }
2765 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00002766 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002767}
2768
2769CXXMethodDecl *
2770Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
2771 CXXRecordDecl *ClassDecl) {
2772 QualType LHSType = Context.getTypeDeclType(ClassDecl);
2773 QualType RHSType(LHSType);
2774 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00002775 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002776 // operator = (B&).
2777 if (ParmDecl->getType().isConstQualified())
2778 RHSType.addConst();
2779 if (ParmDecl->getType().isVolatileQualified())
2780 RHSType.addVolatile();
Mike Stump1eb44332009-09-09 15:08:12 +00002781 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
2782 LHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002783 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00002784 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
2785 RHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002786 SourceLocation()));
2787 Expr *Args[2] = { &*LHS, &*RHS };
2788 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00002789 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002790 CandidateSet);
2791 OverloadCandidateSet::iterator Best;
Mike Stump1eb44332009-09-09 15:08:12 +00002792 if (BestViableFunction(CandidateSet,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002793 ClassDecl->getLocation(), Best) == OR_Success)
2794 return cast<CXXMethodDecl>(Best->Function);
2795 assert(false &&
2796 "getAssignOperatorMethod - copy assignment operator method not found");
2797 return 0;
2798}
2799
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002800void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2801 CXXConstructorDecl *CopyConstructor,
2802 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00002803 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002804 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
2805 !CopyConstructor->isUsed()) &&
2806 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00002807
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002808 CXXRecordDecl *ClassDecl
2809 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
2810 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002811 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00002812 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002813 // implicitly defined, all the implicitly-declared copy constructors
2814 // for its base class and its non-static data members shall have been
2815 // implicitly defined.
2816 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2817 Base != ClassDecl->bases_end(); ++Base) {
2818 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002819 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002820 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002821 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002822 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002823 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002824 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2825 FieldEnd = ClassDecl->field_end();
2826 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002827 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2828 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2829 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002830 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002831 CXXRecordDecl *FieldClassDecl
2832 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002833 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002834 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002835 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002836 }
2837 }
2838 CopyConstructor->setUsed();
2839}
2840
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002841Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00002842Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00002843 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002844 MultiExprArg ExprArgs) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002845 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002846
Douglas Gregor39da0b82009-09-09 23:08:42 +00002847 // C++ [class.copy]p15:
2848 // Whenever a temporary class object is copied using a copy constructor, and
2849 // this object and the copy have the same cv-unqualified type, an
2850 // implementation is permitted to treat the original and the copy as two
2851 // different ways of referring to the same object and not perform a copy at
2852 // all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00002853
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002854 // FIXME: Is this enough?
Douglas Gregor39da0b82009-09-09 23:08:42 +00002855 if (Constructor->isCopyConstructor(Context)) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00002856 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002857 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2858 E = BE->getSubExpr();
Douglas Gregor39da0b82009-09-09 23:08:42 +00002859 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2860 if (ICE->getCastKind() == CastExpr::CK_NoOp)
2861 E = ICE->getSubExpr();
2862
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002863 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
2864 Elidable = true;
2865 }
Mike Stump1eb44332009-09-09 15:08:12 +00002866
2867 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002868 Elidable, move(ExprArgs));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002869}
2870
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002871/// BuildCXXConstructExpr - Creates a complete call to a constructor,
2872/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002873Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00002874Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2875 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002876 MultiExprArg ExprArgs) {
2877 unsigned NumExprs = ExprArgs.size();
2878 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00002879
Douglas Gregor39da0b82009-09-09 23:08:42 +00002880 return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
2881 Elidable, Exprs, NumExprs));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002882}
2883
Anders Carlssone7624a72009-08-27 05:08:22 +00002884Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00002885Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
2886 QualType Ty,
2887 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00002888 MultiExprArg Args,
2889 SourceLocation RParenLoc) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002890 unsigned NumExprs = Args.size();
2891 Expr **Exprs = (Expr **)Args.release();
Mike Stump1eb44332009-09-09 15:08:12 +00002892
Douglas Gregor39da0b82009-09-09 23:08:42 +00002893 return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
2894 TyBeginLoc, Exprs,
2895 NumExprs, RParenLoc));
Anders Carlssone7624a72009-08-27 05:08:22 +00002896}
2897
2898
Mike Stump1eb44332009-09-09 15:08:12 +00002899bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002900 CXXConstructorDecl *Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00002901 QualType DeclInitType,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002902 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002903 OwningExprResult TempResult =
2904 BuildCXXConstructExpr(VD->getLocation(), DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002905 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00002906 if (TempResult.isInvalid())
2907 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002908
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002909 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002910 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +00002911 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor78d15832009-05-26 18:54:04 +00002912 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00002913
Anders Carlssonfe2de492009-08-25 05:18:00 +00002914 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00002915}
2916
Mike Stump1eb44332009-09-09 15:08:12 +00002917void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002918 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00002919 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002920 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00002921 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002922 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002923 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002924}
2925
Mike Stump1eb44332009-09-09 15:08:12 +00002926/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002927/// ActOnDeclarator, when a C++ direct initializer is present.
2928/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00002929void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
2930 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00002931 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002932 SourceLocation *CommaLocs,
2933 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00002934 unsigned NumExprs = Exprs.size();
2935 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00002936 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002937
2938 // If there is no declaration, there was an error parsing it. Just ignore
2939 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002940 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002941 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002942
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002943 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2944 if (!VDecl) {
2945 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
2946 RealDecl->setInvalidDecl();
2947 return;
2948 }
2949
Douglas Gregor83ddad32009-08-26 21:14:46 +00002950 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00002951 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002952 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
2953 //
2954 // Clients that want to distinguish between the two forms, can check for
2955 // direct initializer using VarDecl::hasCXXDirectInitializer().
2956 // A major benefit is that clients that don't particularly care about which
2957 // exactly form was it (like the CodeGen) can handle both cases without
2958 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002959
Douglas Gregor83ddad32009-08-26 21:14:46 +00002960 // If either the declaration has a dependent type or if any of the expressions
2961 // is type-dependent, we represent the initialization via a ParenListExpr for
2962 // later use during template instantiation.
2963 if (VDecl->getType()->isDependentType() ||
2964 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
2965 // Let clients know that initialization was done with a direct initializer.
2966 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00002967
Douglas Gregor83ddad32009-08-26 21:14:46 +00002968 // Store the initialization expressions as a ParenListExpr.
2969 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00002970 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00002971 new (Context) ParenListExpr(Context, LParenLoc,
2972 (Expr **)Exprs.release(),
2973 NumExprs, RParenLoc));
2974 return;
2975 }
Mike Stump1eb44332009-09-09 15:08:12 +00002976
Douglas Gregor83ddad32009-08-26 21:14:46 +00002977
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002978 // C++ 8.5p11:
2979 // The form of initialization (using parentheses or '=') is generally
2980 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002981 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00002982 QualType DeclInitType = VDecl->getType();
2983 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
2984 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002985
Douglas Gregor615c5d42009-03-24 16:43:20 +00002986 // FIXME: This isn't the right place to complete the type.
2987 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
2988 diag::err_typecheck_decl_incomplete_type)) {
2989 VDecl->setInvalidDecl();
2990 return;
2991 }
2992
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002993 if (VDecl->getType()->isRecordType()) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002994 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2995
Douglas Gregor18fe5682008-11-03 20:45:27 +00002996 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00002997 = PerformInitializationByConstructor(DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00002998 move(Exprs),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002999 VDecl->getLocation(),
3000 SourceRange(VDecl->getLocation(),
3001 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003002 VDecl->getDeclName(),
Douglas Gregor39da0b82009-09-09 23:08:42 +00003003 IK_Direct,
3004 ConstructorArgs);
Sebastian Redlf53597f2009-03-15 17:47:39 +00003005 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00003006 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00003007 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00003008 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003009 if (InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003010 move_arg(ConstructorArgs)))
Anders Carlssonfe2de492009-08-25 05:18:00 +00003011 RealDecl->setInvalidDecl();
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003012 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00003013 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003014 return;
3015 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003016
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003017 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003018 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3019 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003020 RealDecl->setInvalidDecl();
3021 return;
3022 }
3023
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003024 // Let clients know that initialization was done with a direct initializer.
3025 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003026
3027 assert(NumExprs == 1 && "Expected 1 expression");
3028 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00003029 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3030 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003031}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003032
Douglas Gregor39da0b82009-09-09 23:08:42 +00003033/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3034/// may occur as part of direct-initialization or copy-initialization.
3035///
3036/// \param ClassType the type of the object being initialized, which must have
3037/// class type.
3038///
3039/// \param ArgsPtr the arguments provided to initialize the object
3040///
3041/// \param Loc the source location where the initialization occurs
3042///
3043/// \param Range the source range that covers the entire initialization
3044///
3045/// \param InitEntity the name of the entity being initialized, if known
3046///
3047/// \param Kind the type of initialization being performed
3048///
3049/// \param ConvertedArgs a vector that will be filled in with the
3050/// appropriately-converted arguments to the constructor (if initialization
3051/// succeeded).
3052///
3053/// \returns the constructor used to initialize the object, if successful.
3054/// Otherwise, emits a diagnostic and returns NULL.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003055CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003056Sema::PerformInitializationByConstructor(QualType ClassType,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003057 MultiExprArg ArgsPtr,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003058 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003059 DeclarationName InitEntity,
Douglas Gregor39da0b82009-09-09 23:08:42 +00003060 InitializationKind Kind,
3061 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003062 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregor18fe5682008-11-03 20:45:27 +00003063 assert(ClassRec && "Can only initialize a class type here");
Douglas Gregor39da0b82009-09-09 23:08:42 +00003064 Expr **Args = (Expr **)ArgsPtr.get();
3065 unsigned NumArgs = ArgsPtr.size();
3066
Mike Stump1eb44332009-09-09 15:08:12 +00003067 // C++ [dcl.init]p14:
Douglas Gregor18fe5682008-11-03 20:45:27 +00003068 // If the initialization is direct-initialization, or if it is
3069 // copy-initialization where the cv-unqualified version of the
3070 // source type is the same class as, or a derived class of, the
3071 // class of the destination, constructors are considered. The
3072 // applicable constructors are enumerated (13.3.1.3), and the
3073 // best one is chosen through overload resolution (13.3). The
3074 // constructor so selected is called to initialize the object,
3075 // with the initializer expression(s) as its argument(s). If no
3076 // constructor applies, or the overload resolution is ambiguous,
3077 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003078 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3079 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003080
3081 // Add constructors to the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00003082 DeclarationName ConstructorName
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003083 = Context.DeclarationNames.getCXXConstructorName(
3084 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003085 DeclContext::lookup_const_iterator Con, ConEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003086 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003087 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00003088 // Find the constructor (which may be a template).
3089 CXXConstructorDecl *Constructor = 0;
3090 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3091 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003092 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003093 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3094 else
3095 Constructor = cast<CXXConstructorDecl>(*Con);
3096
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003097 if ((Kind == IK_Direct) ||
Mike Stump1eb44332009-09-09 15:08:12 +00003098 (Kind == IK_Copy &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00003099 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregordec06662009-08-21 18:42:58 +00003100 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
3101 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003102 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
Douglas Gregordec06662009-08-21 18:42:58 +00003103 Args, NumArgs, CandidateSet);
3104 else
3105 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3106 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003107 }
3108
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003109 // FIXME: When we decide not to synthesize the implicitly-declared
3110 // constructors, we'll need to make them appear here.
3111
Douglas Gregor18fe5682008-11-03 20:45:27 +00003112 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003113 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00003114 case OR_Success:
Douglas Gregor39da0b82009-09-09 23:08:42 +00003115 // We found a constructor. Break out so that we can convert the arguments
3116 // appropriately.
3117 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003118
Douglas Gregor18fe5682008-11-03 20:45:27 +00003119 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003120 if (InitEntity)
3121 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003122 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00003123 else
3124 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003125 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00003126 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00003127 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003128
Douglas Gregor18fe5682008-11-03 20:45:27 +00003129 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003130 if (InitEntity)
3131 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3132 else
3133 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003134 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3135 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003136
3137 case OR_Deleted:
3138 if (InitEntity)
3139 Diag(Loc, diag::err_ovl_deleted_init)
3140 << Best->Function->isDeleted()
3141 << InitEntity << Range;
3142 else
3143 Diag(Loc, diag::err_ovl_deleted_init)
3144 << Best->Function->isDeleted()
3145 << InitEntity << Range;
3146 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3147 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003148 }
Mike Stump1eb44332009-09-09 15:08:12 +00003149
Douglas Gregor39da0b82009-09-09 23:08:42 +00003150 // Convert the arguments, fill in default arguments, etc.
3151 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3152 if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3153 return 0;
3154
3155 return Constructor;
3156}
3157
3158/// \brief Given a constructor and the set of arguments provided for the
3159/// constructor, convert the arguments and add any required default arguments
3160/// to form a proper call to this constructor.
3161///
3162/// \returns true if an error occurred, false otherwise.
3163bool
3164Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3165 MultiExprArg ArgsPtr,
3166 SourceLocation Loc,
3167 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3168 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3169 unsigned NumArgs = ArgsPtr.size();
3170 Expr **Args = (Expr **)ArgsPtr.get();
3171
3172 const FunctionProtoType *Proto
3173 = Constructor->getType()->getAs<FunctionProtoType>();
3174 assert(Proto && "Constructor without a prototype?");
3175 unsigned NumArgsInProto = Proto->getNumArgs();
3176 unsigned NumArgsToCheck = NumArgs;
3177
3178 // If too few arguments are available, we'll fill in the rest with defaults.
3179 if (NumArgs < NumArgsInProto) {
3180 NumArgsToCheck = NumArgsInProto;
3181 ConvertedArgs.reserve(NumArgsInProto);
3182 } else {
3183 ConvertedArgs.reserve(NumArgs);
3184 if (NumArgs > NumArgsInProto)
3185 NumArgsToCheck = NumArgsInProto;
3186 }
3187
3188 // Convert arguments
3189 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3190 QualType ProtoArgType = Proto->getArgType(i);
3191
3192 Expr *Arg;
3193 if (i < NumArgs) {
3194 Arg = Args[i];
3195
3196 // Pass the argument.
3197 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3198 return true;
3199
3200 Args[i] = 0;
3201 } else {
3202 ParmVarDecl *Param = Constructor->getParamDecl(i);
3203
3204 OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3205 if (DefArg.isInvalid())
3206 return true;
3207
3208 Arg = DefArg.takeAs<Expr>();
3209 }
3210
3211 ConvertedArgs.push_back(Arg);
3212 }
3213
3214 // If this is a variadic call, handle args passed through "...".
3215 if (Proto->isVariadic()) {
3216 // Promote the arguments (C99 6.5.2.2p7).
3217 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3218 Expr *Arg = Args[i];
3219 if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3220 return true;
3221
3222 ConvertedArgs.push_back(Arg);
3223 Args[i] = 0;
3224 }
3225 }
3226
3227 return false;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003228}
3229
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003230/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3231/// determine whether they are reference-related,
3232/// reference-compatible, reference-compatible with added
3233/// qualification, or incompatible, for use in C++ initialization by
3234/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3235/// type, and the first type (T1) is the pointee type of the reference
3236/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00003237Sema::ReferenceCompareResult
3238Sema::CompareReferenceRelationship(QualType T1, QualType T2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003239 bool& DerivedToBase) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003240 assert(!T1->isReferenceType() &&
3241 "T1 must be the pointee type of the reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003242 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
3243
3244 T1 = Context.getCanonicalType(T1);
3245 T2 = Context.getCanonicalType(T2);
3246 QualType UnqualT1 = T1.getUnqualifiedType();
3247 QualType UnqualT2 = T2.getUnqualifiedType();
3248
3249 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003250 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00003251 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003252 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003253 if (UnqualT1 == UnqualT2)
3254 DerivedToBase = false;
3255 else if (IsDerivedFrom(UnqualT2, UnqualT1))
3256 DerivedToBase = true;
3257 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003258 return Ref_Incompatible;
3259
3260 // At this point, we know that T1 and T2 are reference-related (at
3261 // least).
3262
3263 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003264 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003265 // reference-related to T2 and cv1 is the same cv-qualification
3266 // as, or greater cv-qualification than, cv2. For purposes of
3267 // overload resolution, cases for which cv1 is greater
3268 // cv-qualification than cv2 are identified as
3269 // reference-compatible with added qualification (see 13.3.3.2).
3270 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3271 return Ref_Compatible;
3272 else if (T1.isMoreQualifiedThan(T2))
3273 return Ref_Compatible_With_Added_Qualification;
3274 else
3275 return Ref_Related;
3276}
3277
3278/// CheckReferenceInit - Check the initialization of a reference
3279/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3280/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00003281/// list), and DeclType is the type of the declaration. When ICS is
3282/// non-null, this routine will compute the implicit conversion
3283/// sequence according to C++ [over.ics.ref] and will not produce any
3284/// diagnostics; when ICS is null, it will emit diagnostics when any
3285/// errors are found. Either way, a return value of true indicates
3286/// that there was a failure, a return value of false indicates that
3287/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00003288///
3289/// When @p SuppressUserConversions, user-defined conversions are
3290/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003291/// When @p AllowExplicit, we also permit explicit user-defined
3292/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00003293/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00003294bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003295Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003296 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00003297 bool AllowExplicit, bool ForceRValue,
3298 ImplicitConversionSequence *ICS) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003299 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3300
Ted Kremenek6217b802009-07-29 21:53:49 +00003301 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003302 QualType T2 = Init->getType();
3303
Douglas Gregor904eed32008-11-10 20:40:00 +00003304 // If the initializer is the address of an overloaded function, try
3305 // to resolve the overloaded function. If all goes well, T2 is the
3306 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00003307 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00003308 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003309 ICS != 0);
3310 if (Fn) {
3311 // Since we're performing this reference-initialization for
3312 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003313 if (!ICS) {
3314 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
3315 return true;
3316
Douglas Gregor904eed32008-11-10 20:40:00 +00003317 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003318 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003319
3320 T2 = Fn->getType();
3321 }
3322 }
3323
Douglas Gregor15da57e2008-10-29 02:00:59 +00003324 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003325 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00003326 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00003327 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3328 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003329 ReferenceCompareResult RefRelationship
Douglas Gregor15da57e2008-10-29 02:00:59 +00003330 = CompareReferenceRelationship(T1, T2, DerivedToBase);
3331
3332 // Most paths end in a failed conversion.
3333 if (ICS)
3334 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003335
3336 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00003337 // A reference to type "cv1 T1" is initialized by an expression
3338 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003339
3340 // -- If the initializer expression
3341
Sebastian Redla9845802009-03-29 15:27:50 +00003342 // Rvalue references cannot bind to lvalues (N2812).
3343 // There is absolutely no situation where they can. In particular, note that
3344 // this is ill-formed, even if B has a user-defined conversion to A&&:
3345 // B b;
3346 // A&& r = b;
3347 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3348 if (!ICS)
3349 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
3350 << Init->getSourceRange();
3351 return true;
3352 }
3353
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003354 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00003355 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3356 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00003357 //
3358 // Note that the bit-field check is skipped if we are just computing
3359 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003360 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003361 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003362 BindsDirectly = true;
3363
Douglas Gregor15da57e2008-10-29 02:00:59 +00003364 if (ICS) {
3365 // C++ [over.ics.ref]p1:
3366 // When a parameter of reference type binds directly (8.5.3)
3367 // to an argument expression, the implicit conversion sequence
3368 // is the identity conversion, unless the argument expression
3369 // has a type that is a derived class of the parameter type,
3370 // in which case the implicit conversion sequence is a
3371 // derived-to-base Conversion (13.3.3.1).
3372 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3373 ICS->Standard.First = ICK_Identity;
3374 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3375 ICS->Standard.Third = ICK_Identity;
3376 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3377 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003378 ICS->Standard.ReferenceBinding = true;
3379 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003380 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00003381 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003382
3383 // Nothing more to do: the inaccessibility/ambiguity check for
3384 // derived-to-base conversions is suppressed when we're
3385 // computing the implicit conversion sequence (C++
3386 // [over.best.ics]p2).
3387 return false;
3388 } else {
3389 // Perform the conversion.
Douglas Gregor39da0b82009-09-09 23:08:42 +00003390 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3391 if (DerivedToBase)
3392 CK = CastExpr::CK_DerivedToBase;
3393 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003394 }
3395 }
3396
3397 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00003398 // implicitly converted to an lvalue of type "cv3 T3,"
3399 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003400 // 92) (this conversion is selected by enumerating the
3401 // applicable conversion functions (13.3.1.6) and choosing
3402 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00003403 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
3404 !RequireCompleteType(SourceLocation(), T2, 0)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003405 // FIXME: Look for conversions in base classes!
Mike Stump1eb44332009-09-09 15:08:12 +00003406 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003407 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003408
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003409 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003410 OverloadedFunctionDecl *Conversions
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003411 = T2RecordDecl->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00003412 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003413 = Conversions->function_begin();
3414 Func != Conversions->function_end(); ++Func) {
Mike Stump1eb44332009-09-09 15:08:12 +00003415 FunctionTemplateDecl *ConvTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003416 = dyn_cast<FunctionTemplateDecl>(*Func);
3417 CXXConversionDecl *Conv;
3418 if (ConvTemplate)
3419 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3420 else
3421 Conv = cast<CXXConversionDecl>(*Func);
Sebastian Redldfe292d2009-03-22 21:28:55 +00003422
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003423 // If the conversion function doesn't return a reference type,
3424 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003425 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003426 (AllowExplicit || !Conv->isExplicit())) {
3427 if (ConvTemplate)
Mike Stump1eb44332009-09-09 15:08:12 +00003428 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003429 CandidateSet);
3430 else
3431 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3432 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003433 }
3434
3435 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003436 switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003437 case OR_Success:
3438 // This is a direct binding.
3439 BindsDirectly = true;
3440
3441 if (ICS) {
3442 // C++ [over.ics.ref]p1:
3443 //
3444 // [...] If the parameter binds directly to the result of
3445 // applying a conversion function to the argument
3446 // expression, the implicit conversion sequence is a
3447 // user-defined conversion sequence (13.3.3.1.2), with the
3448 // second standard conversion sequence either an identity
3449 // conversion or, if the conversion function returns an
3450 // entity of a type that is a derived class of the parameter
3451 // type, a derived-to-base Conversion.
3452 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3453 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3454 ICS->UserDefined.After = Best->FinalConversion;
3455 ICS->UserDefined.ConversionFunction = Best->Function;
3456 assert(ICS->UserDefined.After.ReferenceBinding &&
3457 ICS->UserDefined.After.DirectBinding &&
3458 "Expected a direct reference binding!");
3459 return false;
3460 } else {
3461 // Perform the conversion.
Mike Stump390b4cc2009-05-16 07:39:55 +00003462 // FIXME: Binding to a subobject of the lvalue is going to require more
3463 // AST annotation than this.
Anders Carlsson3503d042009-07-31 01:23:52 +00003464 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003465 }
3466 break;
3467
3468 case OR_Ambiguous:
3469 assert(false && "Ambiguous reference binding conversions not implemented.");
3470 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003471
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003472 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003473 case OR_Deleted:
3474 // There was no suitable conversion, or we found a deleted
3475 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003476 break;
3477 }
3478 }
Mike Stump1eb44332009-09-09 15:08:12 +00003479
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003480 if (BindsDirectly) {
3481 // C++ [dcl.init.ref]p4:
3482 // [...] In all cases where the reference-related or
3483 // reference-compatible relationship of two types is used to
3484 // establish the validity of a reference binding, and T1 is a
3485 // base class of T2, a program that necessitates such a binding
3486 // is ill-formed if T1 is an inaccessible (clause 11) or
3487 // ambiguous (10.2) base class of T2.
3488 //
3489 // Note that we only check this condition when we're allowed to
3490 // complain about errors, because we should not be checking for
3491 // ambiguity (or inaccessibility) unless the reference binding
3492 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00003493 if (DerivedToBase)
3494 return CheckDerivedToBaseConversion(T2, T1,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003495 Init->getSourceRange().getBegin(),
3496 Init->getSourceRange());
3497 else
3498 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003499 }
3500
3501 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00003502 // type (i.e., cv1 shall be const), or the reference shall be an
3503 // rvalue reference and the initializer expression shall be an rvalue.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003504 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00003505 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003506 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003507 diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00003508 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3509 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003510 return true;
3511 }
3512
3513 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00003514 // class type, and "cv1 T1" is reference-compatible with
3515 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003516 // following ways (the choice is implementation-defined):
3517 //
3518 // -- The reference is bound to the object represented by
3519 // the rvalue (see 3.10) or to a sub-object within that
3520 // object.
3521 //
Eli Friedman33a31382009-08-05 19:21:58 +00003522 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003523 // a constructor is called to copy the entire rvalue
3524 // object into the temporary. The reference is bound to
3525 // the temporary or to a sub-object within the
3526 // temporary.
3527 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003528 // The constructor that would be used to make the copy
3529 // shall be callable whether or not the copy is actually
3530 // done.
3531 //
Sebastian Redla9845802009-03-29 15:27:50 +00003532 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003533 // freedom, so we will always take the first option and never build
3534 // a temporary in this case. FIXME: We will, however, have to check
3535 // for the presence of a copy constructor in C++98/03 mode.
3536 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003537 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3538 if (ICS) {
3539 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3540 ICS->Standard.First = ICK_Identity;
3541 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3542 ICS->Standard.Third = ICK_Identity;
3543 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3544 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003545 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003546 ICS->Standard.DirectBinding = false;
3547 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00003548 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003549 } else {
Douglas Gregor39da0b82009-09-09 23:08:42 +00003550 CastExpr::CastKind CK = CastExpr::CK_NoOp;
3551 if (DerivedToBase)
3552 CK = CastExpr::CK_DerivedToBase;
3553 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003554 }
3555 return false;
3556 }
3557
Eli Friedman33a31382009-08-05 19:21:58 +00003558 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003559 // initialized from the initializer expression using the
3560 // rules for a non-reference copy initialization (8.5). The
3561 // reference is then bound to the temporary. If T1 is
3562 // reference-related to T2, cv1 must be the same
3563 // cv-qualification as, or greater cv-qualification than,
3564 // cv2; otherwise, the program is ill-formed.
3565 if (RefRelationship == Ref_Related) {
3566 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3567 // we would be reference-compatible or reference-compatible with
3568 // added qualification. But that wasn't the case, so the reference
3569 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003570 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003571 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003572 diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00003573 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3574 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003575 return true;
3576 }
3577
Douglas Gregor734d9862009-01-30 23:27:23 +00003578 // If at least one of the types is a class type, the types are not
3579 // related, and we aren't allowed any user conversions, the
3580 // reference binding fails. This case is important for breaking
3581 // recursion, since TryImplicitConversion below will attempt to
3582 // create a temporary through the use of a copy constructor.
3583 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3584 (T1->isRecordType() || T2->isRecordType())) {
3585 if (!ICS)
3586 Diag(Init->getSourceRange().getBegin(),
3587 diag::err_typecheck_convert_incompatible)
3588 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3589 return true;
3590 }
3591
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003592 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003593 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00003594 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003595 //
Sebastian Redla9845802009-03-29 15:27:50 +00003596 // When a parameter of reference type is not bound directly to
3597 // an argument expression, the conversion sequence is the one
3598 // required to convert the argument expression to the
3599 // underlying type of the reference according to
3600 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3601 // to copy-initializing a temporary of the underlying type with
3602 // the argument expression. Any difference in top-level
3603 // cv-qualification is subsumed by the initialization itself
3604 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003605 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
3606 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00003607 /*ForceRValue=*/false,
3608 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003609
Sebastian Redla9845802009-03-29 15:27:50 +00003610 // Of course, that's still a reference binding.
3611 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3612 ICS->Standard.ReferenceBinding = true;
3613 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003614 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00003615 ImplicitConversionSequence::UserDefinedConversion) {
3616 ICS->UserDefined.After.ReferenceBinding = true;
3617 ICS->UserDefined.After.RRefBinding = isRValRef;
3618 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00003619 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3620 } else {
Douglas Gregor45920e82008-12-19 17:40:08 +00003621 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor15da57e2008-10-29 02:00:59 +00003622 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003623}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003624
3625/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3626/// of this overloaded operator is well-formed. If so, returns false;
3627/// otherwise, emits appropriate diagnostics and returns true.
3628bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003629 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003630 "Expected an overloaded operator declaration");
3631
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003632 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
3633
Mike Stump1eb44332009-09-09 15:08:12 +00003634 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003635 // The allocation and deallocation functions, operator new,
3636 // operator new[], operator delete and operator delete[], are
3637 // described completely in 3.7.3. The attributes and restrictions
3638 // found in the rest of this subclause do not apply to them unless
3639 // explicitly stated in 3.7.3.
Mike Stump390b4cc2009-05-16 07:39:55 +00003640 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003641 if (Op == OO_New || Op == OO_Array_New ||
3642 Op == OO_Delete || Op == OO_Array_Delete)
3643 return false;
3644
3645 // C++ [over.oper]p6:
3646 // An operator function shall either be a non-static member
3647 // function or be a non-member function and have at least one
3648 // parameter whose type is a class, a reference to a class, an
3649 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003650 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
3651 if (MethodDecl->isStatic())
3652 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003653 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003654 } else {
3655 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003656 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
3657 ParamEnd = FnDecl->param_end();
3658 Param != ParamEnd; ++Param) {
3659 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00003660 if (ParamType->isDependentType() || ParamType->isRecordType() ||
3661 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003662 ClassOrEnumParam = true;
3663 break;
3664 }
3665 }
3666
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003667 if (!ClassOrEnumParam)
3668 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003669 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003670 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003671 }
3672
3673 // C++ [over.oper]p8:
3674 // An operator function cannot have default arguments (8.3.6),
3675 // except where explicitly stated below.
3676 //
Mike Stump1eb44332009-09-09 15:08:12 +00003677 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003678 // (C++ [over.call]p1).
3679 if (Op != OO_Call) {
3680 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
3681 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00003682 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00003683 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00003684 diag::err_operator_overload_default_arg)
3685 << FnDecl->getDeclName();
3686 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003687 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003688 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003689 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003690 }
3691 }
3692
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003693 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
3694 { false, false, false }
3695#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3696 , { Unary, Binary, MemberOnly }
3697#include "clang/Basic/OperatorKinds.def"
3698 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003699
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003700 bool CanBeUnaryOperator = OperatorUses[Op][0];
3701 bool CanBeBinaryOperator = OperatorUses[Op][1];
3702 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003703
3704 // C++ [over.oper]p8:
3705 // [...] Operator functions cannot have more or fewer parameters
3706 // than the number required for the corresponding operator, as
3707 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00003708 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003709 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003710 if (Op != OO_Call &&
3711 ((NumParams == 1 && !CanBeUnaryOperator) ||
3712 (NumParams == 2 && !CanBeBinaryOperator) ||
3713 (NumParams < 1) || (NumParams > 2))) {
3714 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00003715 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003716 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00003717 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003718 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00003719 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003720 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00003721 assert(CanBeBinaryOperator &&
3722 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00003723 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003724 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003725
Chris Lattner416e46f2008-11-21 07:57:12 +00003726 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003727 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003728 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003729
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003730 // Overloaded operators other than operator() cannot be variadic.
3731 if (Op != OO_Call &&
Douglas Gregor72564e72009-02-26 23:50:07 +00003732 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003733 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003734 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003735 }
3736
3737 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003738 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
3739 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003740 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003741 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003742 }
3743
3744 // C++ [over.inc]p1:
3745 // The user-defined function called operator++ implements the
3746 // prefix and postfix ++ operator. If this function is a member
3747 // function with no parameters, or a non-member function with one
3748 // parameter of class or enumeration type, it defines the prefix
3749 // increment operator ++ for objects of that type. If the function
3750 // is a member function with one parameter (which shall be of type
3751 // int) or a non-member function with two parameters (the second
3752 // of which shall be of type int), it defines the postfix
3753 // increment operator ++ for objects of that type.
3754 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
3755 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
3756 bool ParamIsInt = false;
3757 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
3758 ParamIsInt = BT->getKind() == BuiltinType::Int;
3759
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00003760 if (!ParamIsInt)
3761 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003762 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00003763 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003764 }
3765
Sebastian Redl64b45f72009-01-05 20:52:13 +00003766 // Notify the class if it got an assignment operator.
3767 if (Op == OO_Equal) {
3768 // Would have returned earlier otherwise.
3769 assert(isa<CXXMethodDecl>(FnDecl) &&
3770 "Overloaded = not member, but not filtered.");
3771 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Fariborz Jahanianad258832009-08-13 21:09:41 +00003772 Method->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003773 Method->getParent()->addedAssignmentOperator(Context, Method);
3774 }
3775
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003776 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003777}
Chris Lattner5a003a42008-12-17 07:09:26 +00003778
Douglas Gregor074149e2009-01-05 19:45:36 +00003779/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
3780/// linkage specification, including the language and (if present)
3781/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
3782/// the location of the language string literal, which is provided
3783/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
3784/// the '{' brace. Otherwise, this linkage specification does not
3785/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003786Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
3787 SourceLocation ExternLoc,
3788 SourceLocation LangLoc,
3789 const char *Lang,
3790 unsigned StrSize,
3791 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00003792 LinkageSpecDecl::LanguageIDs Language;
3793 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3794 Language = LinkageSpecDecl::lang_c;
3795 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3796 Language = LinkageSpecDecl::lang_cxx;
3797 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00003798 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003799 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00003800 }
Mike Stump1eb44332009-09-09 15:08:12 +00003801
Chris Lattnercc98eac2008-12-17 07:13:27 +00003802 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00003803
Douglas Gregor074149e2009-01-05 19:45:36 +00003804 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00003805 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00003806 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003807 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00003808 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003809 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00003810}
3811
Douglas Gregor074149e2009-01-05 19:45:36 +00003812/// ActOnFinishLinkageSpecification - Completely the definition of
3813/// the C++ linkage specification LinkageSpec. If RBraceLoc is
3814/// valid, it's the position of the closing '}' brace in a linkage
3815/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003816Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
3817 DeclPtrTy LinkageSpec,
3818 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00003819 if (LinkageSpec)
3820 PopDeclContext();
3821 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00003822}
3823
Douglas Gregord308e622009-05-18 20:51:54 +00003824/// \brief Perform semantic analysis for the variable declaration that
3825/// occurs within a C++ catch clause, returning the newly-created
3826/// variable.
3827VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003828 DeclaratorInfo *DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00003829 IdentifierInfo *Name,
3830 SourceLocation Loc,
3831 SourceRange Range) {
3832 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003833
3834 // Arrays and functions decay.
3835 if (ExDeclType->isArrayType())
3836 ExDeclType = Context.getArrayDecayedType(ExDeclType);
3837 else if (ExDeclType->isFunctionType())
3838 ExDeclType = Context.getPointerType(ExDeclType);
3839
3840 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
3841 // The exception-declaration shall not denote a pointer or reference to an
3842 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003843 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00003844 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00003845 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003846 Invalid = true;
3847 }
Douglas Gregord308e622009-05-18 20:51:54 +00003848
Sebastian Redl4b07b292008-12-22 19:15:10 +00003849 QualType BaseType = ExDeclType;
3850 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003851 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00003852 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003853 BaseType = Ptr->getPointeeType();
3854 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003855 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00003856 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003857 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00003858 BaseType = Ref->getPointeeType();
3859 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003860 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003861 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003862 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00003863 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00003864 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003865
Mike Stump1eb44332009-09-09 15:08:12 +00003866 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00003867 RequireNonAbstractType(Loc, ExDeclType,
3868 diag::err_abstract_type_in_decl,
3869 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00003870 Invalid = true;
3871
Douglas Gregord308e622009-05-18 20:51:54 +00003872 // FIXME: Need to test for ability to copy-construct and destroy the
3873 // exception variable.
3874
Sebastian Redl8351da02008-12-22 21:35:02 +00003875 // FIXME: Need to check for abstract classes.
3876
Mike Stump1eb44332009-09-09 15:08:12 +00003877 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003878 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00003879
3880 if (Invalid)
3881 ExDecl->setInvalidDecl();
3882
3883 return ExDecl;
3884}
3885
3886/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
3887/// handler.
3888Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003889 DeclaratorInfo *DInfo = 0;
3890 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00003891
3892 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00003893 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003894 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003895 // The scope should be freshly made just for us. There is just no way
3896 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003897 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00003898 if (PrevDecl->isTemplateParameter()) {
3899 // Maybe we will complain about the shadowed template parameter.
3900 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003901 }
3902 }
3903
Chris Lattnereaaebc72009-04-25 08:06:05 +00003904 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003905 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
3906 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00003907 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003908 }
3909
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003910 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00003911 D.getIdentifier(),
3912 D.getIdentifierLoc(),
3913 D.getDeclSpec().getSourceRange());
3914
Chris Lattnereaaebc72009-04-25 08:06:05 +00003915 if (Invalid)
3916 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003917
Sebastian Redl4b07b292008-12-22 19:15:10 +00003918 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00003919 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00003920 PushOnScopeChains(ExDecl, S);
3921 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003922 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003923
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003924 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003925 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003926}
Anders Carlssonfb311762009-03-14 00:25:26 +00003927
Mike Stump1eb44332009-09-09 15:08:12 +00003928Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003929 ExprArg assertexpr,
3930 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00003931 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003932 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00003933 cast<StringLiteral>((Expr *)assertmessageexpr.get());
3934
Anders Carlssonc3082412009-03-14 00:33:21 +00003935 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
3936 llvm::APSInt Value(32);
3937 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
3938 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
3939 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003940 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00003941 }
Anders Carlssonfb311762009-03-14 00:25:26 +00003942
Anders Carlssonc3082412009-03-14 00:33:21 +00003943 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00003944 std::string str(AssertMessage->getStrData(),
Anders Carlssonc3082412009-03-14 00:33:21 +00003945 AssertMessage->getByteLength());
Mike Stump1eb44332009-09-09 15:08:12 +00003946 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson94b15fb2009-03-15 18:44:04 +00003947 << str << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00003948 }
3949 }
Mike Stump1eb44332009-09-09 15:08:12 +00003950
Anders Carlsson77d81422009-03-15 17:35:16 +00003951 assertexpr.release();
3952 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003953 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00003954 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00003955
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003956 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003957 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00003958}
Sebastian Redl50de12f2009-03-24 22:27:57 +00003959
John McCall67d1a672009-08-06 02:15:43 +00003960Sema::DeclPtrTy Sema::ActOnFriendDecl(Scope *S,
John McCall3f9a8a62009-08-11 06:59:38 +00003961 llvm::PointerUnion<const DeclSpec*,Declarator*> DU,
3962 bool IsDefinition) {
John McCall02cace72009-08-28 07:59:38 +00003963 if (DU.is<Declarator*>())
3964 return ActOnFriendFunctionDecl(S, *DU.get<Declarator*>(), IsDefinition);
3965 else
3966 return ActOnFriendTypeDecl(S, *DU.get<const DeclSpec*>(), IsDefinition);
3967}
3968
3969Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S,
3970 const DeclSpec &DS,
3971 bool IsDefinition) {
3972 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00003973
3974 assert(DS.isFriendSpecified());
3975 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
3976
John McCall6b2becf2009-09-08 17:47:29 +00003977 // Try to convert the decl specifier to a type.
3978 bool invalid = false;
3979 QualType T = ConvertDeclSpecToType(DS, Loc, invalid);
3980 if (invalid) return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00003981
John McCall02cace72009-08-28 07:59:38 +00003982 // C++ [class.friend]p2:
3983 // An elaborated-type-specifier shall be used in a friend declaration
3984 // for a class.*
3985 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00003986 // This is one of the rare places in Clang where it's legitimate to
3987 // ask about the "spelling" of the type.
3988 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
3989 // If we evaluated the type to a record type, suggest putting
3990 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00003991 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00003992 RecordDecl *RD = RT->getDecl();
3993
3994 std::string InsertionText = std::string(" ") + RD->getKindName();
3995
3996 Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type)
3997 << (RD->isUnion())
3998 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
3999 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00004000 return DeclPtrTy();
4001 }else {
John McCall6b2becf2009-09-08 17:47:29 +00004002 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4003 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004004 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00004005 }
4006 }
4007
John McCall6b2becf2009-09-08 17:47:29 +00004008 FriendDecl::FriendUnion FU = T.getTypePtr();
4009
4010 // The parser doesn't quite handle
4011 // friend class A { ... }
4012 // optimally, because it might have been the (valid) prefix of
4013 // friend class A { ... } foo();
4014 // So in a very particular set of circumstances, we need to adjust
4015 // IsDefinition.
4016 //
4017 // Also, if we made a RecordDecl in ActOnTag, we want that to be the
4018 // object of our friend declaration.
4019 switch (DS.getTypeSpecType()) {
4020 default: break;
4021 case DeclSpec::TST_class:
4022 case DeclSpec::TST_struct:
4023 case DeclSpec::TST_union:
4024 CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep());
4025 if (RD) {
4026 IsDefinition |= RD->isDefinition();
4027 FU = RD;
4028 }
4029 break;
4030 }
John McCall02cace72009-08-28 07:59:38 +00004031
4032 // C++ [class.friend]p2: A class shall not be defined inside
4033 // a friend declaration.
4034 if (IsDefinition) {
4035 Diag(DS.getFriendSpecLoc(), diag::err_friend_decl_defines_class)
4036 << DS.getSourceRange();
4037 return DeclPtrTy();
4038 }
4039
4040 // C++98 [class.friend]p1: A friend of a class is a function
4041 // or class that is not a member of the class . . .
4042 // But that's a silly restriction which nobody implements for
4043 // inner classes, and C++0x removes it anyway, so we only report
4044 // this (as a warning) if we're being pedantic.
John McCall6b2becf2009-09-08 17:47:29 +00004045 if (!getLangOptions().CPlusPlus0x)
4046 if (const RecordType *RT = T->getAs<RecordType>())
4047 if (RT->getDecl()->getDeclContext() == CurContext)
4048 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCall02cace72009-08-28 07:59:38 +00004049
4050 FriendDecl *FD = FriendDecl::Create(Context, CurContext, Loc, FU,
4051 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00004052 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00004053 CurContext->addDecl(FD);
4054
4055 return DeclPtrTy::make(FD);
4056}
4057
4058Sema::DeclPtrTy Sema::ActOnFriendFunctionDecl(Scope *S,
4059 Declarator &D,
4060 bool IsDefinition) {
4061 const DeclSpec &DS = D.getDeclSpec();
4062
4063 assert(DS.isFriendSpecified());
4064 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4065
4066 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004067 DeclaratorInfo *DInfo = 0;
John McCall02cace72009-08-28 07:59:38 +00004068 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall67d1a672009-08-06 02:15:43 +00004069
4070 // C++ [class.friend]p1
4071 // A friend of a class is a function or class....
4072 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00004073 // It *doesn't* see through dependent types, which is correct
4074 // according to [temp.arg.type]p3:
4075 // If a declaration acquires a function type through a
4076 // type dependent on a template-parameter and this causes
4077 // a declaration that does not use the syntactic form of a
4078 // function declarator to have a function type, the program
4079 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00004080 if (!T->isFunctionType()) {
4081 Diag(Loc, diag::err_unexpected_friend);
4082
4083 // It might be worthwhile to try to recover by creating an
4084 // appropriate declaration.
4085 return DeclPtrTy();
4086 }
4087
4088 // C++ [namespace.memdef]p3
4089 // - If a friend declaration in a non-local class first declares a
4090 // class or function, the friend class or function is a member
4091 // of the innermost enclosing namespace.
4092 // - The name of the friend is not found by simple name lookup
4093 // until a matching declaration is provided in that namespace
4094 // scope (either before or after the class declaration granting
4095 // friendship).
4096 // - If a friend function is called, its name may be found by the
4097 // name lookup that considers functions from namespaces and
4098 // classes associated with the types of the function arguments.
4099 // - When looking for a prior declaration of a class or a function
4100 // declared as a friend, scopes outside the innermost enclosing
4101 // namespace scope are not considered.
4102
John McCall02cace72009-08-28 07:59:38 +00004103 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4104 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00004105 assert(Name);
4106
4107 // The existing declaration we found.
4108 FunctionDecl *FD = NULL;
4109
4110 // The context we found the declaration in, or in which we should
4111 // create the declaration.
4112 DeclContext *DC;
4113
4114 // FIXME: handle local classes
4115
4116 // Recover from invalid scope qualifiers as if they just weren't there.
4117 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
4118 DC = computeDeclContext(ScopeQual);
4119
4120 // FIXME: handle dependent contexts
4121 if (!DC) return DeclPtrTy();
4122
4123 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
4124
4125 // If searching in that context implicitly found a declaration in
4126 // a different context, treat it like it wasn't found at all.
4127 // TODO: better diagnostics for this case. Suggesting the right
4128 // qualified scope would be nice...
4129 if (!Dec || Dec->getDeclContext() != DC) {
John McCall02cace72009-08-28 07:59:38 +00004130 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00004131 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4132 return DeclPtrTy();
4133 }
4134
4135 // C++ [class.friend]p1: A friend of a class is a function or
4136 // class that is not a member of the class . . .
4137 if (DC == CurContext)
4138 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4139
4140 FD = cast<FunctionDecl>(Dec);
4141
4142 // Otherwise walk out to the nearest namespace scope looking for matches.
4143 } else {
4144 // TODO: handle local class contexts.
4145
4146 DC = CurContext;
4147 while (true) {
4148 // Skip class contexts. If someone can cite chapter and verse
4149 // for this behavior, that would be nice --- it's what GCC and
4150 // EDG do, and it seems like a reasonable intent, but the spec
4151 // really only says that checks for unqualified existing
4152 // declarations should stop at the nearest enclosing namespace,
4153 // not that they should only consider the nearest enclosing
4154 // namespace.
4155 while (DC->isRecord()) DC = DC->getParent();
4156
4157 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
4158
4159 // TODO: decide what we think about using declarations.
4160 if (Dec) {
4161 FD = cast<FunctionDecl>(Dec);
4162 break;
4163 }
4164 if (DC->isFileContext()) break;
4165 DC = DC->getParent();
4166 }
4167
4168 // C++ [class.friend]p1: A friend of a class is a function or
4169 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00004170 // C++0x changes this for both friend types and functions.
4171 // Most C++ 98 compilers do seem to give an error here, so
4172 // we do, too.
4173 if (FD && DC == CurContext && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00004174 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4175 }
4176
John McCall3f9a8a62009-08-11 06:59:38 +00004177 bool Redeclaration = (FD != 0);
4178
4179 // If we found a match, create a friend function declaration with
4180 // that function as the previous declaration.
4181 if (Redeclaration) {
4182 // Create it in the semantic context of the original declaration.
4183 DC = FD->getDeclContext();
4184
John McCall67d1a672009-08-06 02:15:43 +00004185 // If we didn't find something matching the type exactly, create
4186 // a declaration. This declaration should only be findable via
4187 // argument-dependent lookup.
John McCall3f9a8a62009-08-11 06:59:38 +00004188 } else {
John McCall67d1a672009-08-06 02:15:43 +00004189 assert(DC->isFileContext());
4190
4191 // This implies that it has to be an operator or function.
John McCall02cace72009-08-28 07:59:38 +00004192 if (D.getKind() == Declarator::DK_Constructor ||
4193 D.getKind() == Declarator::DK_Destructor ||
4194 D.getKind() == Declarator::DK_Conversion) {
John McCall67d1a672009-08-06 02:15:43 +00004195 Diag(Loc, diag::err_introducing_special_friend) <<
John McCall02cace72009-08-28 07:59:38 +00004196 (D.getKind() == Declarator::DK_Constructor ? 0 :
4197 D.getKind() == Declarator::DK_Destructor ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00004198 return DeclPtrTy();
4199 }
John McCall67d1a672009-08-06 02:15:43 +00004200 }
4201
John McCall02cace72009-08-28 07:59:38 +00004202 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo,
John McCall3f9a8a62009-08-11 06:59:38 +00004203 /* PrevDecl = */ FD,
4204 MultiTemplateParamsArg(*this),
4205 IsDefinition,
4206 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00004207 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00004208
4209 assert(cast<FunctionDecl>(ND)->getPreviousDeclaration() == FD &&
4210 "lost reference to previous declaration");
4211
John McCall02cace72009-08-28 07:59:38 +00004212 FD = cast<FunctionDecl>(ND);
John McCall3f9a8a62009-08-11 06:59:38 +00004213
John McCall88232aa2009-08-18 00:00:49 +00004214 assert(FD->getDeclContext() == DC);
4215 assert(FD->getLexicalDeclContext() == CurContext);
4216
John McCallab88d972009-08-31 22:39:49 +00004217 // Add the function declaration to the appropriate lookup tables,
4218 // adjusting the redeclarations list as necessary. We don't
4219 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00004220 //
John McCallab88d972009-08-31 22:39:49 +00004221 // Also update the scope-based lookup if the target context's
4222 // lookup context is in lexical scope.
4223 if (!CurContext->isDependentContext()) {
4224 DC = DC->getLookupContext();
4225 DC->makeDeclVisibleInContext(FD, /* Recoverable=*/ false);
4226 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4227 PushOnScopeChains(FD, EnclosingScope, /*AddToContext=*/ false);
4228 }
John McCall02cace72009-08-28 07:59:38 +00004229
4230 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
4231 D.getIdentifierLoc(), FD,
4232 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00004233 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00004234 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00004235
4236 return DeclPtrTy::make(FD);
Anders Carlsson00338362009-05-11 22:55:49 +00004237}
4238
Chris Lattnerb28317a2009-03-28 19:18:32 +00004239void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004240 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004241
Chris Lattnerb28317a2009-03-28 19:18:32 +00004242 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00004243 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4244 if (!Fn) {
4245 Diag(DelLoc, diag::err_deleted_non_function);
4246 return;
4247 }
4248 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4249 Diag(DelLoc, diag::err_deleted_decl_not_first);
4250 Diag(Prev->getLocation(), diag::note_previous_declaration);
4251 // If the declaration wasn't the first, we delete the function anyway for
4252 // recovery.
4253 }
4254 Fn->setDeleted();
4255}
Sebastian Redl13e88542009-04-27 21:33:24 +00004256
4257static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4258 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4259 ++CI) {
4260 Stmt *SubStmt = *CI;
4261 if (!SubStmt)
4262 continue;
4263 if (isa<ReturnStmt>(SubStmt))
4264 Self.Diag(SubStmt->getSourceRange().getBegin(),
4265 diag::err_return_in_constructor_handler);
4266 if (!isa<Expr>(SubStmt))
4267 SearchForReturnInStmt(Self, SubStmt);
4268 }
4269}
4270
4271void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4272 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4273 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4274 SearchForReturnInStmt(*this, Handler);
4275 }
4276}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004277
Mike Stump1eb44332009-09-09 15:08:12 +00004278bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004279 const CXXMethodDecl *Old) {
4280 QualType NewTy = New->getType()->getAsFunctionType()->getResultType();
4281 QualType OldTy = Old->getType()->getAsFunctionType()->getResultType();
4282
4283 QualType CNewTy = Context.getCanonicalType(NewTy);
4284 QualType COldTy = Context.getCanonicalType(OldTy);
4285
Mike Stump1eb44332009-09-09 15:08:12 +00004286 if (CNewTy == COldTy &&
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004287 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
4288 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004289
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004290 // Check if the return types are covariant
4291 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004292
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004293 /// Both types must be pointers or references to classes.
4294 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4295 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4296 NewClassTy = NewPT->getPointeeType();
4297 OldClassTy = OldPT->getPointeeType();
4298 }
4299 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4300 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4301 NewClassTy = NewRT->getPointeeType();
4302 OldClassTy = OldRT->getPointeeType();
4303 }
4304 }
Mike Stump1eb44332009-09-09 15:08:12 +00004305
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004306 // The return types aren't either both pointers or references to a class type.
4307 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004308 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004309 diag::err_different_return_type_for_overriding_virtual_function)
4310 << New->getDeclName() << NewTy << OldTy;
4311 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00004312
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004313 return true;
4314 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004315
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004316 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
4317 // Check if the new class derives from the old class.
4318 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4319 Diag(New->getLocation(),
4320 diag::err_covariant_return_not_derived)
4321 << New->getDeclName() << NewTy << OldTy;
4322 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4323 return true;
4324 }
Mike Stump1eb44332009-09-09 15:08:12 +00004325
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004326 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00004327 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004328 diag::err_covariant_return_inaccessible_base,
4329 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4330 // FIXME: Should this point to the return type?
4331 New->getLocation(), SourceRange(), New->getDeclName())) {
4332 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4333 return true;
4334 }
4335 }
Mike Stump1eb44332009-09-09 15:08:12 +00004336
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004337 // The qualifiers of the return types must be the same.
4338 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
4339 Diag(New->getLocation(),
4340 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004341 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004342 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4343 return true;
4344 };
Mike Stump1eb44332009-09-09 15:08:12 +00004345
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004346
4347 // The new class type must have the same or less qualifiers as the old type.
4348 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4349 Diag(New->getLocation(),
4350 diag::err_covariant_return_type_class_type_more_qualified)
4351 << New->getDeclName() << NewTy << OldTy;
4352 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4353 return true;
4354 };
Mike Stump1eb44332009-09-09 15:08:12 +00004355
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004356 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004357}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004358
Sebastian Redl23c7d062009-07-07 20:29:57 +00004359bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
Mike Stump1eb44332009-09-09 15:08:12 +00004360 const CXXMethodDecl *Old) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00004361 return CheckExceptionSpecSubset(diag::err_override_exception_spec,
4362 diag::note_overridden_virtual_function,
4363 Old->getType()->getAsFunctionProtoType(),
4364 Old->getLocation(),
4365 New->getType()->getAsFunctionProtoType(),
4366 New->getLocation());
4367}
4368
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004369/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4370/// initializer for the declaration 'Dcl'.
4371/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4372/// static data member of class X, names should be looked up in the scope of
4373/// class X.
4374void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004375 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004376
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004377 Decl *D = Dcl.getAs<Decl>();
4378 // If there is no declaration, there was an error parsing it.
4379 if (D == 0)
4380 return;
4381
4382 // Check whether it is a declaration with a nested name specifier like
4383 // int foo::bar;
4384 if (!D->isOutOfLine())
4385 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004386
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004387 // C++ [basic.lookup.unqual]p13
4388 //
4389 // A name used in the definition of a static data member of class X
4390 // (after the qualified-id of the static member) is looked up as if the name
4391 // was used in a member function of X.
Mike Stump1eb44332009-09-09 15:08:12 +00004392
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004393 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004394 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004395}
4396
4397/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4398/// initializer for the declaration 'Dcl'.
4399void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004400 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004401
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004402 Decl *D = Dcl.getAs<Decl>();
4403 // If there is no declaration, there was an error parsing it.
4404 if (D == 0)
4405 return;
4406
4407 // Check whether it is a declaration with a nested name specifier like
4408 // int foo::bar;
4409 if (!D->isOutOfLine())
4410 return;
4411
4412 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004413 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004414}