blob: 64dc41e31a49f812898b9c76fadceaf828a4e1cb [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>()) {
Eli Friedman59c04372009-07-29 19:44:27 +0000784 if (!HasDependentArg)
785 C = PerformInitializationByConstructor(
Mike Stump1eb44332009-09-09 15:08:12 +0000786 FieldType, (Expr **)Args, NumArgs, IdLoc,
Eli Friedman59c04372009-07-29 19:44:27 +0000787 SourceRange(IdLoc, RParenLoc), Member->getDeclName(), IK_Direct);
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +0000788 } else if (NumArgs != 1 && NumArgs != 0) {
Mike Stump1eb44332009-09-09 15:08:12 +0000789 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
Eli Friedman59c04372009-07-29 19:44:27 +0000790 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
791 } else if (!HasDependentArg) {
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +0000792 Expr *NewExp;
793 if (NumArgs == 0) {
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000794 if (FieldType->isReferenceType()) {
795 Diag(IdLoc, diag::err_null_intialized_reference_member)
796 << Member->getDeclName();
797 return Diag(Member->getLocation(), diag::note_declared_at);
798 }
Fariborz Jahanian636a0ff2009-09-02 17:10:17 +0000799 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc);
800 NumArgs = 1;
801 }
802 else
803 NewExp = (Expr*)Args[0];
Eli Friedman59c04372009-07-29 19:44:27 +0000804 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
805 return true;
806 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +0000807 }
Eli Friedman59c04372009-07-29 19:44:27 +0000808 // FIXME: Perform direct initialization of the member.
Mike Stump1eb44332009-09-09 15:08:12 +0000809 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +0000810 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +0000811}
812
813Sema::MemInitResult
814Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
815 unsigned NumArgs, SourceLocation IdLoc,
816 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
817 bool HasDependentArg = false;
818 for (unsigned i = 0; i < NumArgs; i++)
819 HasDependentArg |= Args[i]->isTypeDependent();
820
821 if (!BaseType->isDependentType()) {
822 if (!BaseType->isRecordType())
823 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
824 << BaseType << SourceRange(IdLoc, RParenLoc);
825
826 // C++ [class.base.init]p2:
827 // [...] Unless the mem-initializer-id names a nonstatic data
828 // member of the constructor’s class or a direct or virtual base
829 // of that class, the mem-initializer is ill-formed. A
830 // mem-initializer-list can initialize a base class using any
831 // name that denotes that base class type.
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Eli Friedman59c04372009-07-29 19:44:27 +0000833 // First, check for a direct base class.
834 const CXXBaseSpecifier *DirectBaseSpec = 0;
835 for (CXXRecordDecl::base_class_const_iterator Base =
836 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +0000837 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
Eli Friedman59c04372009-07-29 19:44:27 +0000838 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
839 // We found a direct base of this type. That's what we're
840 // initializing.
841 DirectBaseSpec = &*Base;
842 break;
843 }
844 }
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Eli Friedman59c04372009-07-29 19:44:27 +0000846 // Check for a virtual base class.
847 // FIXME: We might be able to short-circuit this if we know in advance that
848 // there are no virtual bases.
849 const CXXBaseSpecifier *VirtualBaseSpec = 0;
850 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
851 // We haven't found a base yet; search the class hierarchy for a
852 // virtual base class.
853 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
854 /*DetectVirtual=*/false);
855 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000856 for (BasePaths::paths_iterator Path = Paths.begin();
Eli Friedman59c04372009-07-29 19:44:27 +0000857 Path != Paths.end(); ++Path) {
858 if (Path->back().Base->isVirtual()) {
859 VirtualBaseSpec = Path->back().Base;
860 break;
861 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000862 }
863 }
864 }
Eli Friedman59c04372009-07-29 19:44:27 +0000865
866 // C++ [base.class.init]p2:
867 // If a mem-initializer-id is ambiguous because it designates both
868 // a direct non-virtual base class and an inherited virtual base
869 // class, the mem-initializer is ill-formed.
870 if (DirectBaseSpec && VirtualBaseSpec)
871 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
872 << BaseType << SourceRange(IdLoc, RParenLoc);
873 // C++ [base.class.init]p2:
874 // Unless the mem-initializer-id names a nonstatic data membeer of the
875 // constructor's class ot a direst or virtual base of that class, the
876 // mem-initializer is ill-formed.
877 if (!DirectBaseSpec && !VirtualBaseSpec)
878 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
879 << BaseType << ClassDecl->getNameAsCString()
880 << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000881 }
882
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +0000883 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +0000884 if (!BaseType->isDependentType() && !HasDependentArg) {
885 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
886 Context.getCanonicalType(BaseType));
887 C = PerformInitializationByConstructor(BaseType, (Expr **)Args, NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000888 IdLoc, SourceRange(IdLoc, RParenLoc),
Eli Friedman59c04372009-07-29 19:44:27 +0000889 Name, IK_Direct);
890 }
891
Mike Stump1eb44332009-09-09 15:08:12 +0000892 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +0000893 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000894}
895
Fariborz Jahanian87595e42009-07-23 23:32:59 +0000896void
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000897Sema::setBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
898 CXXBaseOrMemberInitializer **Initializers,
899 unsigned NumInitializers,
Mike Stump1eb44332009-09-09 15:08:12 +0000900 llvm::SmallVectorImpl<CXXBaseSpecifier *>& Bases,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000901 llvm::SmallVectorImpl<FieldDecl *>&Fields) {
902 // We need to build the initializer AST according to order of construction
903 // and not what user specified in the Initializers list.
904 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
905 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
906 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
907 bool HasDependentBaseInit = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000908
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000909 for (unsigned i = 0; i < NumInitializers; i++) {
910 CXXBaseOrMemberInitializer *Member = Initializers[i];
911 if (Member->isBaseInitializer()) {
912 if (Member->getBaseClass()->isDependentType())
913 HasDependentBaseInit = true;
914 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
915 } else {
916 AllBaseFields[Member->getMember()] = Member;
917 }
918 }
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000920 if (HasDependentBaseInit) {
921 // FIXME. This does not preserve the ordering of the initializers.
922 // Try (with -Wreorder)
923 // template<class X> struct A {};
Mike Stump1eb44332009-09-09 15:08:12 +0000924 // template<class X> struct B : A<X> {
925 // B() : x1(10), A<X>() {}
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000926 // int x1;
927 // };
928 // B<int> x;
929 // On seeing one dependent type, we should essentially exit this routine
930 // while preserving user-declared initializer list. When this routine is
931 // called during instantiatiation process, this routine will rebuild the
932 // oderdered initializer list correctly.
Mike Stump1eb44332009-09-09 15:08:12 +0000933
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000934 // If we have a dependent base initialization, we can't determine the
935 // association between initializers and bases; just dump the known
936 // initializers into the list, and don't try to deal with other bases.
937 for (unsigned i = 0; i < NumInitializers; i++) {
938 CXXBaseOrMemberInitializer *Member = Initializers[i];
939 if (Member->isBaseInitializer())
940 AllToInit.push_back(Member);
941 }
942 } else {
943 // Push virtual bases before others.
944 for (CXXRecordDecl::base_class_iterator VBase =
945 ClassDecl->vbases_begin(),
946 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
947 if (VBase->getType()->isDependentType())
948 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000949 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +0000950 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000951 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +0000952 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
953 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
954 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
955 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000956 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +0000957 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000958 else {
Mike Stump1eb44332009-09-09 15:08:12 +0000959 CXXRecordDecl *VBaseDecl =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000960 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
961 assert(VBaseDecl && "setBaseOrMemberInitializers - VBaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +0000962 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context);
963 if (!Ctor)
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000964 Bases.push_back(VBase);
Fariborz Jahanian9d436202009-09-03 21:32:41 +0000965 else
966 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
967
Mike Stump1eb44332009-09-09 15:08:12 +0000968 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000969 new (Context) CXXBaseOrMemberInitializer(VBase->getType(), 0, 0,
Fariborz Jahanian9d436202009-09-03 21:32:41 +0000970 Ctor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000971 SourceLocation(),
972 SourceLocation());
973 AllToInit.push_back(Member);
974 }
975 }
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000977 for (CXXRecordDecl::base_class_iterator Base =
978 ClassDecl->bases_begin(),
979 E = ClassDecl->bases_end(); Base != E; ++Base) {
980 // Virtuals are in the virtual base list and already constructed.
981 if (Base->isVirtual())
982 continue;
983 // Skip dependent types.
984 if (Base->getType()->isDependentType())
985 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000986 if (CXXBaseOrMemberInitializer *Value =
Fariborz Jahanian9d436202009-09-03 21:32:41 +0000987 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000988 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +0000989 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
990 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
991 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context))
992 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000993 AllToInit.push_back(Value);
Fariborz Jahanian9d436202009-09-03 21:32:41 +0000994 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000995 else {
Mike Stump1eb44332009-09-09 15:08:12 +0000996 CXXRecordDecl *BaseDecl =
Fariborz Jahanian9d436202009-09-03 21:32:41 +0000997 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +0000998 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null");
Fariborz Jahanian9d436202009-09-03 21:32:41 +0000999 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context);
1000 if (!Ctor)
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001001 Bases.push_back(Base);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001002 else
1003 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
1004
Mike Stump1eb44332009-09-09 15:08:12 +00001005 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001006 new (Context) CXXBaseOrMemberInitializer(Base->getType(), 0, 0,
1007 BaseDecl->getDefaultConstructor(Context),
1008 SourceLocation(),
1009 SourceLocation());
1010 AllToInit.push_back(Member);
1011 }
1012 }
1013 }
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001015 // non-static data members.
1016 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1017 E = ClassDecl->field_end(); Field != E; ++Field) {
1018 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001019 if (const RecordType *FieldClassType =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001020 Field->getType()->getAs<RecordType>()) {
1021 CXXRecordDecl *FieldClassDecl
1022 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001023 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001024 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1025 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1026 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1027 // set to the anonymous union data member used in the initializer
1028 // list.
1029 Value->setMember(*Field);
1030 Value->setAnonUnionMember(*FA);
1031 AllToInit.push_back(Value);
1032 break;
1033 }
1034 }
1035 }
1036 continue;
1037 }
1038 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001039 QualType FT = (*Field)->getType();
1040 if (const RecordType* RT = FT->getAs<RecordType>()) {
1041 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl());
1042 assert(FieldRecDecl && "setBaseOrMemberInitializers - BaseDecl null");
Mike Stump1eb44332009-09-09 15:08:12 +00001043 if (CXXConstructorDecl *Ctor =
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001044 FieldRecDecl->getDefaultConstructor(Context))
1045 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor);
1046 }
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001047 AllToInit.push_back(Value);
1048 continue;
1049 }
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001051 QualType FT = Context.getBaseElementType((*Field)->getType());
1052 if (const RecordType* RT = FT->getAs<RecordType>()) {
1053 CXXConstructorDecl *Ctor =
1054 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context);
1055 if (!Ctor && !FT->isDependentType())
1056 Fields.push_back(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001057 CXXBaseOrMemberInitializer *Member =
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001058 new (Context) CXXBaseOrMemberInitializer((*Field), 0, 0,
1059 Ctor,
1060 SourceLocation(),
1061 SourceLocation());
1062 AllToInit.push_back(Member);
Fariborz Jahanian9d436202009-09-03 21:32:41 +00001063 if (Ctor)
1064 MarkDeclarationReferenced(Constructor->getLocation(), Ctor);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001065 if (FT.isConstQualified() && (!Ctor || Ctor->isTrivial())) {
1066 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1067 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1068 Diag((*Field)->getLocation(), diag::note_declared_at);
1069 }
1070 }
1071 else if (FT->isReferenceType()) {
1072 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1073 << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getDeclName();
1074 Diag((*Field)->getLocation(), diag::note_declared_at);
1075 }
1076 else if (FT.isConstQualified()) {
1077 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor)
1078 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName();
1079 Diag((*Field)->getLocation(), diag::note_declared_at);
1080 }
1081 }
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001083 NumInitializers = AllToInit.size();
1084 if (NumInitializers > 0) {
1085 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1086 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1087 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001089 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1090 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1091 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1092 }
1093}
1094
1095void
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001096Sema::BuildBaseOrMemberInitializers(ASTContext &C,
1097 CXXConstructorDecl *Constructor,
1098 CXXBaseOrMemberInitializer **Initializers,
1099 unsigned NumInitializers
1100 ) {
1101 llvm::SmallVector<CXXBaseSpecifier *, 4>Bases;
1102 llvm::SmallVector<FieldDecl *, 4>Members;
Mike Stump1eb44332009-09-09 15:08:12 +00001103
1104 setBaseOrMemberInitializers(Constructor,
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00001105 Initializers, NumInitializers, Bases, Members);
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001106 for (unsigned int i = 0; i < Bases.size(); i++)
Mike Stump1eb44332009-09-09 15:08:12 +00001107 Diag(Bases[i]->getSourceRange().getBegin(),
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001108 diag::err_missing_default_constructor) << 0 << Bases[i]->getType();
1109 for (unsigned int i = 0; i < Members.size(); i++)
Mike Stump1eb44332009-09-09 15:08:12 +00001110 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor)
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001111 << 1 << Members[i]->getType();
1112}
1113
Eli Friedman6347f422009-07-21 19:28:10 +00001114static void *GetKeyForTopLevelField(FieldDecl *Field) {
1115 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00001116 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00001117 if (RT->getDecl()->isAnonymousStructOrUnion())
1118 return static_cast<void *>(RT->getDecl());
1119 }
1120 return static_cast<void *>(Field);
1121}
1122
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001123static void *GetKeyForBase(QualType BaseType) {
1124 if (const RecordType *RT = BaseType->getAs<RecordType>())
1125 return (void *)RT;
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001127 assert(0 && "Unexpected base type!");
1128 return 0;
1129}
1130
Mike Stump1eb44332009-09-09 15:08:12 +00001131static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001132 bool MemberMaybeAnon = false) {
Eli Friedman6347f422009-07-21 19:28:10 +00001133 // For fields injected into the class via declaration of an anonymous union,
1134 // use its anonymous union class declaration as the unique key.
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001135 if (Member->isMemberInitializer()) {
1136 FieldDecl *Field = Member->getMember();
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001138 // After BuildBaseOrMemberInitializers call, Field is the anonymous union
Mike Stump1eb44332009-09-09 15:08:12 +00001139 // data member of the class. Data member used in the initializer list is
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001140 // in AnonUnionMember field.
1141 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1142 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +00001143 if (Field->getDeclContext()->isRecord()) {
1144 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1145 if (RD->isAnonymousStructOrUnion())
1146 return static_cast<void *>(RD);
1147 }
1148 return static_cast<void *>(Field);
1149 }
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001151 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
Eli Friedman6347f422009-07-21 19:28:10 +00001152}
1153
Mike Stump1eb44332009-09-09 15:08:12 +00001154void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +00001155 SourceLocation ColonLoc,
1156 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001157 if (!ConstructorDecl)
1158 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001159
1160 AdjustDeclIfTemplate(ConstructorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001161
1162 CXXConstructorDecl *Constructor
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001163 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Anders Carlssona7b35212009-03-25 02:58:17 +00001165 if (!Constructor) {
1166 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1167 return;
1168 }
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001170 if (!Constructor->isDependentContext()) {
1171 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1172 bool err = false;
1173 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001174 CXXBaseOrMemberInitializer *Member =
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001175 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1176 void *KeyToMember = GetKeyForMember(Member);
1177 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1178 if (!PrevMember) {
1179 PrevMember = Member;
1180 continue;
1181 }
1182 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001183 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001184 diag::error_multiple_mem_initialization)
1185 << Field->getNameAsString();
1186 else {
1187 Type *BaseClass = Member->getBaseClass();
1188 assert(BaseClass && "ActOnMemInitializers - neither field or base");
Mike Stump1eb44332009-09-09 15:08:12 +00001189 Diag(Member->getSourceLocation(),
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001190 diag::error_multiple_base_initialization)
1191 << BaseClass->getDesugaredType(true);
1192 }
1193 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1194 << 0;
1195 err = true;
1196 }
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001198 if (err)
1199 return;
1200 }
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001202 BuildBaseOrMemberInitializers(Context, Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00001203 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001204 NumMemInits);
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00001206 if (Constructor->isDependentContext())
1207 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001208
1209 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001210 Diagnostic::Ignored &&
Mike Stump1eb44332009-09-09 15:08:12 +00001211 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001212 Diagnostic::Ignored)
1213 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001215 // Also issue warning if order of ctor-initializer list does not match order
1216 // of 1) base class declarations and 2) order of non-static data members.
1217 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001219 CXXRecordDecl *ClassDecl
1220 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1221 // Push virtual bases before others.
1222 for (CXXRecordDecl::base_class_iterator VBase =
1223 ClassDecl->vbases_begin(),
1224 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001225 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001227 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1228 E = ClassDecl->bases_end(); Base != E; ++Base) {
1229 // Virtuals are alread in the virtual base list and are constructed
1230 // first.
1231 if (Base->isVirtual())
1232 continue;
Anders Carlssoncdc83c72009-09-01 06:22:14 +00001233 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001234 }
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001236 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1237 E = ClassDecl->field_end(); Field != E; ++Field)
1238 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001240 int Last = AllBaseOrMembers.size();
1241 int curIndex = 0;
1242 CXXBaseOrMemberInitializer *PrevMember = 0;
1243 for (unsigned i = 0; i < NumMemInits; i++) {
Mike Stump1eb44332009-09-09 15:08:12 +00001244 CXXBaseOrMemberInitializer *Member =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001245 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1246 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001247
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001248 for (; curIndex < Last; curIndex++)
1249 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1250 break;
1251 if (curIndex == Last) {
1252 assert(PrevMember && "Member not in member list?!");
1253 // Initializer as specified in ctor-initializer list is out of order.
1254 // Issue a warning diagnostic.
1255 if (PrevMember->isBaseInitializer()) {
1256 // Diagnostics is for an initialized base class.
1257 Type *BaseClass = PrevMember->getBaseClass();
1258 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001259 diag::warn_base_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001260 << BaseClass->getDesugaredType(true);
1261 } else {
1262 FieldDecl *Field = PrevMember->getMember();
1263 Diag(PrevMember->getSourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001264 diag::warn_field_initialized)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001265 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001266 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001267 // Also the note!
1268 if (FieldDecl *Field = Member->getMember())
Mike Stump1eb44332009-09-09 15:08:12 +00001269 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001270 diag::note_fieldorbase_initialized_here) << 0
1271 << Field->getNameAsString();
1272 else {
1273 Type *BaseClass = Member->getBaseClass();
Mike Stump1eb44332009-09-09 15:08:12 +00001274 Diag(Member->getSourceLocation(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001275 diag::note_fieldorbase_initialized_here) << 1
1276 << BaseClass->getDesugaredType(true);
1277 }
1278 for (curIndex = 0; curIndex < Last; curIndex++)
Mike Stump1eb44332009-09-09 15:08:12 +00001279 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001280 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001281 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001282 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001283 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001284}
1285
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001286void
1287Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) {
1288 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext());
1289 llvm::SmallVector<uintptr_t, 32> AllToDestruct;
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001291 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1292 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1293 if (VBase->getType()->isDependentType())
1294 continue;
1295 // Skip over virtual bases which have trivial destructors.
1296 CXXRecordDecl *BaseClassDecl
1297 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1298 if (BaseClassDecl->hasTrivialDestructor())
1299 continue;
1300 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001301 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001302 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001303
1304 uintptr_t Member =
1305 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001306 | CXXDestructorDecl::VBASE;
1307 AllToDestruct.push_back(Member);
1308 }
1309 for (CXXRecordDecl::base_class_iterator Base =
1310 ClassDecl->bases_begin(),
1311 E = ClassDecl->bases_end(); Base != E; ++Base) {
1312 if (Base->isVirtual())
1313 continue;
1314 if (Base->getType()->isDependentType())
1315 continue;
1316 // Skip over virtual bases which have trivial destructors.
1317 CXXRecordDecl *BaseClassDecl
1318 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1319 if (BaseClassDecl->hasTrivialDestructor())
1320 continue;
1321 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001322 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001323 const_cast<CXXDestructorDecl*>(Dtor));
Mike Stump1eb44332009-09-09 15:08:12 +00001324 uintptr_t Member =
1325 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001326 | CXXDestructorDecl::DRCTNONVBASE;
1327 AllToDestruct.push_back(Member);
1328 }
Mike Stump1eb44332009-09-09 15:08:12 +00001329
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001330 // non-static data members.
1331 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1332 E = ClassDecl->field_end(); Field != E; ++Field) {
1333 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001334
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001335 if (const RecordType* RT = FieldType->getAs<RecordType>()) {
1336 // Skip over virtual bases which have trivial destructors.
1337 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1338 if (FieldClassDecl->hasTrivialDestructor())
1339 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001340 if (const CXXDestructorDecl *Dtor =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001341 FieldClassDecl->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001342 MarkDeclarationReferenced(Destructor->getLocation(),
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001343 const_cast<CXXDestructorDecl*>(Dtor));
1344 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field);
1345 AllToDestruct.push_back(Member);
1346 }
1347 }
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001349 unsigned NumDestructions = AllToDestruct.size();
1350 if (NumDestructions > 0) {
1351 Destructor->setNumBaseOrMemberDestructions(NumDestructions);
Mike Stump1eb44332009-09-09 15:08:12 +00001352 uintptr_t *BaseOrMemberDestructions =
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001353 new (Context) uintptr_t [NumDestructions];
1354 // Insert in reverse order.
1355 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx)
1356 BaseOrMemberDestructions[i++] = AllToDestruct[Idx];
1357 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions);
1358 }
1359}
1360
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001361void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001362 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001363 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001365 AdjustDeclIfTemplate(CDtorDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001366
1367 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001368 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001369 BuildBaseOrMemberInitializers(Context,
1370 Constructor,
1371 (CXXBaseOrMemberInitializer **)0, 0);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001372}
1373
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001374namespace {
1375 /// PureVirtualMethodCollector - traverses a class and its superclasses
1376 /// and determines if it has any pure virtual methods.
1377 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1378 ASTContext &Context;
1379
Sebastian Redldfe292d2009-03-22 21:28:55 +00001380 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001381 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001382
1383 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001384 MethodList Methods;
Mike Stump1eb44332009-09-09 15:08:12 +00001385
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001386 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
Mike Stump1eb44332009-09-09 15:08:12 +00001387
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001388 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001389 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001390 : Context(Ctx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001392 MethodList List;
1393 Collect(RD, List);
Mike Stump1eb44332009-09-09 15:08:12 +00001394
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001395 // Copy the temporary list to methods, and make sure to ignore any
1396 // null entries.
1397 for (size_t i = 0, e = List.size(); i != e; ++i) {
1398 if (List[i])
1399 Methods.push_back(List[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00001400 }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001401 }
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001403 bool empty() const { return Methods.empty(); }
Mike Stump1eb44332009-09-09 15:08:12 +00001404
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001405 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1406 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001407 };
Mike Stump1eb44332009-09-09 15:08:12 +00001408
1409 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001410 MethodList& Methods) {
1411 // First, collect the pure virtual methods for the base classes.
1412 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1413 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001414 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001415 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001416 if (BaseDecl && BaseDecl->isAbstract())
1417 Collect(BaseDecl, Methods);
1418 }
1419 }
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001421 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001422 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001424 MethodSetTy OverriddenMethods;
1425 size_t MethodsSize = Methods.size();
1426
Mike Stump1eb44332009-09-09 15:08:12 +00001427 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001428 i != e; ++i) {
1429 // Traverse the record, looking for methods.
1430 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001431 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001432 if (MD->isPure()) {
1433 Methods.push_back(MD);
1434 continue;
1435 }
Mike Stump1eb44332009-09-09 15:08:12 +00001436
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001437 // Otherwise, record all the overridden methods in our set.
1438 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1439 E = MD->end_overridden_methods(); I != E; ++I) {
1440 // Keep track of the overridden methods.
1441 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001442 }
1443 }
1444 }
Mike Stump1eb44332009-09-09 15:08:12 +00001445
1446 // Now go through the methods and zero out all the ones we know are
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001447 // overridden.
1448 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1449 if (OverriddenMethods.count(Methods[i]))
1450 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001451 }
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001453 }
1454}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001455
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001456
Mike Stump1eb44332009-09-09 15:08:12 +00001457bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001458 unsigned DiagID, AbstractDiagSelID SelID,
1459 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001460 if (SelID == -1)
1461 return RequireNonAbstractType(Loc, T,
1462 PDiag(DiagID), CurrentRD);
1463 else
1464 return RequireNonAbstractType(Loc, T,
1465 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001466}
1467
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001468bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1469 const PartialDiagnostic &PD,
1470 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001471 if (!getLangOptions().CPlusPlus)
1472 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Anders Carlsson11f21a02009-03-23 19:10:31 +00001474 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001475 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001476 CurrentRD);
Mike Stump1eb44332009-09-09 15:08:12 +00001477
Ted Kremenek6217b802009-07-29 21:53:49 +00001478 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001479 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001480 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001481 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001483 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001484 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001485 }
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Ted Kremenek6217b802009-07-29 21:53:49 +00001487 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001488 if (!RT)
1489 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001491 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1492 if (!RD)
1493 return false;
1494
Anders Carlssone65a3c82009-03-24 17:23:42 +00001495 if (CurrentRD && CurrentRD != RD)
1496 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001498 if (!RD->isAbstract())
1499 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001501 Diag(Loc, PD) << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001503 // Check if we've already emitted the list of pure virtual functions for this
1504 // class.
1505 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1506 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001507
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001508 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001509
1510 for (PureVirtualMethodCollector::MethodList::const_iterator I =
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001511 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1512 const CXXMethodDecl *MD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001513
1514 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001515 MD->getDeclName();
1516 }
1517
1518 if (!PureVirtualClassDiagSet)
1519 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1520 PureVirtualClassDiagSet->insert(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001522 return true;
1523}
1524
Anders Carlsson8211eff2009-03-24 01:19:16 +00001525namespace {
Mike Stump1eb44332009-09-09 15:08:12 +00001526 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
Anders Carlsson8211eff2009-03-24 01:19:16 +00001527 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1528 Sema &SemaRef;
1529 CXXRecordDecl *AbstractClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Anders Carlssone65a3c82009-03-24 17:23:42 +00001531 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001532 bool Invalid = false;
1533
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001534 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1535 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001536 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001537
Anders Carlsson8211eff2009-03-24 01:19:16 +00001538 return Invalid;
1539 }
Mike Stump1eb44332009-09-09 15:08:12 +00001540
Anders Carlssone65a3c82009-03-24 17:23:42 +00001541 public:
1542 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1543 : SemaRef(SemaRef), AbstractClass(ac) {
1544 Visit(SemaRef.Context.getTranslationUnitDecl());
1545 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001546
Anders Carlssone65a3c82009-03-24 17:23:42 +00001547 bool VisitFunctionDecl(const FunctionDecl *FD) {
1548 if (FD->isThisDeclarationADefinition()) {
1549 // No need to do the check if we're in a definition, because it requires
1550 // that the return/param types are complete.
Mike Stump1eb44332009-09-09 15:08:12 +00001551 // because that requires
Anders Carlssone65a3c82009-03-24 17:23:42 +00001552 return VisitDeclContext(FD);
1553 }
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Anders Carlssone65a3c82009-03-24 17:23:42 +00001555 // Check the return type.
1556 QualType RTy = FD->getType()->getAsFunctionType()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001557 bool Invalid =
Anders Carlssone65a3c82009-03-24 17:23:42 +00001558 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1559 diag::err_abstract_type_in_decl,
1560 Sema::AbstractReturnType,
1561 AbstractClass);
1562
Mike Stump1eb44332009-09-09 15:08:12 +00001563 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssone65a3c82009-03-24 17:23:42 +00001564 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001565 const ParmVarDecl *VD = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001566 Invalid |=
Anders Carlsson8211eff2009-03-24 01:19:16 +00001567 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001568 VD->getOriginalType(),
1569 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001570 Sema::AbstractParamType,
1571 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001572 }
1573
1574 return Invalid;
1575 }
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Anders Carlssone65a3c82009-03-24 17:23:42 +00001577 bool VisitDecl(const Decl* D) {
1578 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1579 return VisitDeclContext(DC);
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Anders Carlssone65a3c82009-03-24 17:23:42 +00001581 return false;
1582 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001583 };
1584}
1585
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001586void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001587 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001588 SourceLocation LBrac,
1589 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001590 if (!TagDecl)
1591 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Douglas Gregor42af25f2009-05-11 19:58:34 +00001593 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001594 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001595 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00001596 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001597
Chris Lattnerb28317a2009-03-28 19:18:32 +00001598 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001599 if (!RD->isAbstract()) {
1600 // Collect all the pure virtual methods and see if this is an abstract
1601 // class after all.
1602 PureVirtualMethodCollector Collector(Context, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001603 if (!Collector.empty())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001604 RD->setAbstract(true);
1605 }
Mike Stump1eb44332009-09-09 15:08:12 +00001606
1607 if (RD->isAbstract())
Anders Carlssone65a3c82009-03-24 17:23:42 +00001608 AbstractClassUsageDiagnoser(*this, RD);
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Douglas Gregor42af25f2009-05-11 19:58:34 +00001610 if (!RD->isDependentType())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001611 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001612}
1613
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001614/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1615/// special functions, such as the default constructor, copy
1616/// constructor, or destructor, to the given C++ class (C++
1617/// [special]p1). This routine can only be executed just before the
1618/// definition of the class is complete.
1619void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00001620 CanQualType ClassType
Douglas Gregor50d62d12009-08-05 05:36:45 +00001621 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001622
Sebastian Redl465226e2009-05-27 22:11:52 +00001623 // FIXME: Implicit declarations have exception specifications, which are
1624 // the union of the specifications of the implicitly called functions.
1625
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001626 if (!ClassDecl->hasUserDeclaredConstructor()) {
1627 // C++ [class.ctor]p5:
1628 // A default constructor for a class X is a constructor of class X
1629 // that can be called without an argument. If there is no
1630 // user-declared constructor for class X, a default constructor is
1631 // implicitly declared. An implicitly-declared default constructor
1632 // is an inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001633 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001634 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00001635 CXXConstructorDecl *DefaultCon =
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001636 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001637 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001638 Context.getFunctionType(Context.VoidTy,
1639 0, 0, false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001640 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001641 /*isExplicit=*/false,
1642 /*isInline=*/true,
1643 /*isImplicitlyDeclared=*/true);
1644 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001645 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001646 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001647 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001648 }
1649
1650 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1651 // C++ [class.copy]p4:
1652 // If the class definition does not explicitly declare a copy
1653 // constructor, one is declared implicitly.
1654
1655 // C++ [class.copy]p5:
1656 // The implicitly-declared copy constructor for a class X will
1657 // have the form
1658 //
1659 // X::X(const X&)
1660 //
1661 // if
1662 bool HasConstCopyConstructor = true;
1663
1664 // -- each direct or virtual base class B of X has a copy
1665 // constructor whose first parameter is of type const B& or
1666 // const volatile B&, and
1667 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1668 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1669 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00001670 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001671 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001672 = BaseClassDecl->hasConstCopyConstructor(Context);
1673 }
1674
1675 // -- for all the nonstatic data members of X that are of a
1676 // class type M (or array thereof), each such class type
1677 // has a copy constructor whose first parameter is of type
1678 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001679 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1680 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001681 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001682 QualType FieldType = (*Field)->getType();
1683 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1684 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001685 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001686 const CXXRecordDecl *FieldClassDecl
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001687 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001688 HasConstCopyConstructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001689 = FieldClassDecl->hasConstCopyConstructor(Context);
1690 }
1691 }
1692
Sebastian Redl64b45f72009-01-05 20:52:13 +00001693 // Otherwise, the implicitly declared copy constructor will have
1694 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001695 //
1696 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00001697 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001698 if (HasConstCopyConstructor)
1699 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001700 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001701
Sebastian Redl64b45f72009-01-05 20:52:13 +00001702 // An implicitly-declared copy constructor is an inline public
1703 // member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001704 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001705 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001706 CXXConstructorDecl *CopyConstructor
1707 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001708 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001709 Context.getFunctionType(Context.VoidTy,
1710 &ArgType, 1,
1711 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001712 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001713 /*isExplicit=*/false,
1714 /*isInline=*/true,
1715 /*isImplicitlyDeclared=*/true);
1716 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001717 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001718 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001719
1720 // Add the parameter to the constructor.
1721 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1722 ClassDecl->getLocation(),
1723 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001724 ArgType, /*DInfo=*/0,
1725 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00001726 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001727 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001728 }
1729
Sebastian Redl64b45f72009-01-05 20:52:13 +00001730 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1731 // Note: The following rules are largely analoguous to the copy
1732 // constructor rules. Note that virtual bases are not taken into account
1733 // for determining the argument type of the operator. Note also that
1734 // operators taking an object instead of a reference are allowed.
1735 //
1736 // C++ [class.copy]p10:
1737 // If the class definition does not explicitly declare a copy
1738 // assignment operator, one is declared implicitly.
1739 // The implicitly-defined copy assignment operator for a class X
1740 // will have the form
1741 //
1742 // X& X::operator=(const X&)
1743 //
1744 // if
1745 bool HasConstCopyAssignment = true;
1746
1747 // -- each direct base class B of X has a copy assignment operator
1748 // whose parameter is of type const B&, const volatile B& or B,
1749 // and
1750 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1751 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1752 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00001753 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001754 const CXXMethodDecl *MD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001755 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001756 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001757 }
1758
1759 // -- for all the nonstatic data members of X that are of a class
1760 // type M (or array thereof), each such class type has a copy
1761 // assignment operator whose parameter is of type const M&,
1762 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001763 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1764 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001765 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00001766 QualType FieldType = (*Field)->getType();
1767 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1768 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001769 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00001770 const CXXRecordDecl *FieldClassDecl
1771 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001772 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00001773 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001774 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001775 }
1776 }
1777
1778 // Otherwise, the implicitly declared copy assignment operator will
1779 // have the form
1780 //
1781 // X& X::operator=(X&)
1782 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001783 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001784 if (HasConstCopyAssignment)
1785 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001786 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001787
1788 // An implicitly-declared copy assignment operator is an inline public
1789 // member of its class.
1790 DeclarationName Name =
1791 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1792 CXXMethodDecl *CopyAssignment =
1793 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1794 Context.getFunctionType(RetType, &ArgType, 1,
1795 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001796 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001797 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001798 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001799 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001800 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001801
1802 // Add the parameter to the operator.
1803 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1804 ClassDecl->getLocation(),
1805 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001806 ArgType, /*DInfo=*/0,
1807 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00001808 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001809
1810 // Don't call addedAssignmentOperator. There is no way to distinguish an
1811 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001812 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001813 }
1814
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001815 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001816 // C++ [class.dtor]p2:
1817 // If a class has no user-declared destructor, a destructor is
1818 // declared implicitly. An implicitly-declared destructor is an
1819 // inline public member of its class.
Mike Stump1eb44332009-09-09 15:08:12 +00001820 DeclarationName Name
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001821 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump1eb44332009-09-09 15:08:12 +00001822 CXXDestructorDecl *Destructor
Douglas Gregor42a552f2008-11-05 20:51:48 +00001823 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001824 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00001825 Context.getFunctionType(Context.VoidTy,
1826 0, 0, false, 0),
1827 /*isInline=*/true,
1828 /*isImplicitlyDeclared=*/true);
1829 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001830 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001831 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001832 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001833 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001834}
1835
Douglas Gregor6569d682009-05-27 23:11:45 +00001836void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
1837 TemplateDecl *Template = TemplateD.getAs<TemplateDecl>();
1838 if (!Template)
1839 return;
1840
1841 TemplateParameterList *Params = Template->getTemplateParameters();
1842 for (TemplateParameterList::iterator Param = Params->begin(),
1843 ParamEnd = Params->end();
1844 Param != ParamEnd; ++Param) {
1845 NamedDecl *Named = cast<NamedDecl>(*Param);
1846 if (Named->getDeclName()) {
1847 S->AddDecl(DeclPtrTy::make(Named));
1848 IdResolver.AddDecl(Named);
1849 }
1850 }
1851}
1852
Douglas Gregor72b505b2008-12-16 21:30:33 +00001853/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1854/// parsing a top-level (non-nested) C++ class, and we are now
1855/// parsing those parts of the given Method declaration that could
1856/// not be parsed earlier (C++ [class.mem]p2), such as default
1857/// arguments. This action should enter the scope of the given
1858/// Method declaration as if we had just parsed the qualified method
1859/// name. However, it should not bring the parameters into scope;
1860/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001861void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001862 if (!MethodD)
1863 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001865 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Douglas Gregor72b505b2008-12-16 21:30:33 +00001867 CXXScopeSpec SS;
Chris Lattnerb28317a2009-03-28 19:18:32 +00001868 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00001869 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00001870 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1871 SS.setScopeRep(
1872 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001873 ActOnCXXEnterDeclaratorScope(S, SS);
1874}
1875
1876/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1877/// C++ method declaration. We're (re-)introducing the given
1878/// function parameter into scope for use in parsing later parts of
1879/// the method declaration. For example, we could see an
1880/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001881void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001882 if (!ParamD)
1883 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Chris Lattnerb28317a2009-03-28 19:18:32 +00001885 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00001886
1887 // If this parameter has an unparsed default argument, clear it out
1888 // to make way for the parsed default argument.
1889 if (Param->hasUnparsedDefaultArg())
1890 Param->setDefaultArg(0);
1891
Chris Lattnerb28317a2009-03-28 19:18:32 +00001892 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001893 if (Param->getDeclName())
1894 IdResolver.AddDecl(Param);
1895}
1896
1897/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1898/// processing the delayed method declaration for Method. The method
1899/// declaration is now considered finished. There may be a separate
1900/// ActOnStartOfFunctionDef action later (not necessarily
1901/// immediately!) for this method, if it was also defined inside the
1902/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001903void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001904 if (!MethodD)
1905 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001907 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Chris Lattnerb28317a2009-03-28 19:18:32 +00001909 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00001910 CXXScopeSpec SS;
Mike Stump1eb44332009-09-09 15:08:12 +00001911 QualType ClassTy
Douglas Gregorab452ba2009-03-26 23:50:42 +00001912 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1913 SS.setScopeRep(
1914 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001915 ActOnCXXExitDeclaratorScope(S, SS);
1916
1917 // Now that we have our default arguments, check the constructor
1918 // again. It could produce additional diagnostics or affect whether
1919 // the class has implicitly-declared destructors, among other
1920 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00001921 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
1922 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00001923
1924 // Check the default arguments, which we may have added.
1925 if (!Method->isInvalidDecl())
1926 CheckCXXDefaultArguments(Method);
1927}
1928
Douglas Gregor42a552f2008-11-05 20:51:48 +00001929/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00001930/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00001931/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00001932/// emit diagnostics and set the invalid bit to true. In any case, the type
1933/// will be updated to reflect a well-formed type for the constructor and
1934/// returned.
1935QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
1936 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001937 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001938
1939 // C++ [class.ctor]p3:
1940 // A constructor shall not be virtual (10.3) or static (9.4). A
1941 // constructor can be invoked for a const, volatile or const
1942 // volatile object. A constructor shall not be declared const,
1943 // volatile, or const volatile (9.3.2).
1944 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00001945 if (!D.isInvalidType())
1946 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1947 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1948 << SourceRange(D.getIdentifierLoc());
1949 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001950 }
1951 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00001952 if (!D.isInvalidType())
1953 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1954 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1955 << SourceRange(D.getIdentifierLoc());
1956 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001957 SC = FunctionDecl::None;
1958 }
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Chris Lattner65401802009-04-25 08:28:21 +00001960 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1961 if (FTI.TypeQuals != 0) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001962 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001963 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1964 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001965 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001966 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1967 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001968 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001969 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1970 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001971 }
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Douglas Gregor42a552f2008-11-05 20:51:48 +00001973 // Rebuild the function type "R" without any type qualifiers (in
1974 // case any of the errors above fired) and with "void" as the
1975 // return type, since constructors don't have return types. We
1976 // *always* have to do this, because GetTypeForDeclarator will
1977 // put in a result type of "int" when none was specified.
Douglas Gregor72564e72009-02-26 23:50:07 +00001978 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Chris Lattner65401802009-04-25 08:28:21 +00001979 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1980 Proto->getNumArgs(),
1981 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001982}
1983
Douglas Gregor72b505b2008-12-16 21:30:33 +00001984/// CheckConstructor - Checks a fully-formed constructor for
1985/// well-formedness, issuing any diagnostics required. Returns true if
1986/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00001987void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00001988 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00001989 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
1990 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00001991 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00001992
1993 // C++ [class.copy]p3:
1994 // A declaration of a constructor for a class X is ill-formed if
1995 // its first parameter is of type (optionally cv-qualified) X and
1996 // either there are no other parameters or else all other
1997 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00001998 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001999 ((Constructor->getNumParams() == 1) ||
2000 (Constructor->getNumParams() > 1 &&
Anders Carlssonae0b4e72009-06-06 04:14:07 +00002001 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002002 QualType ParamType = Constructor->getParamDecl(0)->getType();
2003 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2004 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00002005 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2006 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00002007 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattner6e475012009-04-25 08:35:12 +00002008 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00002009 }
2010 }
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Douglas Gregor72b505b2008-12-16 21:30:33 +00002012 // Notify the class that we've added a constructor.
2013 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00002014}
2015
Mike Stump1eb44332009-09-09 15:08:12 +00002016static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002017FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2018 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2019 FTI.ArgInfo[0].Param &&
2020 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2021}
2022
Douglas Gregor42a552f2008-11-05 20:51:48 +00002023/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2024/// the well-formednes of the destructor declarator @p D with type @p
2025/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00002026/// emit diagnostics and set the declarator to invalid. Even if this happens,
2027/// will be updated to reflect a well-formed type for the destructor and
2028/// returned.
2029QualType Sema::CheckDestructorDeclarator(Declarator &D,
2030 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002031 // C++ [class.dtor]p1:
2032 // [...] A typedef-name that names a class is a class-name
2033 // (7.1.3); however, a typedef-name that names a class shall not
2034 // be used as the identifier in the declarator for a destructor
2035 // declaration.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002036 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType());
Chris Lattner65401802009-04-25 08:28:21 +00002037 if (isa<TypedefType>(DeclaratorType)) {
2038 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00002039 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00002040 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002041 }
2042
2043 // C++ [class.dtor]p2:
2044 // A destructor is used to destroy objects of its class type. A
2045 // destructor takes no parameters, and no return type can be
2046 // specified for it (not even void). The address of a destructor
2047 // shall not be taken. A destructor shall not be static. A
2048 // destructor can be invoked for a const, volatile or const
2049 // volatile object. A destructor shall not be declared const,
2050 // volatile or const volatile (9.3.2).
2051 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00002052 if (!D.isInvalidType())
2053 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2054 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2055 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002056 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00002057 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002058 }
Chris Lattner65401802009-04-25 08:28:21 +00002059 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002060 // Destructors don't have return types, but the parser will
2061 // happily parse something like:
2062 //
2063 // class X {
2064 // float ~X();
2065 // };
2066 //
2067 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002068 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2069 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2070 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002071 }
Mike Stump1eb44332009-09-09 15:08:12 +00002072
Chris Lattner65401802009-04-25 08:28:21 +00002073 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2074 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002075 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002076 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2077 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002078 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002079 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2080 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00002081 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002082 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2083 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00002084 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002085 }
2086
2087 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00002088 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002089 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2090
2091 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00002092 FTI.freeArgs();
2093 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00002094 }
2095
Mike Stump1eb44332009-09-09 15:08:12 +00002096 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00002097 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00002098 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00002099 D.setInvalidType();
2100 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00002101
2102 // Rebuild the function type "R" without any type qualifiers or
2103 // parameters (in case any of the errors above fired) and with
2104 // "void" as the return type, since destructors don't have return
2105 // types. We *always* have to do this, because GetTypeForDeclarator
2106 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00002107 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00002108}
2109
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002110/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2111/// well-formednes of the conversion function declarator @p D with
2112/// type @p R. If there are any errors in the declarator, this routine
2113/// will emit diagnostics and return true. Otherwise, it will return
2114/// false. Either way, the type @p R will be updated to reflect a
2115/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00002116void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002117 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002118 // C++ [class.conv.fct]p1:
2119 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00002120 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00002121 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002122 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00002123 if (!D.isInvalidType())
2124 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2125 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2126 << SourceRange(D.getIdentifierLoc());
2127 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002128 SC = FunctionDecl::None;
2129 }
Chris Lattner6e475012009-04-25 08:35:12 +00002130 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002131 // Conversion functions don't have return types, but the parser will
2132 // happily parse something like:
2133 //
2134 // class X {
2135 // float operator bool();
2136 // };
2137 //
2138 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002139 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2140 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2141 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002142 }
2143
2144 // Make sure we don't have any parameters.
Douglas Gregor72564e72009-02-26 23:50:07 +00002145 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002146 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2147
2148 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00002149 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00002150 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002151 }
2152
Mike Stump1eb44332009-09-09 15:08:12 +00002153 // Make sure the conversion function isn't variadic.
Chris Lattner6e475012009-04-25 08:35:12 +00002154 if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002155 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00002156 D.setInvalidType();
2157 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002158
2159 // C++ [class.conv.fct]p4:
2160 // The conversion-type-id shall not represent a function type nor
2161 // an array type.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002162 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002163 if (ConvType->isArrayType()) {
2164 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2165 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002166 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002167 } else if (ConvType->isFunctionType()) {
2168 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2169 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00002170 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002171 }
2172
2173 // Rebuild the function type "R" without any parameters (in case any
2174 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00002175 // return type.
2176 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor72564e72009-02-26 23:50:07 +00002177 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002178
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002179 // C++0x explicit conversion operators.
2180 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump1eb44332009-09-09 15:08:12 +00002181 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002182 diag::warn_explicit_conversion_functions)
2183 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002184}
2185
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002186/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2187/// the declaration of the given C++ conversion function. This routine
2188/// is responsible for recording the conversion function in the C++
2189/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002190Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002191 assert(Conversion && "Expected to receive a conversion function declaration");
2192
Douglas Gregor9d350972008-12-12 08:25:50 +00002193 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002194
2195 // Make sure we aren't redeclaring the conversion function.
2196 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002197
2198 // C++ [class.conv.fct]p1:
2199 // [...] A conversion function is never used to convert a
2200 // (possibly cv-qualified) object to the (possibly cv-qualified)
2201 // same object type (or a reference to it), to a (possibly
2202 // cv-qualified) base class of that type (or a reference to it),
2203 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00002204 // FIXME: Suppress this warning if the conversion function ends up being a
2205 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00002206 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002207 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00002208 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002209 ConvType = ConvTypeRef->getPointeeType();
2210 if (ConvType->isRecordType()) {
2211 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2212 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00002213 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002214 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002215 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00002216 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002217 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002218 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00002219 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00002220 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002221 }
2222
Douglas Gregor70316a02008-12-26 15:00:45 +00002223 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002224 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
Mike Stump1eb44332009-09-09 15:08:12 +00002225 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002226 = Conversion->getDescribedFunctionTemplate())
2227 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor70316a02008-12-26 15:00:45 +00002228 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00002229 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor70316a02008-12-26 15:00:45 +00002230 Conv = Conversions->function_begin(),
2231 ConvEnd = Conversions->function_end();
2232 Conv != ConvEnd; ++Conv) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002233 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor70316a02008-12-26 15:00:45 +00002234 *Conv = Conversion;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002235 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00002236 }
2237 }
2238 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump1eb44332009-09-09 15:08:12 +00002239 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002240 = Conversion->getDescribedFunctionTemplate())
2241 ClassDecl->addConversionFunction(Context, ConversionTemplate);
2242 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Douglas Gregor70316a02008-12-26 15:00:45 +00002243 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002244
Chris Lattnerb28317a2009-03-28 19:18:32 +00002245 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00002246}
2247
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002248//===----------------------------------------------------------------------===//
2249// Namespace Handling
2250//===----------------------------------------------------------------------===//
2251
2252/// ActOnStartNamespaceDef - This is called at the start of a namespace
2253/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002254Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2255 SourceLocation IdentLoc,
2256 IdentifierInfo *II,
2257 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002258 NamespaceDecl *Namespc =
2259 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2260 Namespc->setLBracLoc(LBrace);
2261
2262 Scope *DeclRegionScope = NamespcScope->getParent();
2263
2264 if (II) {
2265 // C++ [namespace.def]p2:
2266 // The identifier in an original-namespace-definition shall not have been
2267 // previously defined in the declarative region in which the
2268 // original-namespace-definition appears. The identifier in an
2269 // original-namespace-definition is the name of the namespace. Subsequently
2270 // in that declarative region, it is treated as an original-namespace-name.
2271
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002272 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
2273 true);
Mike Stump1eb44332009-09-09 15:08:12 +00002274
Douglas Gregor44b43212008-12-11 16:49:14 +00002275 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2276 // This is an extended namespace definition.
2277 // Attach this namespace decl to the chain of extended namespace
2278 // definitions.
2279 OrigNS->setNextNamespace(Namespc);
2280 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002281
Mike Stump1eb44332009-09-09 15:08:12 +00002282 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002283 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00002284 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002285 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002286 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002287 } else if (PrevDecl) {
2288 // This is an invalid name redefinition.
2289 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2290 << Namespc->getDeclName();
2291 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2292 Namespc->setInvalidDecl();
2293 // Continue on to push Namespc as current DeclContext and return it.
Mike Stump1eb44332009-09-09 15:08:12 +00002294 }
Douglas Gregor44b43212008-12-11 16:49:14 +00002295
2296 PushOnScopeChains(Namespc, DeclRegionScope);
2297 } else {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002298 // FIXME: Handle anonymous namespaces
2299 }
2300
2301 // Although we could have an invalid decl (i.e. the namespace name is a
2302 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002303 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2304 // for the namespace has the declarations that showed up in that particular
2305 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002306 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002307 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002308}
2309
2310/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2311/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002312void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2313 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002314 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2315 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2316 Namespc->setRBracLoc(RBrace);
2317 PopDeclContext();
2318}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002319
Chris Lattnerb28317a2009-03-28 19:18:32 +00002320Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2321 SourceLocation UsingLoc,
2322 SourceLocation NamespcLoc,
2323 const CXXScopeSpec &SS,
2324 SourceLocation IdentLoc,
2325 IdentifierInfo *NamespcName,
2326 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002327 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2328 assert(NamespcName && "Invalid NamespcName.");
2329 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002330 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002331
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002332 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002333
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002334 // Lookup namespace name.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002335 LookupResult R = LookupParsedName(S, &SS, NamespcName,
2336 LookupNamespaceName, false);
2337 if (R.isAmbiguous()) {
2338 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002339 return DeclPtrTy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002340 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002341 if (NamedDecl *NS = R) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002342 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002343 // C++ [namespace.udir]p1:
2344 // A using-directive specifies that the names in the nominated
2345 // namespace can be used in the scope in which the
2346 // using-directive appears after the using-directive. During
2347 // unqualified name lookup (3.4.1), the names appear as if they
2348 // were declared in the nearest enclosing namespace which
2349 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002350 // namespace. [Note: in this context, "contains" means "contains
2351 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002352
2353 // Find enclosing context containing both using-directive and
2354 // nominated namespace.
2355 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2356 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2357 CommonAncestor = CommonAncestor->getParent();
2358
Mike Stump1eb44332009-09-09 15:08:12 +00002359 UDir = UsingDirectiveDecl::Create(Context,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002360 CurContext, UsingLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002361 NamespcLoc,
Douglas Gregor8419fa32009-05-30 06:31:56 +00002362 SS.getRange(),
2363 (NestedNameSpecifier *)SS.getScopeRep(),
2364 IdentLoc,
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002365 cast<NamespaceDecl>(NS),
2366 CommonAncestor);
2367 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002368 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002369 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002370 }
2371
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002372 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002373 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002374 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002375}
2376
2377void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2378 // If scope has associated entity, then using directive is at namespace
2379 // or translation unit scope. We add UsingDirectiveDecls, into
2380 // it's lookup structure.
2381 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002382 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002383 else
2384 // Otherwise it is block-sope. using-directives will affect lookup
2385 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002386 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002387}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002388
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002389
2390Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson595adc12009-08-29 19:54:19 +00002391 AccessSpecifier AS,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002392 SourceLocation UsingLoc,
2393 const CXXScopeSpec &SS,
2394 SourceLocation IdentLoc,
2395 IdentifierInfo *TargetName,
2396 OverloadedOperatorKind Op,
2397 AttributeList *AttrList,
2398 bool IsTypeName) {
Eli Friedman5d39dee2009-06-27 05:59:59 +00002399 assert((TargetName || Op) && "Invalid TargetName.");
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002400 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00002401
Anders Carlsson0c6139d2009-06-27 00:27:47 +00002402 DeclarationName Name;
2403 if (TargetName)
2404 Name = TargetName;
2405 else
2406 Name = Context.DeclarationNames.getCXXOperatorName(Op);
Mike Stump1eb44332009-09-09 15:08:12 +00002407
2408 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS, IdentLoc,
Anders Carlssonc72160b2009-08-28 05:40:36 +00002409 Name, AttrList, IsTypeName);
Anders Carlsson595adc12009-08-29 19:54:19 +00002410 if (UD) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00002411 PushOnScopeChains(UD, S);
Anders Carlsson595adc12009-08-29 19:54:19 +00002412 UD->setAccess(AS);
2413 }
Mike Stump1eb44332009-09-09 15:08:12 +00002414
Anders Carlssonc72160b2009-08-28 05:40:36 +00002415 return DeclPtrTy::make(UD);
2416}
2417
2418NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2419 const CXXScopeSpec &SS,
2420 SourceLocation IdentLoc,
2421 DeclarationName Name,
2422 AttributeList *AttrList,
2423 bool IsTypeName) {
2424 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2425 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00002426
Anders Carlsson550b14b2009-08-28 05:49:21 +00002427 // FIXME: We ignore attributes for now.
2428 delete AttrList;
Mike Stump1eb44332009-09-09 15:08:12 +00002429
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002430 if (SS.isEmpty()) {
2431 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002432 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002433 }
Mike Stump1eb44332009-09-09 15:08:12 +00002434
2435 NestedNameSpecifier *NNS =
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002436 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2437
Anders Carlsson550b14b2009-08-28 05:49:21 +00002438 if (isUnknownSpecialization(SS)) {
2439 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2440 SS.getRange(), NNS,
2441 IdentLoc, Name, IsTypeName);
2442 }
Mike Stump1eb44332009-09-09 15:08:12 +00002443
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002444 DeclContext *LookupContext = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002445
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002446 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2447 // C++0x N2914 [namespace.udecl]p3:
2448 // A using-declaration used as a member-declaration shall refer to a member
2449 // of a base class of the class being defined, shall refer to a member of an
2450 // anonymous union that is a member of a base class of the class being
Mike Stump1eb44332009-09-09 15:08:12 +00002451 // defined, or shall refer to an enumerator for an enumeration type that is
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002452 // a member of a base class of the class being defined.
2453 const Type *Ty = NNS->getAsType();
2454 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) {
2455 Diag(SS.getRange().getBegin(),
2456 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2457 << NNS << RD->getDeclName();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002458 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002459 }
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002460
2461 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0));
2462 LookupContext = BaseTy->getAs<RecordType>()->getDecl();
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002463 } else {
2464 // C++0x N2914 [namespace.udecl]p8:
2465 // A using-declaration for a class member shall be a member-declaration.
2466 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002467 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002468 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002469 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002470 }
Mike Stump1eb44332009-09-09 15:08:12 +00002471
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002472 // C++0x N2914 [namespace.udecl]p9:
2473 // In a using-declaration, a prefix :: refers to the global namespace.
2474 if (NNS->getKind() == NestedNameSpecifier::Global)
2475 LookupContext = Context.getTranslationUnitDecl();
2476 else
2477 LookupContext = NNS->getAsNamespace();
2478 }
2479
2480
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002481 // Lookup target name.
Mike Stump1eb44332009-09-09 15:08:12 +00002482 LookupResult R = LookupQualifiedName(LookupContext,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002483 Name, LookupOrdinaryName);
Mike Stump1eb44332009-09-09 15:08:12 +00002484
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002485 if (!R) {
Anders Carlsson05180af2009-08-30 00:58:45 +00002486 DiagnoseMissingMember(IdentLoc, Name, NNS, SS.getRange());
Anders Carlssonc72160b2009-08-28 05:40:36 +00002487 return 0;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002488 }
2489
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002490 NamedDecl *ND = R.getAsDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002491
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002492 if (IsTypeName && !isa<TypeDecl>(ND)) {
2493 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002494 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002495 }
2496
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002497 // C++0x N2914 [namespace.udecl]p6:
2498 // A using-declaration shall not name a namespace.
2499 if (isa<NamespaceDecl>(ND)) {
2500 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2501 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002502 return 0;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002503 }
Mike Stump1eb44332009-09-09 15:08:12 +00002504
Anders Carlssonc72160b2009-08-28 05:40:36 +00002505 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2506 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002507}
2508
Anders Carlsson81c85c42009-03-28 23:53:49 +00002509/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2510/// is a namespace alias, returns the namespace it points to.
2511static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2512 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2513 return AD->getNamespace();
2514 return dyn_cast_or_null<NamespaceDecl>(D);
2515}
2516
Mike Stump1eb44332009-09-09 15:08:12 +00002517Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002518 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002519 SourceLocation AliasLoc,
2520 IdentifierInfo *Alias,
2521 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002522 SourceLocation IdentLoc,
2523 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00002524
Anders Carlsson81c85c42009-03-28 23:53:49 +00002525 // Lookup the namespace name.
2526 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
2527
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002528 // Check if we have a previous declaration with the same name.
Anders Carlssondd729fc2009-03-28 23:49:35 +00002529 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00002530 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002531 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00002532 // namespace, so don't create a new one.
2533 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
2534 return DeclPtrTy();
2535 }
Mike Stump1eb44332009-09-09 15:08:12 +00002536
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002537 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2538 diag::err_redefinition_different_kind;
2539 Diag(AliasLoc, DiagID) << Alias;
2540 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002541 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002542 }
2543
Anders Carlsson5721c682009-03-28 06:42:02 +00002544 if (R.isAmbiguous()) {
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002545 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002546 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002547 }
Mike Stump1eb44332009-09-09 15:08:12 +00002548
Anders Carlsson5721c682009-03-28 06:42:02 +00002549 if (!R) {
2550 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00002551 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002552 }
Mike Stump1eb44332009-09-09 15:08:12 +00002553
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002554 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00002555 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2556 Alias, SS.getRange(),
Douglas Gregor6c9c9402009-05-30 06:48:27 +00002557 (NestedNameSpecifier *)SS.getScopeRep(),
Anders Carlsson68771c72009-03-28 22:58:02 +00002558 IdentLoc, R);
Mike Stump1eb44332009-09-09 15:08:12 +00002559
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002560 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00002561 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00002562}
2563
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002564void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2565 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00002566 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2567 !Constructor->isUsed()) &&
2568 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00002569
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002570 CXXRecordDecl *ClassDecl
2571 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002572 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Mike Stump1eb44332009-09-09 15:08:12 +00002573 // Before the implicitly-declared default constructor for a class is
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002574 // implicitly defined, all the implicitly-declared default constructors
2575 // for its base class and its non-static data members shall have been
2576 // implicitly defined.
2577 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002578 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2579 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002580 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002581 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002582 if (!BaseClassDecl->hasTrivialConstructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002583 if (CXXConstructorDecl *BaseCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002584 BaseClassDecl->getDefaultConstructor(Context))
2585 MarkDeclarationReferenced(CurrentLocation, BaseCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002586 else {
Mike Stump1eb44332009-09-09 15:08:12 +00002587 Diag(CurrentLocation, diag::err_defining_default_ctor)
2588 << Context.getTagDeclType(ClassDecl) << 1
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002589 << Context.getTagDeclType(BaseClassDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002590 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002591 << Context.getTagDeclType(BaseClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002592 err = true;
2593 }
2594 }
2595 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002596 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2597 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002598 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2599 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2600 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002601 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002602 CXXRecordDecl *FieldClassDecl
2603 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Duncan Sands6887e632009-06-25 09:03:06 +00002604 if (!FieldClassDecl->hasTrivialConstructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002605 if (CXXConstructorDecl *FieldCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002606 FieldClassDecl->getDefaultConstructor(Context))
2607 MarkDeclarationReferenced(CurrentLocation, FieldCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002608 else {
Mike Stump1eb44332009-09-09 15:08:12 +00002609 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002610 << Context.getTagDeclType(ClassDecl) << 0 <<
2611 Context.getTagDeclType(FieldClassDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002612 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002613 << Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002614 err = true;
2615 }
2616 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002617 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002618 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00002619 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002620 Diag((*Field)->getLocation(), diag::note_declared_at);
2621 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002622 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002623 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00002624 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002625 Diag((*Field)->getLocation(), diag::note_declared_at);
2626 err = true;
2627 }
2628 }
2629 if (!err)
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00002630 Constructor->setUsed();
2631 else
2632 Constructor->setInvalidDecl();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002633}
2634
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002635void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00002636 CXXDestructorDecl *Destructor) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002637 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2638 "DefineImplicitDestructor - call it for implicit default dtor");
Mike Stump1eb44332009-09-09 15:08:12 +00002639
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002640 CXXRecordDecl *ClassDecl
2641 = cast<CXXRecordDecl>(Destructor->getDeclContext());
2642 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2643 // C++ [class.dtor] p5
Mike Stump1eb44332009-09-09 15:08:12 +00002644 // Before the implicitly-declared default destructor for a class is
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002645 // implicitly defined, all the implicitly-declared default destructors
2646 // for its base class and its non-static data members shall have been
2647 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002648 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2649 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002650 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002651 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002652 if (!BaseClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002653 if (CXXDestructorDecl *BaseDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002654 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2655 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2656 else
Mike Stump1eb44332009-09-09 15:08:12 +00002657 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002658 "DefineImplicitDestructor - missing dtor in a base class");
2659 }
2660 }
Mike Stump1eb44332009-09-09 15:08:12 +00002661
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002662 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2663 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002664 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2665 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2666 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002667 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002668 CXXRecordDecl *FieldClassDecl
2669 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2670 if (!FieldClassDecl->hasTrivialDestructor()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002671 if (CXXDestructorDecl *FieldDtor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002672 const_cast<CXXDestructorDecl*>(
2673 FieldClassDecl->getDestructor(Context)))
2674 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
2675 else
Mike Stump1eb44332009-09-09 15:08:12 +00002676 assert(false &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002677 "DefineImplicitDestructor - missing dtor in class of a data member");
2678 }
2679 }
2680 }
2681 Destructor->setUsed();
2682}
2683
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002684void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
2685 CXXMethodDecl *MethodDecl) {
2686 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
2687 MethodDecl->getOverloadedOperator() == OO_Equal &&
2688 !MethodDecl->isUsed()) &&
2689 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
Mike Stump1eb44332009-09-09 15:08:12 +00002690
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002691 CXXRecordDecl *ClassDecl
2692 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002693
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00002694 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002695 // Before the implicitly-declared copy assignment operator for a class is
2696 // implicitly defined, all implicitly-declared copy assignment operators
2697 // for its direct base classes and its nonstatic data members shall have
2698 // been implicitly defined.
2699 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002700 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2701 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002702 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002703 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002704 if (CXXMethodDecl *BaseAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002705 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
2706 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
2707 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002708 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2709 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002710 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2711 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2712 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002713 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002714 CXXRecordDecl *FieldClassDecl
2715 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002716 if (CXXMethodDecl *FieldAssignOpMethod =
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002717 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
2718 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002719 } else if (FieldType->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002720 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00002721 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
2722 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002723 Diag(CurrentLocation, diag::note_first_required_here);
2724 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002725 } else if (FieldType.isConstQualified()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002726 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00002727 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
2728 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002729 Diag(CurrentLocation, diag::note_first_required_here);
2730 err = true;
2731 }
2732 }
2733 if (!err)
Mike Stump1eb44332009-09-09 15:08:12 +00002734 MethodDecl->setUsed();
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002735}
2736
2737CXXMethodDecl *
2738Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
2739 CXXRecordDecl *ClassDecl) {
2740 QualType LHSType = Context.getTypeDeclType(ClassDecl);
2741 QualType RHSType(LHSType);
2742 // If class's assignment operator argument is const/volatile qualified,
Mike Stump1eb44332009-09-09 15:08:12 +00002743 // look for operator = (const/volatile B&). Otherwise, look for
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002744 // operator = (B&).
2745 if (ParmDecl->getType().isConstQualified())
2746 RHSType.addConst();
2747 if (ParmDecl->getType().isVolatileQualified())
2748 RHSType.addVolatile();
Mike Stump1eb44332009-09-09 15:08:12 +00002749 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
2750 LHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002751 SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +00002752 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
2753 RHSType,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002754 SourceLocation()));
2755 Expr *Args[2] = { &*LHS, &*RHS };
2756 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00002757 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002758 CandidateSet);
2759 OverloadCandidateSet::iterator Best;
Mike Stump1eb44332009-09-09 15:08:12 +00002760 if (BestViableFunction(CandidateSet,
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002761 ClassDecl->getLocation(), Best) == OR_Success)
2762 return cast<CXXMethodDecl>(Best->Function);
2763 assert(false &&
2764 "getAssignOperatorMethod - copy assignment operator method not found");
2765 return 0;
2766}
2767
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002768void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2769 CXXConstructorDecl *CopyConstructor,
2770 unsigned TypeQuals) {
Mike Stump1eb44332009-09-09 15:08:12 +00002771 assert((CopyConstructor->isImplicit() &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002772 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
2773 !CopyConstructor->isUsed()) &&
2774 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00002775
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002776 CXXRecordDecl *ClassDecl
2777 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
2778 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002779 // C++ [class.copy] p209
Mike Stump1eb44332009-09-09 15:08:12 +00002780 // Before the implicitly-declared copy constructor for a class is
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002781 // implicitly defined, all the implicitly-declared copy constructors
2782 // for its base class and its non-static data members shall have been
2783 // implicitly defined.
2784 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2785 Base != ClassDecl->bases_end(); ++Base) {
2786 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002787 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002788 if (CXXConstructorDecl *BaseCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002789 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002790 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002791 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002792 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2793 FieldEnd = ClassDecl->field_end();
2794 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002795 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2796 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2797 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002798 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002799 CXXRecordDecl *FieldClassDecl
2800 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002801 if (CXXConstructorDecl *FieldCopyCtor =
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002802 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002803 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002804 }
2805 }
2806 CopyConstructor->setUsed();
2807}
2808
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002809Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00002810Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00002811 CXXConstructorDecl *Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002812 MultiExprArg ExprArgs) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002813 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002814
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002815 // [class.copy]p15:
Mike Stump1eb44332009-09-09 15:08:12 +00002816 // Whenever a temporary class object is copied using a copy constructor, and
2817 // this object and the copy have the same cv-unqualified type, an
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002818 // implementation is permitted to treat the original and the copy as two
2819 // different ways of referring to the same object and not perform a copy at
2820 //all, even if the class copy constructor or destructor have side effects.
Mike Stump1eb44332009-09-09 15:08:12 +00002821
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002822 // FIXME: Is this enough?
Anders Carlssonf47511a2009-09-07 22:23:31 +00002823 if (Constructor->isCopyConstructor(Context) && ExprArgs.size() == 1) {
2824 Expr *E = ((Expr **)ExprArgs.get())[0];
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002825 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2826 E = BE->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002827
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002828 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
2829 Elidable = true;
2830 }
Mike Stump1eb44332009-09-09 15:08:12 +00002831
2832 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002833 Elidable, move(ExprArgs));
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002834}
2835
Anders Carlssond74d4142009-09-08 01:48:42 +00002836static bool
2837CheckConstructArgumentTypes(Sema &SemaRef, SourceLocation ConstructLoc,
2838 CXXConstructExpr *E) {
2839 CXXConstructorDecl *Ctor = E->getConstructor();
2840 const FunctionProtoType *Proto = Ctor->getType()->getAsFunctionProtoType();
Mike Stump1eb44332009-09-09 15:08:12 +00002841
Anders Carlssond74d4142009-09-08 01:48:42 +00002842 unsigned NumArgs = E->getNumArgs();
2843 unsigned NumArgsInProto = Proto->getNumArgs();
2844 unsigned NumRequiredArgs = Ctor->getMinRequiredArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00002845
Anders Carlssond74d4142009-09-08 01:48:42 +00002846 for (unsigned i = 0; i != NumArgsInProto; ++i) {
2847 QualType ProtoArgType = Proto->getArgType(i);
2848
2849 Expr *Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002850
Anders Carlssond74d4142009-09-08 01:48:42 +00002851 if (i < NumRequiredArgs) {
2852 Arg = E->getArg(i);
Mike Stump1eb44332009-09-09 15:08:12 +00002853
Anders Carlssond74d4142009-09-08 01:48:42 +00002854 // Pass the argument.
2855 // FIXME: Do this.
2856 } else {
2857 // Build a default argument.
2858 ParmVarDecl *Param = Ctor->getParamDecl(i);
Mike Stump1eb44332009-09-09 15:08:12 +00002859
2860 Sema::OwningExprResult ArgExpr =
Anders Carlssond74d4142009-09-08 01:48:42 +00002861 SemaRef.BuildCXXDefaultArgExpr(ConstructLoc, Ctor, Param);
2862 if (ArgExpr.isInvalid())
2863 return true;
2864
2865 Arg = ArgExpr.takeAs<Expr>();
2866 }
Mike Stump1eb44332009-09-09 15:08:12 +00002867
Anders Carlssond74d4142009-09-08 01:48:42 +00002868 E->setArg(i, Arg);
2869 }
2870
2871 // If this is a variadic call, handle args passed through "...".
2872 if (Proto->isVariadic()) {
2873 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002874
Anders Carlssond74d4142009-09-08 01:48:42 +00002875 // Promote the arguments (C99 6.5.2.2p7).
2876 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2877 Expr *Arg = E->getArg(i);
Mike Stump1eb44332009-09-09 15:08:12 +00002878 Invalid |=
2879 SemaRef.DefaultVariadicArgumentPromotion(Arg,
Anders Carlssond74d4142009-09-08 01:48:42 +00002880 Sema::VariadicConstructor);
2881 E->setArg(i, Arg);
2882 }
Mike Stump1eb44332009-09-09 15:08:12 +00002883
Anders Carlssond74d4142009-09-08 01:48:42 +00002884 return Invalid;
2885 }
Mike Stump1eb44332009-09-09 15:08:12 +00002886
Anders Carlssond74d4142009-09-08 01:48:42 +00002887 return false;
2888}
2889
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002890/// BuildCXXConstructExpr - Creates a complete call to a constructor,
2891/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002892Sema::OwningExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00002893Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2894 CXXConstructorDecl *Constructor, bool Elidable,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002895 MultiExprArg ExprArgs) {
2896 unsigned NumExprs = ExprArgs.size();
2897 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00002898
2899 ExprOwningPtr<CXXConstructExpr> Temp(this,
2900 CXXConstructExpr::Create(Context,
2901 DeclInitType,
2902 Constructor,
Anders Carlsson8644aec2009-08-25 13:07:08 +00002903 Elidable,
2904 Exprs,
2905 NumExprs));
Mike Stump1eb44332009-09-09 15:08:12 +00002906
Anders Carlssond74d4142009-09-08 01:48:42 +00002907 if (CheckConstructArgumentTypes(*this, ConstructLoc, Temp.get()))
2908 return ExprError();
Anders Carlsson8644aec2009-08-25 13:07:08 +00002909
Anders Carlsson8644aec2009-08-25 13:07:08 +00002910 return move(Temp);
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002911}
2912
Anders Carlssone7624a72009-08-27 05:08:22 +00002913Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00002914Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
2915 QualType Ty,
2916 SourceLocation TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00002917 MultiExprArg Args,
2918 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002919 CXXTemporaryObjectExpr *E
2920 = new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty, TyBeginLoc,
Anders Carlssone7624a72009-08-27 05:08:22 +00002921 (Expr **)Args.get(),
2922 Args.size(), RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002923
Anders Carlssone7624a72009-08-27 05:08:22 +00002924 ExprOwningPtr<CXXTemporaryObjectExpr> Temp(this, E);
2925
Anders Carlssond74d4142009-09-08 01:48:42 +00002926 if (CheckConstructArgumentTypes(*this, TyBeginLoc, Temp.get()))
2927 return ExprError();
Anders Carlssone7624a72009-08-27 05:08:22 +00002928
Anders Carlssone7624a72009-08-27 05:08:22 +00002929 return move(Temp);
2930}
2931
2932
Mike Stump1eb44332009-09-09 15:08:12 +00002933bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002934 CXXConstructorDecl *Constructor,
Mike Stump1eb44332009-09-09 15:08:12 +00002935 QualType DeclInitType,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002936 MultiExprArg Exprs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002937 OwningExprResult TempResult =
2938 BuildCXXConstructExpr(VD->getLocation(), DeclInitType, Constructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00002939 move(Exprs));
Anders Carlssonfe2de492009-08-25 05:18:00 +00002940 if (TempResult.isInvalid())
2941 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002942
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002943 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002944 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +00002945 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor78d15832009-05-26 18:54:04 +00002946 VD->setInit(Context, Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00002947
Anders Carlssonfe2de492009-08-25 05:18:00 +00002948 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00002949}
2950
Mike Stump1eb44332009-09-09 15:08:12 +00002951void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002952 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00002953 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002954 if (!ClassDecl->hasTrivialDestructor())
Mike Stump1eb44332009-09-09 15:08:12 +00002955 if (CXXDestructorDecl *Destructor =
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002956 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002957 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002958}
2959
Mike Stump1eb44332009-09-09 15:08:12 +00002960/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002961/// ActOnDeclarator, when a C++ direct initializer is present.
2962/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00002963void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
2964 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00002965 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002966 SourceLocation *CommaLocs,
2967 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00002968 unsigned NumExprs = Exprs.size();
2969 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00002970 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002971
2972 // If there is no declaration, there was an error parsing it. Just ignore
2973 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002974 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002975 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002976
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002977 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2978 if (!VDecl) {
2979 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
2980 RealDecl->setInvalidDecl();
2981 return;
2982 }
2983
Douglas Gregor83ddad32009-08-26 21:14:46 +00002984 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00002985 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002986 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
2987 //
2988 // Clients that want to distinguish between the two forms, can check for
2989 // direct initializer using VarDecl::hasCXXDirectInitializer().
2990 // A major benefit is that clients that don't particularly care about which
2991 // exactly form was it (like the CodeGen) can handle both cases without
2992 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002993
Douglas Gregor83ddad32009-08-26 21:14:46 +00002994 // If either the declaration has a dependent type or if any of the expressions
2995 // is type-dependent, we represent the initialization via a ParenListExpr for
2996 // later use during template instantiation.
2997 if (VDecl->getType()->isDependentType() ||
2998 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
2999 // Let clients know that initialization was done with a direct initializer.
3000 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003001
Douglas Gregor83ddad32009-08-26 21:14:46 +00003002 // Store the initialization expressions as a ParenListExpr.
3003 unsigned NumExprs = Exprs.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003004 VDecl->setInit(Context,
Douglas Gregor83ddad32009-08-26 21:14:46 +00003005 new (Context) ParenListExpr(Context, LParenLoc,
3006 (Expr **)Exprs.release(),
3007 NumExprs, RParenLoc));
3008 return;
3009 }
Mike Stump1eb44332009-09-09 15:08:12 +00003010
Douglas Gregor83ddad32009-08-26 21:14:46 +00003011
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003012 // C++ 8.5p11:
3013 // The form of initialization (using parentheses or '=') is generally
3014 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003015 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003016 QualType DeclInitType = VDecl->getType();
3017 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
3018 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003019
Douglas Gregor615c5d42009-03-24 16:43:20 +00003020 // FIXME: This isn't the right place to complete the type.
3021 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3022 diag::err_typecheck_decl_incomplete_type)) {
3023 VDecl->setInvalidDecl();
3024 return;
3025 }
3026
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003027 if (VDecl->getType()->isRecordType()) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00003028 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00003029 = PerformInitializationByConstructor(DeclInitType,
3030 (Expr **)Exprs.get(), NumExprs,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003031 VDecl->getLocation(),
3032 SourceRange(VDecl->getLocation(),
3033 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003034 VDecl->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003035 IK_Direct);
Sebastian Redlf53597f2009-03-15 17:47:39 +00003036 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00003037 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00003038 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00003039 VDecl->setCXXDirectInitializer(true);
Mike Stump1eb44332009-09-09 15:08:12 +00003040 if (InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
Anders Carlssonf47511a2009-09-07 22:23:31 +00003041 move(Exprs)))
Anders Carlssonfe2de492009-08-25 05:18:00 +00003042 RealDecl->setInvalidDecl();
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00003043 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00003044 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00003045 return;
3046 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003047
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003048 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003049 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3050 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003051 RealDecl->setInvalidDecl();
3052 return;
3053 }
3054
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003055 // Let clients know that initialization was done with a direct initializer.
3056 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00003057
3058 assert(NumExprs == 1 && "Expected 1 expression");
3059 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00003060 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3061 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00003062}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003063
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003064/// PerformInitializationByConstructor - Perform initialization by
3065/// constructor (C++ [dcl.init]p14), which may occur as part of
3066/// direct-initialization or copy-initialization. We are initializing
3067/// an object of type @p ClassType with the given arguments @p
3068/// Args. @p Loc is the location in the source code where the
3069/// initializer occurs (e.g., a declaration, member initializer,
3070/// functional cast, etc.) while @p Range covers the whole
3071/// initialization. @p InitEntity is the entity being initialized,
3072/// which may by the name of a declaration or a type. @p Kind is the
3073/// kind of initialization we're performing, which affects whether
3074/// explicit constructors will be considered. When successful, returns
Douglas Gregor18fe5682008-11-03 20:45:27 +00003075/// the constructor that will be used to perform the initialization;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003076/// when the initialization fails, emits a diagnostic and returns
3077/// null.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003078CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003079Sema::PerformInitializationByConstructor(QualType ClassType,
3080 Expr **Args, unsigned NumArgs,
3081 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003082 DeclarationName InitEntity,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003083 InitializationKind Kind) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003084 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregor18fe5682008-11-03 20:45:27 +00003085 assert(ClassRec && "Can only initialize a class type here");
3086
Mike Stump1eb44332009-09-09 15:08:12 +00003087 // C++ [dcl.init]p14:
Douglas Gregor18fe5682008-11-03 20:45:27 +00003088 //
3089 // If the initialization is direct-initialization, or if it is
3090 // copy-initialization where the cv-unqualified version of the
3091 // source type is the same class as, or a derived class of, the
3092 // class of the destination, constructors are considered. The
3093 // applicable constructors are enumerated (13.3.1.3), and the
3094 // best one is chosen through overload resolution (13.3). The
3095 // constructor so selected is called to initialize the object,
3096 // with the initializer expression(s) as its argument(s). If no
3097 // constructor applies, or the overload resolution is ambiguous,
3098 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00003099 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3100 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003101
3102 // Add constructors to the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00003103 DeclarationName ConstructorName
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003104 = Context.DeclarationNames.getCXXConstructorName(
3105 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003106 DeclContext::lookup_const_iterator Con, ConEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003107 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003108 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00003109 // Find the constructor (which may be a template).
3110 CXXConstructorDecl *Constructor = 0;
3111 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3112 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003113 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003114 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3115 else
3116 Constructor = cast<CXXConstructorDecl>(*Con);
3117
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003118 if ((Kind == IK_Direct) ||
Mike Stump1eb44332009-09-09 15:08:12 +00003119 (Kind == IK_Copy &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00003120 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregordec06662009-08-21 18:42:58 +00003121 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
3122 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003123 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
Douglas Gregordec06662009-08-21 18:42:58 +00003124 Args, NumArgs, CandidateSet);
3125 else
3126 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3127 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00003128 }
3129
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00003130 // FIXME: When we decide not to synthesize the implicitly-declared
3131 // constructors, we'll need to make them appear here.
3132
Douglas Gregor18fe5682008-11-03 20:45:27 +00003133 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003134 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00003135 case OR_Success:
3136 // We found a constructor. Return it.
3137 return cast<CXXConstructorDecl>(Best->Function);
Mike Stump1eb44332009-09-09 15:08:12 +00003138
Douglas Gregor18fe5682008-11-03 20:45:27 +00003139 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003140 if (InitEntity)
3141 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003142 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00003143 else
3144 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00003145 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00003146 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00003147 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003148
Douglas Gregor18fe5682008-11-03 20:45:27 +00003149 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00003150 if (InitEntity)
3151 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3152 else
3153 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003154 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3155 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003156
3157 case OR_Deleted:
3158 if (InitEntity)
3159 Diag(Loc, diag::err_ovl_deleted_init)
3160 << Best->Function->isDeleted()
3161 << InitEntity << Range;
3162 else
3163 Diag(Loc, diag::err_ovl_deleted_init)
3164 << Best->Function->isDeleted()
3165 << InitEntity << Range;
3166 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3167 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00003168 }
Mike Stump1eb44332009-09-09 15:08:12 +00003169
Douglas Gregor18fe5682008-11-03 20:45:27 +00003170 return 0;
3171}
3172
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003173/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3174/// determine whether they are reference-related,
3175/// reference-compatible, reference-compatible with added
3176/// qualification, or incompatible, for use in C++ initialization by
3177/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3178/// type, and the first type (T1) is the pointee type of the reference
3179/// type being initialized.
Mike Stump1eb44332009-09-09 15:08:12 +00003180Sema::ReferenceCompareResult
3181Sema::CompareReferenceRelationship(QualType T1, QualType T2,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003182 bool& DerivedToBase) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003183 assert(!T1->isReferenceType() &&
3184 "T1 must be the pointee type of the reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003185 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
3186
3187 T1 = Context.getCanonicalType(T1);
3188 T2 = Context.getCanonicalType(T2);
3189 QualType UnqualT1 = T1.getUnqualifiedType();
3190 QualType UnqualT2 = T2.getUnqualifiedType();
3191
3192 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003193 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
Mike Stump1eb44332009-09-09 15:08:12 +00003194 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003195 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003196 if (UnqualT1 == UnqualT2)
3197 DerivedToBase = false;
3198 else if (IsDerivedFrom(UnqualT2, UnqualT1))
3199 DerivedToBase = true;
3200 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003201 return Ref_Incompatible;
3202
3203 // At this point, we know that T1 and T2 are reference-related (at
3204 // least).
3205
3206 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00003207 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003208 // reference-related to T2 and cv1 is the same cv-qualification
3209 // as, or greater cv-qualification than, cv2. For purposes of
3210 // overload resolution, cases for which cv1 is greater
3211 // cv-qualification than cv2 are identified as
3212 // reference-compatible with added qualification (see 13.3.3.2).
3213 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3214 return Ref_Compatible;
3215 else if (T1.isMoreQualifiedThan(T2))
3216 return Ref_Compatible_With_Added_Qualification;
3217 else
3218 return Ref_Related;
3219}
3220
3221/// CheckReferenceInit - Check the initialization of a reference
3222/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3223/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00003224/// list), and DeclType is the type of the declaration. When ICS is
3225/// non-null, this routine will compute the implicit conversion
3226/// sequence according to C++ [over.ics.ref] and will not produce any
3227/// diagnostics; when ICS is null, it will emit diagnostics when any
3228/// errors are found. Either way, a return value of true indicates
3229/// that there was a failure, a return value of false indicates that
3230/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00003231///
3232/// When @p SuppressUserConversions, user-defined conversions are
3233/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003234/// When @p AllowExplicit, we also permit explicit user-defined
3235/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00003236/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00003237bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003238Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003239 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00003240 bool AllowExplicit, bool ForceRValue,
3241 ImplicitConversionSequence *ICS) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003242 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3243
Ted Kremenek6217b802009-07-29 21:53:49 +00003244 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003245 QualType T2 = Init->getType();
3246
Douglas Gregor904eed32008-11-10 20:40:00 +00003247 // If the initializer is the address of an overloaded function, try
3248 // to resolve the overloaded function. If all goes well, T2 is the
3249 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00003250 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Mike Stump1eb44332009-09-09 15:08:12 +00003251 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003252 ICS != 0);
3253 if (Fn) {
3254 // Since we're performing this reference-initialization for
3255 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003256 if (!ICS) {
3257 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
3258 return true;
3259
Douglas Gregor904eed32008-11-10 20:40:00 +00003260 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003261 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003262
3263 T2 = Fn->getType();
3264 }
3265 }
3266
Douglas Gregor15da57e2008-10-29 02:00:59 +00003267 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003268 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00003269 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00003270 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3271 Init->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003272 ReferenceCompareResult RefRelationship
Douglas Gregor15da57e2008-10-29 02:00:59 +00003273 = CompareReferenceRelationship(T1, T2, DerivedToBase);
3274
3275 // Most paths end in a failed conversion.
3276 if (ICS)
3277 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003278
3279 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00003280 // A reference to type "cv1 T1" is initialized by an expression
3281 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003282
3283 // -- If the initializer expression
3284
Sebastian Redla9845802009-03-29 15:27:50 +00003285 // Rvalue references cannot bind to lvalues (N2812).
3286 // There is absolutely no situation where they can. In particular, note that
3287 // this is ill-formed, even if B has a user-defined conversion to A&&:
3288 // B b;
3289 // A&& r = b;
3290 if (isRValRef && InitLvalue == Expr::LV_Valid) {
3291 if (!ICS)
3292 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
3293 << Init->getSourceRange();
3294 return true;
3295 }
3296
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003297 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00003298 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3299 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00003300 //
3301 // Note that the bit-field check is skipped if we are just computing
3302 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00003303 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003304 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003305 BindsDirectly = true;
3306
Douglas Gregor15da57e2008-10-29 02:00:59 +00003307 if (ICS) {
3308 // C++ [over.ics.ref]p1:
3309 // When a parameter of reference type binds directly (8.5.3)
3310 // to an argument expression, the implicit conversion sequence
3311 // is the identity conversion, unless the argument expression
3312 // has a type that is a derived class of the parameter type,
3313 // in which case the implicit conversion sequence is a
3314 // derived-to-base Conversion (13.3.3.1).
3315 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3316 ICS->Standard.First = ICK_Identity;
3317 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3318 ICS->Standard.Third = ICK_Identity;
3319 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3320 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003321 ICS->Standard.ReferenceBinding = true;
3322 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003323 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00003324 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003325
3326 // Nothing more to do: the inaccessibility/ambiguity check for
3327 // derived-to-base conversions is suppressed when we're
3328 // computing the implicit conversion sequence (C++
3329 // [over.best.ics]p2).
3330 return false;
3331 } else {
3332 // Perform the conversion.
Mike Stump390b4cc2009-05-16 07:39:55 +00003333 // FIXME: Binding to a subobject of the lvalue is going to require more
3334 // AST annotation than this.
Mike Stump1eb44332009-09-09 15:08:12 +00003335 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003336 }
3337 }
3338
3339 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00003340 // implicitly converted to an lvalue of type "cv3 T3,"
3341 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003342 // 92) (this conversion is selected by enumerating the
3343 // applicable conversion functions (13.3.1.6) and choosing
3344 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00003345 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
3346 !RequireCompleteType(SourceLocation(), T2, 0)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003347 // FIXME: Look for conversions in base classes!
Mike Stump1eb44332009-09-09 15:08:12 +00003348 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003349 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003350
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003351 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00003352 OverloadedFunctionDecl *Conversions
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003353 = T2RecordDecl->getConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00003354 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003355 = Conversions->function_begin();
3356 Func != Conversions->function_end(); ++Func) {
Mike Stump1eb44332009-09-09 15:08:12 +00003357 FunctionTemplateDecl *ConvTemplate
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003358 = dyn_cast<FunctionTemplateDecl>(*Func);
3359 CXXConversionDecl *Conv;
3360 if (ConvTemplate)
3361 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3362 else
3363 Conv = cast<CXXConversionDecl>(*Func);
Sebastian Redldfe292d2009-03-22 21:28:55 +00003364
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003365 // If the conversion function doesn't return a reference type,
3366 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003367 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003368 (AllowExplicit || !Conv->isExplicit())) {
3369 if (ConvTemplate)
Mike Stump1eb44332009-09-09 15:08:12 +00003370 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003371 CandidateSet);
3372 else
3373 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3374 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003375 }
3376
3377 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003378 switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003379 case OR_Success:
3380 // This is a direct binding.
3381 BindsDirectly = true;
3382
3383 if (ICS) {
3384 // C++ [over.ics.ref]p1:
3385 //
3386 // [...] If the parameter binds directly to the result of
3387 // applying a conversion function to the argument
3388 // expression, the implicit conversion sequence is a
3389 // user-defined conversion sequence (13.3.3.1.2), with the
3390 // second standard conversion sequence either an identity
3391 // conversion or, if the conversion function returns an
3392 // entity of a type that is a derived class of the parameter
3393 // type, a derived-to-base Conversion.
3394 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3395 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3396 ICS->UserDefined.After = Best->FinalConversion;
3397 ICS->UserDefined.ConversionFunction = Best->Function;
3398 assert(ICS->UserDefined.After.ReferenceBinding &&
3399 ICS->UserDefined.After.DirectBinding &&
3400 "Expected a direct reference binding!");
3401 return false;
3402 } else {
3403 // Perform the conversion.
Mike Stump390b4cc2009-05-16 07:39:55 +00003404 // FIXME: Binding to a subobject of the lvalue is going to require more
3405 // AST annotation than this.
Anders Carlsson3503d042009-07-31 01:23:52 +00003406 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003407 }
3408 break;
3409
3410 case OR_Ambiguous:
3411 assert(false && "Ambiguous reference binding conversions not implemented.");
3412 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003413
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003414 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003415 case OR_Deleted:
3416 // There was no suitable conversion, or we found a deleted
3417 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003418 break;
3419 }
3420 }
Mike Stump1eb44332009-09-09 15:08:12 +00003421
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003422 if (BindsDirectly) {
3423 // C++ [dcl.init.ref]p4:
3424 // [...] In all cases where the reference-related or
3425 // reference-compatible relationship of two types is used to
3426 // establish the validity of a reference binding, and T1 is a
3427 // base class of T2, a program that necessitates such a binding
3428 // is ill-formed if T1 is an inaccessible (clause 11) or
3429 // ambiguous (10.2) base class of T2.
3430 //
3431 // Note that we only check this condition when we're allowed to
3432 // complain about errors, because we should not be checking for
3433 // ambiguity (or inaccessibility) unless the reference binding
3434 // actually happens.
Mike Stump1eb44332009-09-09 15:08:12 +00003435 if (DerivedToBase)
3436 return CheckDerivedToBaseConversion(T2, T1,
Douglas Gregor15da57e2008-10-29 02:00:59 +00003437 Init->getSourceRange().getBegin(),
3438 Init->getSourceRange());
3439 else
3440 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003441 }
3442
3443 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00003444 // type (i.e., cv1 shall be const), or the reference shall be an
3445 // rvalue reference and the initializer expression shall be an rvalue.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003446 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00003447 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003448 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003449 diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00003450 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3451 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003452 return true;
3453 }
3454
3455 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00003456 // class type, and "cv1 T1" is reference-compatible with
3457 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003458 // following ways (the choice is implementation-defined):
3459 //
3460 // -- The reference is bound to the object represented by
3461 // the rvalue (see 3.10) or to a sub-object within that
3462 // object.
3463 //
Eli Friedman33a31382009-08-05 19:21:58 +00003464 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003465 // a constructor is called to copy the entire rvalue
3466 // object into the temporary. The reference is bound to
3467 // the temporary or to a sub-object within the
3468 // temporary.
3469 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003470 // The constructor that would be used to make the copy
3471 // shall be callable whether or not the copy is actually
3472 // done.
3473 //
Sebastian Redla9845802009-03-29 15:27:50 +00003474 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003475 // freedom, so we will always take the first option and never build
3476 // a temporary in this case. FIXME: We will, however, have to check
3477 // for the presence of a copy constructor in C++98/03 mode.
3478 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003479 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3480 if (ICS) {
3481 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3482 ICS->Standard.First = ICK_Identity;
3483 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3484 ICS->Standard.Third = ICK_Identity;
3485 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3486 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003487 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003488 ICS->Standard.DirectBinding = false;
3489 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00003490 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003491 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +00003492 // FIXME: Binding to a subobject of the rvalue is going to require more
3493 // AST annotation than this.
Anders Carlsson3503d042009-07-31 01:23:52 +00003494 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003495 }
3496 return false;
3497 }
3498
Eli Friedman33a31382009-08-05 19:21:58 +00003499 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003500 // initialized from the initializer expression using the
3501 // rules for a non-reference copy initialization (8.5). The
3502 // reference is then bound to the temporary. If T1 is
3503 // reference-related to T2, cv1 must be the same
3504 // cv-qualification as, or greater cv-qualification than,
3505 // cv2; otherwise, the program is ill-formed.
3506 if (RefRelationship == Ref_Related) {
3507 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3508 // we would be reference-compatible or reference-compatible with
3509 // added qualification. But that wasn't the case, so the reference
3510 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003511 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003512 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003513 diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00003514 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3515 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003516 return true;
3517 }
3518
Douglas Gregor734d9862009-01-30 23:27:23 +00003519 // If at least one of the types is a class type, the types are not
3520 // related, and we aren't allowed any user conversions, the
3521 // reference binding fails. This case is important for breaking
3522 // recursion, since TryImplicitConversion below will attempt to
3523 // create a temporary through the use of a copy constructor.
3524 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3525 (T1->isRecordType() || T2->isRecordType())) {
3526 if (!ICS)
3527 Diag(Init->getSourceRange().getBegin(),
3528 diag::err_typecheck_convert_incompatible)
3529 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3530 return true;
3531 }
3532
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003533 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003534 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00003535 // C++ [over.ics.ref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00003536 //
Sebastian Redla9845802009-03-29 15:27:50 +00003537 // When a parameter of reference type is not bound directly to
3538 // an argument expression, the conversion sequence is the one
3539 // required to convert the argument expression to the
3540 // underlying type of the reference according to
3541 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3542 // to copy-initializing a temporary of the underlying type with
3543 // the argument expression. Any difference in top-level
3544 // cv-qualification is subsumed by the initialization itself
3545 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003546 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
3547 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00003548 /*ForceRValue=*/false,
3549 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003550
Sebastian Redla9845802009-03-29 15:27:50 +00003551 // Of course, that's still a reference binding.
3552 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3553 ICS->Standard.ReferenceBinding = true;
3554 ICS->Standard.RRefBinding = isRValRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003555 } else if (ICS->ConversionKind ==
Sebastian Redla9845802009-03-29 15:27:50 +00003556 ImplicitConversionSequence::UserDefinedConversion) {
3557 ICS->UserDefined.After.ReferenceBinding = true;
3558 ICS->UserDefined.After.RRefBinding = isRValRef;
3559 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00003560 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3561 } else {
Douglas Gregor45920e82008-12-19 17:40:08 +00003562 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor15da57e2008-10-29 02:00:59 +00003563 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003564}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003565
3566/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3567/// of this overloaded operator is well-formed. If so, returns false;
3568/// otherwise, emits appropriate diagnostics and returns true.
3569bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003570 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003571 "Expected an overloaded operator declaration");
3572
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003573 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
3574
Mike Stump1eb44332009-09-09 15:08:12 +00003575 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003576 // The allocation and deallocation functions, operator new,
3577 // operator new[], operator delete and operator delete[], are
3578 // described completely in 3.7.3. The attributes and restrictions
3579 // found in the rest of this subclause do not apply to them unless
3580 // explicitly stated in 3.7.3.
Mike Stump390b4cc2009-05-16 07:39:55 +00003581 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003582 if (Op == OO_New || Op == OO_Array_New ||
3583 Op == OO_Delete || Op == OO_Array_Delete)
3584 return false;
3585
3586 // C++ [over.oper]p6:
3587 // An operator function shall either be a non-static member
3588 // function or be a non-member function and have at least one
3589 // parameter whose type is a class, a reference to a class, an
3590 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003591 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
3592 if (MethodDecl->isStatic())
3593 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003594 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003595 } else {
3596 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003597 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
3598 ParamEnd = FnDecl->param_end();
3599 Param != ParamEnd; ++Param) {
3600 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00003601 if (ParamType->isDependentType() || ParamType->isRecordType() ||
3602 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003603 ClassOrEnumParam = true;
3604 break;
3605 }
3606 }
3607
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003608 if (!ClassOrEnumParam)
3609 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003610 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003611 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003612 }
3613
3614 // C++ [over.oper]p8:
3615 // An operator function cannot have default arguments (8.3.6),
3616 // except where explicitly stated below.
3617 //
Mike Stump1eb44332009-09-09 15:08:12 +00003618 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003619 // (C++ [over.call]p1).
3620 if (Op != OO_Call) {
3621 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
3622 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00003623 if ((*Param)->hasUnparsedDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00003624 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00003625 diag::err_operator_overload_default_arg)
3626 << FnDecl->getDeclName();
3627 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003628 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003629 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003630 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003631 }
3632 }
3633
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003634 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
3635 { false, false, false }
3636#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3637 , { Unary, Binary, MemberOnly }
3638#include "clang/Basic/OperatorKinds.def"
3639 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003640
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003641 bool CanBeUnaryOperator = OperatorUses[Op][0];
3642 bool CanBeBinaryOperator = OperatorUses[Op][1];
3643 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003644
3645 // C++ [over.oper]p8:
3646 // [...] Operator functions cannot have more or fewer parameters
3647 // than the number required for the corresponding operator, as
3648 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00003649 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003650 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003651 if (Op != OO_Call &&
3652 ((NumParams == 1 && !CanBeUnaryOperator) ||
3653 (NumParams == 2 && !CanBeBinaryOperator) ||
3654 (NumParams < 1) || (NumParams > 2))) {
3655 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00003656 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003657 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00003658 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003659 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00003660 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003661 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00003662 assert(CanBeBinaryOperator &&
3663 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00003664 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003665 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003666
Chris Lattner416e46f2008-11-21 07:57:12 +00003667 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003668 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003669 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003670
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003671 // Overloaded operators other than operator() cannot be variadic.
3672 if (Op != OO_Call &&
Douglas Gregor72564e72009-02-26 23:50:07 +00003673 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003674 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003675 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003676 }
3677
3678 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003679 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
3680 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003681 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003682 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003683 }
3684
3685 // C++ [over.inc]p1:
3686 // The user-defined function called operator++ implements the
3687 // prefix and postfix ++ operator. If this function is a member
3688 // function with no parameters, or a non-member function with one
3689 // parameter of class or enumeration type, it defines the prefix
3690 // increment operator ++ for objects of that type. If the function
3691 // is a member function with one parameter (which shall be of type
3692 // int) or a non-member function with two parameters (the second
3693 // of which shall be of type int), it defines the postfix
3694 // increment operator ++ for objects of that type.
3695 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
3696 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
3697 bool ParamIsInt = false;
3698 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
3699 ParamIsInt = BT->getKind() == BuiltinType::Int;
3700
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00003701 if (!ParamIsInt)
3702 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003703 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00003704 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003705 }
3706
Sebastian Redl64b45f72009-01-05 20:52:13 +00003707 // Notify the class if it got an assignment operator.
3708 if (Op == OO_Equal) {
3709 // Would have returned earlier otherwise.
3710 assert(isa<CXXMethodDecl>(FnDecl) &&
3711 "Overloaded = not member, but not filtered.");
3712 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Fariborz Jahanianad258832009-08-13 21:09:41 +00003713 Method->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003714 Method->getParent()->addedAssignmentOperator(Context, Method);
3715 }
3716
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003717 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003718}
Chris Lattner5a003a42008-12-17 07:09:26 +00003719
Douglas Gregor074149e2009-01-05 19:45:36 +00003720/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
3721/// linkage specification, including the language and (if present)
3722/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
3723/// the location of the language string literal, which is provided
3724/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
3725/// the '{' brace. Otherwise, this linkage specification does not
3726/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003727Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
3728 SourceLocation ExternLoc,
3729 SourceLocation LangLoc,
3730 const char *Lang,
3731 unsigned StrSize,
3732 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00003733 LinkageSpecDecl::LanguageIDs Language;
3734 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3735 Language = LinkageSpecDecl::lang_c;
3736 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3737 Language = LinkageSpecDecl::lang_cxx;
3738 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00003739 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003740 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00003741 }
Mike Stump1eb44332009-09-09 15:08:12 +00003742
Chris Lattnercc98eac2008-12-17 07:13:27 +00003743 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00003744
Douglas Gregor074149e2009-01-05 19:45:36 +00003745 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump1eb44332009-09-09 15:08:12 +00003746 LangLoc, Language,
Douglas Gregor074149e2009-01-05 19:45:36 +00003747 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003748 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00003749 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003750 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00003751}
3752
Douglas Gregor074149e2009-01-05 19:45:36 +00003753/// ActOnFinishLinkageSpecification - Completely the definition of
3754/// the C++ linkage specification LinkageSpec. If RBraceLoc is
3755/// valid, it's the position of the closing '}' brace in a linkage
3756/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003757Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
3758 DeclPtrTy LinkageSpec,
3759 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00003760 if (LinkageSpec)
3761 PopDeclContext();
3762 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00003763}
3764
Douglas Gregord308e622009-05-18 20:51:54 +00003765/// \brief Perform semantic analysis for the variable declaration that
3766/// occurs within a C++ catch clause, returning the newly-created
3767/// variable.
3768VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003769 DeclaratorInfo *DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00003770 IdentifierInfo *Name,
3771 SourceLocation Loc,
3772 SourceRange Range) {
3773 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003774
3775 // Arrays and functions decay.
3776 if (ExDeclType->isArrayType())
3777 ExDeclType = Context.getArrayDecayedType(ExDeclType);
3778 else if (ExDeclType->isFunctionType())
3779 ExDeclType = Context.getPointerType(ExDeclType);
3780
3781 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
3782 // The exception-declaration shall not denote a pointer or reference to an
3783 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003784 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00003785 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00003786 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003787 Invalid = true;
3788 }
Douglas Gregord308e622009-05-18 20:51:54 +00003789
Sebastian Redl4b07b292008-12-22 19:15:10 +00003790 QualType BaseType = ExDeclType;
3791 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003792 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00003793 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003794 BaseType = Ptr->getPointeeType();
3795 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003796 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00003797 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003798 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00003799 BaseType = Ref->getPointeeType();
3800 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003801 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003802 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003803 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00003804 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00003805 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003806
Mike Stump1eb44332009-09-09 15:08:12 +00003807 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00003808 RequireNonAbstractType(Loc, ExDeclType,
3809 diag::err_abstract_type_in_decl,
3810 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00003811 Invalid = true;
3812
Douglas Gregord308e622009-05-18 20:51:54 +00003813 // FIXME: Need to test for ability to copy-construct and destroy the
3814 // exception variable.
3815
Sebastian Redl8351da02008-12-22 21:35:02 +00003816 // FIXME: Need to check for abstract classes.
3817
Mike Stump1eb44332009-09-09 15:08:12 +00003818 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003819 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00003820
3821 if (Invalid)
3822 ExDecl->setInvalidDecl();
3823
3824 return ExDecl;
3825}
3826
3827/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
3828/// handler.
3829Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003830 DeclaratorInfo *DInfo = 0;
3831 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00003832
3833 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00003834 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003835 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003836 // The scope should be freshly made just for us. There is just no way
3837 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003838 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00003839 if (PrevDecl->isTemplateParameter()) {
3840 // Maybe we will complain about the shadowed template parameter.
3841 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003842 }
3843 }
3844
Chris Lattnereaaebc72009-04-25 08:06:05 +00003845 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003846 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
3847 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00003848 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003849 }
3850
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003851 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00003852 D.getIdentifier(),
3853 D.getIdentifierLoc(),
3854 D.getDeclSpec().getSourceRange());
3855
Chris Lattnereaaebc72009-04-25 08:06:05 +00003856 if (Invalid)
3857 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003858
Sebastian Redl4b07b292008-12-22 19:15:10 +00003859 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00003860 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00003861 PushOnScopeChains(ExDecl, S);
3862 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003863 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003864
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003865 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003866 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003867}
Anders Carlssonfb311762009-03-14 00:25:26 +00003868
Mike Stump1eb44332009-09-09 15:08:12 +00003869Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00003870 ExprArg assertexpr,
3871 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00003872 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003873 StringLiteral *AssertMessage =
Anders Carlssonfb311762009-03-14 00:25:26 +00003874 cast<StringLiteral>((Expr *)assertmessageexpr.get());
3875
Anders Carlssonc3082412009-03-14 00:33:21 +00003876 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
3877 llvm::APSInt Value(32);
3878 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
3879 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
3880 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003881 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00003882 }
Anders Carlssonfb311762009-03-14 00:25:26 +00003883
Anders Carlssonc3082412009-03-14 00:33:21 +00003884 if (Value == 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00003885 std::string str(AssertMessage->getStrData(),
Anders Carlssonc3082412009-03-14 00:33:21 +00003886 AssertMessage->getByteLength());
Mike Stump1eb44332009-09-09 15:08:12 +00003887 Diag(AssertLoc, diag::err_static_assert_failed)
Anders Carlsson94b15fb2009-03-15 18:44:04 +00003888 << str << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00003889 }
3890 }
Mike Stump1eb44332009-09-09 15:08:12 +00003891
Anders Carlsson77d81422009-03-15 17:35:16 +00003892 assertexpr.release();
3893 assertmessageexpr.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003894 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlssonfb311762009-03-14 00:25:26 +00003895 AssertExpr, AssertMessage);
Mike Stump1eb44332009-09-09 15:08:12 +00003896
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003897 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003898 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00003899}
Sebastian Redl50de12f2009-03-24 22:27:57 +00003900
John McCall67d1a672009-08-06 02:15:43 +00003901Sema::DeclPtrTy Sema::ActOnFriendDecl(Scope *S,
John McCall3f9a8a62009-08-11 06:59:38 +00003902 llvm::PointerUnion<const DeclSpec*,Declarator*> DU,
3903 bool IsDefinition) {
John McCall02cace72009-08-28 07:59:38 +00003904 if (DU.is<Declarator*>())
3905 return ActOnFriendFunctionDecl(S, *DU.get<Declarator*>(), IsDefinition);
3906 else
3907 return ActOnFriendTypeDecl(S, *DU.get<const DeclSpec*>(), IsDefinition);
3908}
3909
3910Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S,
3911 const DeclSpec &DS,
3912 bool IsDefinition) {
3913 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00003914
3915 assert(DS.isFriendSpecified());
3916 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
3917
John McCall6b2becf2009-09-08 17:47:29 +00003918 // Try to convert the decl specifier to a type.
3919 bool invalid = false;
3920 QualType T = ConvertDeclSpecToType(DS, Loc, invalid);
3921 if (invalid) return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00003922
John McCall02cace72009-08-28 07:59:38 +00003923 // C++ [class.friend]p2:
3924 // An elaborated-type-specifier shall be used in a friend declaration
3925 // for a class.*
3926 // * The class-key of the elaborated-type-specifier is required.
John McCall6b2becf2009-09-08 17:47:29 +00003927 // This is one of the rare places in Clang where it's legitimate to
3928 // ask about the "spelling" of the type.
3929 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
3930 // If we evaluated the type to a record type, suggest putting
3931 // a tag in front.
John McCall02cace72009-08-28 07:59:38 +00003932 if (const RecordType *RT = T->getAs<RecordType>()) {
John McCall6b2becf2009-09-08 17:47:29 +00003933 RecordDecl *RD = RT->getDecl();
3934
3935 std::string InsertionText = std::string(" ") + RD->getKindName();
3936
3937 Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type)
3938 << (RD->isUnion())
3939 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
3940 InsertionText);
John McCall02cace72009-08-28 07:59:38 +00003941 return DeclPtrTy();
3942 }else {
John McCall6b2becf2009-09-08 17:47:29 +00003943 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
3944 << DS.getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003945 return DeclPtrTy();
John McCall02cace72009-08-28 07:59:38 +00003946 }
3947 }
3948
John McCall6b2becf2009-09-08 17:47:29 +00003949 FriendDecl::FriendUnion FU = T.getTypePtr();
3950
3951 // The parser doesn't quite handle
3952 // friend class A { ... }
3953 // optimally, because it might have been the (valid) prefix of
3954 // friend class A { ... } foo();
3955 // So in a very particular set of circumstances, we need to adjust
3956 // IsDefinition.
3957 //
3958 // Also, if we made a RecordDecl in ActOnTag, we want that to be the
3959 // object of our friend declaration.
3960 switch (DS.getTypeSpecType()) {
3961 default: break;
3962 case DeclSpec::TST_class:
3963 case DeclSpec::TST_struct:
3964 case DeclSpec::TST_union:
3965 CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep());
3966 if (RD) {
3967 IsDefinition |= RD->isDefinition();
3968 FU = RD;
3969 }
3970 break;
3971 }
John McCall02cace72009-08-28 07:59:38 +00003972
3973 // C++ [class.friend]p2: A class shall not be defined inside
3974 // a friend declaration.
3975 if (IsDefinition) {
3976 Diag(DS.getFriendSpecLoc(), diag::err_friend_decl_defines_class)
3977 << DS.getSourceRange();
3978 return DeclPtrTy();
3979 }
3980
3981 // C++98 [class.friend]p1: A friend of a class is a function
3982 // or class that is not a member of the class . . .
3983 // But that's a silly restriction which nobody implements for
3984 // inner classes, and C++0x removes it anyway, so we only report
3985 // this (as a warning) if we're being pedantic.
John McCall6b2becf2009-09-08 17:47:29 +00003986 if (!getLangOptions().CPlusPlus0x)
3987 if (const RecordType *RT = T->getAs<RecordType>())
3988 if (RT->getDecl()->getDeclContext() == CurContext)
3989 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
John McCall02cace72009-08-28 07:59:38 +00003990
3991 FriendDecl *FD = FriendDecl::Create(Context, CurContext, Loc, FU,
3992 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00003993 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00003994 CurContext->addDecl(FD);
3995
3996 return DeclPtrTy::make(FD);
3997}
3998
3999Sema::DeclPtrTy Sema::ActOnFriendFunctionDecl(Scope *S,
4000 Declarator &D,
4001 bool IsDefinition) {
4002 const DeclSpec &DS = D.getDeclSpec();
4003
4004 assert(DS.isFriendSpecified());
4005 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4006
4007 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004008 DeclaratorInfo *DInfo = 0;
John McCall02cace72009-08-28 07:59:38 +00004009 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall67d1a672009-08-06 02:15:43 +00004010
4011 // C++ [class.friend]p1
4012 // A friend of a class is a function or class....
4013 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00004014 // It *doesn't* see through dependent types, which is correct
4015 // according to [temp.arg.type]p3:
4016 // If a declaration acquires a function type through a
4017 // type dependent on a template-parameter and this causes
4018 // a declaration that does not use the syntactic form of a
4019 // function declarator to have a function type, the program
4020 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00004021 if (!T->isFunctionType()) {
4022 Diag(Loc, diag::err_unexpected_friend);
4023
4024 // It might be worthwhile to try to recover by creating an
4025 // appropriate declaration.
4026 return DeclPtrTy();
4027 }
4028
4029 // C++ [namespace.memdef]p3
4030 // - If a friend declaration in a non-local class first declares a
4031 // class or function, the friend class or function is a member
4032 // of the innermost enclosing namespace.
4033 // - The name of the friend is not found by simple name lookup
4034 // until a matching declaration is provided in that namespace
4035 // scope (either before or after the class declaration granting
4036 // friendship).
4037 // - If a friend function is called, its name may be found by the
4038 // name lookup that considers functions from namespaces and
4039 // classes associated with the types of the function arguments.
4040 // - When looking for a prior declaration of a class or a function
4041 // declared as a friend, scopes outside the innermost enclosing
4042 // namespace scope are not considered.
4043
John McCall02cace72009-08-28 07:59:38 +00004044 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4045 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00004046 assert(Name);
4047
4048 // The existing declaration we found.
4049 FunctionDecl *FD = NULL;
4050
4051 // The context we found the declaration in, or in which we should
4052 // create the declaration.
4053 DeclContext *DC;
4054
4055 // FIXME: handle local classes
4056
4057 // Recover from invalid scope qualifiers as if they just weren't there.
4058 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
4059 DC = computeDeclContext(ScopeQual);
4060
4061 // FIXME: handle dependent contexts
4062 if (!DC) return DeclPtrTy();
4063
4064 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
4065
4066 // If searching in that context implicitly found a declaration in
4067 // a different context, treat it like it wasn't found at all.
4068 // TODO: better diagnostics for this case. Suggesting the right
4069 // qualified scope would be nice...
4070 if (!Dec || Dec->getDeclContext() != DC) {
John McCall02cace72009-08-28 07:59:38 +00004071 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00004072 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4073 return DeclPtrTy();
4074 }
4075
4076 // C++ [class.friend]p1: A friend of a class is a function or
4077 // class that is not a member of the class . . .
4078 if (DC == CurContext)
4079 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4080
4081 FD = cast<FunctionDecl>(Dec);
4082
4083 // Otherwise walk out to the nearest namespace scope looking for matches.
4084 } else {
4085 // TODO: handle local class contexts.
4086
4087 DC = CurContext;
4088 while (true) {
4089 // Skip class contexts. If someone can cite chapter and verse
4090 // for this behavior, that would be nice --- it's what GCC and
4091 // EDG do, and it seems like a reasonable intent, but the spec
4092 // really only says that checks for unqualified existing
4093 // declarations should stop at the nearest enclosing namespace,
4094 // not that they should only consider the nearest enclosing
4095 // namespace.
4096 while (DC->isRecord()) DC = DC->getParent();
4097
4098 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
4099
4100 // TODO: decide what we think about using declarations.
4101 if (Dec) {
4102 FD = cast<FunctionDecl>(Dec);
4103 break;
4104 }
4105 if (DC->isFileContext()) break;
4106 DC = DC->getParent();
4107 }
4108
4109 // C++ [class.friend]p1: A friend of a class is a function or
4110 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00004111 // C++0x changes this for both friend types and functions.
4112 // Most C++ 98 compilers do seem to give an error here, so
4113 // we do, too.
4114 if (FD && DC == CurContext && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00004115 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4116 }
4117
John McCall3f9a8a62009-08-11 06:59:38 +00004118 bool Redeclaration = (FD != 0);
4119
4120 // If we found a match, create a friend function declaration with
4121 // that function as the previous declaration.
4122 if (Redeclaration) {
4123 // Create it in the semantic context of the original declaration.
4124 DC = FD->getDeclContext();
4125
John McCall67d1a672009-08-06 02:15:43 +00004126 // If we didn't find something matching the type exactly, create
4127 // a declaration. This declaration should only be findable via
4128 // argument-dependent lookup.
John McCall3f9a8a62009-08-11 06:59:38 +00004129 } else {
John McCall67d1a672009-08-06 02:15:43 +00004130 assert(DC->isFileContext());
4131
4132 // This implies that it has to be an operator or function.
John McCall02cace72009-08-28 07:59:38 +00004133 if (D.getKind() == Declarator::DK_Constructor ||
4134 D.getKind() == Declarator::DK_Destructor ||
4135 D.getKind() == Declarator::DK_Conversion) {
John McCall67d1a672009-08-06 02:15:43 +00004136 Diag(Loc, diag::err_introducing_special_friend) <<
John McCall02cace72009-08-28 07:59:38 +00004137 (D.getKind() == Declarator::DK_Constructor ? 0 :
4138 D.getKind() == Declarator::DK_Destructor ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00004139 return DeclPtrTy();
4140 }
John McCall67d1a672009-08-06 02:15:43 +00004141 }
4142
John McCall02cace72009-08-28 07:59:38 +00004143 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo,
John McCall3f9a8a62009-08-11 06:59:38 +00004144 /* PrevDecl = */ FD,
4145 MultiTemplateParamsArg(*this),
4146 IsDefinition,
4147 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00004148 if (!ND) return DeclPtrTy();
John McCallab88d972009-08-31 22:39:49 +00004149
4150 assert(cast<FunctionDecl>(ND)->getPreviousDeclaration() == FD &&
4151 "lost reference to previous declaration");
4152
John McCall02cace72009-08-28 07:59:38 +00004153 FD = cast<FunctionDecl>(ND);
John McCall3f9a8a62009-08-11 06:59:38 +00004154
John McCall88232aa2009-08-18 00:00:49 +00004155 assert(FD->getDeclContext() == DC);
4156 assert(FD->getLexicalDeclContext() == CurContext);
4157
John McCallab88d972009-08-31 22:39:49 +00004158 // Add the function declaration to the appropriate lookup tables,
4159 // adjusting the redeclarations list as necessary. We don't
4160 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +00004161 //
John McCallab88d972009-08-31 22:39:49 +00004162 // Also update the scope-based lookup if the target context's
4163 // lookup context is in lexical scope.
4164 if (!CurContext->isDependentContext()) {
4165 DC = DC->getLookupContext();
4166 DC->makeDeclVisibleInContext(FD, /* Recoverable=*/ false);
4167 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4168 PushOnScopeChains(FD, EnclosingScope, /*AddToContext=*/ false);
4169 }
John McCall02cace72009-08-28 07:59:38 +00004170
4171 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
4172 D.getIdentifierLoc(), FD,
4173 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +00004174 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +00004175 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00004176
4177 return DeclPtrTy::make(FD);
Anders Carlsson00338362009-05-11 22:55:49 +00004178}
4179
Chris Lattnerb28317a2009-03-28 19:18:32 +00004180void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004181 AdjustDeclIfTemplate(dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004182
Chris Lattnerb28317a2009-03-28 19:18:32 +00004183 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00004184 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4185 if (!Fn) {
4186 Diag(DelLoc, diag::err_deleted_non_function);
4187 return;
4188 }
4189 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4190 Diag(DelLoc, diag::err_deleted_decl_not_first);
4191 Diag(Prev->getLocation(), diag::note_previous_declaration);
4192 // If the declaration wasn't the first, we delete the function anyway for
4193 // recovery.
4194 }
4195 Fn->setDeleted();
4196}
Sebastian Redl13e88542009-04-27 21:33:24 +00004197
4198static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4199 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4200 ++CI) {
4201 Stmt *SubStmt = *CI;
4202 if (!SubStmt)
4203 continue;
4204 if (isa<ReturnStmt>(SubStmt))
4205 Self.Diag(SubStmt->getSourceRange().getBegin(),
4206 diag::err_return_in_constructor_handler);
4207 if (!isa<Expr>(SubStmt))
4208 SearchForReturnInStmt(Self, SubStmt);
4209 }
4210}
4211
4212void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4213 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4214 CXXCatchStmt *Handler = TryBlock->getHandler(I);
4215 SearchForReturnInStmt(*this, Handler);
4216 }
4217}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004218
Mike Stump1eb44332009-09-09 15:08:12 +00004219bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004220 const CXXMethodDecl *Old) {
4221 QualType NewTy = New->getType()->getAsFunctionType()->getResultType();
4222 QualType OldTy = Old->getType()->getAsFunctionType()->getResultType();
4223
4224 QualType CNewTy = Context.getCanonicalType(NewTy);
4225 QualType COldTy = Context.getCanonicalType(OldTy);
4226
Mike Stump1eb44332009-09-09 15:08:12 +00004227 if (CNewTy == COldTy &&
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004228 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
4229 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004230
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004231 // Check if the return types are covariant
4232 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004233
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004234 /// Both types must be pointers or references to classes.
4235 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4236 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4237 NewClassTy = NewPT->getPointeeType();
4238 OldClassTy = OldPT->getPointeeType();
4239 }
4240 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4241 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4242 NewClassTy = NewRT->getPointeeType();
4243 OldClassTy = OldRT->getPointeeType();
4244 }
4245 }
Mike Stump1eb44332009-09-09 15:08:12 +00004246
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004247 // The return types aren't either both pointers or references to a class type.
4248 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004249 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004250 diag::err_different_return_type_for_overriding_virtual_function)
4251 << New->getDeclName() << NewTy << OldTy;
4252 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +00004253
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004254 return true;
4255 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004256
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004257 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
4258 // Check if the new class derives from the old class.
4259 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4260 Diag(New->getLocation(),
4261 diag::err_covariant_return_not_derived)
4262 << New->getDeclName() << NewTy << OldTy;
4263 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4264 return true;
4265 }
Mike Stump1eb44332009-09-09 15:08:12 +00004266
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004267 // Check if we the conversion from derived to base is valid.
Mike Stump1eb44332009-09-09 15:08:12 +00004268 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004269 diag::err_covariant_return_inaccessible_base,
4270 diag::err_covariant_return_ambiguous_derived_to_base_conv,
4271 // FIXME: Should this point to the return type?
4272 New->getLocation(), SourceRange(), New->getDeclName())) {
4273 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4274 return true;
4275 }
4276 }
Mike Stump1eb44332009-09-09 15:08:12 +00004277
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004278 // The qualifiers of the return types must be the same.
4279 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
4280 Diag(New->getLocation(),
4281 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004282 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004283 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4284 return true;
4285 };
Mike Stump1eb44332009-09-09 15:08:12 +00004286
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004287
4288 // The new class type must have the same or less qualifiers as the old type.
4289 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4290 Diag(New->getLocation(),
4291 diag::err_covariant_return_type_class_type_more_qualified)
4292 << New->getDeclName() << NewTy << OldTy;
4293 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4294 return true;
4295 };
Mike Stump1eb44332009-09-09 15:08:12 +00004296
Anders Carlssonc3a68b22009-05-14 19:52:19 +00004297 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00004298}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004299
Sebastian Redl23c7d062009-07-07 20:29:57 +00004300bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
Mike Stump1eb44332009-09-09 15:08:12 +00004301 const CXXMethodDecl *Old) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00004302 return CheckExceptionSpecSubset(diag::err_override_exception_spec,
4303 diag::note_overridden_virtual_function,
4304 Old->getType()->getAsFunctionProtoType(),
4305 Old->getLocation(),
4306 New->getType()->getAsFunctionProtoType(),
4307 New->getLocation());
4308}
4309
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004310/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4311/// initializer for the declaration 'Dcl'.
4312/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4313/// static data member of class X, names should be looked up in the scope of
4314/// class X.
4315void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004316 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004317
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004318 Decl *D = Dcl.getAs<Decl>();
4319 // If there is no declaration, there was an error parsing it.
4320 if (D == 0)
4321 return;
4322
4323 // Check whether it is a declaration with a nested name specifier like
4324 // int foo::bar;
4325 if (!D->isOutOfLine())
4326 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004327
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004328 // C++ [basic.lookup.unqual]p13
4329 //
4330 // A name used in the definition of a static data member of class X
4331 // (after the qualified-id of the static member) is looked up as if the name
4332 // was used in a member function of X.
Mike Stump1eb44332009-09-09 15:08:12 +00004333
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004334 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004335 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004336}
4337
4338/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4339/// initializer for the declaration 'Dcl'.
4340void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004341 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +00004342
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004343 Decl *D = Dcl.getAs<Decl>();
4344 // If there is no declaration, there was an error parsing it.
4345 if (D == 0)
4346 return;
4347
4348 // Check whether it is a declaration with a nested name specifier like
4349 // int foo::bar;
4350 if (!D->isOutOfLine())
4351 return;
4352
4353 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004354 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004355}