blob: fe7efbae5f8b1546eb7cc39dfcf8fde50a574d1f [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"
Chris Lattner97316c02008-04-10 02:22:51 +000023#include "llvm/Support/Compiler.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000024#include <algorithm> // for std::equal
Douglas Gregorabed2172008-10-22 17:49:05 +000025#include <map>
Chris Lattnerac7b83a2008-04-08 05:04:30 +000026
27using namespace clang;
28
Chris Lattner97316c02008-04-10 02:22:51 +000029//===----------------------------------------------------------------------===//
30// CheckDefaultArgumentVisitor
31//===----------------------------------------------------------------------===//
32
Chris Lattnerb1856db2008-04-12 23:52:44 +000033namespace {
34 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
35 /// the default argument of a parameter to determine whether it
36 /// contains any ill-formed subexpressions. For example, this will
37 /// diagnose the use of local variables or parameters within the
38 /// default argument expression.
39 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000040 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb1856db2008-04-12 23:52:44 +000041 Expr *DefaultArg;
42 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000043
Chris Lattnerb1856db2008-04-12 23:52:44 +000044 public:
45 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
46 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000047
Chris Lattnerb1856db2008-04-12 23:52:44 +000048 bool VisitExpr(Expr *Node);
49 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregora5b022a2008-11-04 14:32:21 +000050 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb1856db2008-04-12 23:52:44 +000051 };
Chris Lattner97316c02008-04-10 02:22:51 +000052
Chris Lattnerb1856db2008-04-12 23:52:44 +000053 /// VisitExpr - Visit all of the children of this expression.
54 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
55 bool IsInvalid = false;
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000056 for (Stmt::child_iterator I = Node->child_begin(),
57 E = Node->child_end(); I != E; ++I)
58 IsInvalid |= Visit(*I);
Chris Lattnerb1856db2008-04-12 23:52:44 +000059 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000060 }
61
Chris Lattnerb1856db2008-04-12 23:52:44 +000062 /// VisitDeclRefExpr - Visit a reference to a declaration, to
63 /// determine whether this declaration can be used in the default
64 /// argument expression.
65 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregord2baafd2008-10-21 16:13:35 +000066 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb1856db2008-04-12 23:52:44 +000067 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
68 // C++ [dcl.fct.default]p9
69 // Default arguments are evaluated each time the function is
70 // called. The order of evaluation of function arguments is
71 // unspecified. Consequently, parameters of a function shall not
72 // be used in default argument expressions, even if they are not
73 // evaluated. Parameters of a function declared before a default
74 // argument expression are in scope and can hide namespace and
75 // class member names.
76 return S->Diag(DRE->getSourceRange().getBegin(),
77 diag::err_param_default_argument_references_param,
78 Param->getName(), DefaultArg->getSourceRange());
Steve Naroff72a6ebc2008-04-15 22:42:06 +000079 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000080 // C++ [dcl.fct.default]p7
81 // Local variables shall not be used in default argument
82 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000083 if (VDecl->isBlockVarDecl())
84 return S->Diag(DRE->getSourceRange().getBegin(),
85 diag::err_param_default_argument_references_local,
86 VDecl->getName(), DefaultArg->getSourceRange());
Chris Lattnerb1856db2008-04-12 23:52:44 +000087 }
Chris Lattner97316c02008-04-10 02:22:51 +000088
Douglas Gregor3c246952008-11-04 13:41:56 +000089 return false;
90 }
Chris Lattnerb1856db2008-04-12 23:52:44 +000091
Douglas Gregora5b022a2008-11-04 14:32:21 +000092 /// VisitCXXThisExpr - Visit a C++ "this" expression.
93 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
94 // C++ [dcl.fct.default]p8:
95 // The keyword this shall not be used in a default argument of a
96 // member function.
97 return S->Diag(ThisE->getSourceRange().getBegin(),
98 diag::err_param_default_argument_references_this,
99 ThisE->getSourceRange());
Chris Lattnerb1856db2008-04-12 23:52:44 +0000100 }
Chris Lattner97316c02008-04-10 02:22:51 +0000101}
102
103/// ActOnParamDefaultArgument - Check whether the default argument
104/// provided for a function parameter is well-formed. If so, attach it
105/// to the parameter declaration.
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000106void
107Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
108 ExprTy *defarg) {
109 ParmVarDecl *Param = (ParmVarDecl *)param;
110 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
111 QualType ParamType = Param->getType();
112
113 // Default arguments are only permitted in C++
114 if (!getLangOptions().CPlusPlus) {
115 Diag(EqualLoc, diag::err_param_default_argument,
116 DefaultArg->getSourceRange());
117 return;
118 }
119
120 // C++ [dcl.fct.default]p5
121 // A default argument expression is implicitly converted (clause
122 // 4) to the parameter type. The default argument expression has
123 // the same semantic constraints as the initializer expression in
124 // a declaration of a variable of the parameter type, using the
125 // copy-initialization semantics (8.5).
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000126 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor58c428c2008-11-04 13:57:51 +0000127 bool DefaultInitFailed = PerformCopyInitialization(DefaultArgPtr, ParamType,
128 "in default argument");
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000129 if (DefaultArgPtr != DefaultArg.get()) {
130 DefaultArg.take();
131 DefaultArg.reset(DefaultArgPtr);
132 }
Douglas Gregor58c428c2008-11-04 13:57:51 +0000133 if (DefaultInitFailed) {
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000134 return;
135 }
136
Chris Lattner97316c02008-04-10 02:22:51 +0000137 // Check that the default argument is well-formed
Chris Lattnerb1856db2008-04-12 23:52:44 +0000138 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Chris Lattner97316c02008-04-10 02:22:51 +0000139 if (DefaultArgChecker.Visit(DefaultArg.get()))
140 return;
141
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(DefaultArg.take());
144}
145
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000146/// CheckExtraCXXDefaultArguments - Check for any extra default
147/// arguments in the declarator, which is not a function declaration
148/// or definition and therefore is not permitted to have default
149/// arguments. This routine should be invoked for every declarator
150/// that is not a function declaration or definition.
151void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
152 // C++ [dcl.fct.default]p3
153 // A default argument expression shall be specified only in the
154 // parameter-declaration-clause of a function declaration or in a
155 // template-parameter (14.1). It shall not be specified for a
156 // parameter pack. If it is specified in a
157 // parameter-declaration-clause, it shall not occur within a
158 // declarator or abstract-declarator of a parameter-declaration.
159 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
160 DeclaratorChunk &chunk = D.getTypeObject(i);
161 if (chunk.Kind == DeclaratorChunk::Function) {
162 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
163 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
164 if (Param->getDefaultArg()) {
165 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc,
166 Param->getDefaultArg()->getSourceRange());
167 Param->setDefaultArg(0);
168 }
169 }
170 }
171 }
172}
173
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000174// MergeCXXFunctionDecl - Merge two declarations of the same C++
175// function, once we already know that they have the same
176// type. Subroutine of MergeFunctionDecl.
177FunctionDecl *
178Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
179 // C++ [dcl.fct.default]p4:
180 //
181 // For non-template functions, default arguments can be added in
182 // later declarations of a function in the same
183 // scope. Declarations in different scopes have completely
184 // distinct sets of default arguments. That is, declarations in
185 // inner scopes do not acquire default arguments from
186 // declarations in outer scopes, and vice versa. In a given
187 // function declaration, all parameters subsequent to a
188 // parameter with a default argument shall have default
189 // arguments supplied in this or previous declarations. A
190 // default argument shall not be redefined by a later
191 // declaration (not even to the same value).
192 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
193 ParmVarDecl *OldParam = Old->getParamDecl(p);
194 ParmVarDecl *NewParam = New->getParamDecl(p);
195
196 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
197 Diag(NewParam->getLocation(),
198 diag::err_param_default_argument_redefinition,
199 NewParam->getDefaultArg()->getSourceRange());
200 Diag(OldParam->getLocation(), diag::err_previous_definition);
201 } else if (OldParam->getDefaultArg()) {
202 // Merge the old default argument into the new parameter
203 NewParam->setDefaultArg(OldParam->getDefaultArg());
204 }
205 }
206
207 return New;
208}
209
210/// CheckCXXDefaultArguments - Verify that the default arguments for a
211/// function declaration are well-formed according to C++
212/// [dcl.fct.default].
213void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
214 unsigned NumParams = FD->getNumParams();
215 unsigned p;
216
217 // Find first parameter with a default argument
218 for (p = 0; p < NumParams; ++p) {
219 ParmVarDecl *Param = FD->getParamDecl(p);
220 if (Param->getDefaultArg())
221 break;
222 }
223
224 // C++ [dcl.fct.default]p4:
225 // In a given function declaration, all parameters
226 // subsequent to a parameter with a default argument shall
227 // have default arguments supplied in this or previous
228 // declarations. A default argument shall not be redefined
229 // by a later declaration (not even to the same value).
230 unsigned LastMissingDefaultArg = 0;
231 for(; p < NumParams; ++p) {
232 ParmVarDecl *Param = FD->getParamDecl(p);
233 if (!Param->getDefaultArg()) {
234 if (Param->getIdentifier())
235 Diag(Param->getLocation(),
236 diag::err_param_default_argument_missing_name,
237 Param->getIdentifier()->getName());
238 else
239 Diag(Param->getLocation(),
240 diag::err_param_default_argument_missing);
241
242 LastMissingDefaultArg = p;
243 }
244 }
245
246 if (LastMissingDefaultArg > 0) {
247 // Some default arguments were missing. Clear out all of the
248 // default arguments up to (and including) the last missing
249 // default argument, so that we leave the function parameters
250 // in a semantically valid state.
251 for (p = 0; p <= LastMissingDefaultArg; ++p) {
252 ParmVarDecl *Param = FD->getParamDecl(p);
253 if (Param->getDefaultArg()) {
254 delete Param->getDefaultArg();
255 Param->setDefaultArg(0);
256 }
257 }
258 }
259}
Douglas Gregorec93f442008-04-13 21:30:24 +0000260
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000261/// isCurrentClassName - Determine whether the identifier II is the
262/// name of the class type currently being defined. In the case of
263/// nested classes, this will only return true if II is the name of
264/// the innermost class.
265bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *) {
266 if (CXXRecordDecl *CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext))
267 return &II == CurDecl->getIdentifier();
268 else
269 return false;
270}
271
Douglas Gregorec93f442008-04-13 21:30:24 +0000272/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
273/// one entry in the base class list of a class specifier, for
274/// example:
275/// class foo : public bar, virtual private baz {
276/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorabed2172008-10-22 17:49:05 +0000277Sema::BaseResult
278Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
279 bool Virtual, AccessSpecifier Access,
280 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000281 RecordDecl *Decl = (RecordDecl*)classdecl;
282 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
283
284 // Base specifiers must be record types.
285 if (!BaseType->isRecordType()) {
286 Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000287 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000288 }
289
290 // C++ [class.union]p1:
291 // A union shall not be used as a base class.
292 if (BaseType->isUnionType()) {
293 Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000294 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000295 }
296
297 // C++ [class.union]p1:
298 // A union shall not have base classes.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000299 if (Decl->isUnion()) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000300 Diag(Decl->getLocation(), diag::err_base_clause_on_union,
301 SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000302 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000303 }
304
305 // C++ [class.derived]p2:
306 // The class-name in a base-specifier shall not be an incompletely
307 // defined class.
308 if (BaseType->isIncompleteType()) {
309 Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000310 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000311 }
312
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000313 // If the base class is polymorphic, the new one is, too.
314 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
315 assert(BaseDecl && "Record type has no declaration");
316 BaseDecl = BaseDecl->getDefinition(Context);
317 assert(BaseDecl && "Base type is not incomplete, but has no definition");
318 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic()) {
319 cast<CXXRecordDecl>(Decl)->setPolymorphic(true);
320 }
321
Douglas Gregorabed2172008-10-22 17:49:05 +0000322 // Create the base specifier.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000323 return new CXXBaseSpecifier(SpecifierRange, Virtual,
324 BaseType->isClassType(), Access, BaseType);
Douglas Gregorabed2172008-10-22 17:49:05 +0000325}
Douglas Gregorec93f442008-04-13 21:30:24 +0000326
Douglas Gregorabed2172008-10-22 17:49:05 +0000327/// ActOnBaseSpecifiers - Attach the given base specifiers to the
328/// class, after checking whether there are any duplicate base
329/// classes.
330void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
331 unsigned NumBases) {
332 if (NumBases == 0)
333 return;
334
335 // Used to keep track of which base types we have already seen, so
336 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000337 // that the key is always the unqualified canonical type of the base
338 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000339 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
340
341 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000342 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
343 unsigned NumGoodBases = 0;
344 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000345 QualType NewBaseType
Douglas Gregor4fd85902008-10-23 18:13:27 +0000346 = Context.getCanonicalType(BaseSpecs[idx]->getType());
347 NewBaseType = NewBaseType.getUnqualifiedType();
348
Douglas Gregorabed2172008-10-22 17:49:05 +0000349 if (KnownBaseTypes[NewBaseType]) {
350 // C++ [class.mi]p3:
351 // A class shall not be specified as a direct base class of a
352 // derived class more than once.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000353 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Douglas Gregorabed2172008-10-22 17:49:05 +0000354 diag::err_duplicate_base_class,
355 KnownBaseTypes[NewBaseType]->getType().getAsString(),
Douglas Gregor4fd85902008-10-23 18:13:27 +0000356 BaseSpecs[idx]->getSourceRange());
357
358 // Delete the duplicate base class specifier; we're going to
359 // overwrite its pointer later.
360 delete BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000361 } else {
362 // Okay, add this new base class.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000363 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
364 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000365 }
366 }
367
368 // Attach the remaining base class specifiers to the derived class.
369 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000370 Decl->setBases(BaseSpecs, NumGoodBases);
371
372 // Delete the remaining (good) base class specifiers, since their
373 // data has been copied into the CXXRecordDecl.
374 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
375 delete BaseSpecs[idx];
Douglas Gregorec93f442008-04-13 21:30:24 +0000376}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000377
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000378//===----------------------------------------------------------------------===//
379// C++ class member Handling
380//===----------------------------------------------------------------------===//
381
382/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
383/// definition, when on C++.
384void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000385 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
386 PushDeclContext(Dcl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000387 FieldCollector->StartClass();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000388
389 if (Dcl->getIdentifier()) {
390 // C++ [class]p2:
391 // [...] The class-name is also inserted into the scope of the
392 // class itself; this is known as the injected-class-name. For
393 // purposes of access checking, the injected-class-name is treated
394 // as if it were a public member name.
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000395 // FIXME: this should probably have its own kind of type node.
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000396 TypedefDecl *InjectedClassName
397 = TypedefDecl::Create(Context, Dcl, LBrace, Dcl->getIdentifier(),
398 Context.getTypeDeclType(Dcl), /*PrevDecl=*/0);
399 PushOnScopeChains(InjectedClassName, S);
400 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000401}
402
403/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
404/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
405/// bitfield width if there is one and 'InitExpr' specifies the initializer if
406/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
407/// declarators on it.
408///
409/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
410/// an instance field is declared, a new CXXFieldDecl is created but the method
411/// does *not* return it; it returns LastInGroup instead. The other C++ members
412/// (which are all ScopedDecls) are returned after appending them to
413/// LastInGroup.
414Sema::DeclTy *
415Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
416 ExprTy *BW, ExprTy *InitExpr,
417 DeclTy *LastInGroup) {
418 const DeclSpec &DS = D.getDeclSpec();
419 IdentifierInfo *II = D.getIdentifier();
420 Expr *BitWidth = static_cast<Expr*>(BW);
421 Expr *Init = static_cast<Expr*>(InitExpr);
422 SourceLocation Loc = D.getIdentifierLoc();
423
424 // C++ 9.2p6: A member shall not be declared to have automatic storage
425 // duration (auto, register) or with the extern storage-class-specifier.
426 switch (DS.getStorageClassSpec()) {
427 case DeclSpec::SCS_unspecified:
428 case DeclSpec::SCS_typedef:
429 case DeclSpec::SCS_static:
430 // FALL THROUGH.
431 break;
432 default:
433 if (DS.getStorageClassSpecLoc().isValid())
434 Diag(DS.getStorageClassSpecLoc(),
435 diag::err_storageclass_invalid_for_member);
436 else
437 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
438 D.getMutableDeclSpec().ClearStorageClassSpecs();
439 }
440
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000441 bool isFunc = D.isFunctionDeclarator();
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000442 if (!isFunc &&
443 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
444 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000445 // Check also for this case:
446 //
447 // typedef int f();
448 // f a;
449 //
450 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
451 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
452 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000453
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000454 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000455 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000456
457 Decl *Member;
458 bool InvalidDecl = false;
459
460 if (isInstField)
461 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
462 else
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000463 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000464
465 if (!Member) return LastInGroup;
466
Sanjiv Guptafa451432008-10-31 09:52:39 +0000467 assert((II || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000468
469 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
470 // specific methods. Use a wrapper class that can be used with all C++ class
471 // member decls.
472 CXXClassMemberWrapper(Member).setAccess(AS);
473
Douglas Gregor15e04622008-11-05 16:20:31 +0000474 // C++ [dcl.init.aggr]p1:
475 // An aggregate is an array or a class (clause 9) with [...] no
476 // private or protected non-static data members (clause 11).
477 if (isInstField && (AS == AS_private || AS == AS_protected))
478 cast<CXXRecordDecl>(CurContext)->setAggregate(false);
479
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000480 if (DS.isVirtualSpecified()) {
481 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
482 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
483 InvalidDecl = true;
484 } else {
485 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
486 CurClass->setAggregate(false);
487 CurClass->setPolymorphic(true);
488 }
489 }
Douglas Gregor15e04622008-11-05 16:20:31 +0000490
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000491 if (BitWidth) {
492 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
493 // constant-expression be a value equal to zero.
494 // FIXME: Check this.
495
496 if (D.isFunctionDeclarator()) {
497 // FIXME: Emit diagnostic about only constructors taking base initializers
498 // or something similar, when constructor support is in place.
499 Diag(Loc, diag::err_not_bitfield_type,
500 II->getName(), BitWidth->getSourceRange());
501 InvalidDecl = true;
502
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000503 } else if (isInstField) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000504 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000505 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000506 Diag(Loc, diag::err_not_integral_type_bitfield,
507 II->getName(), BitWidth->getSourceRange());
508 InvalidDecl = true;
509 }
510
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000511 } else if (isa<FunctionDecl>(Member)) {
512 // A function typedef ("typedef int f(); f a;").
513 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
514 Diag(Loc, diag::err_not_integral_type_bitfield,
515 II->getName(), BitWidth->getSourceRange());
516 InvalidDecl = true;
517
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000518 } else if (isa<TypedefDecl>(Member)) {
519 // "cannot declare 'A' to be a bit-field type"
520 Diag(Loc, diag::err_not_bitfield_type, II->getName(),
521 BitWidth->getSourceRange());
522 InvalidDecl = true;
523
524 } else {
525 assert(isa<CXXClassVarDecl>(Member) &&
526 "Didn't we cover all member kinds?");
527 // C++ 9.6p3: A bit-field shall not be a static member.
528 // "static member 'A' cannot be a bit-field"
529 Diag(Loc, diag::err_static_not_bitfield, II->getName(),
530 BitWidth->getSourceRange());
531 InvalidDecl = true;
532 }
533 }
534
535 if (Init) {
536 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
537 // if it declares a static member of const integral or const enumeration
538 // type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000539 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
540 // ...static member of...
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000541 CVD->setInit(Init);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000542 // ...const integral or const enumeration type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000543 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
544 CVD->getType()->isIntegralType()) {
545 // constant-initializer
546 if (CheckForConstantInitializer(Init, CVD->getType()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000547 InvalidDecl = true;
548
549 } else {
550 // not const integral.
551 Diag(Loc, diag::err_member_initialization,
552 II->getName(), Init->getSourceRange());
553 InvalidDecl = true;
554 }
555
556 } else {
557 // not static member.
558 Diag(Loc, diag::err_member_initialization,
559 II->getName(), Init->getSourceRange());
560 InvalidDecl = true;
561 }
562 }
563
564 if (InvalidDecl)
565 Member->setInvalidDecl();
566
567 if (isInstField) {
568 FieldCollector->Add(cast<CXXFieldDecl>(Member));
569 return LastInGroup;
570 }
571 return Member;
572}
573
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000574/// ActOnMemInitializer - Handle a C++ member initializer.
575Sema::MemInitResult
576Sema::ActOnMemInitializer(DeclTy *ConstructorD,
577 Scope *S,
578 IdentifierInfo *MemberOrBase,
579 SourceLocation IdLoc,
580 SourceLocation LParenLoc,
581 ExprTy **Args, unsigned NumArgs,
582 SourceLocation *CommaLocs,
583 SourceLocation RParenLoc) {
584 CXXConstructorDecl *Constructor
585 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
586 if (!Constructor) {
587 // The user wrote a constructor initializer on a function that is
588 // not a C++ constructor. Ignore the error for now, because we may
589 // have more member initializers coming; we'll diagnose it just
590 // once in ActOnMemInitializers.
591 return true;
592 }
593
594 CXXRecordDecl *ClassDecl = Constructor->getParent();
595
596 // C++ [class.base.init]p2:
597 // Names in a mem-initializer-id are looked up in the scope of the
598 // constructor’s class and, if not found in that scope, are looked
599 // up in the scope containing the constructor’s
600 // definition. [Note: if the constructor’s class contains a member
601 // with the same name as a direct or virtual base class of the
602 // class, a mem-initializer-id naming the member or base class and
603 // composed of a single identifier refers to the class member. A
604 // mem-initializer-id for the hidden base class may be specified
605 // using a qualified name. ]
606 // Look for a member, first.
607 CXXFieldDecl *Member = ClassDecl->getMember(MemberOrBase);
608
609 // FIXME: Handle members of an anonymous union.
610
611 if (Member) {
612 // FIXME: Perform direct initialization of the member.
613 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
614 }
615
616 // It didn't name a member, so see if it names a class.
617 TypeTy *BaseTy = isTypeName(*MemberOrBase, S);
618 if (!BaseTy)
619 return Diag(IdLoc, diag::err_mem_init_not_member_or_class,
620 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
621
622 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
623 if (!BaseType->isRecordType())
624 return Diag(IdLoc, diag::err_base_init_does_not_name_class,
625 BaseType.getAsString(), SourceRange(IdLoc, RParenLoc));
626
627 // C++ [class.base.init]p2:
628 // [...] Unless the mem-initializer-id names a nonstatic data
629 // member of the constructor’s class or a direct or virtual base
630 // of that class, the mem-initializer is ill-formed. A
631 // mem-initializer-list can initialize a base class using any
632 // name that denotes that base class type.
633
634 // First, check for a direct base class.
635 const CXXBaseSpecifier *DirectBaseSpec = 0;
636 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
637 Base != ClassDecl->bases_end(); ++Base) {
638 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
639 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
640 // We found a direct base of this type. That's what we're
641 // initializing.
642 DirectBaseSpec = &*Base;
643 break;
644 }
645 }
646
647 // Check for a virtual base class.
648 // FIXME: We might be able to short-circuit this if we know in
649 // advance that there are no virtual bases.
650 const CXXBaseSpecifier *VirtualBaseSpec = 0;
651 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
652 // We haven't found a base yet; search the class hierarchy for a
653 // virtual base class.
654 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
655 /*DetectVirtual=*/false);
656 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
657 for (BasePaths::paths_iterator Path = Paths.begin();
658 Path != Paths.end(); ++Path) {
659 if (Path->back().Base->isVirtual()) {
660 VirtualBaseSpec = Path->back().Base;
661 break;
662 }
663 }
664 }
665 }
666
667 // C++ [base.class.init]p2:
668 // If a mem-initializer-id is ambiguous because it designates both
669 // a direct non-virtual base class and an inherited virtual base
670 // class, the mem-initializer is ill-formed.
671 if (DirectBaseSpec && VirtualBaseSpec)
672 return Diag(IdLoc, diag::err_base_init_direct_and_virtual,
673 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
674
675 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
676}
677
678
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000679void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
680 DeclTy *TagDecl,
681 SourceLocation LBrac,
682 SourceLocation RBrac) {
683 ActOnFields(S, RLoc, TagDecl,
684 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +0000685 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000686}
687
Douglas Gregore640ab62008-11-03 17:51:48 +0000688/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
689/// special functions, such as the default constructor, copy
690/// constructor, or destructor, to the given C++ class (C++
691/// [special]p1). This routine can only be executed just before the
692/// definition of the class is complete.
693void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
694 if (!ClassDecl->hasUserDeclaredConstructor()) {
695 // C++ [class.ctor]p5:
696 // A default constructor for a class X is a constructor of class X
697 // that can be called without an argument. If there is no
698 // user-declared constructor for class X, a default constructor is
699 // implicitly declared. An implicitly-declared default constructor
700 // is an inline public member of its class.
701 CXXConstructorDecl *DefaultCon =
702 CXXConstructorDecl::Create(Context, ClassDecl,
703 ClassDecl->getLocation(),
704 ClassDecl->getIdentifier(),
705 Context.getFunctionType(Context.VoidTy,
706 0, 0, false, 0),
707 /*isExplicit=*/false,
708 /*isInline=*/true,
709 /*isImplicitlyDeclared=*/true);
710 DefaultCon->setAccess(AS_public);
711 ClassDecl->addConstructor(Context, DefaultCon);
712 }
713
714 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
715 // C++ [class.copy]p4:
716 // If the class definition does not explicitly declare a copy
717 // constructor, one is declared implicitly.
718
719 // C++ [class.copy]p5:
720 // The implicitly-declared copy constructor for a class X will
721 // have the form
722 //
723 // X::X(const X&)
724 //
725 // if
726 bool HasConstCopyConstructor = true;
727
728 // -- each direct or virtual base class B of X has a copy
729 // constructor whose first parameter is of type const B& or
730 // const volatile B&, and
731 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
732 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
733 const CXXRecordDecl *BaseClassDecl
734 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
735 HasConstCopyConstructor
736 = BaseClassDecl->hasConstCopyConstructor(Context);
737 }
738
739 // -- for all the nonstatic data members of X that are of a
740 // class type M (or array thereof), each such class type
741 // has a copy constructor whose first parameter is of type
742 // const M& or const volatile M&.
743 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
744 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
745 QualType FieldType = (*Field)->getType();
746 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
747 FieldType = Array->getElementType();
748 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
749 const CXXRecordDecl *FieldClassDecl
750 = cast<CXXRecordDecl>(FieldClassType->getDecl());
751 HasConstCopyConstructor
752 = FieldClassDecl->hasConstCopyConstructor(Context);
753 }
754 }
755
756 // Otherwise, the implicitly declared copy constructor will have
757 // the form
758 //
759 // X::X(X&)
760 QualType ArgType = Context.getTypeDeclType(ClassDecl);
761 if (HasConstCopyConstructor)
762 ArgType = ArgType.withConst();
763 ArgType = Context.getReferenceType(ArgType);
764
765 // An implicitly-declared copy constructor is an inline public
766 // member of its class.
767 CXXConstructorDecl *CopyConstructor
768 = CXXConstructorDecl::Create(Context, ClassDecl,
769 ClassDecl->getLocation(),
770 ClassDecl->getIdentifier(),
771 Context.getFunctionType(Context.VoidTy,
772 &ArgType, 1,
773 false, 0),
774 /*isExplicit=*/false,
775 /*isInline=*/true,
776 /*isImplicitlyDeclared=*/true);
777 CopyConstructor->setAccess(AS_public);
778
779 // Add the parameter to the constructor.
780 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
781 ClassDecl->getLocation(),
782 /*IdentifierInfo=*/0,
783 ArgType, VarDecl::None, 0, 0);
784 CopyConstructor->setParams(&FromParam, 1);
785
786 ClassDecl->addConstructor(Context, CopyConstructor);
787 }
788
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000789 if (!ClassDecl->getDestructor()) {
790 // C++ [class.dtor]p2:
791 // If a class has no user-declared destructor, a destructor is
792 // declared implicitly. An implicitly-declared destructor is an
793 // inline public member of its class.
794 std::string DestructorName = "~";
795 DestructorName += ClassDecl->getName();
796 CXXDestructorDecl *Destructor
797 = CXXDestructorDecl::Create(Context, ClassDecl,
798 ClassDecl->getLocation(),
799 &PP.getIdentifierTable().get(DestructorName),
800 Context.getFunctionType(Context.VoidTy,
801 0, 0, false, 0),
802 /*isInline=*/true,
803 /*isImplicitlyDeclared=*/true);
804 Destructor->setAccess(AS_public);
805 ClassDecl->setDestructor(Destructor);
806 }
807
Douglas Gregore640ab62008-11-03 17:51:48 +0000808 // FIXME: Implicit copy assignment operator
809}
810
Argiris Kirtzidis448b4e42008-08-09 00:39:29 +0000811void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000812 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000813 FieldCollector->FinishClass();
Douglas Gregore640ab62008-11-03 17:51:48 +0000814 AddImplicitlyDeclaredMembersToClass(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000815 PopDeclContext();
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000816
817 // Everything, including inline method definitions, have been parsed.
818 // Let the consumer know of the new TagDecl definition.
819 Consumer.HandleTagDeclDefinition(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000820}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000821
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000822/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
823/// the well-formednes of the constructor declarator @p D with type @p
824/// R. If there are any errors in the declarator, this routine will
825/// emit diagnostics and return true. Otherwise, it will return
826/// false. Either way, the type @p R will be updated to reflect a
827/// well-formed type for the constructor.
828bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
829 FunctionDecl::StorageClass& SC) {
830 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
831 bool isInvalid = false;
832
833 // C++ [class.ctor]p3:
834 // A constructor shall not be virtual (10.3) or static (9.4). A
835 // constructor can be invoked for a const, volatile or const
836 // volatile object. A constructor shall not be declared const,
837 // volatile, or const volatile (9.3.2).
838 if (isVirtual) {
839 Diag(D.getIdentifierLoc(),
840 diag::err_constructor_cannot_be,
841 "virtual",
842 SourceRange(D.getDeclSpec().getVirtualSpecLoc()),
843 SourceRange(D.getIdentifierLoc()));
844 isInvalid = true;
845 }
846 if (SC == FunctionDecl::Static) {
847 Diag(D.getIdentifierLoc(),
848 diag::err_constructor_cannot_be,
849 "static",
850 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
851 SourceRange(D.getIdentifierLoc()));
852 isInvalid = true;
853 SC = FunctionDecl::None;
854 }
855 if (D.getDeclSpec().hasTypeSpecifier()) {
856 // Constructors don't have return types, but the parser will
857 // happily parse something like:
858 //
859 // class X {
860 // float X(float);
861 // };
862 //
863 // The return type will be eliminated later.
864 Diag(D.getIdentifierLoc(),
865 diag::err_constructor_return_type,
866 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
867 SourceRange(D.getIdentifierLoc()));
868 }
869 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
870 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
871 if (FTI.TypeQuals & QualType::Const)
872 Diag(D.getIdentifierLoc(),
873 diag::err_invalid_qualified_constructor,
874 "const",
875 SourceRange(D.getIdentifierLoc()));
876 if (FTI.TypeQuals & QualType::Volatile)
877 Diag(D.getIdentifierLoc(),
878 diag::err_invalid_qualified_constructor,
879 "volatile",
880 SourceRange(D.getIdentifierLoc()));
881 if (FTI.TypeQuals & QualType::Restrict)
882 Diag(D.getIdentifierLoc(),
883 diag::err_invalid_qualified_constructor,
884 "restrict",
885 SourceRange(D.getIdentifierLoc()));
886 }
887
888 // Rebuild the function type "R" without any type qualifiers (in
889 // case any of the errors above fired) and with "void" as the
890 // return type, since constructors don't have return types. We
891 // *always* have to do this, because GetTypeForDeclarator will
892 // put in a result type of "int" when none was specified.
893 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto();
894 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
895 Proto->getNumArgs(),
896 Proto->isVariadic(),
897 0);
898
899 return isInvalid;
900}
901
902/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
903/// the well-formednes of the destructor declarator @p D with type @p
904/// R. If there are any errors in the declarator, this routine will
905/// emit diagnostics and return true. Otherwise, it will return
906/// false. Either way, the type @p R will be updated to reflect a
907/// well-formed type for the destructor.
908bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
909 FunctionDecl::StorageClass& SC) {
910 bool isInvalid = false;
911
912 // C++ [class.dtor]p1:
913 // [...] A typedef-name that names a class is a class-name
914 // (7.1.3); however, a typedef-name that names a class shall not
915 // be used as the identifier in the declarator for a destructor
916 // declaration.
917 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType();
918 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) {
919 if (TypedefD->getIdentifier() !=
920 cast<CXXRecordDecl>(CurContext)->getIdentifier()) {
921 // FIXME: This would be easier if we could just look at whether
922 // we found the injected-class-name.
923 Diag(D.getIdentifierLoc(),
924 diag::err_destructor_typedef_name,
925 TypedefD->getName());
926 isInvalid = true;
927 }
928 }
929
930 // C++ [class.dtor]p2:
931 // A destructor is used to destroy objects of its class type. A
932 // destructor takes no parameters, and no return type can be
933 // specified for it (not even void). The address of a destructor
934 // shall not be taken. A destructor shall not be static. A
935 // destructor can be invoked for a const, volatile or const
936 // volatile object. A destructor shall not be declared const,
937 // volatile or const volatile (9.3.2).
938 if (SC == FunctionDecl::Static) {
939 Diag(D.getIdentifierLoc(),
940 diag::err_destructor_cannot_be,
941 "static",
942 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
943 SourceRange(D.getIdentifierLoc()));
944 isInvalid = true;
945 SC = FunctionDecl::None;
946 }
947 if (D.getDeclSpec().hasTypeSpecifier()) {
948 // Destructors don't have return types, but the parser will
949 // happily parse something like:
950 //
951 // class X {
952 // float ~X();
953 // };
954 //
955 // The return type will be eliminated later.
956 Diag(D.getIdentifierLoc(),
957 diag::err_destructor_return_type,
958 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
959 SourceRange(D.getIdentifierLoc()));
960 }
961 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
962 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
963 if (FTI.TypeQuals & QualType::Const)
964 Diag(D.getIdentifierLoc(),
965 diag::err_invalid_qualified_destructor,
966 "const",
967 SourceRange(D.getIdentifierLoc()));
968 if (FTI.TypeQuals & QualType::Volatile)
969 Diag(D.getIdentifierLoc(),
970 diag::err_invalid_qualified_destructor,
971 "volatile",
972 SourceRange(D.getIdentifierLoc()));
973 if (FTI.TypeQuals & QualType::Restrict)
974 Diag(D.getIdentifierLoc(),
975 diag::err_invalid_qualified_destructor,
976 "restrict",
977 SourceRange(D.getIdentifierLoc()));
978 }
979
980 // Make sure we don't have any parameters.
981 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
982 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
983
984 // Delete the parameters.
985 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
986 if (FTI.NumArgs) {
987 delete [] FTI.ArgInfo;
988 FTI.NumArgs = 0;
989 FTI.ArgInfo = 0;
990 }
991 }
992
993 // Make sure the destructor isn't variadic.
994 if (R->getAsFunctionTypeProto()->isVariadic())
995 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
996
997 // Rebuild the function type "R" without any type qualifiers or
998 // parameters (in case any of the errors above fired) and with
999 // "void" as the return type, since destructors don't have return
1000 // types. We *always* have to do this, because GetTypeForDeclarator
1001 // will put in a result type of "int" when none was specified.
1002 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1003
1004 return isInvalid;
1005}
1006
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001007/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1008/// well-formednes of the conversion function declarator @p D with
1009/// type @p R. If there are any errors in the declarator, this routine
1010/// will emit diagnostics and return true. Otherwise, it will return
1011/// false. Either way, the type @p R will be updated to reflect a
1012/// well-formed type for the conversion operator.
1013bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1014 FunctionDecl::StorageClass& SC) {
1015 bool isInvalid = false;
1016
1017 // C++ [class.conv.fct]p1:
1018 // Neither parameter types nor return type can be specified. The
1019 // type of a conversion function (8.3.5) is “function taking no
1020 // parameter returning conversion-type-id.”
1021 if (SC == FunctionDecl::Static) {
1022 Diag(D.getIdentifierLoc(),
1023 diag::err_conv_function_not_member,
1024 "static",
1025 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
1026 SourceRange(D.getIdentifierLoc()));
1027 isInvalid = true;
1028 SC = FunctionDecl::None;
1029 }
1030 if (D.getDeclSpec().hasTypeSpecifier()) {
1031 // Conversion functions don't have return types, but the parser will
1032 // happily parse something like:
1033 //
1034 // class X {
1035 // float operator bool();
1036 // };
1037 //
1038 // The return type will be changed later anyway.
1039 Diag(D.getIdentifierLoc(),
1040 diag::err_conv_function_return_type,
1041 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
1042 SourceRange(D.getIdentifierLoc()));
1043 }
1044
1045 // Make sure we don't have any parameters.
1046 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1047 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1048
1049 // Delete the parameters.
1050 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1051 if (FTI.NumArgs) {
1052 delete [] FTI.ArgInfo;
1053 FTI.NumArgs = 0;
1054 FTI.ArgInfo = 0;
1055 }
1056 }
1057
1058 // Make sure the conversion function isn't variadic.
1059 if (R->getAsFunctionTypeProto()->isVariadic())
1060 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1061
1062 // C++ [class.conv.fct]p4:
1063 // The conversion-type-id shall not represent a function type nor
1064 // an array type.
1065 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1066 if (ConvType->isArrayType()) {
1067 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1068 ConvType = Context.getPointerType(ConvType);
1069 } else if (ConvType->isFunctionType()) {
1070 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1071 ConvType = Context.getPointerType(ConvType);
1072 }
1073
1074 // Rebuild the function type "R" without any parameters (in case any
1075 // of the errors above fired) and with the conversion type as the
1076 // return type.
1077 R = Context.getFunctionType(ConvType, 0, 0, false,
1078 R->getAsFunctionTypeProto()->getTypeQuals());
1079
1080 return isInvalid;
1081}
1082
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001083/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete
1084/// the declaration of the given C++ constructor ConDecl that was
1085/// built from declarator D. This routine is responsible for checking
1086/// that the newly-created constructor declaration is well-formed and
1087/// for recording it in the C++ class. Example:
1088///
1089/// @code
1090/// class X {
1091/// X(); // X::X() will be the ConDecl.
1092/// };
1093/// @endcode
1094Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) {
1095 assert(ConDecl && "Expected to receive a constructor declaration");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001096
1097 // Check default arguments on the constructor
1098 CheckCXXDefaultArguments(ConDecl);
1099
Douglas Gregorccabf082008-10-31 20:25:05 +00001100 CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1101 if (!ClassDecl) {
1102 ConDecl->setInvalidDecl();
1103 return ConDecl;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001104 }
1105
Douglas Gregorccabf082008-10-31 20:25:05 +00001106 // Make sure this constructor is an overload of the existing
1107 // constructors.
1108 OverloadedFunctionDecl::function_iterator MatchedDecl;
1109 if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) {
1110 Diag(ConDecl->getLocation(),
1111 diag::err_constructor_redeclared,
1112 SourceRange(ConDecl->getLocation()));
1113 Diag((*MatchedDecl)->getLocation(),
1114 diag::err_previous_declaration,
1115 SourceRange((*MatchedDecl)->getLocation()));
1116 ConDecl->setInvalidDecl();
1117 return ConDecl;
1118 }
1119
1120
1121 // C++ [class.copy]p3:
1122 // A declaration of a constructor for a class X is ill-formed if
1123 // its first parameter is of type (optionally cv-qualified) X and
1124 // either there are no other parameters or else all other
1125 // parameters have default arguments.
1126 if ((ConDecl->getNumParams() == 1) ||
1127 (ConDecl->getNumParams() > 1 &&
1128 ConDecl->getParamDecl(1)->getDefaultArg() != 0)) {
1129 QualType ParamType = ConDecl->getParamDecl(0)->getType();
1130 QualType ClassTy = Context.getTagDeclType(
1131 const_cast<CXXRecordDecl*>(ConDecl->getParent()));
1132 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1133 Diag(ConDecl->getLocation(),
1134 diag::err_constructor_byvalue_arg,
1135 SourceRange(ConDecl->getParamDecl(0)->getLocation()));
1136 ConDecl->setInvalidDecl();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001137 return ConDecl;
Douglas Gregorccabf082008-10-31 20:25:05 +00001138 }
1139 }
1140
1141 // Add this constructor to the set of constructors of the current
1142 // class.
1143 ClassDecl->addConstructor(Context, ConDecl);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001144 return (DeclTy *)ConDecl;
1145}
1146
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001147/// ActOnDestructorDeclarator - Called by ActOnDeclarator to complete
1148/// the declaration of the given C++ @p Destructor. This routine is
1149/// responsible for recording the destructor in the C++ class, if
1150/// possible.
1151Sema::DeclTy *Sema::ActOnDestructorDeclarator(CXXDestructorDecl *Destructor) {
1152 assert(Destructor && "Expected to receive a destructor declaration");
1153
1154 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext);
1155
1156 // Make sure we aren't redeclaring the destructor.
1157 if (CXXDestructorDecl *PrevDestructor = ClassDecl->getDestructor()) {
1158 Diag(Destructor->getLocation(), diag::err_destructor_redeclared);
1159 Diag(PrevDestructor->getLocation(),
1160 PrevDestructor->isThisDeclarationADefinition()?
1161 diag::err_previous_definition
1162 : diag::err_previous_declaration);
1163 Destructor->setInvalidDecl();
1164 return Destructor;
1165 }
1166
1167 ClassDecl->setDestructor(Destructor);
1168 return (DeclTy *)Destructor;
1169}
1170
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001171/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1172/// the declaration of the given C++ conversion function. This routine
1173/// is responsible for recording the conversion function in the C++
1174/// class, if possible.
1175Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1176 assert(Conversion && "Expected to receive a conversion function declaration");
1177
1178 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext);
1179
1180 // Make sure we aren't redeclaring the conversion function.
1181 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
1182 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1183 for (OverloadedFunctionDecl::function_iterator Func
1184 = Conversions->function_begin();
1185 Func != Conversions->function_end(); ++Func) {
1186 CXXConversionDecl *OtherConv = cast<CXXConversionDecl>(*Func);
1187 if (ConvType == Context.getCanonicalType(OtherConv->getConversionType())) {
1188 Diag(Conversion->getLocation(), diag::err_conv_function_redeclared);
1189 Diag(OtherConv->getLocation(),
1190 OtherConv->isThisDeclarationADefinition()?
1191 diag::err_previous_definition
1192 : diag::err_previous_declaration);
1193 Conversion->setInvalidDecl();
1194 return (DeclTy *)Conversion;
1195 }
1196 }
1197
1198 // C++ [class.conv.fct]p1:
1199 // [...] A conversion function is never used to convert a
1200 // (possibly cv-qualified) object to the (possibly cv-qualified)
1201 // same object type (or a reference to it), to a (possibly
1202 // cv-qualified) base class of that type (or a reference to it),
1203 // or to (possibly cv-qualified) void.
1204 // FIXME: Suppress this warning if the conversion function ends up
1205 // being a virtual function that overrides a virtual function in a
1206 // base class.
1207 QualType ClassType
1208 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1209 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1210 ConvType = ConvTypeRef->getPointeeType();
1211 if (ConvType->isRecordType()) {
1212 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1213 if (ConvType == ClassType)
1214 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used,
1215 ClassType.getAsString());
1216 else if (IsDerivedFrom(ClassType, ConvType))
1217 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used,
1218 ClassType.getAsString(),
1219 ConvType.getAsString());
1220 } else if (ConvType->isVoidType()) {
1221 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used,
1222 ClassType.getAsString(), ConvType.getAsString());
1223 }
1224
1225 ClassDecl->addConversionFunction(Context, Conversion);
1226
1227 return (DeclTy *)Conversion;
1228}
1229
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001230//===----------------------------------------------------------------------===//
1231// Namespace Handling
1232//===----------------------------------------------------------------------===//
1233
1234/// ActOnStartNamespaceDef - This is called at the start of a namespace
1235/// definition.
1236Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1237 SourceLocation IdentLoc,
1238 IdentifierInfo *II,
1239 SourceLocation LBrace) {
1240 NamespaceDecl *Namespc =
1241 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1242 Namespc->setLBracLoc(LBrace);
1243
1244 Scope *DeclRegionScope = NamespcScope->getParent();
1245
1246 if (II) {
1247 // C++ [namespace.def]p2:
1248 // The identifier in an original-namespace-definition shall not have been
1249 // previously defined in the declarative region in which the
1250 // original-namespace-definition appears. The identifier in an
1251 // original-namespace-definition is the name of the namespace. Subsequently
1252 // in that declarative region, it is treated as an original-namespace-name.
1253
1254 Decl *PrevDecl =
Argiris Kirtzidisda64ff42008-10-14 18:28:48 +00001255 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001256 /*enableLazyBuiltinCreation=*/false);
1257
Argiris Kirtzidisad9de132008-09-10 02:11:07 +00001258 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001259 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
1260 // This is an extended namespace definition.
1261 // Attach this namespace decl to the chain of extended namespace
1262 // definitions.
1263 NamespaceDecl *NextNS = OrigNS;
1264 while (NextNS->getNextNamespace())
1265 NextNS = NextNS->getNextNamespace();
1266
1267 NextNS->setNextNamespace(Namespc);
1268 Namespc->setOriginalNamespace(OrigNS);
1269
1270 // We won't add this decl to the current scope. We want the namespace
1271 // name to return the original namespace decl during a name lookup.
1272 } else {
1273 // This is an invalid name redefinition.
1274 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
1275 Namespc->getName());
1276 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1277 Namespc->setInvalidDecl();
1278 // Continue on to push Namespc as current DeclContext and return it.
1279 }
1280 } else {
1281 // This namespace name is declared for the first time.
1282 PushOnScopeChains(Namespc, DeclRegionScope);
1283 }
1284 }
1285 else {
1286 // FIXME: Handle anonymous namespaces
1287 }
1288
1289 // Although we could have an invalid decl (i.e. the namespace name is a
1290 // redefinition), push it as current DeclContext and try to continue parsing.
1291 PushDeclContext(Namespc->getOriginalNamespace());
1292 return Namespc;
1293}
1294
1295/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1296/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1297void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1298 Decl *Dcl = static_cast<Decl *>(D);
1299 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1300 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1301 Namespc->setRBracLoc(RBrace);
1302 PopDeclContext();
1303}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001304
1305
1306/// AddCXXDirectInitializerToDecl - This action is called immediately after
1307/// ActOnDeclarator, when a C++ direct initializer is present.
1308/// e.g: "int x(1);"
1309void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1310 ExprTy **ExprTys, unsigned NumExprs,
1311 SourceLocation *CommaLocs,
1312 SourceLocation RParenLoc) {
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001313 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001314 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001315
1316 // If there is no declaration, there was an error parsing it. Just ignore
1317 // the initializer.
1318 if (RealDecl == 0) {
Ted Kremenek85b4c492008-10-06 20:35:04 +00001319 for (unsigned i = 0; i != NumExprs; ++i)
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001320 delete static_cast<Expr *>(ExprTys[i]);
1321 return;
1322 }
1323
1324 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1325 if (!VDecl) {
1326 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1327 RealDecl->setInvalidDecl();
1328 return;
1329 }
1330
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001331 // We will treat direct-initialization as a copy-initialization:
1332 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001333 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1334 //
1335 // Clients that want to distinguish between the two forms, can check for
1336 // direct initializer using VarDecl::hasCXXDirectInitializer().
1337 // A major benefit is that clients that don't particularly care about which
1338 // exactly form was it (like the CodeGen) can handle both cases without
1339 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001340
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001341 // C++ 8.5p11:
1342 // The form of initialization (using parentheses or '=') is generally
1343 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001344 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +00001345 QualType DeclInitType = VDecl->getType();
1346 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1347 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001348
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001349 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001350 CXXConstructorDecl *Constructor
Douglas Gregor6428e762008-11-05 15:29:30 +00001351 = PerformInitializationByConstructor(DeclInitType,
1352 (Expr **)ExprTys, NumExprs,
1353 VDecl->getLocation(),
1354 SourceRange(VDecl->getLocation(),
1355 RParenLoc),
1356 VDecl->getName(),
1357 IK_Direct);
Douglas Gregor5870a952008-11-03 20:45:27 +00001358 if (!Constructor) {
1359 RealDecl->setInvalidDecl();
1360 }
Douglas Gregor6428e762008-11-05 15:29:30 +00001361
1362 // Let clients know that initialization was done with a direct
1363 // initializer.
1364 VDecl->setCXXDirectInitializer(true);
1365
1366 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1367 // the initializer.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001368 return;
1369 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001370
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001371 if (NumExprs > 1) {
1372 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
1373 SourceRange(VDecl->getLocation(), RParenLoc));
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001374 RealDecl->setInvalidDecl();
1375 return;
1376 }
1377
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001378 // Let clients know that initialization was done with a direct initializer.
1379 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001380
1381 assert(NumExprs == 1 && "Expected 1 expression");
1382 // Set the init expression, handles conversions.
1383 AddInitializerToDecl(Dcl, ExprTys[0]);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001384}
Douglas Gregor81c29152008-10-29 00:13:59 +00001385
Douglas Gregor6428e762008-11-05 15:29:30 +00001386/// PerformInitializationByConstructor - Perform initialization by
1387/// constructor (C++ [dcl.init]p14), which may occur as part of
1388/// direct-initialization or copy-initialization. We are initializing
1389/// an object of type @p ClassType with the given arguments @p
1390/// Args. @p Loc is the location in the source code where the
1391/// initializer occurs (e.g., a declaration, member initializer,
1392/// functional cast, etc.) while @p Range covers the whole
1393/// initialization. @p InitEntity is the entity being initialized,
1394/// which may by the name of a declaration or a type. @p Kind is the
1395/// kind of initialization we're performing, which affects whether
1396/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00001397/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00001398/// when the initialization fails, emits a diagnostic and returns
1399/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00001400CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00001401Sema::PerformInitializationByConstructor(QualType ClassType,
1402 Expr **Args, unsigned NumArgs,
1403 SourceLocation Loc, SourceRange Range,
1404 std::string InitEntity,
1405 InitializationKind Kind) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001406 const RecordType *ClassRec = ClassType->getAsRecordType();
1407 assert(ClassRec && "Can only initialize a class type here");
1408
1409 // C++ [dcl.init]p14:
1410 //
1411 // If the initialization is direct-initialization, or if it is
1412 // copy-initialization where the cv-unqualified version of the
1413 // source type is the same class as, or a derived class of, the
1414 // class of the destination, constructors are considered. The
1415 // applicable constructors are enumerated (13.3.1.3), and the
1416 // best one is chosen through overload resolution (13.3). The
1417 // constructor so selected is called to initialize the object,
1418 // with the initializer expression(s) as its argument(s). If no
1419 // constructor applies, or the overload resolution is ambiguous,
1420 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00001421 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1422 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00001423
1424 // Add constructors to the overload set.
1425 OverloadedFunctionDecl *Constructors
1426 = const_cast<OverloadedFunctionDecl *>(ClassDecl->getConstructors());
1427 for (OverloadedFunctionDecl::function_iterator Con
1428 = Constructors->function_begin();
1429 Con != Constructors->function_end(); ++Con) {
1430 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1431 if ((Kind == IK_Direct) ||
1432 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1433 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1434 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1435 }
1436
Douglas Gregor5870a952008-11-03 20:45:27 +00001437 OverloadCandidateSet::iterator Best;
Douglas Gregor5870a952008-11-03 20:45:27 +00001438 switch (BestViableFunction(CandidateSet, Best)) {
1439 case OR_Success:
1440 // We found a constructor. Return it.
1441 return cast<CXXConstructorDecl>(Best->Function);
1442
1443 case OR_No_Viable_Function:
1444 if (CandidateSet.empty())
1445 Diag(Loc, diag::err_ovl_no_viable_function_in_init,
1446 InitEntity, Range);
1447 else {
1448 Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands,
1449 InitEntity, Range);
1450 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1451 }
1452 return 0;
1453
1454 case OR_Ambiguous:
1455 Diag(Loc, diag::err_ovl_ambiguous_init,
1456 InitEntity, Range);
1457 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1458 return 0;
1459 }
1460
1461 return 0;
1462}
1463
Douglas Gregor81c29152008-10-29 00:13:59 +00001464/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1465/// determine whether they are reference-related,
1466/// reference-compatible, reference-compatible with added
1467/// qualification, or incompatible, for use in C++ initialization by
1468/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1469/// type, and the first type (T1) is the pointee type of the reference
1470/// type being initialized.
1471Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001472Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1473 bool& DerivedToBase) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001474 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1475 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1476
1477 T1 = Context.getCanonicalType(T1);
1478 T2 = Context.getCanonicalType(T2);
1479 QualType UnqualT1 = T1.getUnqualifiedType();
1480 QualType UnqualT2 = T2.getUnqualifiedType();
1481
1482 // C++ [dcl.init.ref]p4:
1483 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1484 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1485 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001486 if (UnqualT1 == UnqualT2)
1487 DerivedToBase = false;
1488 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1489 DerivedToBase = true;
1490 else
Douglas Gregor81c29152008-10-29 00:13:59 +00001491 return Ref_Incompatible;
1492
1493 // At this point, we know that T1 and T2 are reference-related (at
1494 // least).
1495
1496 // C++ [dcl.init.ref]p4:
1497 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1498 // reference-related to T2 and cv1 is the same cv-qualification
1499 // as, or greater cv-qualification than, cv2. For purposes of
1500 // overload resolution, cases for which cv1 is greater
1501 // cv-qualification than cv2 are identified as
1502 // reference-compatible with added qualification (see 13.3.3.2).
1503 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1504 return Ref_Compatible;
1505 else if (T1.isMoreQualifiedThan(T2))
1506 return Ref_Compatible_With_Added_Qualification;
1507 else
1508 return Ref_Related;
1509}
1510
1511/// CheckReferenceInit - Check the initialization of a reference
1512/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1513/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00001514/// list), and DeclType is the type of the declaration. When ICS is
1515/// non-null, this routine will compute the implicit conversion
1516/// sequence according to C++ [over.ics.ref] and will not produce any
1517/// diagnostics; when ICS is null, it will emit diagnostics when any
1518/// errors are found. Either way, a return value of true indicates
1519/// that there was a failure, a return value of false indicates that
1520/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001521///
1522/// When @p SuppressUserConversions, user-defined conversions are
1523/// suppressed.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001524bool
1525Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001526 ImplicitConversionSequence *ICS,
1527 bool SuppressUserConversions) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001528 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1529
1530 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1531 QualType T2 = Init->getType();
1532
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001533 // Compute some basic properties of the types and the initializer.
1534 bool DerivedToBase = false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001535 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001536 ReferenceCompareResult RefRelationship
1537 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1538
1539 // Most paths end in a failed conversion.
1540 if (ICS)
1541 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00001542
1543 // C++ [dcl.init.ref]p5:
1544 // A reference to type “cv1 T1” is initialized by an expression
1545 // of type “cv2 T2” as follows:
1546
1547 // -- If the initializer expression
1548
1549 bool BindsDirectly = false;
1550 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1551 // reference-compatible with “cv2 T2,” or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001552 //
1553 // Note that the bit-field check is skipped if we are just computing
1554 // the implicit conversion sequence (C++ [over.best.ics]p2).
1555 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1556 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001557 BindsDirectly = true;
1558
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001559 if (ICS) {
1560 // C++ [over.ics.ref]p1:
1561 // When a parameter of reference type binds directly (8.5.3)
1562 // to an argument expression, the implicit conversion sequence
1563 // is the identity conversion, unless the argument expression
1564 // has a type that is a derived class of the parameter type,
1565 // in which case the implicit conversion sequence is a
1566 // derived-to-base Conversion (13.3.3.1).
1567 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1568 ICS->Standard.First = ICK_Identity;
1569 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1570 ICS->Standard.Third = ICK_Identity;
1571 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1572 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001573 ICS->Standard.ReferenceBinding = true;
1574 ICS->Standard.DirectBinding = true;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001575
1576 // Nothing more to do: the inaccessibility/ambiguity check for
1577 // derived-to-base conversions is suppressed when we're
1578 // computing the implicit conversion sequence (C++
1579 // [over.best.ics]p2).
1580 return false;
1581 } else {
1582 // Perform the conversion.
Douglas Gregor81c29152008-10-29 00:13:59 +00001583 // FIXME: Binding to a subobject of the lvalue is going to require
1584 // more AST annotation than this.
1585 ImpCastExprToType(Init, T1);
1586 }
1587 }
1588
1589 // -- has a class type (i.e., T2 is a class type) and can be
1590 // implicitly converted to an lvalue of type “cv3 T3,”
1591 // where “cv1 T1” is reference-compatible with “cv3 T3”
1592 // 92) (this conversion is selected by enumerating the
1593 // applicable conversion functions (13.3.1.6) and choosing
1594 // the best one through overload resolution (13.3)),
1595 // FIXME: Implement this second bullet, once we have conversion
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001596 // functions. Also remember C++ [over.ics.ref]p1, second part.
Douglas Gregor81c29152008-10-29 00:13:59 +00001597
1598 if (BindsDirectly) {
1599 // C++ [dcl.init.ref]p4:
1600 // [...] In all cases where the reference-related or
1601 // reference-compatible relationship of two types is used to
1602 // establish the validity of a reference binding, and T1 is a
1603 // base class of T2, a program that necessitates such a binding
1604 // is ill-formed if T1 is an inaccessible (clause 11) or
1605 // ambiguous (10.2) base class of T2.
1606 //
1607 // Note that we only check this condition when we're allowed to
1608 // complain about errors, because we should not be checking for
1609 // ambiguity (or inaccessibility) unless the reference binding
1610 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001611 if (DerivedToBase)
1612 return CheckDerivedToBaseConversion(T2, T1,
1613 Init->getSourceRange().getBegin(),
1614 Init->getSourceRange());
1615 else
1616 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001617 }
1618
1619 // -- Otherwise, the reference shall be to a non-volatile const
1620 // type (i.e., cv1 shall be const).
1621 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001622 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001623 Diag(Init->getSourceRange().getBegin(),
1624 diag::err_not_reference_to_const_init,
1625 T1.getAsString(),
1626 InitLvalue != Expr::LV_Valid? "temporary" : "value",
1627 T2.getAsString(), Init->getSourceRange());
1628 return true;
1629 }
1630
1631 // -- If the initializer expression is an rvalue, with T2 a
1632 // class type, and “cv1 T1” is reference-compatible with
1633 // “cv2 T2,” the reference is bound in one of the
1634 // following ways (the choice is implementation-defined):
1635 //
1636 // -- The reference is bound to the object represented by
1637 // the rvalue (see 3.10) or to a sub-object within that
1638 // object.
1639 //
1640 // -- A temporary of type “cv1 T2” [sic] is created, and
1641 // a constructor is called to copy the entire rvalue
1642 // object into the temporary. The reference is bound to
1643 // the temporary or to a sub-object within the
1644 // temporary.
1645 //
1646 //
1647 // The constructor that would be used to make the copy
1648 // shall be callable whether or not the copy is actually
1649 // done.
1650 //
1651 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1652 // freedom, so we will always take the first option and never build
1653 // a temporary in this case. FIXME: We will, however, have to check
1654 // for the presence of a copy constructor in C++98/03 mode.
1655 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001656 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1657 if (ICS) {
1658 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1659 ICS->Standard.First = ICK_Identity;
1660 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1661 ICS->Standard.Third = ICK_Identity;
1662 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1663 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001664 ICS->Standard.ReferenceBinding = true;
1665 ICS->Standard.DirectBinding = false;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001666 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001667 // FIXME: Binding to a subobject of the rvalue is going to require
1668 // more AST annotation than this.
1669 ImpCastExprToType(Init, T1);
1670 }
1671 return false;
1672 }
1673
1674 // -- Otherwise, a temporary of type “cv1 T1” is created and
1675 // initialized from the initializer expression using the
1676 // rules for a non-reference copy initialization (8.5). The
1677 // reference is then bound to the temporary. If T1 is
1678 // reference-related to T2, cv1 must be the same
1679 // cv-qualification as, or greater cv-qualification than,
1680 // cv2; otherwise, the program is ill-formed.
1681 if (RefRelationship == Ref_Related) {
1682 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1683 // we would be reference-compatible or reference-compatible with
1684 // added qualification. But that wasn't the case, so the reference
1685 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001686 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001687 Diag(Init->getSourceRange().getBegin(),
1688 diag::err_reference_init_drops_quals,
1689 T1.getAsString(),
1690 InitLvalue != Expr::LV_Valid? "temporary" : "value",
1691 T2.getAsString(), Init->getSourceRange());
1692 return true;
1693 }
1694
1695 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001696 if (ICS) {
1697 /// C++ [over.ics.ref]p2:
1698 ///
1699 /// When a parameter of reference type is not bound directly to
1700 /// an argument expression, the conversion sequence is the one
1701 /// required to convert the argument expression to the
1702 /// underlying type of the reference according to
1703 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1704 /// to copy-initializing a temporary of the underlying type with
1705 /// the argument expression. Any difference in top-level
1706 /// cv-qualification is subsumed by the initialization itself
1707 /// and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001708 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001709 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1710 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001711 return PerformImplicitConversion(Init, T1);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001712 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001713}
Douglas Gregore60e5d32008-11-06 22:13:31 +00001714
1715/// CheckOverloadedOperatorDeclaration - Check whether the declaration
1716/// of this overloaded operator is well-formed. If so, returns false;
1717/// otherwise, emits appropriate diagnostics and returns true.
1718bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
1719 assert(FnDecl && FnDecl->getOverloadedOperator() != OO_None &&
1720 "Expected an overloaded operator declaration");
1721
1722 bool IsInvalid = false;
1723
1724 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
1725
1726 // C++ [over.oper]p5:
1727 // The allocation and deallocation functions, operator new,
1728 // operator new[], operator delete and operator delete[], are
1729 // described completely in 3.7.3. The attributes and restrictions
1730 // found in the rest of this subclause do not apply to them unless
1731 // explicitly stated in 3.7.3.
1732 // FIXME: Write a separate routine for checking this. For now, just
1733 // allow it.
1734 if (Op == OO_New || Op == OO_Array_New ||
1735 Op == OO_Delete || Op == OO_Array_Delete)
1736 return false;
1737
1738 // C++ [over.oper]p6:
1739 // An operator function shall either be a non-static member
1740 // function or be a non-member function and have at least one
1741 // parameter whose type is a class, a reference to a class, an
1742 // enumeration, or a reference to an enumeration.
1743 CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl);
1744 if (MethodDecl) {
1745 if (MethodDecl->isStatic()) {
1746 Diag(FnDecl->getLocation(),
1747 diag::err_operator_overload_static,
1748 FnDecl->getName(),
1749 SourceRange(FnDecl->getLocation()));
1750 IsInvalid = true;
1751
1752 // Pretend this isn't a member function; it'll supress
1753 // additional, unnecessary error messages.
1754 MethodDecl = 0;
1755 }
1756 } else {
1757 bool ClassOrEnumParam = false;
1758 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
1759 Param != FnDecl->param_end(); ++Param) {
1760 QualType ParamType = (*Param)->getType();
1761 if (const ReferenceType *RefType = ParamType->getAsReferenceType())
1762 ParamType = RefType->getPointeeType();
1763 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
1764 ClassOrEnumParam = true;
1765 break;
1766 }
1767 }
1768
1769 if (!ClassOrEnumParam) {
1770 Diag(FnDecl->getLocation(),
1771 diag::err_operator_overload_needs_class_or_enum,
1772 FnDecl->getName(),
1773 SourceRange(FnDecl->getLocation()));
1774 IsInvalid = true;
1775 }
1776 }
1777
1778 // C++ [over.oper]p8:
1779 // An operator function cannot have default arguments (8.3.6),
1780 // except where explicitly stated below.
1781 //
1782 // Only the function-call operator allows default arguments
1783 // (C++ [over.call]p1).
1784 if (Op != OO_Call) {
1785 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
1786 Param != FnDecl->param_end(); ++Param) {
1787 if (Expr *DefArg = (*Param)->getDefaultArg()) {
1788 Diag((*Param)->getLocation(),
1789 diag::err_operator_overload_default_arg,
1790 DefArg->getSourceRange());
1791 IsInvalid = true;
1792 }
1793 }
1794 }
1795
1796 bool CanBeUnaryOperator = false;
1797 bool CanBeBinaryOperator = false;
1798 bool MustBeMemberOperator = false;
1799
1800 switch (Op) {
1801 case OO_New:
1802 case OO_Delete:
1803 case OO_Array_New:
1804 case OO_Array_Delete:
1805 assert(false && "Operators new, new[], delete, and delete[] handled above");
1806 return true;
1807
1808 // Unary-only operators
1809 case OO_Arrow:
1810 MustBeMemberOperator = true;
1811 // Fall through
1812
1813 case OO_Tilde:
1814 case OO_Exclaim:
1815 CanBeUnaryOperator = true;
1816 break;
1817
1818 // Binary-only operators
1819 case OO_Equal:
1820 case OO_Subscript:
1821 MustBeMemberOperator = true;
1822 // Fall through
1823
1824 case OO_Slash:
1825 case OO_Percent:
1826 case OO_Caret:
1827 case OO_Pipe:
1828 case OO_Less:
1829 case OO_Greater:
1830 case OO_PlusEqual:
1831 case OO_MinusEqual:
1832 case OO_StarEqual:
1833 case OO_SlashEqual:
1834 case OO_PercentEqual:
1835 case OO_CaretEqual:
1836 case OO_AmpEqual:
1837 case OO_PipeEqual:
1838 case OO_LessLess:
1839 case OO_GreaterGreater:
1840 case OO_LessLessEqual:
1841 case OO_GreaterGreaterEqual:
1842 case OO_EqualEqual:
1843 case OO_ExclaimEqual:
1844 case OO_LessEqual:
1845 case OO_GreaterEqual:
1846 case OO_AmpAmp:
1847 case OO_PipePipe:
1848 case OO_Comma:
1849 CanBeBinaryOperator = true;
1850 break;
1851
1852 // Unary or binary operators
1853 case OO_Amp:
1854 case OO_Plus:
1855 case OO_Minus:
1856 case OO_Star:
1857 case OO_PlusPlus:
1858 case OO_MinusMinus:
1859 case OO_ArrowStar:
1860 CanBeUnaryOperator = true;
1861 CanBeBinaryOperator = true;
1862 break;
1863
1864 case OO_Call:
1865 MustBeMemberOperator = true;
1866 break;
1867
1868 case OO_None:
1869 case NUM_OVERLOADED_OPERATORS:
1870 assert(false && "Not an overloaded operator!");
1871 return true;
1872 }
1873
1874 // C++ [over.oper]p8:
1875 // [...] Operator functions cannot have more or fewer parameters
1876 // than the number required for the corresponding operator, as
1877 // described in the rest of this subclause.
1878 unsigned NumParams = FnDecl->getNumParams() + (MethodDecl? 1 : 0);
1879 if (Op != OO_Call &&
1880 ((NumParams == 1 && !CanBeUnaryOperator) ||
1881 (NumParams == 2 && !CanBeBinaryOperator) ||
1882 (NumParams < 1) || (NumParams > 2))) {
1883 // We have the wrong number of parameters.
1884 std::string NumParamsStr = (llvm::APSInt(32) = NumParams).toString(10);
1885 std::string NumParamsPlural;
1886 if (NumParams != 1)
1887 NumParamsPlural = "s";
1888
1889 diag::kind DK;
1890
1891 if (CanBeUnaryOperator && CanBeBinaryOperator)
1892 DK = diag::err_operator_overload_must_be_unary_or_binary;
1893 else if (CanBeUnaryOperator)
1894 DK = diag::err_operator_overload_must_be_unary;
1895 else if (CanBeBinaryOperator)
1896 DK = diag::err_operator_overload_must_be_binary;
1897 else
1898 assert(false && "All non-call overloaded operators are unary or binary!");
1899
1900 Diag(FnDecl->getLocation(), DK,
1901 FnDecl->getName(), NumParamsStr, NumParamsPlural,
1902 SourceRange(FnDecl->getLocation()));
1903 IsInvalid = true;
1904 }
1905
1906 // Overloaded operators cannot be variadic.
1907 if (FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) {
1908 Diag(FnDecl->getLocation(),
1909 diag::err_operator_overload_variadic,
1910 SourceRange(FnDecl->getLocation()));
1911 IsInvalid = true;
1912 }
1913
1914 // Some operators must be non-static member functions.
1915 if (MustBeMemberOperator && !MethodDecl) {
1916 Diag(FnDecl->getLocation(),
1917 diag::err_operator_overload_must_be_member,
1918 FnDecl->getName(),
1919 SourceRange(FnDecl->getLocation()));
1920 IsInvalid = true;
1921 }
1922
1923 // C++ [over.inc]p1:
1924 // The user-defined function called operator++ implements the
1925 // prefix and postfix ++ operator. If this function is a member
1926 // function with no parameters, or a non-member function with one
1927 // parameter of class or enumeration type, it defines the prefix
1928 // increment operator ++ for objects of that type. If the function
1929 // is a member function with one parameter (which shall be of type
1930 // int) or a non-member function with two parameters (the second
1931 // of which shall be of type int), it defines the postfix
1932 // increment operator ++ for objects of that type.
1933 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
1934 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
1935 bool ParamIsInt = false;
1936 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
1937 ParamIsInt = BT->getKind() == BuiltinType::Int;
1938
1939 if (!ParamIsInt) {
1940 Diag(LastParam->getLocation(),
1941 diag::err_operator_overload_post_incdec_must_be_int,
1942 MethodDecl? std::string() : std::string("second "),
1943 (Op == OO_PlusPlus)? std::string("increment")
1944 : std::string("decrement"),
1945 Context.getCanonicalType(LastParam->getType()).getAsString(),
1946 SourceRange(FnDecl->getLocation()));
1947 IsInvalid = true;
1948 }
1949 }
1950
1951 return IsInvalid;
1952}