blob: a0bc94808bbed297263772c166c1ac8355072cda [file] [log] [blame]
Chris Lattnerac7b83a2008-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 Gregora65e8dd2008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregorec93f442008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Anders Carlsson412c3402009-03-24 01:19:16 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregor05904022008-10-22 21:13:31 +000019#include "clang/AST/TypeOrdering.h"
Chris Lattner97316c02008-04-10 02:22:51 +000020#include "clang/AST/StmtVisitor.h"
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +000021#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000022#include "clang/Parse/DeclSpec.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Chris Lattner97316c02008-04-10 02:22:51 +000024#include "llvm/Support/Compiler.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000025#include <algorithm> // for std::equal
Douglas Gregorabed2172008-10-22 17:49:05 +000026#include <map>
Chris Lattnerac7b83a2008-04-08 05:04:30 +000027
28using namespace clang;
29
Chris Lattner97316c02008-04-10 02:22:51 +000030//===----------------------------------------------------------------------===//
31// CheckDefaultArgumentVisitor
32//===----------------------------------------------------------------------===//
33
Chris Lattnerb1856db2008-04-12 23:52:44 +000034namespace {
35 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
36 /// the default argument of a parameter to determine whether it
37 /// contains any ill-formed subexpressions. For example, this will
38 /// diagnose the use of local variables or parameters within the
39 /// default argument expression.
40 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000041 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb1856db2008-04-12 23:52:44 +000042 Expr *DefaultArg;
43 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000044
Chris Lattnerb1856db2008-04-12 23:52:44 +000045 public:
46 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
47 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000048
Chris Lattnerb1856db2008-04-12 23:52:44 +000049 bool VisitExpr(Expr *Node);
50 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregora5b022a2008-11-04 14:32:21 +000051 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb1856db2008-04-12 23:52:44 +000052 };
Chris Lattner97316c02008-04-10 02:22:51 +000053
Chris Lattnerb1856db2008-04-12 23:52:44 +000054 /// VisitExpr - Visit all of the children of this expression.
55 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
56 bool IsInvalid = false;
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000057 for (Stmt::child_iterator I = Node->child_begin(),
58 E = Node->child_end(); I != E; ++I)
59 IsInvalid |= Visit(*I);
Chris Lattnerb1856db2008-04-12 23:52:44 +000060 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000061 }
62
Chris Lattnerb1856db2008-04-12 23:52:44 +000063 /// VisitDeclRefExpr - Visit a reference to a declaration, to
64 /// determine whether this declaration can be used in the default
65 /// argument expression.
66 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregord2baafd2008-10-21 16:13:35 +000067 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb1856db2008-04-12 23:52:44 +000068 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
69 // C++ [dcl.fct.default]p9
70 // Default arguments are evaluated each time the function is
71 // called. The order of evaluation of function arguments is
72 // unspecified. Consequently, parameters of a function shall not
73 // be used in default argument expressions, even if they are not
74 // evaluated. Parameters of a function declared before a default
75 // argument expression are in scope and can hide namespace and
76 // class member names.
77 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000078 diag::err_param_default_argument_references_param)
Chris Lattnerb1753422008-11-23 21:45:46 +000079 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff72a6ebc2008-04-15 22:42:06 +000080 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000081 // C++ [dcl.fct.default]p7
82 // Local variables shall not be used in default argument
83 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000084 if (VDecl->isBlockVarDecl())
85 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000086 diag::err_param_default_argument_references_local)
Chris Lattnerb1753422008-11-23 21:45:46 +000087 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +000088 }
Chris Lattner97316c02008-04-10 02:22:51 +000089
Douglas Gregor3c246952008-11-04 13:41:56 +000090 return false;
91 }
Chris Lattnerb1856db2008-04-12 23:52:44 +000092
Douglas Gregora5b022a2008-11-04 14:32:21 +000093 /// VisitCXXThisExpr - Visit a C++ "this" expression.
94 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
95 // C++ [dcl.fct.default]p8:
96 // The keyword this shall not be used in a default argument of a
97 // member function.
98 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000099 diag::err_param_default_argument_references_this)
100 << ThisE->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +0000101 }
Chris Lattner97316c02008-04-10 02:22:51 +0000102}
103
104/// ActOnParamDefaultArgument - Check whether the default argument
105/// provided for a function parameter is well-formed. If so, attach it
106/// to the parameter declaration.
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000107void
Chris Lattner5261d0c2009-03-28 19:18:32 +0000108Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000109 ExprArg defarg) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000110 if (!param || !defarg.get())
111 return;
112
Chris Lattner5261d0c2009-03-28 19:18:32 +0000113 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlssona116e6e2009-06-12 16:51:40 +0000114 UnparsedDefaultArgLocs.erase(Param);
115
Anders Carlssonc154a722009-05-01 19:30:39 +0000116 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000117 QualType ParamType = Param->getType();
118
119 // Default arguments are only permitted in C++
120 if (!getLangOptions().CPlusPlus) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000121 Diag(EqualLoc, diag::err_param_default_argument)
122 << DefaultArg->getSourceRange();
Douglas Gregor605de8d2008-12-16 21:30:33 +0000123 Param->setInvalidDecl();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000124 return;
125 }
126
127 // C++ [dcl.fct.default]p5
128 // A default argument expression is implicitly converted (clause
129 // 4) to the parameter type. The default argument expression has
130 // the same semantic constraints as the initializer expression in
131 // a declaration of a variable of the parameter type, using the
132 // copy-initialization semantics (8.5).
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000133 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000134 bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
135 EqualLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000136 Param->getDeclName(),
137 /*DirectInit=*/false);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000138 if (DefaultArgPtr != DefaultArg.get()) {
139 DefaultArg.take();
140 DefaultArg.reset(DefaultArgPtr);
141 }
Douglas Gregor58c428c2008-11-04 13:57:51 +0000142 if (DefaultInitFailed) {
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000143 return;
144 }
145
Chris Lattner97316c02008-04-10 02:22:51 +0000146 // Check that the default argument is well-formed
Chris Lattnerb1856db2008-04-12 23:52:44 +0000147 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Douglas Gregor605de8d2008-12-16 21:30:33 +0000148 if (DefaultArgChecker.Visit(DefaultArg.get())) {
149 Param->setInvalidDecl();
Chris Lattner97316c02008-04-10 02:22:51 +0000150 return;
Douglas Gregor605de8d2008-12-16 21:30:33 +0000151 }
Chris Lattner97316c02008-04-10 02:22:51 +0000152
Anders Carlsson37bb2bd2009-06-16 03:37:31 +0000153 DefaultArgPtr = MaybeCreateCXXExprWithTemporaries(DefaultArg.take(),
154 /*DestroyTemps=*/false);
155
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000156 // Okay: add the default argument to the parameter
Anders Carlsson37bb2bd2009-06-16 03:37:31 +0000157 Param->setDefaultArg(DefaultArgPtr);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000158}
159
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000160/// ActOnParamUnparsedDefaultArgument - We've seen a default
161/// argument for a function parameter, but we can't parse it yet
162/// because we're inside a class definition. Note that this default
163/// argument will be parsed later.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000164void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlssona116e6e2009-06-12 16:51:40 +0000165 SourceLocation EqualLoc,
166 SourceLocation ArgLoc) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000167 if (!param)
168 return;
169
Chris Lattner5261d0c2009-03-28 19:18:32 +0000170 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000171 if (Param)
172 Param->setUnparsedDefaultArg();
Anders Carlssona116e6e2009-06-12 16:51:40 +0000173
174 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000175}
176
Douglas Gregor605de8d2008-12-16 21:30:33 +0000177/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
178/// the default argument for the parameter param failed.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000179void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000180 if (!param)
181 return;
182
Anders Carlssona116e6e2009-06-12 16:51:40 +0000183 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
184
185 Param->setInvalidDecl();
186
187 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor605de8d2008-12-16 21:30:33 +0000188}
189
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000190/// CheckExtraCXXDefaultArguments - Check for any extra default
191/// arguments in the declarator, which is not a function declaration
192/// or definition and therefore is not permitted to have default
193/// arguments. This routine should be invoked for every declarator
194/// that is not a function declaration or definition.
195void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
196 // C++ [dcl.fct.default]p3
197 // A default argument expression shall be specified only in the
198 // parameter-declaration-clause of a function declaration or in a
199 // template-parameter (14.1). It shall not be specified for a
200 // parameter pack. If it is specified in a
201 // parameter-declaration-clause, it shall not occur within a
202 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000203 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000204 DeclaratorChunk &chunk = D.getTypeObject(i);
205 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000206 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
207 ParmVarDecl *Param =
208 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000209 if (Param->hasUnparsedDefaultArg()) {
210 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor605de8d2008-12-16 21:30:33 +0000211 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
212 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
213 delete Toks;
214 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000215 } else if (Param->getDefaultArg()) {
216 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
217 << Param->getDefaultArg()->getSourceRange();
218 Param->setDefaultArg(0);
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000219 }
220 }
221 }
222 }
223}
224
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000225// MergeCXXFunctionDecl - Merge two declarations of the same C++
226// function, once we already know that they have the same
Douglas Gregor083c23e2009-02-16 17:45:42 +0000227// type. Subroutine of MergeFunctionDecl. Returns true if there was an
228// error, false otherwise.
229bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
230 bool Invalid = false;
231
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000232 // C++ [dcl.fct.default]p4:
233 //
234 // For non-template functions, default arguments can be added in
235 // later declarations of a function in the same
236 // scope. Declarations in different scopes have completely
237 // distinct sets of default arguments. That is, declarations in
238 // inner scopes do not acquire default arguments from
239 // declarations in outer scopes, and vice versa. In a given
240 // function declaration, all parameters subsequent to a
241 // parameter with a default argument shall have default
242 // arguments supplied in this or previous declarations. A
243 // default argument shall not be redefined by a later
244 // declaration (not even to the same value).
245 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
246 ParmVarDecl *OldParam = Old->getParamDecl(p);
247 ParmVarDecl *NewParam = New->getParamDecl(p);
248
249 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
250 Diag(NewParam->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000251 diag::err_param_default_argument_redefinition)
252 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner1336cab2008-11-23 23:12:31 +0000253 Diag(OldParam->getLocation(), diag::note_previous_definition);
Douglas Gregor083c23e2009-02-16 17:45:42 +0000254 Invalid = true;
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000255 } else if (OldParam->getDefaultArg()) {
256 // Merge the old default argument into the new parameter
257 NewParam->setDefaultArg(OldParam->getDefaultArg());
258 }
259 }
260
Douglas Gregor083c23e2009-02-16 17:45:42 +0000261 return Invalid;
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000262}
263
264/// CheckCXXDefaultArguments - Verify that the default arguments for a
265/// function declaration are well-formed according to C++
266/// [dcl.fct.default].
267void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
268 unsigned NumParams = FD->getNumParams();
269 unsigned p;
270
271 // Find first parameter with a default argument
272 for (p = 0; p < NumParams; ++p) {
273 ParmVarDecl *Param = FD->getParamDecl(p);
274 if (Param->getDefaultArg())
275 break;
276 }
277
278 // C++ [dcl.fct.default]p4:
279 // In a given function declaration, all parameters
280 // subsequent to a parameter with a default argument shall
281 // have default arguments supplied in this or previous
282 // declarations. A default argument shall not be redefined
283 // by a later declaration (not even to the same value).
284 unsigned LastMissingDefaultArg = 0;
285 for(; p < NumParams; ++p) {
286 ParmVarDecl *Param = FD->getParamDecl(p);
287 if (!Param->getDefaultArg()) {
Douglas Gregor605de8d2008-12-16 21:30:33 +0000288 if (Param->isInvalidDecl())
289 /* We already complained about this parameter. */;
290 else if (Param->getIdentifier())
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000291 Diag(Param->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000292 diag::err_param_default_argument_missing_name)
Chris Lattnere46b8792008-11-19 07:32:16 +0000293 << Param->getIdentifier();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000294 else
295 Diag(Param->getLocation(),
296 diag::err_param_default_argument_missing);
297
298 LastMissingDefaultArg = p;
299 }
300 }
301
302 if (LastMissingDefaultArg > 0) {
303 // Some default arguments were missing. Clear out all of the
304 // default arguments up to (and including) the last missing
305 // default argument, so that we leave the function parameters
306 // in a semantically valid state.
307 for (p = 0; p <= LastMissingDefaultArg; ++p) {
308 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlssona116e6e2009-06-12 16:51:40 +0000309 if (Param->hasDefaultArg()) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000310 if (!Param->hasUnparsedDefaultArg())
311 Param->getDefaultArg()->Destroy(Context);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000312 Param->setDefaultArg(0);
313 }
314 }
315 }
316}
Douglas Gregorec93f442008-04-13 21:30:24 +0000317
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000318/// isCurrentClassName - Determine whether the identifier II is the
319/// name of the class type currently being defined. In the case of
320/// nested classes, this will only return true if II is the name of
321/// the innermost class.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000322bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
323 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000324 CXXRecordDecl *CurDecl;
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000325 if (SS && SS->isSet() && !SS->isInvalid()) {
326 DeclContext *DC = computeDeclContext(*SS);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000327 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
328 } else
329 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
330
331 if (CurDecl)
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000332 return &II == CurDecl->getIdentifier();
333 else
334 return false;
335}
336
Douglas Gregored3a3982009-03-03 04:44:36 +0000337/// \brief Check the validity of a C++ base class specifier.
338///
339/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
340/// and returns NULL otherwise.
341CXXBaseSpecifier *
342Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
343 SourceRange SpecifierRange,
344 bool Virtual, AccessSpecifier Access,
345 QualType BaseType,
346 SourceLocation BaseLoc) {
347 // C++ [class.union]p1:
348 // A union shall not have base classes.
349 if (Class->isUnion()) {
350 Diag(Class->getLocation(), diag::err_base_clause_on_union)
351 << SpecifierRange;
352 return 0;
353 }
354
355 if (BaseType->isDependentType())
356 return new CXXBaseSpecifier(SpecifierRange, Virtual,
357 Class->getTagKind() == RecordDecl::TK_class,
358 Access, BaseType);
359
360 // Base specifiers must be record types.
361 if (!BaseType->isRecordType()) {
362 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
363 return 0;
364 }
365
366 // C++ [class.union]p1:
367 // A union shall not be used as a base class.
368 if (BaseType->isUnionType()) {
369 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
370 return 0;
371 }
372
373 // C++ [class.derived]p2:
374 // The class-name in a base-specifier shall not be an incompletely
375 // defined class.
Douglas Gregorc84d8932009-03-09 16:13:40 +0000376 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
Douglas Gregor375733c2009-03-10 00:06:19 +0000377 SpecifierRange))
Douglas Gregored3a3982009-03-03 04:44:36 +0000378 return 0;
379
380 // If the base class is polymorphic, the new one is, too.
381 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
382 assert(BaseDecl && "Record type has no declaration");
383 BaseDecl = BaseDecl->getDefinition(Context);
384 assert(BaseDecl && "Base type is not incomplete, but has no definition");
385 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
386 Class->setPolymorphic(true);
387
388 // C++ [dcl.init.aggr]p1:
389 // An aggregate is [...] a class with [...] no base classes [...].
390 Class->setAggregate(false);
391 Class->setPOD(false);
392
Anders Carlssonc6363712009-04-16 00:08:20 +0000393 if (Virtual) {
394 // C++ [class.ctor]p5:
395 // A constructor is trivial if its class has no virtual base classes.
396 Class->setHasTrivialConstructor(false);
397 } else {
398 // C++ [class.ctor]p5:
399 // A constructor is trivial if all the direct base classes of its
400 // class have trivial constructors.
401 Class->setHasTrivialConstructor(cast<CXXRecordDecl>(BaseDecl)->
402 hasTrivialConstructor());
403 }
Anders Carlsson39a10db2009-04-17 02:34:54 +0000404
405 // C++ [class.ctor]p3:
406 // A destructor is trivial if all the direct base classes of its class
407 // have trivial destructors.
408 Class->setHasTrivialDestructor(cast<CXXRecordDecl>(BaseDecl)->
409 hasTrivialDestructor());
Anders Carlssonc6363712009-04-16 00:08:20 +0000410
Douglas Gregored3a3982009-03-03 04:44:36 +0000411 // Create the base specifier.
412 // FIXME: Allocate via ASTContext?
413 return new CXXBaseSpecifier(SpecifierRange, Virtual,
414 Class->getTagKind() == RecordDecl::TK_class,
415 Access, BaseType);
416}
417
Douglas Gregorec93f442008-04-13 21:30:24 +0000418/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
419/// one entry in the base class list of a class specifier, for
420/// example:
421/// class foo : public bar, virtual private baz {
422/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorabed2172008-10-22 17:49:05 +0000423Sema::BaseResult
Chris Lattner5261d0c2009-03-28 19:18:32 +0000424Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorabed2172008-10-22 17:49:05 +0000425 bool Virtual, AccessSpecifier Access,
426 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000427 if (!classdecl)
428 return true;
429
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000430 AdjustDeclIfTemplate(classdecl);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000431 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Douglas Gregora60c62e2009-02-09 15:09:02 +0000432 QualType BaseType = QualType::getFromOpaquePtr(basetype);
Douglas Gregored3a3982009-03-03 04:44:36 +0000433 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
434 Virtual, Access,
435 BaseType, BaseLoc))
436 return BaseSpec;
437
438 return true;
Douglas Gregorabed2172008-10-22 17:49:05 +0000439}
Douglas Gregorec93f442008-04-13 21:30:24 +0000440
Douglas Gregored3a3982009-03-03 04:44:36 +0000441/// \brief Performs the actual work of attaching the given base class
442/// specifiers to a C++ class.
443bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
444 unsigned NumBases) {
445 if (NumBases == 0)
446 return false;
Douglas Gregorabed2172008-10-22 17:49:05 +0000447
448 // Used to keep track of which base types we have already seen, so
449 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000450 // that the key is always the unqualified canonical type of the base
451 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000452 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
453
454 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000455 unsigned NumGoodBases = 0;
Douglas Gregored3a3982009-03-03 04:44:36 +0000456 bool Invalid = false;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000457 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000458 QualType NewBaseType
Douglas Gregored3a3982009-03-03 04:44:36 +0000459 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor4fd85902008-10-23 18:13:27 +0000460 NewBaseType = NewBaseType.getUnqualifiedType();
461
Douglas Gregorabed2172008-10-22 17:49:05 +0000462 if (KnownBaseTypes[NewBaseType]) {
463 // C++ [class.mi]p3:
464 // A class shall not be specified as a direct base class of a
465 // derived class more than once.
Douglas Gregored3a3982009-03-03 04:44:36 +0000466 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000467 diag::err_duplicate_base_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000468 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregored3a3982009-03-03 04:44:36 +0000469 << Bases[idx]->getSourceRange();
Douglas Gregor4fd85902008-10-23 18:13:27 +0000470
471 // Delete the duplicate base class specifier; we're going to
472 // overwrite its pointer later.
Douglas Gregored3a3982009-03-03 04:44:36 +0000473 delete Bases[idx];
474
475 Invalid = true;
Douglas Gregorabed2172008-10-22 17:49:05 +0000476 } else {
477 // Okay, add this new base class.
Douglas Gregored3a3982009-03-03 04:44:36 +0000478 KnownBaseTypes[NewBaseType] = Bases[idx];
479 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000480 }
481 }
482
483 // Attach the remaining base class specifiers to the derived class.
Douglas Gregored3a3982009-03-03 04:44:36 +0000484 Class->setBases(Bases, NumGoodBases);
Douglas Gregor4fd85902008-10-23 18:13:27 +0000485
486 // Delete the remaining (good) base class specifiers, since their
487 // data has been copied into the CXXRecordDecl.
488 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregored3a3982009-03-03 04:44:36 +0000489 delete Bases[idx];
490
491 return Invalid;
492}
493
494/// ActOnBaseSpecifiers - Attach the given base specifiers to the
495/// class, after checking whether there are any duplicate base
496/// classes.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000497void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregored3a3982009-03-03 04:44:36 +0000498 unsigned NumBases) {
499 if (!ClassDecl || !Bases || !NumBases)
500 return;
501
502 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000503 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregored3a3982009-03-03 04:44:36 +0000504 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregorec93f442008-04-13 21:30:24 +0000505}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000506
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000507//===----------------------------------------------------------------------===//
508// C++ class member Handling
509//===----------------------------------------------------------------------===//
510
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000511/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
512/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
513/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerd6c78092009-04-12 22:37:57 +0000514/// any.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000515Sema::DeclPtrTy
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000516Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Sebastian Redla55834a2009-04-12 17:16:29 +0000517 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000518 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor6704b312008-11-17 22:58:34 +0000519 DeclarationName Name = GetNameForDeclarator(D);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000520 Expr *BitWidth = static_cast<Expr*>(BW);
521 Expr *Init = static_cast<Expr*>(InitExpr);
522 SourceLocation Loc = D.getIdentifierLoc();
523
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000524 bool isFunc = D.isFunctionDeclarator();
525
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000526 // C++ 9.2p6: A member shall not be declared to have automatic storage
527 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000528 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
529 // data members and cannot be applied to names declared const or static,
530 // and cannot be applied to reference members.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000531 switch (DS.getStorageClassSpec()) {
532 case DeclSpec::SCS_unspecified:
533 case DeclSpec::SCS_typedef:
534 case DeclSpec::SCS_static:
535 // FALL THROUGH.
536 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000537 case DeclSpec::SCS_mutable:
538 if (isFunc) {
539 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000540 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000541 else
Chris Lattner8ba580c2008-11-19 05:08:23 +0000542 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
543
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000544 // FIXME: It would be nicer if the keyword was ignored only for this
545 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000546 D.getMutableDeclSpec().ClearStorageClassSpecs();
547 } else {
548 QualType T = GetTypeForDeclarator(D, S);
549 diag::kind err = static_cast<diag::kind>(0);
550 if (T->isReferenceType())
551 err = diag::err_mutable_reference;
552 else if (T.isConstQualified())
553 err = diag::err_mutable_const;
554 if (err != 0) {
555 if (DS.getStorageClassSpecLoc().isValid())
556 Diag(DS.getStorageClassSpecLoc(), err);
557 else
558 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000559 // FIXME: It would be nicer if the keyword was ignored only for this
560 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000561 D.getMutableDeclSpec().ClearStorageClassSpecs();
562 }
563 }
564 break;
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000565 default:
566 if (DS.getStorageClassSpecLoc().isValid())
567 Diag(DS.getStorageClassSpecLoc(),
568 diag::err_storageclass_invalid_for_member);
569 else
570 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
571 D.getMutableDeclSpec().ClearStorageClassSpecs();
572 }
573
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000574 if (!isFunc &&
Douglas Gregora60c62e2009-02-09 15:09:02 +0000575 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000576 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000577 // Check also for this case:
578 //
579 // typedef int f();
580 // f a;
581 //
Douglas Gregora60c62e2009-02-09 15:09:02 +0000582 QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep());
583 isFunc = TDType->isFunctionType();
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000584 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000585
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000586 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
587 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000588 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000589
590 Decl *Member;
Chris Lattner9cffefc2009-03-05 22:45:59 +0000591 if (isInstField) {
Douglas Gregor2f0ecef2009-03-11 20:50:30 +0000592 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
593 AS);
Chris Lattnere384c182009-03-05 23:03:49 +0000594 assert(Member && "HandleField never returns null");
Chris Lattner9cffefc2009-03-05 22:45:59 +0000595 } else {
Chris Lattnera17991f2009-03-29 16:50:03 +0000596 Member = ActOnDeclarator(S, D).getAs<Decl>();
Chris Lattnere384c182009-03-05 23:03:49 +0000597 if (!Member) {
598 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattnera17991f2009-03-29 16:50:03 +0000599 return DeclPtrTy();
Chris Lattnere384c182009-03-05 23:03:49 +0000600 }
Chris Lattner432780c2009-03-05 23:01:03 +0000601
602 // Non-instance-fields can't have a bitfield.
603 if (BitWidth) {
604 if (Member->isInvalidDecl()) {
605 // don't emit another diagnostic.
Douglas Gregor00660582009-03-11 20:22:50 +0000606 } else if (isa<VarDecl>(Member)) {
Chris Lattner432780c2009-03-05 23:01:03 +0000607 // C++ 9.6p3: A bit-field shall not be a static member.
608 // "static member 'A' cannot be a bit-field"
609 Diag(Loc, diag::err_static_not_bitfield)
610 << Name << BitWidth->getSourceRange();
611 } else if (isa<TypedefDecl>(Member)) {
612 // "typedef member 'x' cannot be a bit-field"
613 Diag(Loc, diag::err_typedef_not_bitfield)
614 << Name << BitWidth->getSourceRange();
615 } else {
616 // A function typedef ("typedef int f(); f a;").
617 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
618 Diag(Loc, diag::err_not_integral_type_bitfield)
Douglas Gregor0e518af2009-03-11 18:59:21 +0000619 << Name << cast<ValueDecl>(Member)->getType()
620 << BitWidth->getSourceRange();
Chris Lattner432780c2009-03-05 23:01:03 +0000621 }
622
623 DeleteExpr(BitWidth);
624 BitWidth = 0;
625 Member->setInvalidDecl();
626 }
Douglas Gregor2f0ecef2009-03-11 20:50:30 +0000627
628 Member->setAccess(AS);
Chris Lattner9cffefc2009-03-05 22:45:59 +0000629 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000630
Douglas Gregor6704b312008-11-17 22:58:34 +0000631 assert((Name || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000632
Douglas Gregor8f53bb72009-03-11 23:00:04 +0000633 if (Init)
Chris Lattner5261d0c2009-03-28 19:18:32 +0000634 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redla55834a2009-04-12 17:16:29 +0000635 if (Deleted) // FIXME: Source location is not very good.
636 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000637
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000638 if (isInstField) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000639 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattnera17991f2009-03-29 16:50:03 +0000640 return DeclPtrTy();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000641 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000642 return DeclPtrTy::make(Member);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000643}
644
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000645/// ActOnMemInitializer - Handle a C++ member initializer.
646Sema::MemInitResult
Chris Lattner5261d0c2009-03-28 19:18:32 +0000647Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000648 Scope *S,
Fariborz Jahanianc37d3062009-06-30 23:26:25 +0000649 const CXXScopeSpec &SS,
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000650 IdentifierInfo *MemberOrBase,
651 SourceLocation IdLoc,
652 SourceLocation LParenLoc,
653 ExprTy **Args, unsigned NumArgs,
654 SourceLocation *CommaLocs,
655 SourceLocation RParenLoc) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000656 if (!ConstructorD)
657 return true;
658
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000659 CXXConstructorDecl *Constructor
Chris Lattner5261d0c2009-03-28 19:18:32 +0000660 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000661 if (!Constructor) {
662 // The user wrote a constructor initializer on a function that is
663 // not a C++ constructor. Ignore the error for now, because we may
664 // have more member initializers coming; we'll diagnose it just
665 // once in ActOnMemInitializers.
666 return true;
667 }
668
669 CXXRecordDecl *ClassDecl = Constructor->getParent();
670
671 // C++ [class.base.init]p2:
672 // Names in a mem-initializer-id are looked up in the scope of the
673 // constructor’s class and, if not found in that scope, are looked
674 // up in the scope containing the constructor’s
675 // definition. [Note: if the constructor’s class contains a member
676 // with the same name as a direct or virtual base class of the
677 // class, a mem-initializer-id naming the member or base class and
678 // composed of a single identifier refers to the class member. A
679 // mem-initializer-id for the hidden base class may be specified
680 // using a qualified name. ]
Fariborz Jahanianc37d3062009-06-30 23:26:25 +0000681 if (!SS.getScopeRep()) {
682 // Look for a member, first.
683 FieldDecl *Member = 0;
684 DeclContext::lookup_result Result
685 = ClassDecl->lookup(MemberOrBase);
686 if (Result.first != Result.second)
687 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000688
Fariborz Jahanianc37d3062009-06-30 23:26:25 +0000689 // FIXME: Handle members of an anonymous union.
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000690
Fariborz Jahanianc37d3062009-06-30 23:26:25 +0000691 if (Member) {
692 // FIXME: Perform direct initialization of the member.
693 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs,
694 IdLoc);
695 }
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000696 }
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000697 // It didn't name a member, so see if it names a class.
Fariborz Jahanianc37d3062009-06-30 23:26:25 +0000698 TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000699 if (!BaseTy)
Chris Lattner65cae292008-11-19 08:23:25 +0000700 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
701 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000702
Douglas Gregora60c62e2009-02-09 15:09:02 +0000703 QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000704 if (!BaseType->isRecordType())
Chris Lattner65cae292008-11-19 08:23:25 +0000705 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattnerb1753422008-11-23 21:45:46 +0000706 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000707
708 // C++ [class.base.init]p2:
709 // [...] Unless the mem-initializer-id names a nonstatic data
710 // member of the constructor’s class or a direct or virtual base
711 // of that class, the mem-initializer is ill-formed. A
712 // mem-initializer-list can initialize a base class using any
713 // name that denotes that base class type.
714
715 // First, check for a direct base class.
716 const CXXBaseSpecifier *DirectBaseSpec = 0;
717 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
718 Base != ClassDecl->bases_end(); ++Base) {
719 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
720 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
721 // We found a direct base of this type. That's what we're
722 // initializing.
723 DirectBaseSpec = &*Base;
724 break;
725 }
726 }
727
728 // Check for a virtual base class.
Mike Stumpe127ae32009-05-16 07:39:55 +0000729 // FIXME: We might be able to short-circuit this if we know in advance that
730 // there are no virtual bases.
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000731 const CXXBaseSpecifier *VirtualBaseSpec = 0;
732 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
733 // We haven't found a base yet; search the class hierarchy for a
734 // virtual base class.
735 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
736 /*DetectVirtual=*/false);
737 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
738 for (BasePaths::paths_iterator Path = Paths.begin();
739 Path != Paths.end(); ++Path) {
740 if (Path->back().Base->isVirtual()) {
741 VirtualBaseSpec = Path->back().Base;
742 break;
743 }
744 }
745 }
746 }
747
748 // C++ [base.class.init]p2:
749 // If a mem-initializer-id is ambiguous because it designates both
750 // a direct non-virtual base class and an inherited virtual base
751 // class, the mem-initializer is ill-formed.
752 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner65cae292008-11-19 08:23:25 +0000753 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
754 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Fariborz Jahanianc13953a2009-06-30 17:34:52 +0000755 // C++ [base.class.init]p2:
756 // Unless the mem-initializer-id names a nonstatic data membeer of the
757 // constructor's class ot a direst or virtual base of that class, the
758 // mem-initializer is ill-formed.
759 if (!DirectBaseSpec && !VirtualBaseSpec)
760 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
761 << BaseType << ClassDecl->getNameAsCString()
762 << SourceRange(IdLoc, RParenLoc);
763
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000764
Fariborz Jahanian89f61bd2009-06-30 00:02:17 +0000765 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs,
766 IdLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000767}
768
Chris Lattner5261d0c2009-03-28 19:18:32 +0000769void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssonc7f87202009-03-25 02:58:17 +0000770 SourceLocation ColonLoc,
771 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000772 if (!ConstructorDecl)
773 return;
774
775 CXXConstructorDecl *Constructor
776 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Anders Carlssonc7f87202009-03-25 02:58:17 +0000777
778 if (!Constructor) {
779 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
780 return;
781 }
Fariborz Jahanian4b61ba62009-06-30 00:17:27 +0000782 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
Fariborz Jahanian4e0aba82009-06-29 22:33:26 +0000783
784 for (unsigned i = 0; i < NumMemInits; i++) {
785 CXXBaseOrMemberInitializer *Member =
786 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
Fariborz Jahanianf75b9d52009-06-30 21:52:59 +0000787 void *KeyToMember = Member->getBaseOrMember();
788 // For fields injected into the class via declaration of an anonymous union,
789 // use its anonymous union class declaration as the unique key.
790 if (FieldDecl *Field = Member->getMember())
791 if (Field->getDeclContext()->isRecord() &&
792 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
793 KeyToMember = static_cast<void *>(Field->getDeclContext());
794 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
Fariborz Jahanian4b61ba62009-06-30 00:17:27 +0000795 if (!PrevMember) {
Fariborz Jahanian89f61bd2009-06-30 00:02:17 +0000796 PrevMember = Member;
Fariborz Jahanian4b61ba62009-06-30 00:17:27 +0000797 continue;
Fariborz Jahanian4e0aba82009-06-29 22:33:26 +0000798 }
Fariborz Jahanian4b61ba62009-06-30 00:17:27 +0000799 if (FieldDecl *Field = Member->getMember())
800 Diag(Member->getSourceLocation(),
801 diag::error_multiple_mem_initialization)
802 << Field->getNameAsString();
803 else {
804 Type *BaseClass = Member->getBaseClass();
805 assert(BaseClass && "ActOnMemInitializers - neither field or base");
806 Diag(Member->getSourceLocation(),
807 diag::error_multiple_base_initialization)
808 << BaseClass->getDesugaredType(true);
809 }
810 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
811 << 0;
Fariborz Jahanian4e0aba82009-06-29 22:33:26 +0000812 }
Anders Carlssonc7f87202009-03-25 02:58:17 +0000813}
814
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000815namespace {
816 /// PureVirtualMethodCollector - traverses a class and its superclasses
817 /// and determines if it has any pure virtual methods.
818 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
819 ASTContext &Context;
820
Sebastian Redl16ac38f2009-03-22 21:28:55 +0000821 public:
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000822 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redl16ac38f2009-03-22 21:28:55 +0000823
824 private:
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000825 MethodList Methods;
826
827 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
828
829 public:
830 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
831 : Context(Ctx) {
832
833 MethodList List;
834 Collect(RD, List);
835
836 // Copy the temporary list to methods, and make sure to ignore any
837 // null entries.
838 for (size_t i = 0, e = List.size(); i != e; ++i) {
839 if (List[i])
840 Methods.push_back(List[i]);
841 }
842 }
843
Anders Carlssone1299b32009-03-22 20:18:17 +0000844 bool empty() const { return Methods.empty(); }
845
846 MethodList::const_iterator methods_begin() { return Methods.begin(); }
847 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000848 };
849
850 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
851 MethodList& Methods) {
852 // First, collect the pure virtual methods for the base classes.
853 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
854 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
855 if (const RecordType *RT = Base->getType()->getAsRecordType()) {
Chris Lattner330a05b2009-03-29 05:01:10 +0000856 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000857 if (BaseDecl && BaseDecl->isAbstract())
858 Collect(BaseDecl, Methods);
859 }
860 }
861
862 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson1eba0ac2009-05-17 00:00:05 +0000863 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
864
865 MethodSetTy OverriddenMethods;
866 size_t MethodsSize = Methods.size();
867
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000868 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson1eba0ac2009-05-17 00:00:05 +0000869 i != e; ++i) {
870 // Traverse the record, looking for methods.
871 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
872 // If the method is pre virtual, add it to the methods vector.
873 if (MD->isPure()) {
874 Methods.push_back(MD);
875 continue;
876 }
877
878 // Otherwise, record all the overridden methods in our set.
879 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
880 E = MD->end_overridden_methods(); I != E; ++I) {
881 // Keep track of the overridden methods.
882 OverriddenMethods.insert(*I);
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000883 }
884 }
885 }
886
Anders Carlsson1eba0ac2009-05-17 00:00:05 +0000887 // Now go through the methods and zero out all the ones we know are
888 // overridden.
889 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
890 if (OverriddenMethods.count(Methods[i]))
891 Methods[i] = 0;
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000892 }
Anders Carlsson1eba0ac2009-05-17 00:00:05 +0000893
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000894 }
895}
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000896
Anders Carlssone1299b32009-03-22 20:18:17 +0000897bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonde9e7892009-03-24 17:23:42 +0000898 unsigned DiagID, AbstractDiagSelID SelID,
899 const CXXRecordDecl *CurrentRD) {
Anders Carlssone1299b32009-03-22 20:18:17 +0000900
901 if (!getLangOptions().CPlusPlus)
902 return false;
Anders Carlssonc263c9b2009-03-23 19:10:31 +0000903
904 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssonde9e7892009-03-24 17:23:42 +0000905 return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
906 CurrentRD);
Anders Carlssonce9240e2009-03-24 01:46:45 +0000907
908 if (const PointerType *PT = T->getAsPointerType()) {
909 // Find the innermost pointer type.
910 while (const PointerType *T = PT->getPointeeType()->getAsPointerType())
911 PT = T;
Anders Carlssone1299b32009-03-22 20:18:17 +0000912
Anders Carlssonce9240e2009-03-24 01:46:45 +0000913 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssonde9e7892009-03-24 17:23:42 +0000914 return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
915 CurrentRD);
Anders Carlssonce9240e2009-03-24 01:46:45 +0000916 }
917
Anders Carlssone1299b32009-03-22 20:18:17 +0000918 const RecordType *RT = T->getAsRecordType();
919 if (!RT)
920 return false;
921
922 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
923 if (!RD)
924 return false;
925
Anders Carlssonde9e7892009-03-24 17:23:42 +0000926 if (CurrentRD && CurrentRD != RD)
927 return false;
928
Anders Carlssone1299b32009-03-22 20:18:17 +0000929 if (!RD->isAbstract())
930 return false;
931
Anders Carlssond5a94982009-03-23 17:49:10 +0000932 Diag(Loc, DiagID) << RD->getDeclName() << SelID;
Anders Carlssone1299b32009-03-22 20:18:17 +0000933
934 // Check if we've already emitted the list of pure virtual functions for this
935 // class.
936 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
937 return true;
938
939 PureVirtualMethodCollector Collector(Context, RD);
940
941 for (PureVirtualMethodCollector::MethodList::const_iterator I =
942 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
943 const CXXMethodDecl *MD = *I;
944
945 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
946 MD->getDeclName();
947 }
948
949 if (!PureVirtualClassDiagSet)
950 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
951 PureVirtualClassDiagSet->insert(RD);
952
953 return true;
954}
955
Anders Carlsson412c3402009-03-24 01:19:16 +0000956namespace {
957 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
958 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
959 Sema &SemaRef;
960 CXXRecordDecl *AbstractClass;
961
Anders Carlssonde9e7892009-03-24 17:23:42 +0000962 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson412c3402009-03-24 01:19:16 +0000963 bool Invalid = false;
964
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000965 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
966 E = DC->decls_end(); I != E; ++I)
Anders Carlsson412c3402009-03-24 01:19:16 +0000967 Invalid |= Visit(*I);
Anders Carlssonde9e7892009-03-24 17:23:42 +0000968
Anders Carlsson412c3402009-03-24 01:19:16 +0000969 return Invalid;
970 }
Anders Carlssonde9e7892009-03-24 17:23:42 +0000971
972 public:
973 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
974 : SemaRef(SemaRef), AbstractClass(ac) {
975 Visit(SemaRef.Context.getTranslationUnitDecl());
976 }
Anders Carlsson412c3402009-03-24 01:19:16 +0000977
Anders Carlssonde9e7892009-03-24 17:23:42 +0000978 bool VisitFunctionDecl(const FunctionDecl *FD) {
979 if (FD->isThisDeclarationADefinition()) {
980 // No need to do the check if we're in a definition, because it requires
981 // that the return/param types are complete.
982 // because that requires
983 return VisitDeclContext(FD);
984 }
985
986 // Check the return type.
987 QualType RTy = FD->getType()->getAsFunctionType()->getResultType();
988 bool Invalid =
989 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
990 diag::err_abstract_type_in_decl,
991 Sema::AbstractReturnType,
992 AbstractClass);
993
994 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
995 E = FD->param_end(); I != E; ++I) {
Anders Carlsson412c3402009-03-24 01:19:16 +0000996 const ParmVarDecl *VD = *I;
997 Invalid |=
998 SemaRef.RequireNonAbstractType(VD->getLocation(),
999 VD->getOriginalType(),
1000 diag::err_abstract_type_in_decl,
Anders Carlssonde9e7892009-03-24 17:23:42 +00001001 Sema::AbstractParamType,
1002 AbstractClass);
Anders Carlsson412c3402009-03-24 01:19:16 +00001003 }
1004
1005 return Invalid;
1006 }
Anders Carlssonde9e7892009-03-24 17:23:42 +00001007
1008 bool VisitDecl(const Decl* D) {
1009 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1010 return VisitDeclContext(DC);
1011
1012 return false;
1013 }
Anders Carlsson412c3402009-03-24 01:19:16 +00001014 };
1015}
1016
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001017void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +00001018 DeclPtrTy TagDecl,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001019 SourceLocation LBrac,
1020 SourceLocation RBrac) {
Douglas Gregorac77dd62009-06-22 23:20:33 +00001021 if (!TagDecl)
1022 return;
1023
Douglas Gregor3eb20702009-05-11 19:58:34 +00001024 AdjustDeclIfTemplate(TagDecl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001025 ActOnFields(S, RLoc, TagDecl,
Chris Lattner5261d0c2009-03-28 19:18:32 +00001026 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +00001027 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregored3a3982009-03-03 04:44:36 +00001028
Chris Lattner5261d0c2009-03-28 19:18:32 +00001029 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001030 if (!RD->isAbstract()) {
1031 // Collect all the pure virtual methods and see if this is an abstract
1032 // class after all.
1033 PureVirtualMethodCollector Collector(Context, RD);
1034 if (!Collector.empty())
1035 RD->setAbstract(true);
1036 }
1037
Anders Carlssonde9e7892009-03-24 17:23:42 +00001038 if (RD->isAbstract())
1039 AbstractClassUsageDiagnoser(*this, RD);
Anders Carlsson412c3402009-03-24 01:19:16 +00001040
Anders Carlsson39a10db2009-04-17 02:34:54 +00001041 if (RD->hasTrivialConstructor() || RD->hasTrivialDestructor()) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001042 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1043 i != e; ++i) {
Anders Carlssonc6363712009-04-16 00:08:20 +00001044 // All the nonstatic data members must have trivial constructors.
1045 QualType FTy = i->getType();
1046 while (const ArrayType *AT = Context.getAsArrayType(FTy))
1047 FTy = AT->getElementType();
1048
1049 if (const RecordType *RT = FTy->getAsRecordType()) {
1050 CXXRecordDecl *FieldRD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson39a10db2009-04-17 02:34:54 +00001051
1052 if (!FieldRD->hasTrivialConstructor())
Anders Carlssonc6363712009-04-16 00:08:20 +00001053 RD->setHasTrivialConstructor(false);
Anders Carlsson39a10db2009-04-17 02:34:54 +00001054 if (!FieldRD->hasTrivialDestructor())
1055 RD->setHasTrivialDestructor(false);
1056
1057 // If RD has neither a trivial constructor nor a trivial destructor
1058 // we don't need to continue checking.
1059 if (!RD->hasTrivialConstructor() && !RD->hasTrivialDestructor())
Anders Carlssonc6363712009-04-16 00:08:20 +00001060 break;
Anders Carlssonc6363712009-04-16 00:08:20 +00001061 }
1062 }
1063 }
1064
Douglas Gregor3eb20702009-05-11 19:58:34 +00001065 if (!RD->isDependentType())
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001066 AddImplicitlyDeclaredMembersToClass(RD);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001067}
1068
Douglas Gregore640ab62008-11-03 17:51:48 +00001069/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1070/// special functions, such as the default constructor, copy
1071/// constructor, or destructor, to the given C++ class (C++
1072/// [special]p1). This routine can only be executed just before the
1073/// definition of the class is complete.
1074void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001075 QualType ClassType = Context.getTypeDeclType(ClassDecl);
1076 ClassType = Context.getCanonicalType(ClassType);
1077
Sebastian Redl2767d882009-05-27 22:11:52 +00001078 // FIXME: Implicit declarations have exception specifications, which are
1079 // the union of the specifications of the implicitly called functions.
1080
Douglas Gregore640ab62008-11-03 17:51:48 +00001081 if (!ClassDecl->hasUserDeclaredConstructor()) {
1082 // C++ [class.ctor]p5:
1083 // A default constructor for a class X is a constructor of class X
1084 // that can be called without an argument. If there is no
1085 // user-declared constructor for class X, a default constructor is
1086 // implicitly declared. An implicitly-declared default constructor
1087 // is an inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001088 DeclarationName Name
1089 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +00001090 CXXConstructorDecl *DefaultCon =
1091 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001092 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +00001093 Context.getFunctionType(Context.VoidTy,
1094 0, 0, false, 0),
1095 /*isExplicit=*/false,
1096 /*isInline=*/true,
1097 /*isImplicitlyDeclared=*/true);
1098 DefaultCon->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001099 DefaultCon->setImplicit();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001100 ClassDecl->addDecl(DefaultCon);
Douglas Gregore640ab62008-11-03 17:51:48 +00001101 }
1102
1103 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1104 // C++ [class.copy]p4:
1105 // If the class definition does not explicitly declare a copy
1106 // constructor, one is declared implicitly.
1107
1108 // C++ [class.copy]p5:
1109 // The implicitly-declared copy constructor for a class X will
1110 // have the form
1111 //
1112 // X::X(const X&)
1113 //
1114 // if
1115 bool HasConstCopyConstructor = true;
1116
1117 // -- each direct or virtual base class B of X has a copy
1118 // constructor whose first parameter is of type const B& or
1119 // const volatile B&, and
1120 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1121 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1122 const CXXRecordDecl *BaseClassDecl
1123 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
1124 HasConstCopyConstructor
1125 = BaseClassDecl->hasConstCopyConstructor(Context);
1126 }
1127
1128 // -- for all the nonstatic data members of X that are of a
1129 // class type M (or array thereof), each such class type
1130 // has a copy constructor whose first parameter is of type
1131 // const M& or const volatile M&.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001132 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1133 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001134 ++Field) {
Douglas Gregore640ab62008-11-03 17:51:48 +00001135 QualType FieldType = (*Field)->getType();
1136 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1137 FieldType = Array->getElementType();
1138 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
1139 const CXXRecordDecl *FieldClassDecl
1140 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1141 HasConstCopyConstructor
1142 = FieldClassDecl->hasConstCopyConstructor(Context);
1143 }
1144 }
1145
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001146 // Otherwise, the implicitly declared copy constructor will have
1147 // the form
Douglas Gregore640ab62008-11-03 17:51:48 +00001148 //
1149 // X::X(X&)
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001150 QualType ArgType = ClassType;
Douglas Gregore640ab62008-11-03 17:51:48 +00001151 if (HasConstCopyConstructor)
1152 ArgType = ArgType.withConst();
Sebastian Redlce6fff02009-03-16 23:22:08 +00001153 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregore640ab62008-11-03 17:51:48 +00001154
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001155 // An implicitly-declared copy constructor is an inline public
1156 // member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001157 DeclarationName Name
1158 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +00001159 CXXConstructorDecl *CopyConstructor
1160 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001161 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +00001162 Context.getFunctionType(Context.VoidTy,
1163 &ArgType, 1,
1164 false, 0),
1165 /*isExplicit=*/false,
1166 /*isInline=*/true,
1167 /*isImplicitlyDeclared=*/true);
1168 CopyConstructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001169 CopyConstructor->setImplicit();
Douglas Gregore640ab62008-11-03 17:51:48 +00001170
1171 // Add the parameter to the constructor.
1172 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1173 ClassDecl->getLocation(),
1174 /*IdentifierInfo=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001175 ArgType, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +00001176 CopyConstructor->setParams(Context, &FromParam, 1);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001177 ClassDecl->addDecl(CopyConstructor);
Douglas Gregore640ab62008-11-03 17:51:48 +00001178 }
1179
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001180 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1181 // Note: The following rules are largely analoguous to the copy
1182 // constructor rules. Note that virtual bases are not taken into account
1183 // for determining the argument type of the operator. Note also that
1184 // operators taking an object instead of a reference are allowed.
1185 //
1186 // C++ [class.copy]p10:
1187 // If the class definition does not explicitly declare a copy
1188 // assignment operator, one is declared implicitly.
1189 // The implicitly-defined copy assignment operator for a class X
1190 // will have the form
1191 //
1192 // X& X::operator=(const X&)
1193 //
1194 // if
1195 bool HasConstCopyAssignment = true;
1196
1197 // -- each direct base class B of X has a copy assignment operator
1198 // whose parameter is of type const B&, const volatile B& or B,
1199 // and
1200 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1201 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1202 const CXXRecordDecl *BaseClassDecl
1203 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
1204 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
1205 }
1206
1207 // -- for all the nonstatic data members of X that are of a class
1208 // type M (or array thereof), each such class type has a copy
1209 // assignment operator whose parameter is of type const M&,
1210 // const volatile M& or M.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001211 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1212 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001213 ++Field) {
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001214 QualType FieldType = (*Field)->getType();
1215 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1216 FieldType = Array->getElementType();
1217 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
1218 const CXXRecordDecl *FieldClassDecl
1219 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1220 HasConstCopyAssignment
1221 = FieldClassDecl->hasConstCopyAssignment(Context);
1222 }
1223 }
1224
1225 // Otherwise, the implicitly declared copy assignment operator will
1226 // have the form
1227 //
1228 // X& X::operator=(X&)
1229 QualType ArgType = ClassType;
Sebastian Redlce6fff02009-03-16 23:22:08 +00001230 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001231 if (HasConstCopyAssignment)
1232 ArgType = ArgType.withConst();
Sebastian Redlce6fff02009-03-16 23:22:08 +00001233 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001234
1235 // An implicitly-declared copy assignment operator is an inline public
1236 // member of its class.
1237 DeclarationName Name =
1238 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1239 CXXMethodDecl *CopyAssignment =
1240 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1241 Context.getFunctionType(RetType, &ArgType, 1,
1242 false, 0),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001243 /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001244 CopyAssignment->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001245 CopyAssignment->setImplicit();
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001246
1247 // Add the parameter to the operator.
1248 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1249 ClassDecl->getLocation(),
1250 /*IdentifierInfo=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001251 ArgType, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +00001252 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001253
1254 // Don't call addedAssignmentOperator. There is no way to distinguish an
1255 // implicit from an explicit assignment operator.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001256 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001257 }
1258
Douglas Gregorb9213832008-12-15 21:24:18 +00001259 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001260 // C++ [class.dtor]p2:
1261 // If a class has no user-declared destructor, a destructor is
1262 // declared implicitly. An implicitly-declared destructor is an
1263 // inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001264 DeclarationName Name
1265 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001266 CXXDestructorDecl *Destructor
1267 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001268 ClassDecl->getLocation(), Name,
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001269 Context.getFunctionType(Context.VoidTy,
1270 0, 0, false, 0),
1271 /*isInline=*/true,
1272 /*isImplicitlyDeclared=*/true);
1273 Destructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001274 Destructor->setImplicit();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001275 ClassDecl->addDecl(Destructor);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001276 }
Douglas Gregore640ab62008-11-03 17:51:48 +00001277}
1278
Douglas Gregora376cbd2009-05-27 23:11:45 +00001279void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
1280 TemplateDecl *Template = TemplateD.getAs<TemplateDecl>();
1281 if (!Template)
1282 return;
1283
1284 TemplateParameterList *Params = Template->getTemplateParameters();
1285 for (TemplateParameterList::iterator Param = Params->begin(),
1286 ParamEnd = Params->end();
1287 Param != ParamEnd; ++Param) {
1288 NamedDecl *Named = cast<NamedDecl>(*Param);
1289 if (Named->getDeclName()) {
1290 S->AddDecl(DeclPtrTy::make(Named));
1291 IdResolver.AddDecl(Named);
1292 }
1293 }
1294}
1295
Douglas Gregor605de8d2008-12-16 21:30:33 +00001296/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1297/// parsing a top-level (non-nested) C++ class, and we are now
1298/// parsing those parts of the given Method declaration that could
1299/// not be parsed earlier (C++ [class.mem]p2), such as default
1300/// arguments. This action should enter the scope of the given
1301/// Method declaration as if we had just parsed the qualified method
1302/// name. However, it should not bring the parameters into scope;
1303/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001304void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregorac77dd62009-06-22 23:20:33 +00001305 if (!MethodD)
1306 return;
1307
Douglas Gregor605de8d2008-12-16 21:30:33 +00001308 CXXScopeSpec SS;
Chris Lattner5261d0c2009-03-28 19:18:32 +00001309 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001310 QualType ClassTy
1311 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1312 SS.setScopeRep(
1313 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor605de8d2008-12-16 21:30:33 +00001314 ActOnCXXEnterDeclaratorScope(S, SS);
1315}
1316
1317/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1318/// C++ method declaration. We're (re-)introducing the given
1319/// function parameter into scope for use in parsing later parts of
1320/// the method declaration. For example, we could see an
1321/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001322void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregorac77dd62009-06-22 23:20:33 +00001323 if (!ParamD)
1324 return;
1325
Chris Lattner5261d0c2009-03-28 19:18:32 +00001326 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001327
1328 // If this parameter has an unparsed default argument, clear it out
1329 // to make way for the parsed default argument.
1330 if (Param->hasUnparsedDefaultArg())
1331 Param->setDefaultArg(0);
1332
Chris Lattner5261d0c2009-03-28 19:18:32 +00001333 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor605de8d2008-12-16 21:30:33 +00001334 if (Param->getDeclName())
1335 IdResolver.AddDecl(Param);
1336}
1337
1338/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1339/// processing the delayed method declaration for Method. The method
1340/// declaration is now considered finished. There may be a separate
1341/// ActOnStartOfFunctionDef action later (not necessarily
1342/// immediately!) for this method, if it was also defined inside the
1343/// class body.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001344void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregorac77dd62009-06-22 23:20:33 +00001345 if (!MethodD)
1346 return;
1347
Chris Lattner5261d0c2009-03-28 19:18:32 +00001348 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor605de8d2008-12-16 21:30:33 +00001349 CXXScopeSpec SS;
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001350 QualType ClassTy
1351 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1352 SS.setScopeRep(
1353 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor605de8d2008-12-16 21:30:33 +00001354 ActOnCXXExitDeclaratorScope(S, SS);
1355
1356 // Now that we have our default arguments, check the constructor
1357 // again. It could produce additional diagnostics or affect whether
1358 // the class has implicitly-declared destructors, among other
1359 // things.
Chris Lattner08da4772009-04-25 08:35:12 +00001360 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
1361 CheckConstructor(Constructor);
Douglas Gregor605de8d2008-12-16 21:30:33 +00001362
1363 // Check the default arguments, which we may have added.
1364 if (!Method->isInvalidDecl())
1365 CheckCXXDefaultArguments(Method);
1366}
1367
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001368/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor605de8d2008-12-16 21:30:33 +00001369/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001370/// R. If there are any errors in the declarator, this routine will
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001371/// emit diagnostics and set the invalid bit to true. In any case, the type
1372/// will be updated to reflect a well-formed type for the constructor and
1373/// returned.
1374QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
1375 FunctionDecl::StorageClass &SC) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001376 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001377
1378 // C++ [class.ctor]p3:
1379 // A constructor shall not be virtual (10.3) or static (9.4). A
1380 // constructor can be invoked for a const, volatile or const
1381 // volatile object. A constructor shall not be declared const,
1382 // volatile, or const volatile (9.3.2).
1383 if (isVirtual) {
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001384 if (!D.isInvalidType())
1385 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1386 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1387 << SourceRange(D.getIdentifierLoc());
1388 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001389 }
1390 if (SC == FunctionDecl::Static) {
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001391 if (!D.isInvalidType())
1392 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1393 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1394 << SourceRange(D.getIdentifierLoc());
1395 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001396 SC = FunctionDecl::None;
1397 }
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001398
1399 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1400 if (FTI.TypeQuals != 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001401 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001402 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1403 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001404 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001405 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1406 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001407 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001408 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1409 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001410 }
1411
1412 // Rebuild the function type "R" without any type qualifiers (in
1413 // case any of the errors above fired) and with "void" as the
1414 // return type, since constructors don't have return types. We
1415 // *always* have to do this, because GetTypeForDeclarator will
1416 // put in a result type of "int" when none was specified.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001417 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001418 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1419 Proto->getNumArgs(),
1420 Proto->isVariadic(), 0);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001421}
1422
Douglas Gregor605de8d2008-12-16 21:30:33 +00001423/// CheckConstructor - Checks a fully-formed constructor for
1424/// well-formedness, issuing any diagnostics required. Returns true if
1425/// the constructor declarator is invalid.
Chris Lattner08da4772009-04-25 08:35:12 +00001426void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Douglas Gregor869cabf2009-03-27 04:38:56 +00001427 CXXRecordDecl *ClassDecl
1428 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
1429 if (!ClassDecl)
Chris Lattner08da4772009-04-25 08:35:12 +00001430 return Constructor->setInvalidDecl();
Douglas Gregor605de8d2008-12-16 21:30:33 +00001431
1432 // C++ [class.copy]p3:
1433 // A declaration of a constructor for a class X is ill-formed if
1434 // its first parameter is of type (optionally cv-qualified) X and
1435 // either there are no other parameters or else all other
1436 // parameters have default arguments.
Douglas Gregor869cabf2009-03-27 04:38:56 +00001437 if (!Constructor->isInvalidDecl() &&
1438 ((Constructor->getNumParams() == 1) ||
1439 (Constructor->getNumParams() > 1 &&
Anders Carlssond2e57d92009-06-06 04:14:07 +00001440 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor605de8d2008-12-16 21:30:33 +00001441 QualType ParamType = Constructor->getParamDecl(0)->getType();
1442 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1443 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00001444 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
1445 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor133d2552009-04-02 01:08:08 +00001446 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattner08da4772009-04-25 08:35:12 +00001447 Constructor->setInvalidDecl();
Douglas Gregor605de8d2008-12-16 21:30:33 +00001448 }
1449 }
1450
1451 // Notify the class that we've added a constructor.
1452 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor605de8d2008-12-16 21:30:33 +00001453}
1454
Anders Carlssonfcfa2442009-04-30 23:18:11 +00001455static inline bool
1456FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
1457 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1458 FTI.ArgInfo[0].Param &&
1459 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
1460}
1461
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001462/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1463/// the well-formednes of the destructor declarator @p D with type @p
1464/// R. If there are any errors in the declarator, this routine will
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001465/// emit diagnostics and set the declarator to invalid. Even if this happens,
1466/// will be updated to reflect a well-formed type for the destructor and
1467/// returned.
1468QualType Sema::CheckDestructorDeclarator(Declarator &D,
1469 FunctionDecl::StorageClass& SC) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001470 // C++ [class.dtor]p1:
1471 // [...] A typedef-name that names a class is a class-name
1472 // (7.1.3); however, a typedef-name that names a class shall not
1473 // be used as the identifier in the declarator for a destructor
1474 // declaration.
Douglas Gregora60c62e2009-02-09 15:09:02 +00001475 QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001476 if (isa<TypedefType>(DeclaratorType)) {
1477 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregora60c62e2009-02-09 15:09:02 +00001478 << DeclaratorType;
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001479 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001480 }
1481
1482 // C++ [class.dtor]p2:
1483 // A destructor is used to destroy objects of its class type. A
1484 // destructor takes no parameters, and no return type can be
1485 // specified for it (not even void). The address of a destructor
1486 // shall not be taken. A destructor shall not be static. A
1487 // destructor can be invoked for a const, volatile or const
1488 // volatile object. A destructor shall not be declared const,
1489 // volatile or const volatile (9.3.2).
1490 if (SC == FunctionDecl::Static) {
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001491 if (!D.isInvalidType())
1492 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1493 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1494 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001495 SC = FunctionDecl::None;
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001496 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001497 }
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001498 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001499 // Destructors don't have return types, but the parser will
1500 // happily parse something like:
1501 //
1502 // class X {
1503 // float ~X();
1504 // };
1505 //
1506 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001507 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1508 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1509 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001510 }
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001511
1512 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1513 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001514 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001515 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1516 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001517 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001518 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1519 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001520 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001521 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1522 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001523 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001524 }
1525
1526 // Make sure we don't have any parameters.
Anders Carlssonfcfa2442009-04-30 23:18:11 +00001527 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001528 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1529
1530 // Delete the parameters.
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001531 FTI.freeArgs();
1532 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001533 }
1534
1535 // Make sure the destructor isn't variadic.
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001536 if (FTI.isVariadic) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001537 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001538 D.setInvalidType();
1539 }
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001540
1541 // Rebuild the function type "R" without any type qualifiers or
1542 // parameters (in case any of the errors above fired) and with
1543 // "void" as the return type, since destructors don't have return
1544 // types. We *always* have to do this, because GetTypeForDeclarator
1545 // will put in a result type of "int" when none was specified.
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001546 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001547}
1548
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001549/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1550/// well-formednes of the conversion function declarator @p D with
1551/// type @p R. If there are any errors in the declarator, this routine
1552/// will emit diagnostics and return true. Otherwise, it will return
1553/// false. Either way, the type @p R will be updated to reflect a
1554/// well-formed type for the conversion operator.
Chris Lattner08da4772009-04-25 08:35:12 +00001555void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001556 FunctionDecl::StorageClass& SC) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001557 // C++ [class.conv.fct]p1:
1558 // Neither parameter types nor return type can be specified. The
1559 // type of a conversion function (8.3.5) is “function taking no
1560 // parameter returning conversion-type-id.”
1561 if (SC == FunctionDecl::Static) {
Chris Lattner08da4772009-04-25 08:35:12 +00001562 if (!D.isInvalidType())
1563 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1564 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1565 << SourceRange(D.getIdentifierLoc());
1566 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001567 SC = FunctionDecl::None;
1568 }
Chris Lattner08da4772009-04-25 08:35:12 +00001569 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001570 // Conversion functions don't have return types, but the parser will
1571 // happily parse something like:
1572 //
1573 // class X {
1574 // float operator bool();
1575 // };
1576 //
1577 // The return type will be changed later anyway.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001578 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1579 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1580 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001581 }
1582
1583 // Make sure we don't have any parameters.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001584 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001585 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1586
1587 // Delete the parameters.
Chris Lattner5c6139b2009-01-20 21:06:38 +00001588 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner08da4772009-04-25 08:35:12 +00001589 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001590 }
1591
1592 // Make sure the conversion function isn't variadic.
Chris Lattner08da4772009-04-25 08:35:12 +00001593 if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001594 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner08da4772009-04-25 08:35:12 +00001595 D.setInvalidType();
1596 }
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001597
1598 // C++ [class.conv.fct]p4:
1599 // The conversion-type-id shall not represent a function type nor
1600 // an array type.
1601 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1602 if (ConvType->isArrayType()) {
1603 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1604 ConvType = Context.getPointerType(ConvType);
Chris Lattner08da4772009-04-25 08:35:12 +00001605 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001606 } else if (ConvType->isFunctionType()) {
1607 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1608 ConvType = Context.getPointerType(ConvType);
Chris Lattner08da4772009-04-25 08:35:12 +00001609 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001610 }
1611
1612 // Rebuild the function type "R" without any parameters (in case any
1613 // of the errors above fired) and with the conversion type as the
1614 // return type.
1615 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor4fa58902009-02-26 23:50:07 +00001616 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001617
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001618 // C++0x explicit conversion operators.
1619 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1620 Diag(D.getDeclSpec().getExplicitSpecLoc(),
1621 diag::warn_explicit_conversion_functions)
1622 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001623}
1624
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001625/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1626/// the declaration of the given C++ conversion function. This routine
1627/// is responsible for recording the conversion function in the C++
1628/// class, if possible.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001629Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001630 assert(Conversion && "Expected to receive a conversion function declaration");
1631
Douglas Gregor98341042008-12-12 08:25:50 +00001632 // Set the lexical context of this conversion function
1633 Conversion->setLexicalDeclContext(CurContext);
1634
1635 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001636
1637 // Make sure we aren't redeclaring the conversion function.
1638 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001639
1640 // C++ [class.conv.fct]p1:
1641 // [...] A conversion function is never used to convert a
1642 // (possibly cv-qualified) object to the (possibly cv-qualified)
1643 // same object type (or a reference to it), to a (possibly
1644 // cv-qualified) base class of that type (or a reference to it),
1645 // or to (possibly cv-qualified) void.
Mike Stumpe127ae32009-05-16 07:39:55 +00001646 // FIXME: Suppress this warning if the conversion function ends up being a
1647 // virtual function that overrides a virtual function in a base class.
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001648 QualType ClassType
1649 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1650 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1651 ConvType = ConvTypeRef->getPointeeType();
1652 if (ConvType->isRecordType()) {
1653 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1654 if (ConvType == ClassType)
Chris Lattner8d756812008-11-20 06:13:02 +00001655 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001656 << ClassType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001657 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner8d756812008-11-20 06:13:02 +00001658 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001659 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001660 } else if (ConvType->isVoidType()) {
Chris Lattner8d756812008-11-20 06:13:02 +00001661 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001662 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001663 }
1664
Douglas Gregor853dd392008-12-26 15:00:45 +00001665 if (Conversion->getPreviousDeclaration()) {
1666 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1667 for (OverloadedFunctionDecl::function_iterator
1668 Conv = Conversions->function_begin(),
1669 ConvEnd = Conversions->function_end();
1670 Conv != ConvEnd; ++Conv) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00001671 if (*Conv
1672 == cast_or_null<NamedDecl>(Conversion->getPreviousDeclaration())) {
Douglas Gregor853dd392008-12-26 15:00:45 +00001673 *Conv = Conversion;
Chris Lattner5261d0c2009-03-28 19:18:32 +00001674 return DeclPtrTy::make(Conversion);
Douglas Gregor853dd392008-12-26 15:00:45 +00001675 }
1676 }
1677 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1678 } else
1679 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001680
Chris Lattner5261d0c2009-03-28 19:18:32 +00001681 return DeclPtrTy::make(Conversion);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001682}
1683
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001684//===----------------------------------------------------------------------===//
1685// Namespace Handling
1686//===----------------------------------------------------------------------===//
1687
1688/// ActOnStartNamespaceDef - This is called at the start of a namespace
1689/// definition.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001690Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1691 SourceLocation IdentLoc,
1692 IdentifierInfo *II,
1693 SourceLocation LBrace) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001694 NamespaceDecl *Namespc =
1695 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1696 Namespc->setLBracLoc(LBrace);
1697
1698 Scope *DeclRegionScope = NamespcScope->getParent();
1699
1700 if (II) {
1701 // C++ [namespace.def]p2:
1702 // The identifier in an original-namespace-definition shall not have been
1703 // previously defined in the declarative region in which the
1704 // original-namespace-definition appears. The identifier in an
1705 // original-namespace-definition is the name of the namespace. Subsequently
1706 // in that declarative region, it is treated as an original-namespace-name.
1707
Douglas Gregor09be81b2009-02-04 17:27:36 +00001708 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1709 true);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001710
1711 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1712 // This is an extended namespace definition.
1713 // Attach this namespace decl to the chain of extended namespace
1714 // definitions.
1715 OrigNS->setNextNamespace(Namespc);
1716 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001717
Douglas Gregor8acb7272008-12-11 16:49:14 +00001718 // Remove the previous declaration from the scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001719 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor39677622008-12-11 20:41:00 +00001720 IdResolver.RemoveDecl(OrigNS);
Chris Lattner5261d0c2009-03-28 19:18:32 +00001721 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001722 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001723 } else if (PrevDecl) {
1724 // This is an invalid name redefinition.
1725 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1726 << Namespc->getDeclName();
1727 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1728 Namespc->setInvalidDecl();
1729 // Continue on to push Namespc as current DeclContext and return it.
1730 }
1731
1732 PushOnScopeChains(Namespc, DeclRegionScope);
1733 } else {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001734 // FIXME: Handle anonymous namespaces
1735 }
1736
1737 // Although we could have an invalid decl (i.e. the namespace name is a
1738 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stumpe127ae32009-05-16 07:39:55 +00001739 // FIXME: We should be able to push Namespc here, so that the each DeclContext
1740 // for the namespace has the declarations that showed up in that particular
1741 // namespace definition.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001742 PushDeclContext(NamespcScope, Namespc);
Chris Lattner5261d0c2009-03-28 19:18:32 +00001743 return DeclPtrTy::make(Namespc);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001744}
1745
1746/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1747/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001748void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
1749 Decl *Dcl = D.getAs<Decl>();
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001750 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1751 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1752 Namespc->setRBracLoc(RBrace);
1753 PopDeclContext();
1754}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001755
Chris Lattner5261d0c2009-03-28 19:18:32 +00001756Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
1757 SourceLocation UsingLoc,
1758 SourceLocation NamespcLoc,
1759 const CXXScopeSpec &SS,
1760 SourceLocation IdentLoc,
1761 IdentifierInfo *NamespcName,
1762 AttributeList *AttrList) {
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001763 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1764 assert(NamespcName && "Invalid NamespcName.");
1765 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor7a7be652009-02-03 19:21:40 +00001766 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001767
Douglas Gregor7a7be652009-02-03 19:21:40 +00001768 UsingDirectiveDecl *UDir = 0;
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001769
Douglas Gregor78d70132009-01-14 22:20:51 +00001770 // Lookup namespace name.
Douglas Gregor7a7be652009-02-03 19:21:40 +00001771 LookupResult R = LookupParsedName(S, &SS, NamespcName,
1772 LookupNamespaceName, false);
1773 if (R.isAmbiguous()) {
1774 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattner5261d0c2009-03-28 19:18:32 +00001775 return DeclPtrTy();
Douglas Gregor7a7be652009-02-03 19:21:40 +00001776 }
Douglas Gregor09be81b2009-02-04 17:27:36 +00001777 if (NamedDecl *NS = R) {
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001778 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor7a7be652009-02-03 19:21:40 +00001779 // C++ [namespace.udir]p1:
1780 // A using-directive specifies that the names in the nominated
1781 // namespace can be used in the scope in which the
1782 // using-directive appears after the using-directive. During
1783 // unqualified name lookup (3.4.1), the names appear as if they
1784 // were declared in the nearest enclosing namespace which
1785 // contains both the using-directive and the nominated
1786 // namespace. [Note: in this context, “contains” means “contains
1787 // directly or indirectly”. ]
1788
1789 // Find enclosing context containing both using-directive and
1790 // nominated namespace.
1791 DeclContext *CommonAncestor = cast<DeclContext>(NS);
1792 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1793 CommonAncestor = CommonAncestor->getParent();
1794
Douglas Gregor1d27d692009-05-30 06:31:56 +00001795 UDir = UsingDirectiveDecl::Create(Context,
1796 CurContext, UsingLoc,
1797 NamespcLoc,
1798 SS.getRange(),
1799 (NestedNameSpecifier *)SS.getScopeRep(),
1800 IdentLoc,
Douglas Gregor7a7be652009-02-03 19:21:40 +00001801 cast<NamespaceDecl>(NS),
1802 CommonAncestor);
1803 PushUsingDirective(S, UDir);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001804 } else {
Chris Lattner954381a2009-01-06 07:24:29 +00001805 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001806 }
1807
Douglas Gregor7a7be652009-02-03 19:21:40 +00001808 // FIXME: We ignore attributes for now.
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001809 delete AttrList;
Chris Lattner5261d0c2009-03-28 19:18:32 +00001810 return DeclPtrTy::make(UDir);
Douglas Gregor7a7be652009-02-03 19:21:40 +00001811}
1812
1813void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1814 // If scope has associated entity, then using directive is at namespace
1815 // or translation unit scope. We add UsingDirectiveDecls, into
1816 // it's lookup structure.
1817 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001818 Ctx->addDecl(UDir);
Douglas Gregor7a7be652009-02-03 19:21:40 +00001819 else
1820 // Otherwise it is block-sope. using-directives will affect lookup
1821 // only to the end of scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001822 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001823}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001824
Douglas Gregor683a1142009-06-20 00:51:54 +00001825
1826Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
1827 SourceLocation UsingLoc,
1828 const CXXScopeSpec &SS,
1829 SourceLocation IdentLoc,
1830 IdentifierInfo *TargetName,
Anders Carlssone8c36f22009-06-27 00:27:47 +00001831 OverloadedOperatorKind Op,
Douglas Gregor683a1142009-06-20 00:51:54 +00001832 AttributeList *AttrList,
1833 bool IsTypeName) {
1834 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Eli Friedmana73d6b12009-06-27 05:59:59 +00001835 assert((TargetName || Op) && "Invalid TargetName.");
Douglas Gregor683a1142009-06-20 00:51:54 +00001836 assert(IdentLoc.isValid() && "Invalid TargetName location.");
1837 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
1838
1839 UsingDecl *UsingAlias = 0;
1840
Anders Carlssone8c36f22009-06-27 00:27:47 +00001841 DeclarationName Name;
1842 if (TargetName)
1843 Name = TargetName;
1844 else
1845 Name = Context.DeclarationNames.getCXXOperatorName(Op);
1846
Douglas Gregor683a1142009-06-20 00:51:54 +00001847 // Lookup target name.
Anders Carlssone8c36f22009-06-27 00:27:47 +00001848 LookupResult R = LookupParsedName(S, &SS, Name, LookupOrdinaryName, false);
Douglas Gregor683a1142009-06-20 00:51:54 +00001849
1850 if (NamedDecl *NS = R) {
1851 if (IsTypeName && !isa<TypeDecl>(NS)) {
1852 Diag(IdentLoc, diag::err_using_typename_non_type);
1853 }
1854 UsingAlias = UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
1855 NS->getLocation(), UsingLoc, NS,
1856 static_cast<NestedNameSpecifier *>(SS.getScopeRep()),
1857 IsTypeName);
1858 PushOnScopeChains(UsingAlias, S);
1859 } else {
1860 Diag(IdentLoc, diag::err_using_requires_qualname) << SS.getRange();
1861 }
1862
1863 // FIXME: We ignore attributes for now.
1864 delete AttrList;
1865 return DeclPtrTy::make(UsingAlias);
1866}
1867
Anders Carlsson7c1c5482009-03-28 23:53:49 +00001868/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
1869/// is a namespace alias, returns the namespace it points to.
1870static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
1871 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
1872 return AD->getNamespace();
1873 return dyn_cast_or_null<NamespaceDecl>(D);
1874}
1875
Chris Lattner5261d0c2009-03-28 19:18:32 +00001876Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson26de7882009-03-28 22:53:22 +00001877 SourceLocation NamespaceLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +00001878 SourceLocation AliasLoc,
1879 IdentifierInfo *Alias,
1880 const CXXScopeSpec &SS,
Anders Carlsson26de7882009-03-28 22:53:22 +00001881 SourceLocation IdentLoc,
1882 IdentifierInfo *Ident) {
Anders Carlsson640eb7c2009-03-28 06:23:46 +00001883
Anders Carlsson7c1c5482009-03-28 23:53:49 +00001884 // Lookup the namespace name.
1885 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
1886
Anders Carlsson640eb7c2009-03-28 06:23:46 +00001887 // Check if we have a previous declaration with the same name.
Anders Carlsson1cd05f52009-03-28 23:49:35 +00001888 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlsson7c1c5482009-03-28 23:53:49 +00001889 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
1890 // We already have an alias with the same name that points to the same
1891 // namespace, so don't create a new one.
1892 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
1893 return DeclPtrTy();
1894 }
1895
Anders Carlsson640eb7c2009-03-28 06:23:46 +00001896 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
1897 diag::err_redefinition_different_kind;
1898 Diag(AliasLoc, DiagID) << Alias;
1899 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner5261d0c2009-03-28 19:18:32 +00001900 return DeclPtrTy();
Anders Carlsson640eb7c2009-03-28 06:23:46 +00001901 }
1902
Anders Carlsson279ebc42009-03-28 06:42:02 +00001903 if (R.isAmbiguous()) {
Anders Carlsson26de7882009-03-28 22:53:22 +00001904 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattner5261d0c2009-03-28 19:18:32 +00001905 return DeclPtrTy();
Anders Carlsson279ebc42009-03-28 06:42:02 +00001906 }
1907
1908 if (!R) {
1909 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner5261d0c2009-03-28 19:18:32 +00001910 return DeclPtrTy();
Anders Carlsson279ebc42009-03-28 06:42:02 +00001911 }
1912
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00001913 NamespaceAliasDecl *AliasDecl =
Douglas Gregor8d8ddca2009-05-30 06:48:27 +00001914 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
1915 Alias, SS.getRange(),
1916 (NestedNameSpecifier *)SS.getScopeRep(),
Anders Carlssonddb1d8b2009-03-28 22:58:02 +00001917 IdentLoc, R);
1918
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001919 CurContext->addDecl(AliasDecl);
Anders Carlssonddb1d8b2009-03-28 22:58:02 +00001920 return DeclPtrTy::make(AliasDecl);
Anders Carlsson8cffcd62009-03-28 05:27:17 +00001921}
1922
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00001923void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
1924 CXXConstructorDecl *Constructor) {
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00001925 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
1926 !Constructor->isUsed()) &&
1927 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00001928
1929 CXXRecordDecl *ClassDecl
1930 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanian599778e2009-06-22 23:34:40 +00001931 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00001932 // Before the implicitly-declared default constructor for a class is
1933 // implicitly defined, all the implicitly-declared default constructors
1934 // for its base class and its non-static data members shall have been
1935 // implicitly defined.
1936 bool err = false;
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00001937 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1938 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00001939 CXXRecordDecl *BaseClassDecl
1940 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
1941 if (!BaseClassDecl->hasTrivialConstructor()) {
1942 if (CXXConstructorDecl *BaseCtor =
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00001943 BaseClassDecl->getDefaultConstructor(Context))
1944 MarkDeclarationReferenced(CurrentLocation, BaseCtor);
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00001945 else {
1946 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian16443602009-06-20 20:23:38 +00001947 << Context.getTagDeclType(ClassDecl) << 1
1948 << Context.getTagDeclType(BaseClassDecl);
1949 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
1950 << Context.getTagDeclType(BaseClassDecl);
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00001951 err = true;
1952 }
1953 }
1954 }
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00001955 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1956 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00001957 QualType FieldType = Context.getCanonicalType((*Field)->getType());
1958 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1959 FieldType = Array->getElementType();
1960 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
1961 CXXRecordDecl *FieldClassDecl
1962 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Duncan Sands78146712009-06-25 09:03:06 +00001963 if (!FieldClassDecl->hasTrivialConstructor()) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00001964 if (CXXConstructorDecl *FieldCtor =
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00001965 FieldClassDecl->getDefaultConstructor(Context))
1966 MarkDeclarationReferenced(CurrentLocation, FieldCtor);
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00001967 else {
1968 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian16443602009-06-20 20:23:38 +00001969 << Context.getTagDeclType(ClassDecl) << 0 <<
1970 Context.getTagDeclType(FieldClassDecl);
1971 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
1972 << Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00001973 err = true;
1974 }
1975 }
Duncan Sands78146712009-06-25 09:03:06 +00001976 }
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00001977 else if (FieldType->isReferenceType()) {
1978 Diag(CurrentLocation, diag::err_unintialized_member)
Fariborz Jahanian16443602009-06-20 20:23:38 +00001979 << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getNameAsCString();
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00001980 Diag((*Field)->getLocation(), diag::note_declared_at);
1981 err = true;
1982 }
1983 else if (FieldType.isConstQualified()) {
1984 Diag(CurrentLocation, diag::err_unintialized_member)
Fariborz Jahanian16443602009-06-20 20:23:38 +00001985 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getNameAsCString();
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00001986 Diag((*Field)->getLocation(), diag::note_declared_at);
1987 err = true;
1988 }
1989 }
1990 if (!err)
Fariborz Jahanian2c313fb2009-06-26 16:08:57 +00001991 Constructor->setUsed();
1992 else
1993 Constructor->setInvalidDecl();
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00001994}
1995
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00001996void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
1997 CXXDestructorDecl *Destructor) {
1998 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
1999 "DefineImplicitDestructor - call it for implicit default dtor");
2000
2001 CXXRecordDecl *ClassDecl
2002 = cast<CXXRecordDecl>(Destructor->getDeclContext());
2003 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2004 // C++ [class.dtor] p5
2005 // Before the implicitly-declared default destructor for a class is
2006 // implicitly defined, all the implicitly-declared default destructors
2007 // for its base class and its non-static data members shall have been
2008 // implicitly defined.
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002009 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2010 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002011 CXXRecordDecl *BaseClassDecl
2012 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
2013 if (!BaseClassDecl->hasTrivialDestructor()) {
2014 if (CXXDestructorDecl *BaseDtor =
2015 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2016 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2017 else
2018 assert(false &&
2019 "DefineImplicitDestructor - missing dtor in a base class");
2020 }
2021 }
2022
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002023 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2024 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002025 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2026 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2027 FieldType = Array->getElementType();
2028 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
2029 CXXRecordDecl *FieldClassDecl
2030 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2031 if (!FieldClassDecl->hasTrivialDestructor()) {
2032 if (CXXDestructorDecl *FieldDtor =
2033 const_cast<CXXDestructorDecl*>(
2034 FieldClassDecl->getDestructor(Context)))
2035 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
2036 else
2037 assert(false &&
2038 "DefineImplicitDestructor - missing dtor in class of a data member");
2039 }
2040 }
2041 }
2042 Destructor->setUsed();
2043}
2044
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002045void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
2046 CXXMethodDecl *MethodDecl) {
2047 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
2048 MethodDecl->getOverloadedOperator() == OO_Equal &&
2049 !MethodDecl->isUsed()) &&
2050 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
2051
2052 CXXRecordDecl *ClassDecl
2053 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002054
Fariborz Jahanian2c313fb2009-06-26 16:08:57 +00002055 // C++[class.copy] p12
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002056 // Before the implicitly-declared copy assignment operator for a class is
2057 // implicitly defined, all implicitly-declared copy assignment operators
2058 // for its direct base classes and its nonstatic data members shall have
2059 // been implicitly defined.
2060 bool err = false;
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002061 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2062 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002063 CXXRecordDecl *BaseClassDecl
2064 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
2065 if (CXXMethodDecl *BaseAssignOpMethod =
2066 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
2067 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
2068 }
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002069 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2070 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002071 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2072 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2073 FieldType = Array->getElementType();
2074 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
2075 CXXRecordDecl *FieldClassDecl
2076 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2077 if (CXXMethodDecl *FieldAssignOpMethod =
2078 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
2079 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
2080 }
2081 else if (FieldType->isReferenceType()) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002082 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002083 << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getNameAsCString();
2084 Diag((*Field)->getLocation(), diag::note_declared_at);
2085 Diag(CurrentLocation, diag::note_first_required_here);
2086 err = true;
2087 }
2088 else if (FieldType.isConstQualified()) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002089 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002090 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getNameAsCString();
2091 Diag((*Field)->getLocation(), diag::note_declared_at);
2092 Diag(CurrentLocation, diag::note_first_required_here);
2093 err = true;
2094 }
2095 }
2096 if (!err)
2097 MethodDecl->setUsed();
2098}
2099
2100CXXMethodDecl *
2101Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
2102 CXXRecordDecl *ClassDecl) {
2103 QualType LHSType = Context.getTypeDeclType(ClassDecl);
2104 QualType RHSType(LHSType);
2105 // If class's assignment operator argument is const/volatile qualified,
2106 // look for operator = (const/volatile B&). Otherwise, look for
2107 // operator = (B&).
2108 if (ParmDecl->getType().isConstQualified())
2109 RHSType.addConst();
2110 if (ParmDecl->getType().isVolatileQualified())
2111 RHSType.addVolatile();
2112 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
2113 LHSType,
2114 SourceLocation()));
2115 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
2116 RHSType,
2117 SourceLocation()));
2118 Expr *Args[2] = { &*LHS, &*RHS };
2119 OverloadCandidateSet CandidateSet;
2120 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
2121 CandidateSet);
2122 OverloadCandidateSet::iterator Best;
2123 if (BestViableFunction(CandidateSet,
2124 ClassDecl->getLocation(), Best) == OR_Success)
2125 return cast<CXXMethodDecl>(Best->Function);
2126 assert(false &&
2127 "getAssignOperatorMethod - copy assignment operator method not found");
2128 return 0;
2129}
2130
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002131void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2132 CXXConstructorDecl *CopyConstructor,
2133 unsigned TypeQuals) {
2134 assert((CopyConstructor->isImplicit() &&
2135 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
2136 !CopyConstructor->isUsed()) &&
2137 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
2138
2139 CXXRecordDecl *ClassDecl
2140 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
2141 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002142 // C++ [class.copy] p209
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002143 // Before the implicitly-declared copy constructor for a class is
2144 // implicitly defined, all the implicitly-declared copy constructors
2145 // for its base class and its non-static data members shall have been
2146 // implicitly defined.
2147 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2148 Base != ClassDecl->bases_end(); ++Base) {
2149 CXXRecordDecl *BaseClassDecl
2150 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
2151 if (CXXConstructorDecl *BaseCopyCtor =
2152 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002153 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002154 }
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002155 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2156 FieldEnd = ClassDecl->field_end();
2157 Field != FieldEnd; ++Field) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002158 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2159 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2160 FieldType = Array->getElementType();
2161 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
2162 CXXRecordDecl *FieldClassDecl
2163 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2164 if (CXXConstructorDecl *FieldCopyCtor =
2165 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002166 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002167 }
2168 }
2169 CopyConstructor->setUsed();
2170}
2171
Anders Carlsson05e59652009-04-16 23:50:50 +00002172void Sema::InitializeVarWithConstructor(VarDecl *VD,
2173 CXXConstructorDecl *Constructor,
2174 QualType DeclInitType,
2175 Expr **Exprs, unsigned NumExprs) {
Anders Carlsson7b7b2552009-05-30 20:56:46 +00002176 Expr *Temp = CXXConstructExpr::Create(Context, DeclInitType, Constructor,
Anders Carlsson6a95cd12009-04-24 05:16:06 +00002177 false, Exprs, NumExprs);
Douglas Gregorcad27f62009-06-22 23:06:13 +00002178 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Douglas Gregor4833ff02009-05-26 18:54:04 +00002179 VD->setInit(Context, Temp);
Anders Carlsson05e59652009-04-16 23:50:50 +00002180}
2181
Fariborz Jahanian4e75d392009-06-27 15:05:11 +00002182void Sema::MarkDestructorReferenced(SourceLocation Loc, QualType DeclInitType)
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002183{
2184 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
2185 DeclInitType->getAsRecordType()->getDecl());
2186 if (!ClassDecl->hasTrivialDestructor())
2187 if (CXXDestructorDecl *Destructor =
2188 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
2189 MarkDeclarationReferenced(Loc, Destructor);
2190}
2191
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002192/// AddCXXDirectInitializerToDecl - This action is called immediately after
2193/// ActOnDeclarator, when a C++ direct initializer is present.
2194/// e.g: "int x(1);"
Chris Lattner5261d0c2009-03-28 19:18:32 +00002195void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
2196 SourceLocation LParenLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002197 MultiExprArg Exprs,
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002198 SourceLocation *CommaLocs,
2199 SourceLocation RParenLoc) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002200 unsigned NumExprs = Exprs.size();
2201 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner5261d0c2009-03-28 19:18:32 +00002202 Decl *RealDecl = Dcl.getAs<Decl>();
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002203
2204 // If there is no declaration, there was an error parsing it. Just ignore
2205 // the initializer.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002206 if (RealDecl == 0)
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002207 return;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002208
2209 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2210 if (!VDecl) {
2211 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
2212 RealDecl->setInvalidDecl();
2213 return;
2214 }
2215
Douglas Gregorad7d1812009-03-24 16:43:20 +00002216 // FIXME: Need to handle dependent types and expressions here.
2217
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00002218 // We will treat direct-initialization as a copy-initialization:
2219 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002220 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
2221 //
2222 // Clients that want to distinguish between the two forms, can check for
2223 // direct initializer using VarDecl::hasCXXDirectInitializer().
2224 // A major benefit is that clients that don't particularly care about which
2225 // exactly form was it (like the CodeGen) can handle both cases without
2226 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002227
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002228 // C++ 8.5p11:
2229 // The form of initialization (using parentheses or '=') is generally
2230 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002231 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +00002232 QualType DeclInitType = VDecl->getType();
2233 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
2234 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002235
Douglas Gregorad7d1812009-03-24 16:43:20 +00002236 // FIXME: This isn't the right place to complete the type.
2237 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
2238 diag::err_typecheck_decl_incomplete_type)) {
2239 VDecl->setInvalidDecl();
2240 return;
2241 }
2242
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002243 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +00002244 CXXConstructorDecl *Constructor
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002245 = PerformInitializationByConstructor(DeclInitType,
2246 (Expr **)Exprs.get(), NumExprs,
Douglas Gregor6428e762008-11-05 15:29:30 +00002247 VDecl->getLocation(),
2248 SourceRange(VDecl->getLocation(),
2249 RParenLoc),
Chris Lattner271d4c22008-11-24 05:29:24 +00002250 VDecl->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00002251 IK_Direct);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002252 if (!Constructor)
Douglas Gregor5870a952008-11-03 20:45:27 +00002253 RealDecl->setInvalidDecl();
Anders Carlsson9c7b4922009-04-15 21:48:18 +00002254 else {
Anders Carlsson9c7b4922009-04-15 21:48:18 +00002255 VDecl->setCXXDirectInitializer(true);
Anders Carlsson05e59652009-04-16 23:50:50 +00002256 InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
2257 (Expr**)Exprs.release(), NumExprs);
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002258 // FIXME. Must do all that is needed to destroy the object
2259 // on scope exit. For now, just mark the destructor as used.
Fariborz Jahanian4e75d392009-06-27 15:05:11 +00002260 MarkDestructorReferenced(VDecl->getLocation(), DeclInitType);
Anders Carlsson9c7b4922009-04-15 21:48:18 +00002261 }
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002262 return;
2263 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002264
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00002265 if (NumExprs > 1) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00002266 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
2267 << SourceRange(VDecl->getLocation(), RParenLoc);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002268 RealDecl->setInvalidDecl();
2269 return;
2270 }
2271
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002272 // Let clients know that initialization was done with a direct initializer.
2273 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00002274
2275 assert(NumExprs == 1 && "Expected 1 expression");
2276 // Set the init expression, handles conversions.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002277 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
2278 /*DirectInit=*/true);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002279}
Douglas Gregor81c29152008-10-29 00:13:59 +00002280
Douglas Gregor6428e762008-11-05 15:29:30 +00002281/// PerformInitializationByConstructor - Perform initialization by
2282/// constructor (C++ [dcl.init]p14), which may occur as part of
2283/// direct-initialization or copy-initialization. We are initializing
2284/// an object of type @p ClassType with the given arguments @p
2285/// Args. @p Loc is the location in the source code where the
2286/// initializer occurs (e.g., a declaration, member initializer,
2287/// functional cast, etc.) while @p Range covers the whole
2288/// initialization. @p InitEntity is the entity being initialized,
2289/// which may by the name of a declaration or a type. @p Kind is the
2290/// kind of initialization we're performing, which affects whether
2291/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00002292/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00002293/// when the initialization fails, emits a diagnostic and returns
2294/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00002295CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00002296Sema::PerformInitializationByConstructor(QualType ClassType,
2297 Expr **Args, unsigned NumArgs,
2298 SourceLocation Loc, SourceRange Range,
Chris Lattner271d4c22008-11-24 05:29:24 +00002299 DeclarationName InitEntity,
Douglas Gregor6428e762008-11-05 15:29:30 +00002300 InitializationKind Kind) {
Douglas Gregor5870a952008-11-03 20:45:27 +00002301 const RecordType *ClassRec = ClassType->getAsRecordType();
2302 assert(ClassRec && "Can only initialize a class type here");
2303
2304 // C++ [dcl.init]p14:
2305 //
2306 // If the initialization is direct-initialization, or if it is
2307 // copy-initialization where the cv-unqualified version of the
2308 // source type is the same class as, or a derived class of, the
2309 // class of the destination, constructors are considered. The
2310 // applicable constructors are enumerated (13.3.1.3), and the
2311 // best one is chosen through overload resolution (13.3). The
2312 // constructor so selected is called to initialize the object,
2313 // with the initializer expression(s) as its argument(s). If no
2314 // constructor applies, or the overload resolution is ambiguous,
2315 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00002316 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
2317 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00002318
2319 // Add constructors to the overload set.
Douglas Gregorb9213832008-12-15 21:24:18 +00002320 DeclarationName ConstructorName
2321 = Context.DeclarationNames.getCXXConstructorName(
2322 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002323 DeclContext::lookup_const_iterator Con, ConEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002324 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002325 Con != ConEnd; ++Con) {
2326 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor6428e762008-11-05 15:29:30 +00002327 if ((Kind == IK_Direct) ||
2328 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
2329 (Kind == IK_Default && Constructor->isDefaultConstructor()))
2330 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2331 }
2332
Douglas Gregorb9213832008-12-15 21:24:18 +00002333 // FIXME: When we decide not to synthesize the implicitly-declared
2334 // constructors, we'll need to make them appear here.
2335
Douglas Gregor5870a952008-11-03 20:45:27 +00002336 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00002337 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor5870a952008-11-03 20:45:27 +00002338 case OR_Success:
2339 // We found a constructor. Return it.
2340 return cast<CXXConstructorDecl>(Best->Function);
2341
2342 case OR_No_Viable_Function:
Douglas Gregor538a4c22009-02-02 17:43:21 +00002343 if (InitEntity)
2344 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00002345 << InitEntity << Range;
Douglas Gregor538a4c22009-02-02 17:43:21 +00002346 else
2347 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00002348 << ClassType << Range;
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00002349 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor5870a952008-11-03 20:45:27 +00002350 return 0;
2351
2352 case OR_Ambiguous:
Douglas Gregor538a4c22009-02-02 17:43:21 +00002353 if (InitEntity)
2354 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
2355 else
2356 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor5870a952008-11-03 20:45:27 +00002357 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2358 return 0;
Douglas Gregoraa57e862009-02-18 21:56:37 +00002359
2360 case OR_Deleted:
2361 if (InitEntity)
2362 Diag(Loc, diag::err_ovl_deleted_init)
2363 << Best->Function->isDeleted()
2364 << InitEntity << Range;
2365 else
2366 Diag(Loc, diag::err_ovl_deleted_init)
2367 << Best->Function->isDeleted()
2368 << InitEntity << Range;
2369 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2370 return 0;
Douglas Gregor5870a952008-11-03 20:45:27 +00002371 }
2372
2373 return 0;
2374}
2375
Douglas Gregor81c29152008-10-29 00:13:59 +00002376/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2377/// determine whether they are reference-related,
2378/// reference-compatible, reference-compatible with added
2379/// qualification, or incompatible, for use in C++ initialization by
2380/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2381/// type, and the first type (T1) is the pointee type of the reference
2382/// type being initialized.
2383Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002384Sema::CompareReferenceRelationship(QualType T1, QualType T2,
2385 bool& DerivedToBase) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00002386 assert(!T1->isReferenceType() &&
2387 "T1 must be the pointee type of the reference type");
Douglas Gregor81c29152008-10-29 00:13:59 +00002388 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
2389
2390 T1 = Context.getCanonicalType(T1);
2391 T2 = Context.getCanonicalType(T2);
2392 QualType UnqualT1 = T1.getUnqualifiedType();
2393 QualType UnqualT2 = T2.getUnqualifiedType();
2394
2395 // C++ [dcl.init.ref]p4:
2396 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
2397 // reference-related to “cv2 T2” if T1 is the same type as T2, or
2398 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002399 if (UnqualT1 == UnqualT2)
2400 DerivedToBase = false;
2401 else if (IsDerivedFrom(UnqualT2, UnqualT1))
2402 DerivedToBase = true;
2403 else
Douglas Gregor81c29152008-10-29 00:13:59 +00002404 return Ref_Incompatible;
2405
2406 // At this point, we know that T1 and T2 are reference-related (at
2407 // least).
2408
2409 // C++ [dcl.init.ref]p4:
2410 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
2411 // reference-related to T2 and cv1 is the same cv-qualification
2412 // as, or greater cv-qualification than, cv2. For purposes of
2413 // overload resolution, cases for which cv1 is greater
2414 // cv-qualification than cv2 are identified as
2415 // reference-compatible with added qualification (see 13.3.3.2).
2416 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2417 return Ref_Compatible;
2418 else if (T1.isMoreQualifiedThan(T2))
2419 return Ref_Compatible_With_Added_Qualification;
2420 else
2421 return Ref_Related;
2422}
2423
2424/// CheckReferenceInit - Check the initialization of a reference
2425/// variable with the given initializer (C++ [dcl.init.ref]). Init is
2426/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00002427/// list), and DeclType is the type of the declaration. When ICS is
2428/// non-null, this routine will compute the implicit conversion
2429/// sequence according to C++ [over.ics.ref] and will not produce any
2430/// diagnostics; when ICS is null, it will emit diagnostics when any
2431/// errors are found. Either way, a return value of true indicates
2432/// that there was a failure, a return value of false indicates that
2433/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002434///
2435/// When @p SuppressUserConversions, user-defined conversions are
2436/// suppressed.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002437/// When @p AllowExplicit, we also permit explicit user-defined
2438/// conversion functions.
Sebastian Redla55834a2009-04-12 17:16:29 +00002439/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002440bool
Sebastian Redlbd261962009-04-16 17:51:27 +00002441Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002442 ImplicitConversionSequence *ICS,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002443 bool SuppressUserConversions,
Sebastian Redla55834a2009-04-12 17:16:29 +00002444 bool AllowExplicit, bool ForceRValue) {
Douglas Gregor81c29152008-10-29 00:13:59 +00002445 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2446
2447 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
2448 QualType T2 = Init->getType();
2449
Douglas Gregor45014fd2008-11-10 20:40:00 +00002450 // If the initializer is the address of an overloaded function, try
2451 // to resolve the overloaded function. If all goes well, T2 is the
2452 // type of the resulting function.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002453 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00002454 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
2455 ICS != 0);
2456 if (Fn) {
2457 // Since we're performing this reference-initialization for
2458 // real, update the initializer with the resulting function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00002459 if (!ICS) {
2460 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
2461 return true;
2462
Douglas Gregor45014fd2008-11-10 20:40:00 +00002463 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregoraa57e862009-02-18 21:56:37 +00002464 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00002465
2466 T2 = Fn->getType();
2467 }
2468 }
2469
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002470 // Compute some basic properties of the types and the initializer.
Sebastian Redlce6fff02009-03-16 23:22:08 +00002471 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002472 bool DerivedToBase = false;
Sebastian Redla55834a2009-04-12 17:16:29 +00002473 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2474 Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002475 ReferenceCompareResult RefRelationship
2476 = CompareReferenceRelationship(T1, T2, DerivedToBase);
2477
2478 // Most paths end in a failed conversion.
2479 if (ICS)
2480 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00002481
2482 // C++ [dcl.init.ref]p5:
2483 // A reference to type “cv1 T1” is initialized by an expression
2484 // of type “cv2 T2” as follows:
2485
2486 // -- If the initializer expression
2487
Sebastian Redldfc30332009-03-29 15:27:50 +00002488 // Rvalue references cannot bind to lvalues (N2812).
2489 // There is absolutely no situation where they can. In particular, note that
2490 // this is ill-formed, even if B has a user-defined conversion to A&&:
2491 // B b;
2492 // A&& r = b;
2493 if (isRValRef && InitLvalue == Expr::LV_Valid) {
2494 if (!ICS)
2495 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
2496 << Init->getSourceRange();
2497 return true;
2498 }
2499
Douglas Gregor81c29152008-10-29 00:13:59 +00002500 bool BindsDirectly = false;
2501 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
2502 // reference-compatible with “cv2 T2,” or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002503 //
2504 // Note that the bit-field check is skipped if we are just computing
2505 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor531434b2009-05-02 02:18:30 +00002506 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002507 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00002508 BindsDirectly = true;
2509
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002510 if (ICS) {
2511 // C++ [over.ics.ref]p1:
2512 // When a parameter of reference type binds directly (8.5.3)
2513 // to an argument expression, the implicit conversion sequence
2514 // is the identity conversion, unless the argument expression
2515 // has a type that is a derived class of the parameter type,
2516 // in which case the implicit conversion sequence is a
2517 // derived-to-base Conversion (13.3.3.1).
2518 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2519 ICS->Standard.First = ICK_Identity;
2520 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2521 ICS->Standard.Third = ICK_Identity;
2522 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2523 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00002524 ICS->Standard.ReferenceBinding = true;
2525 ICS->Standard.DirectBinding = true;
Sebastian Redldfc30332009-03-29 15:27:50 +00002526 ICS->Standard.RRefBinding = false;
Sebastian Redld3169132009-04-17 16:30:52 +00002527 ICS->Standard.CopyConstructor = 0;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002528
2529 // Nothing more to do: the inaccessibility/ambiguity check for
2530 // derived-to-base conversions is suppressed when we're
2531 // computing the implicit conversion sequence (C++
2532 // [over.best.ics]p2).
2533 return false;
2534 } else {
2535 // Perform the conversion.
Mike Stumpe127ae32009-05-16 07:39:55 +00002536 // FIXME: Binding to a subobject of the lvalue is going to require more
2537 // AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00002538 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00002539 }
2540 }
2541
2542 // -- has a class type (i.e., T2 is a class type) and can be
2543 // implicitly converted to an lvalue of type “cv3 T3,”
2544 // where “cv1 T1” is reference-compatible with “cv3 T3”
2545 // 92) (this conversion is selected by enumerating the
2546 // applicable conversion functions (13.3.1.6) and choosing
2547 // the best one through overload resolution (13.3)),
Sebastian Redlce6fff02009-03-16 23:22:08 +00002548 if (!isRValRef && !SuppressUserConversions && T2->isRecordType()) {
Douglas Gregore6985fe2008-11-10 16:14:15 +00002549 // FIXME: Look for conversions in base classes!
2550 CXXRecordDecl *T2RecordDecl
2551 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor81c29152008-10-29 00:13:59 +00002552
Douglas Gregore6985fe2008-11-10 16:14:15 +00002553 OverloadCandidateSet CandidateSet;
2554 OverloadedFunctionDecl *Conversions
2555 = T2RecordDecl->getConversionFunctions();
2556 for (OverloadedFunctionDecl::function_iterator Func
2557 = Conversions->function_begin();
2558 Func != Conversions->function_end(); ++Func) {
2559 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Sebastian Redl16ac38f2009-03-22 21:28:55 +00002560
Douglas Gregore6985fe2008-11-10 16:14:15 +00002561 // If the conversion function doesn't return a reference type,
2562 // it can't be considered for this conversion.
Sebastian Redlce6fff02009-03-16 23:22:08 +00002563 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002564 (AllowExplicit || !Conv->isExplicit()))
Douglas Gregore6985fe2008-11-10 16:14:15 +00002565 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
2566 }
2567
2568 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00002569 switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) {
Douglas Gregore6985fe2008-11-10 16:14:15 +00002570 case OR_Success:
2571 // This is a direct binding.
2572 BindsDirectly = true;
2573
2574 if (ICS) {
2575 // C++ [over.ics.ref]p1:
2576 //
2577 // [...] If the parameter binds directly to the result of
2578 // applying a conversion function to the argument
2579 // expression, the implicit conversion sequence is a
2580 // user-defined conversion sequence (13.3.3.1.2), with the
2581 // second standard conversion sequence either an identity
2582 // conversion or, if the conversion function returns an
2583 // entity of a type that is a derived class of the parameter
2584 // type, a derived-to-base Conversion.
2585 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
2586 ICS->UserDefined.Before = Best->Conversions[0].Standard;
2587 ICS->UserDefined.After = Best->FinalConversion;
2588 ICS->UserDefined.ConversionFunction = Best->Function;
2589 assert(ICS->UserDefined.After.ReferenceBinding &&
2590 ICS->UserDefined.After.DirectBinding &&
2591 "Expected a direct reference binding!");
2592 return false;
2593 } else {
2594 // Perform the conversion.
Mike Stumpe127ae32009-05-16 07:39:55 +00002595 // FIXME: Binding to a subobject of the lvalue is going to require more
2596 // AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00002597 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregore6985fe2008-11-10 16:14:15 +00002598 }
2599 break;
2600
2601 case OR_Ambiguous:
2602 assert(false && "Ambiguous reference binding conversions not implemented.");
2603 return true;
2604
2605 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00002606 case OR_Deleted:
2607 // There was no suitable conversion, or we found a deleted
2608 // conversion; continue with other checks.
Douglas Gregore6985fe2008-11-10 16:14:15 +00002609 break;
2610 }
2611 }
2612
Douglas Gregor81c29152008-10-29 00:13:59 +00002613 if (BindsDirectly) {
2614 // C++ [dcl.init.ref]p4:
2615 // [...] In all cases where the reference-related or
2616 // reference-compatible relationship of two types is used to
2617 // establish the validity of a reference binding, and T1 is a
2618 // base class of T2, a program that necessitates such a binding
2619 // is ill-formed if T1 is an inaccessible (clause 11) or
2620 // ambiguous (10.2) base class of T2.
2621 //
2622 // Note that we only check this condition when we're allowed to
2623 // complain about errors, because we should not be checking for
2624 // ambiguity (or inaccessibility) unless the reference binding
2625 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002626 if (DerivedToBase)
2627 return CheckDerivedToBaseConversion(T2, T1,
2628 Init->getSourceRange().getBegin(),
2629 Init->getSourceRange());
2630 else
2631 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00002632 }
2633
2634 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redldfc30332009-03-29 15:27:50 +00002635 // type (i.e., cv1 shall be const), or the reference shall be an
2636 // rvalue reference and the initializer expression shall be an rvalue.
Sebastian Redlce6fff02009-03-16 23:22:08 +00002637 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002638 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00002639 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00002640 diag::err_not_reference_to_const_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002641 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2642 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00002643 return true;
2644 }
2645
2646 // -- If the initializer expression is an rvalue, with T2 a
2647 // class type, and “cv1 T1” is reference-compatible with
2648 // “cv2 T2,” the reference is bound in one of the
2649 // following ways (the choice is implementation-defined):
2650 //
2651 // -- The reference is bound to the object represented by
2652 // the rvalue (see 3.10) or to a sub-object within that
2653 // object.
2654 //
2655 // -- A temporary of type “cv1 T2” [sic] is created, and
2656 // a constructor is called to copy the entire rvalue
2657 // object into the temporary. The reference is bound to
2658 // the temporary or to a sub-object within the
2659 // temporary.
2660 //
Douglas Gregor81c29152008-10-29 00:13:59 +00002661 // The constructor that would be used to make the copy
2662 // shall be callable whether or not the copy is actually
2663 // done.
2664 //
Sebastian Redldfc30332009-03-29 15:27:50 +00002665 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor81c29152008-10-29 00:13:59 +00002666 // freedom, so we will always take the first option and never build
2667 // a temporary in this case. FIXME: We will, however, have to check
2668 // for the presence of a copy constructor in C++98/03 mode.
2669 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002670 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
2671 if (ICS) {
2672 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2673 ICS->Standard.First = ICK_Identity;
2674 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2675 ICS->Standard.Third = ICK_Identity;
2676 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2677 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00002678 ICS->Standard.ReferenceBinding = true;
Sebastian Redldfc30332009-03-29 15:27:50 +00002679 ICS->Standard.DirectBinding = false;
2680 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redld3169132009-04-17 16:30:52 +00002681 ICS->Standard.CopyConstructor = 0;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002682 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +00002683 // FIXME: Binding to a subobject of the rvalue is going to require more
2684 // AST annotation than this.
Anders Carlsson30c35bf2009-05-19 00:38:24 +00002685 ImpCastExprToType(Init, T1, /*isLvalue=*/false);
Douglas Gregor81c29152008-10-29 00:13:59 +00002686 }
2687 return false;
2688 }
2689
2690 // -- Otherwise, a temporary of type “cv1 T1” is created and
2691 // initialized from the initializer expression using the
2692 // rules for a non-reference copy initialization (8.5). The
2693 // reference is then bound to the temporary. If T1 is
2694 // reference-related to T2, cv1 must be the same
2695 // cv-qualification as, or greater cv-qualification than,
2696 // cv2; otherwise, the program is ill-formed.
2697 if (RefRelationship == Ref_Related) {
2698 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2699 // we would be reference-compatible or reference-compatible with
2700 // added qualification. But that wasn't the case, so the reference
2701 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002702 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00002703 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00002704 diag::err_reference_init_drops_quals)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002705 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2706 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00002707 return true;
2708 }
2709
Douglas Gregorb206cc42009-01-30 23:27:23 +00002710 // If at least one of the types is a class type, the types are not
2711 // related, and we aren't allowed any user conversions, the
2712 // reference binding fails. This case is important for breaking
2713 // recursion, since TryImplicitConversion below will attempt to
2714 // create a temporary through the use of a copy constructor.
2715 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
2716 (T1->isRecordType() || T2->isRecordType())) {
2717 if (!ICS)
2718 Diag(Init->getSourceRange().getBegin(),
2719 diag::err_typecheck_convert_incompatible)
2720 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
2721 return true;
2722 }
2723
Douglas Gregor81c29152008-10-29 00:13:59 +00002724 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002725 if (ICS) {
Sebastian Redldfc30332009-03-29 15:27:50 +00002726 // C++ [over.ics.ref]p2:
2727 //
2728 // When a parameter of reference type is not bound directly to
2729 // an argument expression, the conversion sequence is the one
2730 // required to convert the argument expression to the
2731 // underlying type of the reference according to
2732 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2733 // to copy-initializing a temporary of the underlying type with
2734 // the argument expression. Any difference in top-level
2735 // cv-qualification is subsumed by the initialization itself
2736 // and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002737 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Sebastian Redldfc30332009-03-29 15:27:50 +00002738 // Of course, that's still a reference binding.
2739 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
2740 ICS->Standard.ReferenceBinding = true;
2741 ICS->Standard.RRefBinding = isRValRef;
2742 } else if(ICS->ConversionKind ==
2743 ImplicitConversionSequence::UserDefinedConversion) {
2744 ICS->UserDefined.After.ReferenceBinding = true;
2745 ICS->UserDefined.After.RRefBinding = isRValRef;
2746 }
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002747 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
2748 } else {
Douglas Gregor6fd35572008-12-19 17:40:08 +00002749 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002750 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002751}
Douglas Gregore60e5d32008-11-06 22:13:31 +00002752
2753/// CheckOverloadedOperatorDeclaration - Check whether the declaration
2754/// of this overloaded operator is well-formed. If so, returns false;
2755/// otherwise, emits appropriate diagnostics and returns true.
2756bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002757 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregore60e5d32008-11-06 22:13:31 +00002758 "Expected an overloaded operator declaration");
2759
Douglas Gregore60e5d32008-11-06 22:13:31 +00002760 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
2761
2762 // C++ [over.oper]p5:
2763 // The allocation and deallocation functions, operator new,
2764 // operator new[], operator delete and operator delete[], are
2765 // described completely in 3.7.3. The attributes and restrictions
2766 // found in the rest of this subclause do not apply to them unless
2767 // explicitly stated in 3.7.3.
Mike Stumpe127ae32009-05-16 07:39:55 +00002768 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregore60e5d32008-11-06 22:13:31 +00002769 if (Op == OO_New || Op == OO_Array_New ||
2770 Op == OO_Delete || Op == OO_Array_Delete)
2771 return false;
2772
2773 // C++ [over.oper]p6:
2774 // An operator function shall either be a non-static member
2775 // function or be a non-member function and have at least one
2776 // parameter whose type is a class, a reference to a class, an
2777 // enumeration, or a reference to an enumeration.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002778 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
2779 if (MethodDecl->isStatic())
2780 return Diag(FnDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00002781 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002782 } else {
2783 bool ClassOrEnumParam = false;
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002784 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2785 ParamEnd = FnDecl->param_end();
2786 Param != ParamEnd; ++Param) {
2787 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedmana73d6b12009-06-27 05:59:59 +00002788 if (ParamType->isDependentType() || ParamType->isRecordType() ||
2789 ParamType->isEnumeralType()) {
Douglas Gregore60e5d32008-11-06 22:13:31 +00002790 ClassOrEnumParam = true;
2791 break;
2792 }
2793 }
2794
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002795 if (!ClassOrEnumParam)
2796 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002797 diag::err_operator_overload_needs_class_or_enum)
Chris Lattner271d4c22008-11-24 05:29:24 +00002798 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002799 }
2800
2801 // C++ [over.oper]p8:
2802 // An operator function cannot have default arguments (8.3.6),
2803 // except where explicitly stated below.
2804 //
2805 // Only the function-call operator allows default arguments
2806 // (C++ [over.call]p1).
2807 if (Op != OO_Call) {
2808 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2809 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002810 if ((*Param)->hasUnparsedDefaultArg())
2811 return Diag((*Param)->getLocation(),
2812 diag::err_operator_overload_default_arg)
2813 << FnDecl->getDeclName();
2814 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002815 return Diag((*Param)->getLocation(),
Chris Lattner77d52da2008-11-20 06:06:08 +00002816 diag::err_operator_overload_default_arg)
Chris Lattner271d4c22008-11-24 05:29:24 +00002817 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002818 }
2819 }
2820
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002821 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2822 { false, false, false }
2823#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2824 , { Unary, Binary, MemberOnly }
2825#include "clang/Basic/OperatorKinds.def"
2826 };
Douglas Gregore60e5d32008-11-06 22:13:31 +00002827
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002828 bool CanBeUnaryOperator = OperatorUses[Op][0];
2829 bool CanBeBinaryOperator = OperatorUses[Op][1];
2830 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregore60e5d32008-11-06 22:13:31 +00002831
2832 // C++ [over.oper]p8:
2833 // [...] Operator functions cannot have more or fewer parameters
2834 // than the number required for the corresponding operator, as
2835 // described in the rest of this subclause.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002836 unsigned NumParams = FnDecl->getNumParams()
2837 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregore60e5d32008-11-06 22:13:31 +00002838 if (Op != OO_Call &&
2839 ((NumParams == 1 && !CanBeUnaryOperator) ||
2840 (NumParams == 2 && !CanBeBinaryOperator) ||
2841 (NumParams < 1) || (NumParams > 2))) {
2842 // We have the wrong number of parameters.
Chris Lattnerbb002332008-11-21 07:57:12 +00002843 unsigned ErrorKind;
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002844 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00002845 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002846 } else if (CanBeUnaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00002847 ErrorKind = 0; // 0 -> unary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002848 } else {
Chris Lattnera7021ee2008-11-21 07:50:02 +00002849 assert(CanBeBinaryOperator &&
2850 "All non-call overloaded operators are unary or binary!");
Chris Lattnerbb002332008-11-21 07:57:12 +00002851 ErrorKind = 1; // 1 -> binary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002852 }
Douglas Gregore60e5d32008-11-06 22:13:31 +00002853
Chris Lattnerbb002332008-11-21 07:57:12 +00002854 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattner271d4c22008-11-24 05:29:24 +00002855 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregore60e5d32008-11-06 22:13:31 +00002856 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00002857
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002858 // Overloaded operators other than operator() cannot be variadic.
2859 if (Op != OO_Call &&
Douglas Gregor4fa58902009-02-26 23:50:07 +00002860 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002861 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattner271d4c22008-11-24 05:29:24 +00002862 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002863 }
2864
2865 // Some operators must be non-static member functions.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002866 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2867 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002868 diag::err_operator_overload_must_be_member)
Chris Lattner271d4c22008-11-24 05:29:24 +00002869 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002870 }
2871
2872 // C++ [over.inc]p1:
2873 // The user-defined function called operator++ implements the
2874 // prefix and postfix ++ operator. If this function is a member
2875 // function with no parameters, or a non-member function with one
2876 // parameter of class or enumeration type, it defines the prefix
2877 // increment operator ++ for objects of that type. If the function
2878 // is a member function with one parameter (which shall be of type
2879 // int) or a non-member function with two parameters (the second
2880 // of which shall be of type int), it defines the postfix
2881 // increment operator ++ for objects of that type.
2882 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2883 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2884 bool ParamIsInt = false;
2885 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2886 ParamIsInt = BT->getKind() == BuiltinType::Int;
2887
Chris Lattnera7021ee2008-11-21 07:50:02 +00002888 if (!ParamIsInt)
2889 return Diag(LastParam->getLocation(),
2890 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002891 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregore60e5d32008-11-06 22:13:31 +00002892 }
2893
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00002894 // Notify the class if it got an assignment operator.
2895 if (Op == OO_Equal) {
2896 // Would have returned earlier otherwise.
2897 assert(isa<CXXMethodDecl>(FnDecl) &&
2898 "Overloaded = not member, but not filtered.");
2899 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2900 Method->getParent()->addedAssignmentOperator(Context, Method);
2901 }
2902
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002903 return false;
Douglas Gregore60e5d32008-11-06 22:13:31 +00002904}
Chris Lattnerf58d52b2008-12-17 07:09:26 +00002905
Douglas Gregord8028382009-01-05 19:45:36 +00002906/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2907/// linkage specification, including the language and (if present)
2908/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2909/// the location of the language string literal, which is provided
2910/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2911/// the '{' brace. Otherwise, this linkage specification does not
2912/// have any braces.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002913Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
2914 SourceLocation ExternLoc,
2915 SourceLocation LangLoc,
2916 const char *Lang,
2917 unsigned StrSize,
2918 SourceLocation LBraceLoc) {
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002919 LinkageSpecDecl::LanguageIDs Language;
2920 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2921 Language = LinkageSpecDecl::lang_c;
2922 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2923 Language = LinkageSpecDecl::lang_cxx;
2924 else {
Douglas Gregord8028382009-01-05 19:45:36 +00002925 Diag(LangLoc, diag::err_bad_language);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002926 return DeclPtrTy();
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002927 }
2928
2929 // FIXME: Add all the various semantics of linkage specifications
2930
Douglas Gregord8028382009-01-05 19:45:36 +00002931 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2932 LangLoc, Language,
2933 LBraceLoc.isValid());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002934 CurContext->addDecl(D);
Douglas Gregord8028382009-01-05 19:45:36 +00002935 PushDeclContext(S, D);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002936 return DeclPtrTy::make(D);
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002937}
2938
Douglas Gregord8028382009-01-05 19:45:36 +00002939/// ActOnFinishLinkageSpecification - Completely the definition of
2940/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2941/// valid, it's the position of the closing '}' brace in a linkage
2942/// specification that uses braces.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002943Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
2944 DeclPtrTy LinkageSpec,
2945 SourceLocation RBraceLoc) {
Douglas Gregord8028382009-01-05 19:45:36 +00002946 if (LinkageSpec)
2947 PopDeclContext();
2948 return LinkageSpec;
Chris Lattnerf58d52b2008-12-17 07:09:26 +00002949}
2950
Douglas Gregor57420b42009-05-18 20:51:54 +00002951/// \brief Perform semantic analysis for the variable declaration that
2952/// occurs within a C++ catch clause, returning the newly-created
2953/// variable.
2954VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
2955 IdentifierInfo *Name,
2956 SourceLocation Loc,
2957 SourceRange Range) {
2958 bool Invalid = false;
Sebastian Redl743c8162008-12-22 19:15:10 +00002959
2960 // Arrays and functions decay.
2961 if (ExDeclType->isArrayType())
2962 ExDeclType = Context.getArrayDecayedType(ExDeclType);
2963 else if (ExDeclType->isFunctionType())
2964 ExDeclType = Context.getPointerType(ExDeclType);
2965
2966 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2967 // The exception-declaration shall not denote a pointer or reference to an
2968 // incomplete type, other than [cv] void*.
Sebastian Redl8a8b3512009-03-22 23:49:27 +00002969 // N2844 forbids rvalue references.
Douglas Gregor3b7e9112009-05-18 21:08:14 +00002970 if(!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor57420b42009-05-18 20:51:54 +00002971 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00002972 Invalid = true;
2973 }
Douglas Gregor57420b42009-05-18 20:51:54 +00002974
Sebastian Redl743c8162008-12-22 19:15:10 +00002975 QualType BaseType = ExDeclType;
2976 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002977 unsigned DK = diag::err_catch_incomplete;
Sebastian Redl743c8162008-12-22 19:15:10 +00002978 if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2979 BaseType = Ptr->getPointeeType();
2980 Mode = 1;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002981 DK = diag::err_catch_incomplete_ptr;
Sebastian Redl743c8162008-12-22 19:15:10 +00002982 } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00002983 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl743c8162008-12-22 19:15:10 +00002984 BaseType = Ref->getPointeeType();
2985 Mode = 2;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002986 DK = diag::err_catch_incomplete_ref;
Sebastian Redl743c8162008-12-22 19:15:10 +00002987 }
Sebastian Redl8a8b3512009-03-22 23:49:27 +00002988 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor57420b42009-05-18 20:51:54 +00002989 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl743c8162008-12-22 19:15:10 +00002990 Invalid = true;
Sebastian Redl743c8162008-12-22 19:15:10 +00002991
Douglas Gregor57420b42009-05-18 20:51:54 +00002992 if (!Invalid && !ExDeclType->isDependentType() &&
2993 RequireNonAbstractType(Loc, ExDeclType,
2994 diag::err_abstract_type_in_decl,
2995 AbstractVariableType))
Sebastian Redl54198652009-04-27 21:03:30 +00002996 Invalid = true;
2997
Douglas Gregor57420b42009-05-18 20:51:54 +00002998 // FIXME: Need to test for ability to copy-construct and destroy the
2999 // exception variable.
3000
Sebastian Redl237116b2008-12-22 21:35:02 +00003001 // FIXME: Need to check for abstract classes.
3002
Douglas Gregor57420b42009-05-18 20:51:54 +00003003 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
3004 Name, ExDeclType, VarDecl::None,
3005 Range.getBegin());
3006
3007 if (Invalid)
3008 ExDecl->setInvalidDecl();
3009
3010 return ExDecl;
3011}
3012
3013/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
3014/// handler.
3015Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
3016 QualType ExDeclType = GetTypeForDeclarator(D, S);
3017
3018 bool Invalid = D.isInvalidType();
Sebastian Redl743c8162008-12-22 19:15:10 +00003019 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor09be81b2009-02-04 17:27:36 +00003020 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl743c8162008-12-22 19:15:10 +00003021 // The scope should be freshly made just for us. There is just no way
3022 // it contains any previous declaration.
Chris Lattner5261d0c2009-03-28 19:18:32 +00003023 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl743c8162008-12-22 19:15:10 +00003024 if (PrevDecl->isTemplateParameter()) {
3025 // Maybe we will complain about the shadowed template parameter.
3026 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl743c8162008-12-22 19:15:10 +00003027 }
3028 }
3029
Chris Lattner34c61332009-04-25 08:06:05 +00003030 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl743c8162008-12-22 19:15:10 +00003031 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
3032 << D.getCXXScopeSpec().getRange();
Chris Lattner34c61332009-04-25 08:06:05 +00003033 Invalid = true;
Sebastian Redl743c8162008-12-22 19:15:10 +00003034 }
3035
Douglas Gregor57420b42009-05-18 20:51:54 +00003036 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType,
3037 D.getIdentifier(),
3038 D.getIdentifierLoc(),
3039 D.getDeclSpec().getSourceRange());
3040
Chris Lattner34c61332009-04-25 08:06:05 +00003041 if (Invalid)
3042 ExDecl->setInvalidDecl();
3043
Sebastian Redl743c8162008-12-22 19:15:10 +00003044 // Add the exception declaration into this scope.
Sebastian Redl743c8162008-12-22 19:15:10 +00003045 if (II)
Douglas Gregor57420b42009-05-18 20:51:54 +00003046 PushOnScopeChains(ExDecl, S);
3047 else
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003048 CurContext->addDecl(ExDecl);
Sebastian Redl743c8162008-12-22 19:15:10 +00003049
Douglas Gregor2a2e0402009-06-17 21:51:59 +00003050 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner5261d0c2009-03-28 19:18:32 +00003051 return DeclPtrTy::make(ExDecl);
Sebastian Redl743c8162008-12-22 19:15:10 +00003052}
Anders Carlssoned691562009-03-14 00:25:26 +00003053
Chris Lattner5261d0c2009-03-28 19:18:32 +00003054Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
3055 ExprArg assertexpr,
3056 ExprArg assertmessageexpr) {
Anders Carlssoned691562009-03-14 00:25:26 +00003057 Expr *AssertExpr = (Expr *)assertexpr.get();
3058 StringLiteral *AssertMessage =
3059 cast<StringLiteral>((Expr *)assertmessageexpr.get());
3060
Anders Carlsson8b842c52009-03-14 00:33:21 +00003061 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
3062 llvm::APSInt Value(32);
3063 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
3064 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
3065 AssertExpr->getSourceRange();
Chris Lattner5261d0c2009-03-28 19:18:32 +00003066 return DeclPtrTy();
Anders Carlsson8b842c52009-03-14 00:33:21 +00003067 }
Anders Carlssoned691562009-03-14 00:25:26 +00003068
Anders Carlsson8b842c52009-03-14 00:33:21 +00003069 if (Value == 0) {
3070 std::string str(AssertMessage->getStrData(),
3071 AssertMessage->getByteLength());
Anders Carlssonc45057a2009-03-15 18:44:04 +00003072 Diag(AssertLoc, diag::err_static_assert_failed)
3073 << str << AssertExpr->getSourceRange();
Anders Carlsson8b842c52009-03-14 00:33:21 +00003074 }
3075 }
3076
Anders Carlsson0f4942b2009-03-15 17:35:16 +00003077 assertexpr.release();
3078 assertmessageexpr.release();
Anders Carlssoned691562009-03-14 00:25:26 +00003079 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
3080 AssertExpr, AssertMessage);
Anders Carlssoned691562009-03-14 00:25:26 +00003081
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003082 CurContext->addDecl(Decl);
Chris Lattner5261d0c2009-03-28 19:18:32 +00003083 return DeclPtrTy::make(Decl);
Anders Carlssoned691562009-03-14 00:25:26 +00003084}
Sebastian Redla8cecf62009-03-24 22:27:57 +00003085
Anders Carlssonb56d8b32009-05-11 22:55:49 +00003086bool Sema::ActOnFriendDecl(Scope *S, SourceLocation FriendLoc, DeclPtrTy Dcl) {
3087 if (!(S->getFlags() & Scope::ClassScope)) {
3088 Diag(FriendLoc, diag::err_friend_decl_outside_class);
3089 return true;
3090 }
3091
3092 return false;
3093}
3094
Chris Lattner5261d0c2009-03-28 19:18:32 +00003095void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
3096 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redla8cecf62009-03-24 22:27:57 +00003097 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
3098 if (!Fn) {
3099 Diag(DelLoc, diag::err_deleted_non_function);
3100 return;
3101 }
3102 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
3103 Diag(DelLoc, diag::err_deleted_decl_not_first);
3104 Diag(Prev->getLocation(), diag::note_previous_declaration);
3105 // If the declaration wasn't the first, we delete the function anyway for
3106 // recovery.
3107 }
3108 Fn->setDeleted();
3109}
Sebastian Redl3b1ef312009-04-27 21:33:24 +00003110
3111static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
3112 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
3113 ++CI) {
3114 Stmt *SubStmt = *CI;
3115 if (!SubStmt)
3116 continue;
3117 if (isa<ReturnStmt>(SubStmt))
3118 Self.Diag(SubStmt->getSourceRange().getBegin(),
3119 diag::err_return_in_constructor_handler);
3120 if (!isa<Expr>(SubStmt))
3121 SearchForReturnInStmt(Self, SubStmt);
3122 }
3123}
3124
3125void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
3126 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
3127 CXXCatchStmt *Handler = TryBlock->getHandler(I);
3128 SearchForReturnInStmt(*this, Handler);
3129 }
3130}
Anders Carlssone80e29c2009-05-14 01:09:04 +00003131
3132bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
3133 const CXXMethodDecl *Old) {
3134 QualType NewTy = New->getType()->getAsFunctionType()->getResultType();
3135 QualType OldTy = Old->getType()->getAsFunctionType()->getResultType();
3136
3137 QualType CNewTy = Context.getCanonicalType(NewTy);
3138 QualType COldTy = Context.getCanonicalType(OldTy);
3139
3140 if (CNewTy == COldTy &&
3141 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
3142 return false;
3143
Anders Carlssonee7177b2009-05-14 19:52:19 +00003144 // Check if the return types are covariant
3145 QualType NewClassTy, OldClassTy;
3146
3147 /// Both types must be pointers or references to classes.
3148 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
3149 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
3150 NewClassTy = NewPT->getPointeeType();
3151 OldClassTy = OldPT->getPointeeType();
3152 }
3153 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
3154 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
3155 NewClassTy = NewRT->getPointeeType();
3156 OldClassTy = OldRT->getPointeeType();
3157 }
3158 }
3159
3160 // The return types aren't either both pointers or references to a class type.
3161 if (NewClassTy.isNull()) {
3162 Diag(New->getLocation(),
3163 diag::err_different_return_type_for_overriding_virtual_function)
3164 << New->getDeclName() << NewTy << OldTy;
3165 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3166
3167 return true;
3168 }
Anders Carlssone80e29c2009-05-14 01:09:04 +00003169
Anders Carlssonee7177b2009-05-14 19:52:19 +00003170 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
3171 // Check if the new class derives from the old class.
3172 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
3173 Diag(New->getLocation(),
3174 diag::err_covariant_return_not_derived)
3175 << New->getDeclName() << NewTy << OldTy;
3176 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3177 return true;
3178 }
3179
3180 // Check if we the conversion from derived to base is valid.
3181 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
3182 diag::err_covariant_return_inaccessible_base,
3183 diag::err_covariant_return_ambiguous_derived_to_base_conv,
3184 // FIXME: Should this point to the return type?
3185 New->getLocation(), SourceRange(), New->getDeclName())) {
3186 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3187 return true;
3188 }
3189 }
3190
3191 // The qualifiers of the return types must be the same.
3192 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
3193 Diag(New->getLocation(),
3194 diag::err_covariant_return_type_different_qualifications)
Anders Carlssone80e29c2009-05-14 01:09:04 +00003195 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonee7177b2009-05-14 19:52:19 +00003196 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3197 return true;
3198 };
3199
3200
3201 // The new class type must have the same or less qualifiers as the old type.
3202 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
3203 Diag(New->getLocation(),
3204 diag::err_covariant_return_type_class_type_more_qualified)
3205 << New->getDeclName() << NewTy << OldTy;
3206 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3207 return true;
3208 };
3209
3210 return false;
Anders Carlssone80e29c2009-05-14 01:09:04 +00003211}
Argiris Kirtzidis68370592009-06-17 22:50:06 +00003212
3213/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
3214/// initializer for the declaration 'Dcl'.
3215/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
3216/// static data member of class X, names should be looked up in the scope of
3217/// class X.
3218void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
3219 Decl *D = Dcl.getAs<Decl>();
3220 // If there is no declaration, there was an error parsing it.
3221 if (D == 0)
3222 return;
3223
3224 // Check whether it is a declaration with a nested name specifier like
3225 // int foo::bar;
3226 if (!D->isOutOfLine())
3227 return;
3228
3229 // C++ [basic.lookup.unqual]p13
3230 //
3231 // A name used in the definition of a static data member of class X
3232 // (after the qualified-id of the static member) is looked up as if the name
3233 // was used in a member function of X.
3234
3235 // Change current context into the context of the initializing declaration.
Argiris Kirtzidisa0b19fe2009-06-17 23:15:40 +00003236 EnterDeclaratorContext(S, D->getDeclContext());
Argiris Kirtzidis68370592009-06-17 22:50:06 +00003237}
3238
3239/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
3240/// initializer for the declaration 'Dcl'.
3241void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
3242 Decl *D = Dcl.getAs<Decl>();
3243 // If there is no declaration, there was an error parsing it.
3244 if (D == 0)
3245 return;
3246
3247 // Check whether it is a declaration with a nested name specifier like
3248 // int foo::bar;
3249 if (!D->isOutOfLine())
3250 return;
3251
3252 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argiris Kirtzidisa0b19fe2009-06-17 23:15:40 +00003253 ExitDeclaratorContext(S);
Argiris Kirtzidis68370592009-06-17 22:50:06 +00003254}