blob: 918fd2ac9a78c312633849a2f220177462ea2747 [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"
Douglas Gregor05904022008-10-22 21:13:31 +000018#include "clang/AST/TypeOrdering.h"
Chris Lattner97316c02008-04-10 02:22:51 +000019#include "clang/AST/StmtVisitor.h"
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +000020#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000021#include "clang/Basic/Diagnostic.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
108Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
109 ExprTy *defarg) {
110 ParmVarDecl *Param = (ParmVarDecl *)param;
111 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
112 QualType ParamType = Param->getType();
113
114 // Default arguments are only permitted in C++
115 if (!getLangOptions().CPlusPlus) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000116 Diag(EqualLoc, diag::err_param_default_argument)
117 << DefaultArg->getSourceRange();
Douglas Gregor605de8d2008-12-16 21:30:33 +0000118 Param->setInvalidDecl();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000119 return;
120 }
121
122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000128 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor58c428c2008-11-04 13:57:51 +0000129 bool DefaultInitFailed = PerformCopyInitialization(DefaultArgPtr, ParamType,
130 "in default argument");
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000131 if (DefaultArgPtr != DefaultArg.get()) {
132 DefaultArg.take();
133 DefaultArg.reset(DefaultArgPtr);
134 }
Douglas Gregor58c428c2008-11-04 13:57:51 +0000135 if (DefaultInitFailed) {
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000136 return;
137 }
138
Chris Lattner97316c02008-04-10 02:22:51 +0000139 // Check that the default argument is well-formed
Chris Lattnerb1856db2008-04-12 23:52:44 +0000140 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Douglas Gregor605de8d2008-12-16 21:30:33 +0000141 if (DefaultArgChecker.Visit(DefaultArg.get())) {
142 Param->setInvalidDecl();
Chris Lattner97316c02008-04-10 02:22:51 +0000143 return;
Douglas Gregor605de8d2008-12-16 21:30:33 +0000144 }
Chris Lattner97316c02008-04-10 02:22:51 +0000145
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000146 // Okay: add the default argument to the parameter
147 Param->setDefaultArg(DefaultArg.take());
148}
149
Douglas Gregor605de8d2008-12-16 21:30:33 +0000150/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
151/// the default argument for the parameter param failed.
152void Sema::ActOnParamDefaultArgumentError(DeclTy *param) {
153 ((ParmVarDecl*)param)->setInvalidDecl();
154}
155
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000156/// CheckExtraCXXDefaultArguments - Check for any extra default
157/// arguments in the declarator, which is not a function declaration
158/// or definition and therefore is not permitted to have default
159/// arguments. This routine should be invoked for every declarator
160/// that is not a function declaration or definition.
161void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
162 // C++ [dcl.fct.default]p3
163 // A default argument expression shall be specified only in the
164 // parameter-declaration-clause of a function declaration or in a
165 // template-parameter (14.1). It shall not be specified for a
166 // parameter pack. If it is specified in a
167 // parameter-declaration-clause, it shall not occur within a
168 // declarator or abstract-declarator of a parameter-declaration.
169 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
170 DeclaratorChunk &chunk = D.getTypeObject(i);
171 if (chunk.Kind == DeclaratorChunk::Function) {
172 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
173 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
174 if (Param->getDefaultArg()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000175 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
176 << Param->getDefaultArg()->getSourceRange();
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000177 Param->setDefaultArg(0);
Douglas Gregor605de8d2008-12-16 21:30:33 +0000178 } else if (CachedTokens *Toks
179 = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens) {
180 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
181 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
182 delete Toks;
183 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000184 }
185 }
186 }
187 }
188}
189
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000190// MergeCXXFunctionDecl - Merge two declarations of the same C++
191// function, once we already know that they have the same
192// type. Subroutine of MergeFunctionDecl.
193FunctionDecl *
194Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
195 // C++ [dcl.fct.default]p4:
196 //
197 // For non-template functions, default arguments can be added in
198 // later declarations of a function in the same
199 // scope. Declarations in different scopes have completely
200 // distinct sets of default arguments. That is, declarations in
201 // inner scopes do not acquire default arguments from
202 // declarations in outer scopes, and vice versa. In a given
203 // function declaration, all parameters subsequent to a
204 // parameter with a default argument shall have default
205 // arguments supplied in this or previous declarations. A
206 // default argument shall not be redefined by a later
207 // declaration (not even to the same value).
208 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
209 ParmVarDecl *OldParam = Old->getParamDecl(p);
210 ParmVarDecl *NewParam = New->getParamDecl(p);
211
212 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
213 Diag(NewParam->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000214 diag::err_param_default_argument_redefinition)
215 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner1336cab2008-11-23 23:12:31 +0000216 Diag(OldParam->getLocation(), diag::note_previous_definition);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000217 } else if (OldParam->getDefaultArg()) {
218 // Merge the old default argument into the new parameter
219 NewParam->setDefaultArg(OldParam->getDefaultArg());
220 }
221 }
222
223 return New;
224}
225
226/// CheckCXXDefaultArguments - Verify that the default arguments for a
227/// function declaration are well-formed according to C++
228/// [dcl.fct.default].
229void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
230 unsigned NumParams = FD->getNumParams();
231 unsigned p;
232
233 // Find first parameter with a default argument
234 for (p = 0; p < NumParams; ++p) {
235 ParmVarDecl *Param = FD->getParamDecl(p);
236 if (Param->getDefaultArg())
237 break;
238 }
239
240 // C++ [dcl.fct.default]p4:
241 // In a given function declaration, all parameters
242 // subsequent to a parameter with a default argument shall
243 // have default arguments supplied in this or previous
244 // declarations. A default argument shall not be redefined
245 // by a later declaration (not even to the same value).
246 unsigned LastMissingDefaultArg = 0;
247 for(; p < NumParams; ++p) {
248 ParmVarDecl *Param = FD->getParamDecl(p);
249 if (!Param->getDefaultArg()) {
Douglas Gregor605de8d2008-12-16 21:30:33 +0000250 if (Param->isInvalidDecl())
251 /* We already complained about this parameter. */;
252 else if (Param->getIdentifier())
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000253 Diag(Param->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000254 diag::err_param_default_argument_missing_name)
Chris Lattnere46b8792008-11-19 07:32:16 +0000255 << Param->getIdentifier();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000256 else
257 Diag(Param->getLocation(),
258 diag::err_param_default_argument_missing);
259
260 LastMissingDefaultArg = p;
261 }
262 }
263
264 if (LastMissingDefaultArg > 0) {
265 // Some default arguments were missing. Clear out all of the
266 // default arguments up to (and including) the last missing
267 // default argument, so that we leave the function parameters
268 // in a semantically valid state.
269 for (p = 0; p <= LastMissingDefaultArg; ++p) {
270 ParmVarDecl *Param = FD->getParamDecl(p);
271 if (Param->getDefaultArg()) {
272 delete Param->getDefaultArg();
273 Param->setDefaultArg(0);
274 }
275 }
276 }
277}
Douglas Gregorec93f442008-04-13 21:30:24 +0000278
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000279/// isCurrentClassName - Determine whether the identifier II is the
280/// name of the class type currently being defined. In the case of
281/// nested classes, this will only return true if II is the name of
282/// the innermost class.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000283bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
284 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000285 CXXRecordDecl *CurDecl;
286 if (SS) {
287 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
288 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
289 } else
290 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
291
292 if (CurDecl)
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000293 return &II == CurDecl->getIdentifier();
294 else
295 return false;
296}
297
Douglas Gregorec93f442008-04-13 21:30:24 +0000298/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
299/// one entry in the base class list of a class specifier, for
300/// example:
301/// class foo : public bar, virtual private baz {
302/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorabed2172008-10-22 17:49:05 +0000303Sema::BaseResult
304Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
305 bool Virtual, AccessSpecifier Access,
306 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000307 RecordDecl *Decl = (RecordDecl*)classdecl;
308 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
309
310 // Base specifiers must be record types.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000311 if (!BaseType->isRecordType())
312 return Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Douglas Gregorec93f442008-04-13 21:30:24 +0000313
314 // C++ [class.union]p1:
315 // A union shall not be used as a base class.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000316 if (BaseType->isUnionType())
317 return Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Douglas Gregorec93f442008-04-13 21:30:24 +0000318
319 // C++ [class.union]p1:
320 // A union shall not have base classes.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000321 if (Decl->isUnion())
322 return Diag(Decl->getLocation(), diag::err_base_clause_on_union)
323 << SpecifierRange;
Douglas Gregorec93f442008-04-13 21:30:24 +0000324
325 // C++ [class.derived]p2:
326 // The class-name in a base-specifier shall not be an incompletely
327 // defined class.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000328 if (BaseType->isIncompleteType())
329 return Diag(BaseLoc, diag::err_incomplete_base_class) << SpecifierRange;
Douglas Gregorec93f442008-04-13 21:30:24 +0000330
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000331 // If the base class is polymorphic, the new one is, too.
332 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
333 assert(BaseDecl && "Record type has no declaration");
334 BaseDecl = BaseDecl->getDefinition(Context);
335 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Chris Lattner8ba580c2008-11-19 05:08:23 +0000336 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000337 cast<CXXRecordDecl>(Decl)->setPolymorphic(true);
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000338
Douglas Gregorabed2172008-10-22 17:49:05 +0000339 // Create the base specifier.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000340 return new CXXBaseSpecifier(SpecifierRange, Virtual,
341 BaseType->isClassType(), Access, BaseType);
Douglas Gregorabed2172008-10-22 17:49:05 +0000342}
Douglas Gregorec93f442008-04-13 21:30:24 +0000343
Douglas Gregorabed2172008-10-22 17:49:05 +0000344/// ActOnBaseSpecifiers - Attach the given base specifiers to the
345/// class, after checking whether there are any duplicate base
346/// classes.
347void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
348 unsigned NumBases) {
349 if (NumBases == 0)
350 return;
351
352 // Used to keep track of which base types we have already seen, so
353 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000354 // that the key is always the unqualified canonical type of the base
355 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000356 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
357
358 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000359 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
360 unsigned NumGoodBases = 0;
361 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000362 QualType NewBaseType
Douglas Gregor4fd85902008-10-23 18:13:27 +0000363 = Context.getCanonicalType(BaseSpecs[idx]->getType());
364 NewBaseType = NewBaseType.getUnqualifiedType();
365
Douglas Gregorabed2172008-10-22 17:49:05 +0000366 if (KnownBaseTypes[NewBaseType]) {
367 // C++ [class.mi]p3:
368 // A class shall not be specified as a direct base class of a
369 // derived class more than once.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000370 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000371 diag::err_duplicate_base_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000372 << KnownBaseTypes[NewBaseType]->getType()
Chris Lattner8ba580c2008-11-19 05:08:23 +0000373 << BaseSpecs[idx]->getSourceRange();
Douglas Gregor4fd85902008-10-23 18:13:27 +0000374
375 // Delete the duplicate base class specifier; we're going to
376 // overwrite its pointer later.
377 delete BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000378 } else {
379 // Okay, add this new base class.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000380 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
381 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000382 }
383 }
384
385 // Attach the remaining base class specifiers to the derived class.
386 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000387 Decl->setBases(BaseSpecs, NumGoodBases);
388
389 // Delete the remaining (good) base class specifiers, since their
390 // data has been copied into the CXXRecordDecl.
391 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
392 delete BaseSpecs[idx];
Douglas Gregorec93f442008-04-13 21:30:24 +0000393}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000394
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000395//===----------------------------------------------------------------------===//
396// C++ class member Handling
397//===----------------------------------------------------------------------===//
398
399/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
400/// definition, when on C++.
401void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000402 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Douglas Gregor8acb7272008-12-11 16:49:14 +0000403 PushDeclContext(S, Dcl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000404 FieldCollector->StartClass();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000405
406 if (Dcl->getIdentifier()) {
407 // C++ [class]p2:
408 // [...] The class-name is also inserted into the scope of the
409 // class itself; this is known as the injected-class-name. For
410 // purposes of access checking, the injected-class-name is treated
411 // as if it were a public member name.
Douglas Gregor4b00d562008-12-17 16:48:01 +0000412 PushOnScopeChains(CXXRecordDecl::Create(Context, Dcl->getTagKind(),
413 CurContext, Dcl->getLocation(),
414 Dcl->getIdentifier(), Dcl), S);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000415 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000416}
417
418/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
419/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
420/// bitfield width if there is one and 'InitExpr' specifies the initializer if
421/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
422/// declarators on it.
423///
Douglas Gregor605de8d2008-12-16 21:30:33 +0000424/// FIXME: The note below is out-of-date.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000425/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
426/// an instance field is declared, a new CXXFieldDecl is created but the method
427/// does *not* return it; it returns LastInGroup instead. The other C++ members
428/// (which are all ScopedDecls) are returned after appending them to
429/// LastInGroup.
430Sema::DeclTy *
431Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
432 ExprTy *BW, ExprTy *InitExpr,
433 DeclTy *LastInGroup) {
434 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor6704b312008-11-17 22:58:34 +0000435 DeclarationName Name = GetNameForDeclarator(D);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000436 Expr *BitWidth = static_cast<Expr*>(BW);
437 Expr *Init = static_cast<Expr*>(InitExpr);
438 SourceLocation Loc = D.getIdentifierLoc();
439
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000440 bool isFunc = D.isFunctionDeclarator();
441
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000442 // C++ 9.2p6: A member shall not be declared to have automatic storage
443 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000444 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
445 // data members and cannot be applied to names declared const or static,
446 // and cannot be applied to reference members.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000447 switch (DS.getStorageClassSpec()) {
448 case DeclSpec::SCS_unspecified:
449 case DeclSpec::SCS_typedef:
450 case DeclSpec::SCS_static:
451 // FALL THROUGH.
452 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000453 case DeclSpec::SCS_mutable:
454 if (isFunc) {
455 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000456 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000457 else
Chris Lattner8ba580c2008-11-19 05:08:23 +0000458 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
459
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000460 // FIXME: It would be nicer if the keyword was ignored only for this
461 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000462 D.getMutableDeclSpec().ClearStorageClassSpecs();
463 } else {
464 QualType T = GetTypeForDeclarator(D, S);
465 diag::kind err = static_cast<diag::kind>(0);
466 if (T->isReferenceType())
467 err = diag::err_mutable_reference;
468 else if (T.isConstQualified())
469 err = diag::err_mutable_const;
470 if (err != 0) {
471 if (DS.getStorageClassSpecLoc().isValid())
472 Diag(DS.getStorageClassSpecLoc(), err);
473 else
474 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000475 // FIXME: It would be nicer if the keyword was ignored only for this
476 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000477 D.getMutableDeclSpec().ClearStorageClassSpecs();
478 }
479 }
480 break;
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000481 default:
482 if (DS.getStorageClassSpecLoc().isValid())
483 Diag(DS.getStorageClassSpecLoc(),
484 diag::err_storageclass_invalid_for_member);
485 else
486 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
487 D.getMutableDeclSpec().ClearStorageClassSpecs();
488 }
489
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000490 if (!isFunc &&
491 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
492 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000493 // Check also for this case:
494 //
495 // typedef int f();
496 // f a;
497 //
498 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
499 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
500 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000501
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000502 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
503 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000504 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000505
506 Decl *Member;
507 bool InvalidDecl = false;
508
509 if (isInstField)
Douglas Gregor8acb7272008-12-11 16:49:14 +0000510 Member = static_cast<Decl*>(ActOnField(S, cast<CXXRecordDecl>(CurContext),
511 Loc, D, BitWidth));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000512 else
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000513 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000514
515 if (!Member) return LastInGroup;
516
Douglas Gregor6704b312008-11-17 22:58:34 +0000517 assert((Name || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000518
519 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
520 // specific methods. Use a wrapper class that can be used with all C++ class
521 // member decls.
522 CXXClassMemberWrapper(Member).setAccess(AS);
523
Douglas Gregor15e04622008-11-05 16:20:31 +0000524 // C++ [dcl.init.aggr]p1:
525 // An aggregate is an array or a class (clause 9) with [...] no
526 // private or protected non-static data members (clause 11).
527 if (isInstField && (AS == AS_private || AS == AS_protected))
528 cast<CXXRecordDecl>(CurContext)->setAggregate(false);
529
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000530 if (DS.isVirtualSpecified()) {
531 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
532 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
533 InvalidDecl = true;
534 } else {
535 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
536 CurClass->setAggregate(false);
537 CurClass->setPolymorphic(true);
538 }
539 }
Douglas Gregor15e04622008-11-05 16:20:31 +0000540
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000541 if (BitWidth) {
542 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
543 // constant-expression be a value equal to zero.
544 // FIXME: Check this.
545
546 if (D.isFunctionDeclarator()) {
547 // FIXME: Emit diagnostic about only constructors taking base initializers
548 // or something similar, when constructor support is in place.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000549 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000550 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000551 InvalidDecl = true;
552
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000553 } else if (isInstField) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000554 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000555 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000556 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000557 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000558 InvalidDecl = true;
559 }
560
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000561 } else if (isa<FunctionDecl>(Member)) {
562 // A function typedef ("typedef int f(); f a;").
563 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000564 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000565 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000566 InvalidDecl = true;
567
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000568 } else if (isa<TypedefDecl>(Member)) {
569 // "cannot declare 'A' to be a bit-field type"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000570 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000571 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000572 InvalidDecl = true;
573
574 } else {
575 assert(isa<CXXClassVarDecl>(Member) &&
576 "Didn't we cover all member kinds?");
577 // C++ 9.6p3: A bit-field shall not be a static member.
578 // "static member 'A' cannot be a bit-field"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000579 Diag(Loc, diag::err_static_not_bitfield)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000580 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000581 InvalidDecl = true;
582 }
583 }
584
585 if (Init) {
586 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
587 // if it declares a static member of const integral or const enumeration
588 // type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000589 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
590 // ...static member of...
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000591 CVD->setInit(Init);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000592 // ...const integral or const enumeration type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000593 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
594 CVD->getType()->isIntegralType()) {
595 // constant-initializer
596 if (CheckForConstantInitializer(Init, CVD->getType()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000597 InvalidDecl = true;
598
599 } else {
600 // not const integral.
Chris Lattner77d52da2008-11-20 06:06:08 +0000601 Diag(Loc, diag::err_member_initialization)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000602 << Name << Init->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000603 InvalidDecl = true;
604 }
605
606 } else {
607 // not static member.
Chris Lattner77d52da2008-11-20 06:06:08 +0000608 Diag(Loc, diag::err_member_initialization)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000609 << Name << Init->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000610 InvalidDecl = true;
611 }
612 }
613
614 if (InvalidDecl)
615 Member->setInvalidDecl();
616
617 if (isInstField) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000618 FieldCollector->Add(cast<FieldDecl>(Member));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000619 return LastInGroup;
620 }
621 return Member;
622}
623
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000624/// ActOnMemInitializer - Handle a C++ member initializer.
625Sema::MemInitResult
626Sema::ActOnMemInitializer(DeclTy *ConstructorD,
627 Scope *S,
628 IdentifierInfo *MemberOrBase,
629 SourceLocation IdLoc,
630 SourceLocation LParenLoc,
631 ExprTy **Args, unsigned NumArgs,
632 SourceLocation *CommaLocs,
633 SourceLocation RParenLoc) {
634 CXXConstructorDecl *Constructor
635 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
636 if (!Constructor) {
637 // The user wrote a constructor initializer on a function that is
638 // not a C++ constructor. Ignore the error for now, because we may
639 // have more member initializers coming; we'll diagnose it just
640 // once in ActOnMemInitializers.
641 return true;
642 }
643
644 CXXRecordDecl *ClassDecl = Constructor->getParent();
645
646 // C++ [class.base.init]p2:
647 // Names in a mem-initializer-id are looked up in the scope of the
648 // constructor’s class and, if not found in that scope, are looked
649 // up in the scope containing the constructor’s
650 // definition. [Note: if the constructor’s class contains a member
651 // with the same name as a direct or virtual base class of the
652 // class, a mem-initializer-id naming the member or base class and
653 // composed of a single identifier refers to the class member. A
654 // mem-initializer-id for the hidden base class may be specified
655 // using a qualified name. ]
656 // Look for a member, first.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000657 FieldDecl *Member = 0;
658 DeclContext::lookup_result Result = ClassDecl->lookup(Context, MemberOrBase);
659 if (Result.first != Result.second)
660 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000661
662 // FIXME: Handle members of an anonymous union.
663
664 if (Member) {
665 // FIXME: Perform direct initialization of the member.
666 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
667 }
668
669 // It didn't name a member, so see if it names a class.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000670 TypeTy *BaseTy = isTypeName(*MemberOrBase, S, 0/*SS*/);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000671 if (!BaseTy)
Chris Lattner65cae292008-11-19 08:23:25 +0000672 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
673 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000674
675 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
676 if (!BaseType->isRecordType())
Chris Lattner65cae292008-11-19 08:23:25 +0000677 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattnerb1753422008-11-23 21:45:46 +0000678 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000679
680 // C++ [class.base.init]p2:
681 // [...] Unless the mem-initializer-id names a nonstatic data
682 // member of the constructor’s class or a direct or virtual base
683 // of that class, the mem-initializer is ill-formed. A
684 // mem-initializer-list can initialize a base class using any
685 // name that denotes that base class type.
686
687 // First, check for a direct base class.
688 const CXXBaseSpecifier *DirectBaseSpec = 0;
689 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
690 Base != ClassDecl->bases_end(); ++Base) {
691 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
692 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
693 // We found a direct base of this type. That's what we're
694 // initializing.
695 DirectBaseSpec = &*Base;
696 break;
697 }
698 }
699
700 // Check for a virtual base class.
701 // FIXME: We might be able to short-circuit this if we know in
702 // advance that there are no virtual bases.
703 const CXXBaseSpecifier *VirtualBaseSpec = 0;
704 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
705 // We haven't found a base yet; search the class hierarchy for a
706 // virtual base class.
707 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
708 /*DetectVirtual=*/false);
709 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
710 for (BasePaths::paths_iterator Path = Paths.begin();
711 Path != Paths.end(); ++Path) {
712 if (Path->back().Base->isVirtual()) {
713 VirtualBaseSpec = Path->back().Base;
714 break;
715 }
716 }
717 }
718 }
719
720 // C++ [base.class.init]p2:
721 // If a mem-initializer-id is ambiguous because it designates both
722 // a direct non-virtual base class and an inherited virtual base
723 // class, the mem-initializer is ill-formed.
724 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner65cae292008-11-19 08:23:25 +0000725 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
726 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000727
728 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
729}
730
731
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000732void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
733 DeclTy *TagDecl,
734 SourceLocation LBrac,
735 SourceLocation RBrac) {
736 ActOnFields(S, RLoc, TagDecl,
737 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +0000738 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000739}
740
Douglas Gregore640ab62008-11-03 17:51:48 +0000741/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
742/// special functions, such as the default constructor, copy
743/// constructor, or destructor, to the given C++ class (C++
744/// [special]p1). This routine can only be executed just before the
745/// definition of the class is complete.
746void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000747 QualType ClassType = Context.getTypeDeclType(ClassDecl);
748 ClassType = Context.getCanonicalType(ClassType);
749
Douglas Gregore640ab62008-11-03 17:51:48 +0000750 if (!ClassDecl->hasUserDeclaredConstructor()) {
751 // C++ [class.ctor]p5:
752 // A default constructor for a class X is a constructor of class X
753 // that can be called without an argument. If there is no
754 // user-declared constructor for class X, a default constructor is
755 // implicitly declared. An implicitly-declared default constructor
756 // is an inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000757 DeclarationName Name
758 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000759 CXXConstructorDecl *DefaultCon =
760 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000761 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000762 Context.getFunctionType(Context.VoidTy,
763 0, 0, false, 0),
764 /*isExplicit=*/false,
765 /*isInline=*/true,
766 /*isImplicitlyDeclared=*/true);
767 DefaultCon->setAccess(AS_public);
Douglas Gregorb9213832008-12-15 21:24:18 +0000768 ClassDecl->addDecl(Context, DefaultCon);
769
770 // Notify the class that we've added a constructor.
771 ClassDecl->addedConstructor(Context, DefaultCon);
Douglas Gregore640ab62008-11-03 17:51:48 +0000772 }
773
774 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
775 // C++ [class.copy]p4:
776 // If the class definition does not explicitly declare a copy
777 // constructor, one is declared implicitly.
778
779 // C++ [class.copy]p5:
780 // The implicitly-declared copy constructor for a class X will
781 // have the form
782 //
783 // X::X(const X&)
784 //
785 // if
786 bool HasConstCopyConstructor = true;
787
788 // -- each direct or virtual base class B of X has a copy
789 // constructor whose first parameter is of type const B& or
790 // const volatile B&, and
791 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
792 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
793 const CXXRecordDecl *BaseClassDecl
794 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
795 HasConstCopyConstructor
796 = BaseClassDecl->hasConstCopyConstructor(Context);
797 }
798
799 // -- for all the nonstatic data members of X that are of a
800 // class type M (or array thereof), each such class type
801 // has a copy constructor whose first parameter is of type
802 // const M& or const volatile M&.
803 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
804 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
805 QualType FieldType = (*Field)->getType();
806 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
807 FieldType = Array->getElementType();
808 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
809 const CXXRecordDecl *FieldClassDecl
810 = cast<CXXRecordDecl>(FieldClassType->getDecl());
811 HasConstCopyConstructor
812 = FieldClassDecl->hasConstCopyConstructor(Context);
813 }
814 }
815
816 // Otherwise, the implicitly declared copy constructor will have
817 // the form
818 //
819 // X::X(X&)
820 QualType ArgType = Context.getTypeDeclType(ClassDecl);
821 if (HasConstCopyConstructor)
822 ArgType = ArgType.withConst();
823 ArgType = Context.getReferenceType(ArgType);
824
825 // An implicitly-declared copy constructor is an inline public
826 // member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000827 DeclarationName Name
828 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000829 CXXConstructorDecl *CopyConstructor
830 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000831 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000832 Context.getFunctionType(Context.VoidTy,
833 &ArgType, 1,
834 false, 0),
835 /*isExplicit=*/false,
836 /*isInline=*/true,
837 /*isImplicitlyDeclared=*/true);
838 CopyConstructor->setAccess(AS_public);
839
840 // Add the parameter to the constructor.
841 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
842 ClassDecl->getLocation(),
843 /*IdentifierInfo=*/0,
844 ArgType, VarDecl::None, 0, 0);
845 CopyConstructor->setParams(&FromParam, 1);
846
Douglas Gregorb9213832008-12-15 21:24:18 +0000847 ClassDecl->addedConstructor(Context, CopyConstructor);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000848 ClassDecl->addDecl(Context, CopyConstructor);
Douglas Gregore640ab62008-11-03 17:51:48 +0000849 }
850
Douglas Gregorb9213832008-12-15 21:24:18 +0000851 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000852 // C++ [class.dtor]p2:
853 // If a class has no user-declared destructor, a destructor is
854 // declared implicitly. An implicitly-declared destructor is an
855 // inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000856 DeclarationName Name
857 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000858 CXXDestructorDecl *Destructor
859 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000860 ClassDecl->getLocation(), Name,
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000861 Context.getFunctionType(Context.VoidTy,
862 0, 0, false, 0),
863 /*isInline=*/true,
864 /*isImplicitlyDeclared=*/true);
865 Destructor->setAccess(AS_public);
Douglas Gregorb9213832008-12-15 21:24:18 +0000866 ClassDecl->addDecl(Context, Destructor);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000867 }
868
Douglas Gregore640ab62008-11-03 17:51:48 +0000869 // FIXME: Implicit copy assignment operator
870}
871
Argiris Kirtzidis448b4e42008-08-09 00:39:29 +0000872void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000873 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000874 FieldCollector->FinishClass();
Douglas Gregore640ab62008-11-03 17:51:48 +0000875 AddImplicitlyDeclaredMembersToClass(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000876 PopDeclContext();
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000877
878 // Everything, including inline method definitions, have been parsed.
879 // Let the consumer know of the new TagDecl definition.
880 Consumer.HandleTagDeclDefinition(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000881}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000882
Douglas Gregor605de8d2008-12-16 21:30:33 +0000883/// ActOnStartDelayedCXXMethodDeclaration - We have completed
884/// parsing a top-level (non-nested) C++ class, and we are now
885/// parsing those parts of the given Method declaration that could
886/// not be parsed earlier (C++ [class.mem]p2), such as default
887/// arguments. This action should enter the scope of the given
888/// Method declaration as if we had just parsed the qualified method
889/// name. However, it should not bring the parameters into scope;
890/// that will be performed by ActOnDelayedCXXMethodParameter.
891void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) {
892 CXXScopeSpec SS;
893 SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext());
894 ActOnCXXEnterDeclaratorScope(S, SS);
895}
896
897/// ActOnDelayedCXXMethodParameter - We've already started a delayed
898/// C++ method declaration. We're (re-)introducing the given
899/// function parameter into scope for use in parsing later parts of
900/// the method declaration. For example, we could see an
901/// ActOnParamDefaultArgument event for this parameter.
902void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
903 ParmVarDecl *Param = (ParmVarDecl*)ParamD;
904 S->AddDecl(Param);
905 if (Param->getDeclName())
906 IdResolver.AddDecl(Param);
907}
908
909/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
910/// processing the delayed method declaration for Method. The method
911/// declaration is now considered finished. There may be a separate
912/// ActOnStartOfFunctionDef action later (not necessarily
913/// immediately!) for this method, if it was also defined inside the
914/// class body.
915void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
916 FunctionDecl *Method = (FunctionDecl*)MethodD;
917 CXXScopeSpec SS;
918 SS.setScopeRep(Method->getDeclContext());
919 ActOnCXXExitDeclaratorScope(S, SS);
920
921 // Now that we have our default arguments, check the constructor
922 // again. It could produce additional diagnostics or affect whether
923 // the class has implicitly-declared destructors, among other
924 // things.
925 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
926 if (CheckConstructor(Constructor))
927 Constructor->setInvalidDecl();
928 }
929
930 // Check the default arguments, which we may have added.
931 if (!Method->isInvalidDecl())
932 CheckCXXDefaultArguments(Method);
933}
934
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000935/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor605de8d2008-12-16 21:30:33 +0000936/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000937/// R. If there are any errors in the declarator, this routine will
938/// emit diagnostics and return true. Otherwise, it will return
939/// false. Either way, the type @p R will be updated to reflect a
940/// well-formed type for the constructor.
941bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
942 FunctionDecl::StorageClass& SC) {
943 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
944 bool isInvalid = false;
945
946 // C++ [class.ctor]p3:
947 // A constructor shall not be virtual (10.3) or static (9.4). A
948 // constructor can be invoked for a const, volatile or const
949 // volatile object. A constructor shall not be declared const,
950 // volatile, or const volatile (9.3.2).
951 if (isVirtual) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000952 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
953 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
954 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000955 isInvalid = true;
956 }
957 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000958 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
959 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
960 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000961 isInvalid = true;
962 SC = FunctionDecl::None;
963 }
964 if (D.getDeclSpec().hasTypeSpecifier()) {
965 // Constructors don't have return types, but the parser will
966 // happily parse something like:
967 //
968 // class X {
969 // float X(float);
970 // };
971 //
972 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000973 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
974 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
975 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000976 }
977 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
978 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
979 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000980 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
981 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000982 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000983 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
984 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000985 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000986 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
987 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000988 }
989
990 // Rebuild the function type "R" without any type qualifiers (in
991 // case any of the errors above fired) and with "void" as the
992 // return type, since constructors don't have return types. We
993 // *always* have to do this, because GetTypeForDeclarator will
994 // put in a result type of "int" when none was specified.
995 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto();
996 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
997 Proto->getNumArgs(),
998 Proto->isVariadic(),
999 0);
1000
1001 return isInvalid;
1002}
1003
Douglas Gregor605de8d2008-12-16 21:30:33 +00001004/// CheckConstructor - Checks a fully-formed constructor for
1005/// well-formedness, issuing any diagnostics required. Returns true if
1006/// the constructor declarator is invalid.
1007bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1008 if (Constructor->isInvalidDecl())
1009 return true;
1010
1011 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1012 bool Invalid = false;
1013
1014 // C++ [class.copy]p3:
1015 // A declaration of a constructor for a class X is ill-formed if
1016 // its first parameter is of type (optionally cv-qualified) X and
1017 // either there are no other parameters or else all other
1018 // parameters have default arguments.
1019 if ((Constructor->getNumParams() == 1) ||
1020 (Constructor->getNumParams() > 1 &&
1021 Constructor->getParamDecl(1)->getDefaultArg() != 0)) {
1022 QualType ParamType = Constructor->getParamDecl(0)->getType();
1023 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1024 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1025 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1026 << SourceRange(Constructor->getParamDecl(0)->getLocation());
1027 Invalid = true;
1028 }
1029 }
1030
1031 // Notify the class that we've added a constructor.
1032 ClassDecl->addedConstructor(Context, Constructor);
1033
1034 return Invalid;
1035}
1036
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001037/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1038/// the well-formednes of the destructor declarator @p D with type @p
1039/// R. If there are any errors in the declarator, this routine will
1040/// emit diagnostics and return true. Otherwise, it will return
1041/// false. Either way, the type @p R will be updated to reflect a
1042/// well-formed type for the destructor.
1043bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1044 FunctionDecl::StorageClass& SC) {
1045 bool isInvalid = false;
1046
1047 // C++ [class.dtor]p1:
1048 // [...] A typedef-name that names a class is a class-name
1049 // (7.1.3); however, a typedef-name that names a class shall not
1050 // be used as the identifier in the declarator for a destructor
1051 // declaration.
1052 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType();
1053 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001054 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Chris Lattner271d4c22008-11-24 05:29:24 +00001055 << TypedefD->getDeclName();
Douglas Gregorbd19fdb2008-11-10 14:41:22 +00001056 isInvalid = true;
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001057 }
1058
1059 // C++ [class.dtor]p2:
1060 // A destructor is used to destroy objects of its class type. A
1061 // destructor takes no parameters, and no return type can be
1062 // specified for it (not even void). The address of a destructor
1063 // shall not be taken. A destructor shall not be static. A
1064 // destructor can be invoked for a const, volatile or const
1065 // volatile object. A destructor shall not be declared const,
1066 // volatile or const volatile (9.3.2).
1067 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001068 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1069 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1070 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001071 isInvalid = true;
1072 SC = FunctionDecl::None;
1073 }
1074 if (D.getDeclSpec().hasTypeSpecifier()) {
1075 // Destructors don't have return types, but the parser will
1076 // happily parse something like:
1077 //
1078 // class X {
1079 // float ~X();
1080 // };
1081 //
1082 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001083 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1084 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1085 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001086 }
1087 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
1088 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1089 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001090 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1091 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001092 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001093 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1094 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001095 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001096 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1097 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001098 }
1099
1100 // Make sure we don't have any parameters.
1101 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1102 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1103
1104 // Delete the parameters.
1105 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1106 if (FTI.NumArgs) {
1107 delete [] FTI.ArgInfo;
1108 FTI.NumArgs = 0;
1109 FTI.ArgInfo = 0;
1110 }
1111 }
1112
1113 // Make sure the destructor isn't variadic.
1114 if (R->getAsFunctionTypeProto()->isVariadic())
1115 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1116
1117 // Rebuild the function type "R" without any type qualifiers or
1118 // parameters (in case any of the errors above fired) and with
1119 // "void" as the return type, since destructors don't have return
1120 // types. We *always* have to do this, because GetTypeForDeclarator
1121 // will put in a result type of "int" when none was specified.
1122 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1123
1124 return isInvalid;
1125}
1126
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001127/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1128/// well-formednes of the conversion function declarator @p D with
1129/// type @p R. If there are any errors in the declarator, this routine
1130/// will emit diagnostics and return true. Otherwise, it will return
1131/// false. Either way, the type @p R will be updated to reflect a
1132/// well-formed type for the conversion operator.
1133bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1134 FunctionDecl::StorageClass& SC) {
1135 bool isInvalid = false;
1136
1137 // C++ [class.conv.fct]p1:
1138 // Neither parameter types nor return type can be specified. The
1139 // type of a conversion function (8.3.5) is “function taking no
1140 // parameter returning conversion-type-id.”
1141 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001142 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1143 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1144 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001145 isInvalid = true;
1146 SC = FunctionDecl::None;
1147 }
1148 if (D.getDeclSpec().hasTypeSpecifier()) {
1149 // Conversion functions don't have return types, but the parser will
1150 // happily parse something like:
1151 //
1152 // class X {
1153 // float operator bool();
1154 // };
1155 //
1156 // The return type will be changed later anyway.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001157 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1158 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1159 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001160 }
1161
1162 // Make sure we don't have any parameters.
1163 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1164 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1165
1166 // Delete the parameters.
1167 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1168 if (FTI.NumArgs) {
1169 delete [] FTI.ArgInfo;
1170 FTI.NumArgs = 0;
1171 FTI.ArgInfo = 0;
1172 }
1173 }
1174
1175 // Make sure the conversion function isn't variadic.
1176 if (R->getAsFunctionTypeProto()->isVariadic())
1177 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1178
1179 // C++ [class.conv.fct]p4:
1180 // The conversion-type-id shall not represent a function type nor
1181 // an array type.
1182 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1183 if (ConvType->isArrayType()) {
1184 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1185 ConvType = Context.getPointerType(ConvType);
1186 } else if (ConvType->isFunctionType()) {
1187 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1188 ConvType = Context.getPointerType(ConvType);
1189 }
1190
1191 // Rebuild the function type "R" without any parameters (in case any
1192 // of the errors above fired) and with the conversion type as the
1193 // return type.
1194 R = Context.getFunctionType(ConvType, 0, 0, false,
1195 R->getAsFunctionTypeProto()->getTypeQuals());
1196
1197 return isInvalid;
1198}
1199
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001200/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1201/// the declaration of the given C++ conversion function. This routine
1202/// is responsible for recording the conversion function in the C++
1203/// class, if possible.
1204Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1205 assert(Conversion && "Expected to receive a conversion function declaration");
1206
Douglas Gregor98341042008-12-12 08:25:50 +00001207 // Set the lexical context of this conversion function
1208 Conversion->setLexicalDeclContext(CurContext);
1209
1210 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001211
1212 // Make sure we aren't redeclaring the conversion function.
1213 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
1214 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1215 for (OverloadedFunctionDecl::function_iterator Func
1216 = Conversions->function_begin();
1217 Func != Conversions->function_end(); ++Func) {
1218 CXXConversionDecl *OtherConv = cast<CXXConversionDecl>(*Func);
1219 if (ConvType == Context.getCanonicalType(OtherConv->getConversionType())) {
1220 Diag(Conversion->getLocation(), diag::err_conv_function_redeclared);
1221 Diag(OtherConv->getLocation(),
1222 OtherConv->isThisDeclarationADefinition()?
Chris Lattner1336cab2008-11-23 23:12:31 +00001223 diag::note_previous_definition
1224 : diag::note_previous_declaration);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001225 Conversion->setInvalidDecl();
1226 return (DeclTy *)Conversion;
1227 }
1228 }
1229
1230 // C++ [class.conv.fct]p1:
1231 // [...] A conversion function is never used to convert a
1232 // (possibly cv-qualified) object to the (possibly cv-qualified)
1233 // same object type (or a reference to it), to a (possibly
1234 // cv-qualified) base class of that type (or a reference to it),
1235 // or to (possibly cv-qualified) void.
1236 // FIXME: Suppress this warning if the conversion function ends up
1237 // being a virtual function that overrides a virtual function in a
1238 // base class.
1239 QualType ClassType
1240 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1241 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1242 ConvType = ConvTypeRef->getPointeeType();
1243 if (ConvType->isRecordType()) {
1244 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1245 if (ConvType == ClassType)
Chris Lattner8d756812008-11-20 06:13:02 +00001246 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001247 << ClassType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001248 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner8d756812008-11-20 06:13:02 +00001249 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001250 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001251 } else if (ConvType->isVoidType()) {
Chris Lattner8d756812008-11-20 06:13:02 +00001252 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001253 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001254 }
1255
1256 ClassDecl->addConversionFunction(Context, Conversion);
1257
1258 return (DeclTy *)Conversion;
1259}
1260
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001261//===----------------------------------------------------------------------===//
1262// Namespace Handling
1263//===----------------------------------------------------------------------===//
1264
1265/// ActOnStartNamespaceDef - This is called at the start of a namespace
1266/// definition.
1267Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1268 SourceLocation IdentLoc,
1269 IdentifierInfo *II,
1270 SourceLocation LBrace) {
1271 NamespaceDecl *Namespc =
1272 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1273 Namespc->setLBracLoc(LBrace);
1274
1275 Scope *DeclRegionScope = NamespcScope->getParent();
1276
1277 if (II) {
1278 // C++ [namespace.def]p2:
1279 // The identifier in an original-namespace-definition shall not have been
1280 // previously defined in the declarative region in which the
1281 // original-namespace-definition appears. The identifier in an
1282 // original-namespace-definition is the name of the namespace. Subsequently
1283 // in that declarative region, it is treated as an original-namespace-name.
1284
1285 Decl *PrevDecl =
Douglas Gregor8acb7272008-12-11 16:49:14 +00001286 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 0,
1287 /*enableLazyBuiltinCreation=*/false,
1288 /*LookupInParent=*/false);
1289
1290 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1291 // This is an extended namespace definition.
1292 // Attach this namespace decl to the chain of extended namespace
1293 // definitions.
1294 OrigNS->setNextNamespace(Namespc);
1295 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001296
Douglas Gregor8acb7272008-12-11 16:49:14 +00001297 // Remove the previous declaration from the scope.
1298 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor39677622008-12-11 20:41:00 +00001299 IdResolver.RemoveDecl(OrigNS);
1300 DeclRegionScope->RemoveDecl(OrigNS);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001301 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001302 } else if (PrevDecl) {
1303 // This is an invalid name redefinition.
1304 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1305 << Namespc->getDeclName();
1306 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1307 Namespc->setInvalidDecl();
1308 // Continue on to push Namespc as current DeclContext and return it.
1309 }
1310
1311 PushOnScopeChains(Namespc, DeclRegionScope);
1312 } else {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001313 // FIXME: Handle anonymous namespaces
1314 }
1315
1316 // Although we could have an invalid decl (i.e. the namespace name is a
1317 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001318 // FIXME: We should be able to push Namespc here, so that the
1319 // each DeclContext for the namespace has the declarations
1320 // that showed up in that particular namespace definition.
1321 PushDeclContext(NamespcScope, Namespc);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001322 return Namespc;
1323}
1324
1325/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1326/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1327void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1328 Decl *Dcl = static_cast<Decl *>(D);
1329 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1330 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1331 Namespc->setRBracLoc(RBrace);
1332 PopDeclContext();
1333}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001334
1335
1336/// AddCXXDirectInitializerToDecl - This action is called immediately after
1337/// ActOnDeclarator, when a C++ direct initializer is present.
1338/// e.g: "int x(1);"
1339void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1340 ExprTy **ExprTys, unsigned NumExprs,
1341 SourceLocation *CommaLocs,
1342 SourceLocation RParenLoc) {
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001343 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001344 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001345
1346 // If there is no declaration, there was an error parsing it. Just ignore
1347 // the initializer.
1348 if (RealDecl == 0) {
Ted Kremenek85b4c492008-10-06 20:35:04 +00001349 for (unsigned i = 0; i != NumExprs; ++i)
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001350 delete static_cast<Expr *>(ExprTys[i]);
1351 return;
1352 }
1353
1354 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1355 if (!VDecl) {
1356 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1357 RealDecl->setInvalidDecl();
1358 return;
1359 }
1360
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001361 // We will treat direct-initialization as a copy-initialization:
1362 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001363 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1364 //
1365 // Clients that want to distinguish between the two forms, can check for
1366 // direct initializer using VarDecl::hasCXXDirectInitializer().
1367 // A major benefit is that clients that don't particularly care about which
1368 // exactly form was it (like the CodeGen) can handle both cases without
1369 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001370
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001371 // C++ 8.5p11:
1372 // The form of initialization (using parentheses or '=') is generally
1373 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001374 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +00001375 QualType DeclInitType = VDecl->getType();
1376 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1377 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001378
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001379 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001380 CXXConstructorDecl *Constructor
Douglas Gregor6428e762008-11-05 15:29:30 +00001381 = PerformInitializationByConstructor(DeclInitType,
1382 (Expr **)ExprTys, NumExprs,
1383 VDecl->getLocation(),
1384 SourceRange(VDecl->getLocation(),
1385 RParenLoc),
Chris Lattner271d4c22008-11-24 05:29:24 +00001386 VDecl->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00001387 IK_Direct);
Douglas Gregor5870a952008-11-03 20:45:27 +00001388 if (!Constructor) {
1389 RealDecl->setInvalidDecl();
1390 }
Douglas Gregor6428e762008-11-05 15:29:30 +00001391
1392 // Let clients know that initialization was done with a direct
1393 // initializer.
1394 VDecl->setCXXDirectInitializer(true);
1395
1396 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1397 // the initializer.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001398 return;
1399 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001400
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001401 if (NumExprs > 1) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001402 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1403 << SourceRange(VDecl->getLocation(), RParenLoc);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001404 RealDecl->setInvalidDecl();
1405 return;
1406 }
1407
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001408 // Let clients know that initialization was done with a direct initializer.
1409 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001410
1411 assert(NumExprs == 1 && "Expected 1 expression");
1412 // Set the init expression, handles conversions.
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00001413 AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]));
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001414}
Douglas Gregor81c29152008-10-29 00:13:59 +00001415
Douglas Gregor6428e762008-11-05 15:29:30 +00001416/// PerformInitializationByConstructor - Perform initialization by
1417/// constructor (C++ [dcl.init]p14), which may occur as part of
1418/// direct-initialization or copy-initialization. We are initializing
1419/// an object of type @p ClassType with the given arguments @p
1420/// Args. @p Loc is the location in the source code where the
1421/// initializer occurs (e.g., a declaration, member initializer,
1422/// functional cast, etc.) while @p Range covers the whole
1423/// initialization. @p InitEntity is the entity being initialized,
1424/// which may by the name of a declaration or a type. @p Kind is the
1425/// kind of initialization we're performing, which affects whether
1426/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00001427/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00001428/// when the initialization fails, emits a diagnostic and returns
1429/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00001430CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00001431Sema::PerformInitializationByConstructor(QualType ClassType,
1432 Expr **Args, unsigned NumArgs,
1433 SourceLocation Loc, SourceRange Range,
Chris Lattner271d4c22008-11-24 05:29:24 +00001434 DeclarationName InitEntity,
Douglas Gregor6428e762008-11-05 15:29:30 +00001435 InitializationKind Kind) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001436 const RecordType *ClassRec = ClassType->getAsRecordType();
1437 assert(ClassRec && "Can only initialize a class type here");
1438
1439 // C++ [dcl.init]p14:
1440 //
1441 // If the initialization is direct-initialization, or if it is
1442 // copy-initialization where the cv-unqualified version of the
1443 // source type is the same class as, or a derived class of, the
1444 // class of the destination, constructors are considered. The
1445 // applicable constructors are enumerated (13.3.1.3), and the
1446 // best one is chosen through overload resolution (13.3). The
1447 // constructor so selected is called to initialize the object,
1448 // with the initializer expression(s) as its argument(s). If no
1449 // constructor applies, or the overload resolution is ambiguous,
1450 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00001451 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1452 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00001453
1454 // Add constructors to the overload set.
Douglas Gregorb9213832008-12-15 21:24:18 +00001455 DeclarationName ConstructorName
1456 = Context.DeclarationNames.getCXXConstructorName(
1457 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001458 DeclContext::lookup_const_iterator Con, ConEnd;
1459 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(Context, ConstructorName);
1460 Con != ConEnd; ++Con) {
1461 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor6428e762008-11-05 15:29:30 +00001462 if ((Kind == IK_Direct) ||
1463 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1464 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1465 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1466 }
1467
Douglas Gregorb9213832008-12-15 21:24:18 +00001468 // FIXME: When we decide not to synthesize the implicitly-declared
1469 // constructors, we'll need to make them appear here.
1470
Douglas Gregor5870a952008-11-03 20:45:27 +00001471 OverloadCandidateSet::iterator Best;
Douglas Gregor5870a952008-11-03 20:45:27 +00001472 switch (BestViableFunction(CandidateSet, Best)) {
1473 case OR_Success:
1474 // We found a constructor. Return it.
1475 return cast<CXXConstructorDecl>(Best->Function);
1476
1477 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00001478 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1479 << InitEntity << (unsigned)CandidateSet.size() << Range;
1480 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor5870a952008-11-03 20:45:27 +00001481 return 0;
1482
1483 case OR_Ambiguous:
Chris Lattner77d52da2008-11-20 06:06:08 +00001484 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
Douglas Gregor5870a952008-11-03 20:45:27 +00001485 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1486 return 0;
1487 }
1488
1489 return 0;
1490}
1491
Douglas Gregor81c29152008-10-29 00:13:59 +00001492/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1493/// determine whether they are reference-related,
1494/// reference-compatible, reference-compatible with added
1495/// qualification, or incompatible, for use in C++ initialization by
1496/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1497/// type, and the first type (T1) is the pointee type of the reference
1498/// type being initialized.
1499Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001500Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1501 bool& DerivedToBase) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001502 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1503 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1504
1505 T1 = Context.getCanonicalType(T1);
1506 T2 = Context.getCanonicalType(T2);
1507 QualType UnqualT1 = T1.getUnqualifiedType();
1508 QualType UnqualT2 = T2.getUnqualifiedType();
1509
1510 // C++ [dcl.init.ref]p4:
1511 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1512 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1513 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001514 if (UnqualT1 == UnqualT2)
1515 DerivedToBase = false;
1516 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1517 DerivedToBase = true;
1518 else
Douglas Gregor81c29152008-10-29 00:13:59 +00001519 return Ref_Incompatible;
1520
1521 // At this point, we know that T1 and T2 are reference-related (at
1522 // least).
1523
1524 // C++ [dcl.init.ref]p4:
1525 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1526 // reference-related to T2 and cv1 is the same cv-qualification
1527 // as, or greater cv-qualification than, cv2. For purposes of
1528 // overload resolution, cases for which cv1 is greater
1529 // cv-qualification than cv2 are identified as
1530 // reference-compatible with added qualification (see 13.3.3.2).
1531 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1532 return Ref_Compatible;
1533 else if (T1.isMoreQualifiedThan(T2))
1534 return Ref_Compatible_With_Added_Qualification;
1535 else
1536 return Ref_Related;
1537}
1538
1539/// CheckReferenceInit - Check the initialization of a reference
1540/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1541/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00001542/// list), and DeclType is the type of the declaration. When ICS is
1543/// non-null, this routine will compute the implicit conversion
1544/// sequence according to C++ [over.ics.ref] and will not produce any
1545/// diagnostics; when ICS is null, it will emit diagnostics when any
1546/// errors are found. Either way, a return value of true indicates
1547/// that there was a failure, a return value of false indicates that
1548/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001549///
1550/// When @p SuppressUserConversions, user-defined conversions are
1551/// suppressed.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001552bool
1553Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001554 ImplicitConversionSequence *ICS,
1555 bool SuppressUserConversions) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001556 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1557
1558 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1559 QualType T2 = Init->getType();
1560
Douglas Gregor45014fd2008-11-10 20:40:00 +00001561 // If the initializer is the address of an overloaded function, try
1562 // to resolve the overloaded function. If all goes well, T2 is the
1563 // type of the resulting function.
1564 if (T2->isOverloadType()) {
1565 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1566 ICS != 0);
1567 if (Fn) {
1568 // Since we're performing this reference-initialization for
1569 // real, update the initializer with the resulting function.
1570 if (!ICS)
1571 FixOverloadedFunctionReference(Init, Fn);
1572
1573 T2 = Fn->getType();
1574 }
1575 }
1576
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001577 // Compute some basic properties of the types and the initializer.
1578 bool DerivedToBase = false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001579 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001580 ReferenceCompareResult RefRelationship
1581 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1582
1583 // Most paths end in a failed conversion.
1584 if (ICS)
1585 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00001586
1587 // C++ [dcl.init.ref]p5:
1588 // A reference to type “cv1 T1” is initialized by an expression
1589 // of type “cv2 T2” as follows:
1590
1591 // -- If the initializer expression
1592
1593 bool BindsDirectly = false;
1594 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1595 // reference-compatible with “cv2 T2,” or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001596 //
1597 // Note that the bit-field check is skipped if we are just computing
1598 // the implicit conversion sequence (C++ [over.best.ics]p2).
1599 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1600 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001601 BindsDirectly = true;
1602
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001603 if (ICS) {
1604 // C++ [over.ics.ref]p1:
1605 // When a parameter of reference type binds directly (8.5.3)
1606 // to an argument expression, the implicit conversion sequence
1607 // is the identity conversion, unless the argument expression
1608 // has a type that is a derived class of the parameter type,
1609 // in which case the implicit conversion sequence is a
1610 // derived-to-base Conversion (13.3.3.1).
1611 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1612 ICS->Standard.First = ICK_Identity;
1613 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1614 ICS->Standard.Third = ICK_Identity;
1615 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1616 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001617 ICS->Standard.ReferenceBinding = true;
1618 ICS->Standard.DirectBinding = true;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001619
1620 // Nothing more to do: the inaccessibility/ambiguity check for
1621 // derived-to-base conversions is suppressed when we're
1622 // computing the implicit conversion sequence (C++
1623 // [over.best.ics]p2).
1624 return false;
1625 } else {
1626 // Perform the conversion.
Douglas Gregor81c29152008-10-29 00:13:59 +00001627 // FIXME: Binding to a subobject of the lvalue is going to require
1628 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001629 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001630 }
1631 }
1632
1633 // -- has a class type (i.e., T2 is a class type) and can be
1634 // implicitly converted to an lvalue of type “cv3 T3,”
1635 // where “cv1 T1” is reference-compatible with “cv3 T3”
1636 // 92) (this conversion is selected by enumerating the
1637 // applicable conversion functions (13.3.1.6) and choosing
1638 // the best one through overload resolution (13.3)),
Douglas Gregore6985fe2008-11-10 16:14:15 +00001639 if (!SuppressUserConversions && T2->isRecordType()) {
1640 // FIXME: Look for conversions in base classes!
1641 CXXRecordDecl *T2RecordDecl
1642 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor81c29152008-10-29 00:13:59 +00001643
Douglas Gregore6985fe2008-11-10 16:14:15 +00001644 OverloadCandidateSet CandidateSet;
1645 OverloadedFunctionDecl *Conversions
1646 = T2RecordDecl->getConversionFunctions();
1647 for (OverloadedFunctionDecl::function_iterator Func
1648 = Conversions->function_begin();
1649 Func != Conversions->function_end(); ++Func) {
1650 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1651
1652 // If the conversion function doesn't return a reference type,
1653 // it can't be considered for this conversion.
1654 // FIXME: This will change when we support rvalue references.
1655 if (Conv->getConversionType()->isReferenceType())
1656 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1657 }
1658
1659 OverloadCandidateSet::iterator Best;
1660 switch (BestViableFunction(CandidateSet, Best)) {
1661 case OR_Success:
1662 // This is a direct binding.
1663 BindsDirectly = true;
1664
1665 if (ICS) {
1666 // C++ [over.ics.ref]p1:
1667 //
1668 // [...] If the parameter binds directly to the result of
1669 // applying a conversion function to the argument
1670 // expression, the implicit conversion sequence is a
1671 // user-defined conversion sequence (13.3.3.1.2), with the
1672 // second standard conversion sequence either an identity
1673 // conversion or, if the conversion function returns an
1674 // entity of a type that is a derived class of the parameter
1675 // type, a derived-to-base Conversion.
1676 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1677 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1678 ICS->UserDefined.After = Best->FinalConversion;
1679 ICS->UserDefined.ConversionFunction = Best->Function;
1680 assert(ICS->UserDefined.After.ReferenceBinding &&
1681 ICS->UserDefined.After.DirectBinding &&
1682 "Expected a direct reference binding!");
1683 return false;
1684 } else {
1685 // Perform the conversion.
1686 // FIXME: Binding to a subobject of the lvalue is going to require
1687 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001688 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregore6985fe2008-11-10 16:14:15 +00001689 }
1690 break;
1691
1692 case OR_Ambiguous:
1693 assert(false && "Ambiguous reference binding conversions not implemented.");
1694 return true;
1695
1696 case OR_No_Viable_Function:
1697 // There was no suitable conversion; continue with other checks.
1698 break;
1699 }
1700 }
1701
Douglas Gregor81c29152008-10-29 00:13:59 +00001702 if (BindsDirectly) {
1703 // C++ [dcl.init.ref]p4:
1704 // [...] In all cases where the reference-related or
1705 // reference-compatible relationship of two types is used to
1706 // establish the validity of a reference binding, and T1 is a
1707 // base class of T2, a program that necessitates such a binding
1708 // is ill-formed if T1 is an inaccessible (clause 11) or
1709 // ambiguous (10.2) base class of T2.
1710 //
1711 // Note that we only check this condition when we're allowed to
1712 // complain about errors, because we should not be checking for
1713 // ambiguity (or inaccessibility) unless the reference binding
1714 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001715 if (DerivedToBase)
1716 return CheckDerivedToBaseConversion(T2, T1,
1717 Init->getSourceRange().getBegin(),
1718 Init->getSourceRange());
1719 else
1720 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001721 }
1722
1723 // -- Otherwise, the reference shall be to a non-volatile const
1724 // type (i.e., cv1 shall be const).
1725 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001726 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001727 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00001728 diag::err_not_reference_to_const_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001729 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1730 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001731 return true;
1732 }
1733
1734 // -- If the initializer expression is an rvalue, with T2 a
1735 // class type, and “cv1 T1” is reference-compatible with
1736 // “cv2 T2,” the reference is bound in one of the
1737 // following ways (the choice is implementation-defined):
1738 //
1739 // -- The reference is bound to the object represented by
1740 // the rvalue (see 3.10) or to a sub-object within that
1741 // object.
1742 //
1743 // -- A temporary of type “cv1 T2” [sic] is created, and
1744 // a constructor is called to copy the entire rvalue
1745 // object into the temporary. The reference is bound to
1746 // the temporary or to a sub-object within the
1747 // temporary.
1748 //
1749 //
1750 // The constructor that would be used to make the copy
1751 // shall be callable whether or not the copy is actually
1752 // done.
1753 //
1754 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1755 // freedom, so we will always take the first option and never build
1756 // a temporary in this case. FIXME: We will, however, have to check
1757 // for the presence of a copy constructor in C++98/03 mode.
1758 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001759 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1760 if (ICS) {
1761 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1762 ICS->Standard.First = ICK_Identity;
1763 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1764 ICS->Standard.Third = ICK_Identity;
1765 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1766 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001767 ICS->Standard.ReferenceBinding = true;
1768 ICS->Standard.DirectBinding = false;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001769 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001770 // FIXME: Binding to a subobject of the rvalue is going to require
1771 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001772 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001773 }
1774 return false;
1775 }
1776
1777 // -- Otherwise, a temporary of type “cv1 T1” is created and
1778 // initialized from the initializer expression using the
1779 // rules for a non-reference copy initialization (8.5). The
1780 // reference is then bound to the temporary. If T1 is
1781 // reference-related to T2, cv1 must be the same
1782 // cv-qualification as, or greater cv-qualification than,
1783 // cv2; otherwise, the program is ill-formed.
1784 if (RefRelationship == Ref_Related) {
1785 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1786 // we would be reference-compatible or reference-compatible with
1787 // added qualification. But that wasn't the case, so the reference
1788 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001789 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001790 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00001791 diag::err_reference_init_drops_quals)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001792 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1793 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001794 return true;
1795 }
1796
1797 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001798 if (ICS) {
1799 /// C++ [over.ics.ref]p2:
1800 ///
1801 /// When a parameter of reference type is not bound directly to
1802 /// an argument expression, the conversion sequence is the one
1803 /// required to convert the argument expression to the
1804 /// underlying type of the reference according to
1805 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1806 /// to copy-initializing a temporary of the underlying type with
1807 /// the argument expression. Any difference in top-level
1808 /// cv-qualification is subsumed by the initialization itself
1809 /// and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001810 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001811 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1812 } else {
Douglas Gregor6fd35572008-12-19 17:40:08 +00001813 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001814 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001815}
Douglas Gregore60e5d32008-11-06 22:13:31 +00001816
1817/// CheckOverloadedOperatorDeclaration - Check whether the declaration
1818/// of this overloaded operator is well-formed. If so, returns false;
1819/// otherwise, emits appropriate diagnostics and returns true.
1820bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001821 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregore60e5d32008-11-06 22:13:31 +00001822 "Expected an overloaded operator declaration");
1823
Douglas Gregore60e5d32008-11-06 22:13:31 +00001824 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
1825
1826 // C++ [over.oper]p5:
1827 // The allocation and deallocation functions, operator new,
1828 // operator new[], operator delete and operator delete[], are
1829 // described completely in 3.7.3. The attributes and restrictions
1830 // found in the rest of this subclause do not apply to them unless
1831 // explicitly stated in 3.7.3.
1832 // FIXME: Write a separate routine for checking this. For now, just
1833 // allow it.
1834 if (Op == OO_New || Op == OO_Array_New ||
1835 Op == OO_Delete || Op == OO_Array_Delete)
1836 return false;
1837
1838 // C++ [over.oper]p6:
1839 // An operator function shall either be a non-static member
1840 // function or be a non-member function and have at least one
1841 // parameter whose type is a class, a reference to a class, an
1842 // enumeration, or a reference to an enumeration.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001843 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
1844 if (MethodDecl->isStatic())
1845 return Diag(FnDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00001846 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00001847 } else {
1848 bool ClassOrEnumParam = false;
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001849 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
1850 ParamEnd = FnDecl->param_end();
1851 Param != ParamEnd; ++Param) {
1852 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregore60e5d32008-11-06 22:13:31 +00001853 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
1854 ClassOrEnumParam = true;
1855 break;
1856 }
1857 }
1858
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001859 if (!ClassOrEnumParam)
1860 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00001861 diag::err_operator_overload_needs_class_or_enum)
Chris Lattner271d4c22008-11-24 05:29:24 +00001862 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00001863 }
1864
1865 // C++ [over.oper]p8:
1866 // An operator function cannot have default arguments (8.3.6),
1867 // except where explicitly stated below.
1868 //
1869 // Only the function-call operator allows default arguments
1870 // (C++ [over.call]p1).
1871 if (Op != OO_Call) {
1872 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
1873 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001874 if (Expr *DefArg = (*Param)->getDefaultArg())
1875 return Diag((*Param)->getLocation(),
Chris Lattner77d52da2008-11-20 06:06:08 +00001876 diag::err_operator_overload_default_arg)
Chris Lattner271d4c22008-11-24 05:29:24 +00001877 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregore60e5d32008-11-06 22:13:31 +00001878 }
1879 }
1880
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001881 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
1882 { false, false, false }
1883#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1884 , { Unary, Binary, MemberOnly }
1885#include "clang/Basic/OperatorKinds.def"
1886 };
Douglas Gregore60e5d32008-11-06 22:13:31 +00001887
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001888 bool CanBeUnaryOperator = OperatorUses[Op][0];
1889 bool CanBeBinaryOperator = OperatorUses[Op][1];
1890 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregore60e5d32008-11-06 22:13:31 +00001891
1892 // C++ [over.oper]p8:
1893 // [...] Operator functions cannot have more or fewer parameters
1894 // than the number required for the corresponding operator, as
1895 // described in the rest of this subclause.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001896 unsigned NumParams = FnDecl->getNumParams()
1897 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregore60e5d32008-11-06 22:13:31 +00001898 if (Op != OO_Call &&
1899 ((NumParams == 1 && !CanBeUnaryOperator) ||
1900 (NumParams == 2 && !CanBeBinaryOperator) ||
1901 (NumParams < 1) || (NumParams > 2))) {
1902 // We have the wrong number of parameters.
Chris Lattnerbb002332008-11-21 07:57:12 +00001903 unsigned ErrorKind;
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001904 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00001905 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001906 } else if (CanBeUnaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00001907 ErrorKind = 0; // 0 -> unary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001908 } else {
Chris Lattnera7021ee2008-11-21 07:50:02 +00001909 assert(CanBeBinaryOperator &&
1910 "All non-call overloaded operators are unary or binary!");
Chris Lattnerbb002332008-11-21 07:57:12 +00001911 ErrorKind = 1; // 1 -> binary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001912 }
Douglas Gregore60e5d32008-11-06 22:13:31 +00001913
Chris Lattnerbb002332008-11-21 07:57:12 +00001914 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattner271d4c22008-11-24 05:29:24 +00001915 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregore60e5d32008-11-06 22:13:31 +00001916 }
1917
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001918 // Overloaded operators other than operator() cannot be variadic.
1919 if (Op != OO_Call &&
1920 FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00001921 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattner271d4c22008-11-24 05:29:24 +00001922 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00001923 }
1924
1925 // Some operators must be non-static member functions.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001926 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
1927 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00001928 diag::err_operator_overload_must_be_member)
Chris Lattner271d4c22008-11-24 05:29:24 +00001929 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00001930 }
1931
1932 // C++ [over.inc]p1:
1933 // The user-defined function called operator++ implements the
1934 // prefix and postfix ++ operator. If this function is a member
1935 // function with no parameters, or a non-member function with one
1936 // parameter of class or enumeration type, it defines the prefix
1937 // increment operator ++ for objects of that type. If the function
1938 // is a member function with one parameter (which shall be of type
1939 // int) or a non-member function with two parameters (the second
1940 // of which shall be of type int), it defines the postfix
1941 // increment operator ++ for objects of that type.
1942 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
1943 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
1944 bool ParamIsInt = false;
1945 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
1946 ParamIsInt = BT->getKind() == BuiltinType::Int;
1947
Chris Lattnera7021ee2008-11-21 07:50:02 +00001948 if (!ParamIsInt)
1949 return Diag(LastParam->getLocation(),
1950 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001951 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregore60e5d32008-11-06 22:13:31 +00001952 }
1953
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001954 return false;
Douglas Gregore60e5d32008-11-06 22:13:31 +00001955}
Chris Lattnerf58d52b2008-12-17 07:09:26 +00001956
Chris Lattner9bb9abf2008-12-17 07:13:27 +00001957/// ActOnLinkageSpec - Parsed a C++ linkage-specification that
1958/// contained braces. Lang/StrSize contains the language string that
1959/// was parsed at location Loc. Decls/NumDecls provides the
1960/// declarations parsed inside the linkage specification.
1961Sema::DeclTy *Sema::ActOnLinkageSpec(SourceLocation Loc,
1962 SourceLocation LBrace,
1963 SourceLocation RBrace,
1964 const char *Lang,
1965 unsigned StrSize,
1966 DeclTy **Decls, unsigned NumDecls) {
1967 LinkageSpecDecl::LanguageIDs Language;
1968 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1969 Language = LinkageSpecDecl::lang_c;
1970 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1971 Language = LinkageSpecDecl::lang_cxx;
1972 else {
1973 Diag(Loc, diag::err_bad_language);
1974 return 0;
1975 }
1976
1977 // FIXME: Add all the various semantics of linkage specifications
1978
1979 return LinkageSpecDecl::Create(Context, Loc, Language,
1980 (Decl **)Decls, NumDecls);
1981}
1982
Chris Lattnerf58d52b2008-12-17 07:09:26 +00001983Sema::DeclTy *Sema::ActOnLinkageSpec(SourceLocation Loc,
1984 const char *Lang, unsigned StrSize,
1985 DeclTy *D) {
1986 LinkageSpecDecl::LanguageIDs Language;
1987 Decl *dcl = static_cast<Decl *>(D);
1988 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1989 Language = LinkageSpecDecl::lang_c;
1990 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1991 Language = LinkageSpecDecl::lang_cxx;
1992 else {
1993 Diag(Loc, diag::err_bad_language);
1994 return 0;
1995 }
1996
1997 // FIXME: Add all the various semantics of linkage specifications
1998 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
1999}
2000
Sebastian Redl743c8162008-12-22 19:15:10 +00002001/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2002/// handler.
2003Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D)
2004{
2005 QualType ExDeclType = GetTypeForDeclarator(D, S);
2006 SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin();
2007
2008 bool Invalid = false;
2009
2010 // Arrays and functions decay.
2011 if (ExDeclType->isArrayType())
2012 ExDeclType = Context.getArrayDecayedType(ExDeclType);
2013 else if (ExDeclType->isFunctionType())
2014 ExDeclType = Context.getPointerType(ExDeclType);
2015
2016 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2017 // The exception-declaration shall not denote a pointer or reference to an
2018 // incomplete type, other than [cv] void*.
2019 QualType BaseType = ExDeclType;
2020 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
2021 if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2022 BaseType = Ptr->getPointeeType();
2023 Mode = 1;
2024 } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2025 BaseType = Ref->getPointeeType();
2026 Mode = 2;
2027 }
2028 if ((Mode == 0 || !BaseType->isVoidType()) && BaseType->isIncompleteType()) {
2029 Invalid = true;
2030 Diag(Begin, diag::err_catch_incomplete) << BaseType << Mode;
2031 }
2032
Sebastian Redl237116b2008-12-22 21:35:02 +00002033 // FIXME: Need to test for ability to copy-construct and destroy the
2034 // exception variable.
2035 // FIXME: Need to check for abstract classes.
2036
Sebastian Redl743c8162008-12-22 19:15:10 +00002037 IdentifierInfo *II = D.getIdentifier();
2038 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
2039 // The scope should be freshly made just for us. There is just no way
2040 // it contains any previous declaration.
2041 assert(!S->isDeclScope(PrevDecl));
2042 if (PrevDecl->isTemplateParameter()) {
2043 // Maybe we will complain about the shadowed template parameter.
2044 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2045
2046 }
2047 }
2048
2049 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
2050 II, ExDeclType, VarDecl::None, 0, Begin);
2051 if (D.getInvalidType() || Invalid)
2052 ExDecl->setInvalidDecl();
2053
2054 if (D.getCXXScopeSpec().isSet()) {
2055 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2056 << D.getCXXScopeSpec().getRange();
2057 ExDecl->setInvalidDecl();
2058 }
2059
2060 // Add the exception declaration into this scope.
2061 S->AddDecl(ExDecl);
2062 if (II)
2063 IdResolver.AddDecl(ExDecl);
2064
2065 ProcessDeclAttributes(ExDecl, D);
2066 return ExDecl;
2067}