blob: ea3c175f1620503ec79d9a3077ae07e41f22b2ee [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
Douglas Gregorabed2172008-10-22 17:49:05 +0000313 // Create the base specifier.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000314 return new CXXBaseSpecifier(SpecifierRange, Virtual,
315 BaseType->isClassType(), Access, BaseType);
Douglas Gregorabed2172008-10-22 17:49:05 +0000316}
Douglas Gregorec93f442008-04-13 21:30:24 +0000317
Douglas Gregorabed2172008-10-22 17:49:05 +0000318/// ActOnBaseSpecifiers - Attach the given base specifiers to the
319/// class, after checking whether there are any duplicate base
320/// classes.
321void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
322 unsigned NumBases) {
323 if (NumBases == 0)
324 return;
325
326 // Used to keep track of which base types we have already seen, so
327 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000328 // that the key is always the unqualified canonical type of the base
329 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000330 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
331
332 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000333 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
334 unsigned NumGoodBases = 0;
335 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000336 QualType NewBaseType
Douglas Gregor4fd85902008-10-23 18:13:27 +0000337 = Context.getCanonicalType(BaseSpecs[idx]->getType());
338 NewBaseType = NewBaseType.getUnqualifiedType();
339
Douglas Gregorabed2172008-10-22 17:49:05 +0000340 if (KnownBaseTypes[NewBaseType]) {
341 // C++ [class.mi]p3:
342 // A class shall not be specified as a direct base class of a
343 // derived class more than once.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000344 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Douglas Gregorabed2172008-10-22 17:49:05 +0000345 diag::err_duplicate_base_class,
346 KnownBaseTypes[NewBaseType]->getType().getAsString(),
Douglas Gregor4fd85902008-10-23 18:13:27 +0000347 BaseSpecs[idx]->getSourceRange());
348
349 // Delete the duplicate base class specifier; we're going to
350 // overwrite its pointer later.
351 delete BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000352 } else {
353 // Okay, add this new base class.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000354 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
355 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000356 }
357 }
358
359 // Attach the remaining base class specifiers to the derived class.
360 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000361 Decl->setBases(BaseSpecs, NumGoodBases);
362
363 // Delete the remaining (good) base class specifiers, since their
364 // data has been copied into the CXXRecordDecl.
365 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
366 delete BaseSpecs[idx];
Douglas Gregorec93f442008-04-13 21:30:24 +0000367}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000368
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000369//===----------------------------------------------------------------------===//
370// C++ class member Handling
371//===----------------------------------------------------------------------===//
372
373/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
374/// definition, when on C++.
375void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000376 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
377 PushDeclContext(Dcl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000378 FieldCollector->StartClass();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000379
380 if (Dcl->getIdentifier()) {
381 // C++ [class]p2:
382 // [...] The class-name is also inserted into the scope of the
383 // class itself; this is known as the injected-class-name. For
384 // purposes of access checking, the injected-class-name is treated
385 // as if it were a public member name.
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000386 // FIXME: this should probably have its own kind of type node.
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000387 TypedefDecl *InjectedClassName
388 = TypedefDecl::Create(Context, Dcl, LBrace, Dcl->getIdentifier(),
389 Context.getTypeDeclType(Dcl), /*PrevDecl=*/0);
390 PushOnScopeChains(InjectedClassName, S);
391 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000392}
393
394/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
395/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
396/// bitfield width if there is one and 'InitExpr' specifies the initializer if
397/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
398/// declarators on it.
399///
400/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
401/// an instance field is declared, a new CXXFieldDecl is created but the method
402/// does *not* return it; it returns LastInGroup instead. The other C++ members
403/// (which are all ScopedDecls) are returned after appending them to
404/// LastInGroup.
405Sema::DeclTy *
406Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
407 ExprTy *BW, ExprTy *InitExpr,
408 DeclTy *LastInGroup) {
409 const DeclSpec &DS = D.getDeclSpec();
410 IdentifierInfo *II = D.getIdentifier();
411 Expr *BitWidth = static_cast<Expr*>(BW);
412 Expr *Init = static_cast<Expr*>(InitExpr);
413 SourceLocation Loc = D.getIdentifierLoc();
414
415 // C++ 9.2p6: A member shall not be declared to have automatic storage
416 // duration (auto, register) or with the extern storage-class-specifier.
417 switch (DS.getStorageClassSpec()) {
418 case DeclSpec::SCS_unspecified:
419 case DeclSpec::SCS_typedef:
420 case DeclSpec::SCS_static:
421 // FALL THROUGH.
422 break;
423 default:
424 if (DS.getStorageClassSpecLoc().isValid())
425 Diag(DS.getStorageClassSpecLoc(),
426 diag::err_storageclass_invalid_for_member);
427 else
428 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
429 D.getMutableDeclSpec().ClearStorageClassSpecs();
430 }
431
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000432 bool isFunc = D.isFunctionDeclarator();
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000433 if (!isFunc &&
434 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
435 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000436 // Check also for this case:
437 //
438 // typedef int f();
439 // f a;
440 //
441 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
442 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
443 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000444
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000445 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000446 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000447
448 Decl *Member;
449 bool InvalidDecl = false;
450
451 if (isInstField)
452 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
453 else
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000454 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000455
456 if (!Member) return LastInGroup;
457
Sanjiv Guptafa451432008-10-31 09:52:39 +0000458 assert((II || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000459
460 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
461 // specific methods. Use a wrapper class that can be used with all C++ class
462 // member decls.
463 CXXClassMemberWrapper(Member).setAccess(AS);
464
Douglas Gregor15e04622008-11-05 16:20:31 +0000465 // C++ [dcl.init.aggr]p1:
466 // An aggregate is an array or a class (clause 9) with [...] no
467 // private or protected non-static data members (clause 11).
468 if (isInstField && (AS == AS_private || AS == AS_protected))
469 cast<CXXRecordDecl>(CurContext)->setAggregate(false);
470
471 // FIXME: If the member is a virtual function, mark it its class as
472 // a non-aggregate.
473
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000474 if (BitWidth) {
475 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
476 // constant-expression be a value equal to zero.
477 // FIXME: Check this.
478
479 if (D.isFunctionDeclarator()) {
480 // FIXME: Emit diagnostic about only constructors taking base initializers
481 // or something similar, when constructor support is in place.
482 Diag(Loc, diag::err_not_bitfield_type,
483 II->getName(), BitWidth->getSourceRange());
484 InvalidDecl = true;
485
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000486 } else if (isInstField) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000487 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000488 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000489 Diag(Loc, diag::err_not_integral_type_bitfield,
490 II->getName(), BitWidth->getSourceRange());
491 InvalidDecl = true;
492 }
493
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000494 } else if (isa<FunctionDecl>(Member)) {
495 // A function typedef ("typedef int f(); f a;").
496 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
497 Diag(Loc, diag::err_not_integral_type_bitfield,
498 II->getName(), BitWidth->getSourceRange());
499 InvalidDecl = true;
500
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000501 } else if (isa<TypedefDecl>(Member)) {
502 // "cannot declare 'A' to be a bit-field type"
503 Diag(Loc, diag::err_not_bitfield_type, II->getName(),
504 BitWidth->getSourceRange());
505 InvalidDecl = true;
506
507 } else {
508 assert(isa<CXXClassVarDecl>(Member) &&
509 "Didn't we cover all member kinds?");
510 // C++ 9.6p3: A bit-field shall not be a static member.
511 // "static member 'A' cannot be a bit-field"
512 Diag(Loc, diag::err_static_not_bitfield, II->getName(),
513 BitWidth->getSourceRange());
514 InvalidDecl = true;
515 }
516 }
517
518 if (Init) {
519 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
520 // if it declares a static member of const integral or const enumeration
521 // type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000522 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
523 // ...static member of...
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000524 CVD->setInit(Init);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000525 // ...const integral or const enumeration type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000526 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
527 CVD->getType()->isIntegralType()) {
528 // constant-initializer
529 if (CheckForConstantInitializer(Init, CVD->getType()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000530 InvalidDecl = true;
531
532 } else {
533 // not const integral.
534 Diag(Loc, diag::err_member_initialization,
535 II->getName(), Init->getSourceRange());
536 InvalidDecl = true;
537 }
538
539 } else {
540 // not static member.
541 Diag(Loc, diag::err_member_initialization,
542 II->getName(), Init->getSourceRange());
543 InvalidDecl = true;
544 }
545 }
546
547 if (InvalidDecl)
548 Member->setInvalidDecl();
549
550 if (isInstField) {
551 FieldCollector->Add(cast<CXXFieldDecl>(Member));
552 return LastInGroup;
553 }
554 return Member;
555}
556
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000557/// ActOnMemInitializer - Handle a C++ member initializer.
558Sema::MemInitResult
559Sema::ActOnMemInitializer(DeclTy *ConstructorD,
560 Scope *S,
561 IdentifierInfo *MemberOrBase,
562 SourceLocation IdLoc,
563 SourceLocation LParenLoc,
564 ExprTy **Args, unsigned NumArgs,
565 SourceLocation *CommaLocs,
566 SourceLocation RParenLoc) {
567 CXXConstructorDecl *Constructor
568 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
569 if (!Constructor) {
570 // The user wrote a constructor initializer on a function that is
571 // not a C++ constructor. Ignore the error for now, because we may
572 // have more member initializers coming; we'll diagnose it just
573 // once in ActOnMemInitializers.
574 return true;
575 }
576
577 CXXRecordDecl *ClassDecl = Constructor->getParent();
578
579 // C++ [class.base.init]p2:
580 // Names in a mem-initializer-id are looked up in the scope of the
581 // constructor’s class and, if not found in that scope, are looked
582 // up in the scope containing the constructor’s
583 // definition. [Note: if the constructor’s class contains a member
584 // with the same name as a direct or virtual base class of the
585 // class, a mem-initializer-id naming the member or base class and
586 // composed of a single identifier refers to the class member. A
587 // mem-initializer-id for the hidden base class may be specified
588 // using a qualified name. ]
589 // Look for a member, first.
590 CXXFieldDecl *Member = ClassDecl->getMember(MemberOrBase);
591
592 // FIXME: Handle members of an anonymous union.
593
594 if (Member) {
595 // FIXME: Perform direct initialization of the member.
596 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
597 }
598
599 // It didn't name a member, so see if it names a class.
600 TypeTy *BaseTy = isTypeName(*MemberOrBase, S);
601 if (!BaseTy)
602 return Diag(IdLoc, diag::err_mem_init_not_member_or_class,
603 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
604
605 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
606 if (!BaseType->isRecordType())
607 return Diag(IdLoc, diag::err_base_init_does_not_name_class,
608 BaseType.getAsString(), SourceRange(IdLoc, RParenLoc));
609
610 // C++ [class.base.init]p2:
611 // [...] Unless the mem-initializer-id names a nonstatic data
612 // member of the constructor’s class or a direct or virtual base
613 // of that class, the mem-initializer is ill-formed. A
614 // mem-initializer-list can initialize a base class using any
615 // name that denotes that base class type.
616
617 // First, check for a direct base class.
618 const CXXBaseSpecifier *DirectBaseSpec = 0;
619 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
620 Base != ClassDecl->bases_end(); ++Base) {
621 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
622 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
623 // We found a direct base of this type. That's what we're
624 // initializing.
625 DirectBaseSpec = &*Base;
626 break;
627 }
628 }
629
630 // Check for a virtual base class.
631 // FIXME: We might be able to short-circuit this if we know in
632 // advance that there are no virtual bases.
633 const CXXBaseSpecifier *VirtualBaseSpec = 0;
634 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
635 // We haven't found a base yet; search the class hierarchy for a
636 // virtual base class.
637 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
638 /*DetectVirtual=*/false);
639 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
640 for (BasePaths::paths_iterator Path = Paths.begin();
641 Path != Paths.end(); ++Path) {
642 if (Path->back().Base->isVirtual()) {
643 VirtualBaseSpec = Path->back().Base;
644 break;
645 }
646 }
647 }
648 }
649
650 // C++ [base.class.init]p2:
651 // If a mem-initializer-id is ambiguous because it designates both
652 // a direct non-virtual base class and an inherited virtual base
653 // class, the mem-initializer is ill-formed.
654 if (DirectBaseSpec && VirtualBaseSpec)
655 return Diag(IdLoc, diag::err_base_init_direct_and_virtual,
656 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
657
658 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
659}
660
661
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000662void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
663 DeclTy *TagDecl,
664 SourceLocation LBrac,
665 SourceLocation RBrac) {
666 ActOnFields(S, RLoc, TagDecl,
667 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +0000668 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000669}
670
Douglas Gregore640ab62008-11-03 17:51:48 +0000671/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
672/// special functions, such as the default constructor, copy
673/// constructor, or destructor, to the given C++ class (C++
674/// [special]p1). This routine can only be executed just before the
675/// definition of the class is complete.
676void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
677 if (!ClassDecl->hasUserDeclaredConstructor()) {
678 // C++ [class.ctor]p5:
679 // A default constructor for a class X is a constructor of class X
680 // that can be called without an argument. If there is no
681 // user-declared constructor for class X, a default constructor is
682 // implicitly declared. An implicitly-declared default constructor
683 // is an inline public member of its class.
684 CXXConstructorDecl *DefaultCon =
685 CXXConstructorDecl::Create(Context, ClassDecl,
686 ClassDecl->getLocation(),
687 ClassDecl->getIdentifier(),
688 Context.getFunctionType(Context.VoidTy,
689 0, 0, false, 0),
690 /*isExplicit=*/false,
691 /*isInline=*/true,
692 /*isImplicitlyDeclared=*/true);
693 DefaultCon->setAccess(AS_public);
694 ClassDecl->addConstructor(Context, DefaultCon);
695 }
696
697 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
698 // C++ [class.copy]p4:
699 // If the class definition does not explicitly declare a copy
700 // constructor, one is declared implicitly.
701
702 // C++ [class.copy]p5:
703 // The implicitly-declared copy constructor for a class X will
704 // have the form
705 //
706 // X::X(const X&)
707 //
708 // if
709 bool HasConstCopyConstructor = true;
710
711 // -- each direct or virtual base class B of X has a copy
712 // constructor whose first parameter is of type const B& or
713 // const volatile B&, and
714 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
715 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
716 const CXXRecordDecl *BaseClassDecl
717 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
718 HasConstCopyConstructor
719 = BaseClassDecl->hasConstCopyConstructor(Context);
720 }
721
722 // -- for all the nonstatic data members of X that are of a
723 // class type M (or array thereof), each such class type
724 // has a copy constructor whose first parameter is of type
725 // const M& or const volatile M&.
726 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
727 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
728 QualType FieldType = (*Field)->getType();
729 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
730 FieldType = Array->getElementType();
731 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
732 const CXXRecordDecl *FieldClassDecl
733 = cast<CXXRecordDecl>(FieldClassType->getDecl());
734 HasConstCopyConstructor
735 = FieldClassDecl->hasConstCopyConstructor(Context);
736 }
737 }
738
739 // Otherwise, the implicitly declared copy constructor will have
740 // the form
741 //
742 // X::X(X&)
743 QualType ArgType = Context.getTypeDeclType(ClassDecl);
744 if (HasConstCopyConstructor)
745 ArgType = ArgType.withConst();
746 ArgType = Context.getReferenceType(ArgType);
747
748 // An implicitly-declared copy constructor is an inline public
749 // member of its class.
750 CXXConstructorDecl *CopyConstructor
751 = CXXConstructorDecl::Create(Context, ClassDecl,
752 ClassDecl->getLocation(),
753 ClassDecl->getIdentifier(),
754 Context.getFunctionType(Context.VoidTy,
755 &ArgType, 1,
756 false, 0),
757 /*isExplicit=*/false,
758 /*isInline=*/true,
759 /*isImplicitlyDeclared=*/true);
760 CopyConstructor->setAccess(AS_public);
761
762 // Add the parameter to the constructor.
763 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
764 ClassDecl->getLocation(),
765 /*IdentifierInfo=*/0,
766 ArgType, VarDecl::None, 0, 0);
767 CopyConstructor->setParams(&FromParam, 1);
768
769 ClassDecl->addConstructor(Context, CopyConstructor);
770 }
771
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000772 if (!ClassDecl->getDestructor()) {
773 // C++ [class.dtor]p2:
774 // If a class has no user-declared destructor, a destructor is
775 // declared implicitly. An implicitly-declared destructor is an
776 // inline public member of its class.
777 std::string DestructorName = "~";
778 DestructorName += ClassDecl->getName();
779 CXXDestructorDecl *Destructor
780 = CXXDestructorDecl::Create(Context, ClassDecl,
781 ClassDecl->getLocation(),
782 &PP.getIdentifierTable().get(DestructorName),
783 Context.getFunctionType(Context.VoidTy,
784 0, 0, false, 0),
785 /*isInline=*/true,
786 /*isImplicitlyDeclared=*/true);
787 Destructor->setAccess(AS_public);
788 ClassDecl->setDestructor(Destructor);
789 }
790
Douglas Gregore640ab62008-11-03 17:51:48 +0000791 // FIXME: Implicit copy assignment operator
792}
793
Argiris Kirtzidis448b4e42008-08-09 00:39:29 +0000794void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000795 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000796 FieldCollector->FinishClass();
Douglas Gregore640ab62008-11-03 17:51:48 +0000797 AddImplicitlyDeclaredMembersToClass(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000798 PopDeclContext();
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000799
800 // Everything, including inline method definitions, have been parsed.
801 // Let the consumer know of the new TagDecl definition.
802 Consumer.HandleTagDeclDefinition(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000803}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000804
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000805/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
806/// the well-formednes of the constructor declarator @p D with type @p
807/// R. If there are any errors in the declarator, this routine will
808/// emit diagnostics and return true. Otherwise, it will return
809/// false. Either way, the type @p R will be updated to reflect a
810/// well-formed type for the constructor.
811bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
812 FunctionDecl::StorageClass& SC) {
813 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
814 bool isInvalid = false;
815
816 // C++ [class.ctor]p3:
817 // A constructor shall not be virtual (10.3) or static (9.4). A
818 // constructor can be invoked for a const, volatile or const
819 // volatile object. A constructor shall not be declared const,
820 // volatile, or const volatile (9.3.2).
821 if (isVirtual) {
822 Diag(D.getIdentifierLoc(),
823 diag::err_constructor_cannot_be,
824 "virtual",
825 SourceRange(D.getDeclSpec().getVirtualSpecLoc()),
826 SourceRange(D.getIdentifierLoc()));
827 isInvalid = true;
828 }
829 if (SC == FunctionDecl::Static) {
830 Diag(D.getIdentifierLoc(),
831 diag::err_constructor_cannot_be,
832 "static",
833 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
834 SourceRange(D.getIdentifierLoc()));
835 isInvalid = true;
836 SC = FunctionDecl::None;
837 }
838 if (D.getDeclSpec().hasTypeSpecifier()) {
839 // Constructors don't have return types, but the parser will
840 // happily parse something like:
841 //
842 // class X {
843 // float X(float);
844 // };
845 //
846 // The return type will be eliminated later.
847 Diag(D.getIdentifierLoc(),
848 diag::err_constructor_return_type,
849 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
850 SourceRange(D.getIdentifierLoc()));
851 }
852 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
853 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
854 if (FTI.TypeQuals & QualType::Const)
855 Diag(D.getIdentifierLoc(),
856 diag::err_invalid_qualified_constructor,
857 "const",
858 SourceRange(D.getIdentifierLoc()));
859 if (FTI.TypeQuals & QualType::Volatile)
860 Diag(D.getIdentifierLoc(),
861 diag::err_invalid_qualified_constructor,
862 "volatile",
863 SourceRange(D.getIdentifierLoc()));
864 if (FTI.TypeQuals & QualType::Restrict)
865 Diag(D.getIdentifierLoc(),
866 diag::err_invalid_qualified_constructor,
867 "restrict",
868 SourceRange(D.getIdentifierLoc()));
869 }
870
871 // Rebuild the function type "R" without any type qualifiers (in
872 // case any of the errors above fired) and with "void" as the
873 // return type, since constructors don't have return types. We
874 // *always* have to do this, because GetTypeForDeclarator will
875 // put in a result type of "int" when none was specified.
876 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto();
877 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
878 Proto->getNumArgs(),
879 Proto->isVariadic(),
880 0);
881
882 return isInvalid;
883}
884
885/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
886/// the well-formednes of the destructor declarator @p D with type @p
887/// R. If there are any errors in the declarator, this routine will
888/// emit diagnostics and return true. Otherwise, it will return
889/// false. Either way, the type @p R will be updated to reflect a
890/// well-formed type for the destructor.
891bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
892 FunctionDecl::StorageClass& SC) {
893 bool isInvalid = false;
894
895 // C++ [class.dtor]p1:
896 // [...] A typedef-name that names a class is a class-name
897 // (7.1.3); however, a typedef-name that names a class shall not
898 // be used as the identifier in the declarator for a destructor
899 // declaration.
900 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType();
901 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) {
902 if (TypedefD->getIdentifier() !=
903 cast<CXXRecordDecl>(CurContext)->getIdentifier()) {
904 // FIXME: This would be easier if we could just look at whether
905 // we found the injected-class-name.
906 Diag(D.getIdentifierLoc(),
907 diag::err_destructor_typedef_name,
908 TypedefD->getName());
909 isInvalid = true;
910 }
911 }
912
913 // C++ [class.dtor]p2:
914 // A destructor is used to destroy objects of its class type. A
915 // destructor takes no parameters, and no return type can be
916 // specified for it (not even void). The address of a destructor
917 // shall not be taken. A destructor shall not be static. A
918 // destructor can be invoked for a const, volatile or const
919 // volatile object. A destructor shall not be declared const,
920 // volatile or const volatile (9.3.2).
921 if (SC == FunctionDecl::Static) {
922 Diag(D.getIdentifierLoc(),
923 diag::err_destructor_cannot_be,
924 "static",
925 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
926 SourceRange(D.getIdentifierLoc()));
927 isInvalid = true;
928 SC = FunctionDecl::None;
929 }
930 if (D.getDeclSpec().hasTypeSpecifier()) {
931 // Destructors don't have return types, but the parser will
932 // happily parse something like:
933 //
934 // class X {
935 // float ~X();
936 // };
937 //
938 // The return type will be eliminated later.
939 Diag(D.getIdentifierLoc(),
940 diag::err_destructor_return_type,
941 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
942 SourceRange(D.getIdentifierLoc()));
943 }
944 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
945 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
946 if (FTI.TypeQuals & QualType::Const)
947 Diag(D.getIdentifierLoc(),
948 diag::err_invalid_qualified_destructor,
949 "const",
950 SourceRange(D.getIdentifierLoc()));
951 if (FTI.TypeQuals & QualType::Volatile)
952 Diag(D.getIdentifierLoc(),
953 diag::err_invalid_qualified_destructor,
954 "volatile",
955 SourceRange(D.getIdentifierLoc()));
956 if (FTI.TypeQuals & QualType::Restrict)
957 Diag(D.getIdentifierLoc(),
958 diag::err_invalid_qualified_destructor,
959 "restrict",
960 SourceRange(D.getIdentifierLoc()));
961 }
962
963 // Make sure we don't have any parameters.
964 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
965 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
966
967 // Delete the parameters.
968 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
969 if (FTI.NumArgs) {
970 delete [] FTI.ArgInfo;
971 FTI.NumArgs = 0;
972 FTI.ArgInfo = 0;
973 }
974 }
975
976 // Make sure the destructor isn't variadic.
977 if (R->getAsFunctionTypeProto()->isVariadic())
978 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
979
980 // Rebuild the function type "R" without any type qualifiers or
981 // parameters (in case any of the errors above fired) and with
982 // "void" as the return type, since destructors don't have return
983 // types. We *always* have to do this, because GetTypeForDeclarator
984 // will put in a result type of "int" when none was specified.
985 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
986
987 return isInvalid;
988}
989
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000990/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete
991/// the declaration of the given C++ constructor ConDecl that was
992/// built from declarator D. This routine is responsible for checking
993/// that the newly-created constructor declaration is well-formed and
994/// for recording it in the C++ class. Example:
995///
996/// @code
997/// class X {
998/// X(); // X::X() will be the ConDecl.
999/// };
1000/// @endcode
1001Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) {
1002 assert(ConDecl && "Expected to receive a constructor declaration");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001003
1004 // Check default arguments on the constructor
1005 CheckCXXDefaultArguments(ConDecl);
1006
Douglas Gregorccabf082008-10-31 20:25:05 +00001007 CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1008 if (!ClassDecl) {
1009 ConDecl->setInvalidDecl();
1010 return ConDecl;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001011 }
1012
Douglas Gregorccabf082008-10-31 20:25:05 +00001013 // Make sure this constructor is an overload of the existing
1014 // constructors.
1015 OverloadedFunctionDecl::function_iterator MatchedDecl;
1016 if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) {
1017 Diag(ConDecl->getLocation(),
1018 diag::err_constructor_redeclared,
1019 SourceRange(ConDecl->getLocation()));
1020 Diag((*MatchedDecl)->getLocation(),
1021 diag::err_previous_declaration,
1022 SourceRange((*MatchedDecl)->getLocation()));
1023 ConDecl->setInvalidDecl();
1024 return ConDecl;
1025 }
1026
1027
1028 // C++ [class.copy]p3:
1029 // A declaration of a constructor for a class X is ill-formed if
1030 // its first parameter is of type (optionally cv-qualified) X and
1031 // either there are no other parameters or else all other
1032 // parameters have default arguments.
1033 if ((ConDecl->getNumParams() == 1) ||
1034 (ConDecl->getNumParams() > 1 &&
1035 ConDecl->getParamDecl(1)->getDefaultArg() != 0)) {
1036 QualType ParamType = ConDecl->getParamDecl(0)->getType();
1037 QualType ClassTy = Context.getTagDeclType(
1038 const_cast<CXXRecordDecl*>(ConDecl->getParent()));
1039 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1040 Diag(ConDecl->getLocation(),
1041 diag::err_constructor_byvalue_arg,
1042 SourceRange(ConDecl->getParamDecl(0)->getLocation()));
1043 ConDecl->setInvalidDecl();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001044 return ConDecl;
Douglas Gregorccabf082008-10-31 20:25:05 +00001045 }
1046 }
1047
1048 // Add this constructor to the set of constructors of the current
1049 // class.
1050 ClassDecl->addConstructor(Context, ConDecl);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001051 return (DeclTy *)ConDecl;
1052}
1053
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001054/// ActOnDestructorDeclarator - Called by ActOnDeclarator to complete
1055/// the declaration of the given C++ @p Destructor. This routine is
1056/// responsible for recording the destructor in the C++ class, if
1057/// possible.
1058Sema::DeclTy *Sema::ActOnDestructorDeclarator(CXXDestructorDecl *Destructor) {
1059 assert(Destructor && "Expected to receive a destructor declaration");
1060
1061 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext);
1062
1063 // Make sure we aren't redeclaring the destructor.
1064 if (CXXDestructorDecl *PrevDestructor = ClassDecl->getDestructor()) {
1065 Diag(Destructor->getLocation(), diag::err_destructor_redeclared);
1066 Diag(PrevDestructor->getLocation(),
1067 PrevDestructor->isThisDeclarationADefinition()?
1068 diag::err_previous_definition
1069 : diag::err_previous_declaration);
1070 Destructor->setInvalidDecl();
1071 return Destructor;
1072 }
1073
1074 ClassDecl->setDestructor(Destructor);
1075 return (DeclTy *)Destructor;
1076}
1077
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001078//===----------------------------------------------------------------------===//
1079// Namespace Handling
1080//===----------------------------------------------------------------------===//
1081
1082/// ActOnStartNamespaceDef - This is called at the start of a namespace
1083/// definition.
1084Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1085 SourceLocation IdentLoc,
1086 IdentifierInfo *II,
1087 SourceLocation LBrace) {
1088 NamespaceDecl *Namespc =
1089 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1090 Namespc->setLBracLoc(LBrace);
1091
1092 Scope *DeclRegionScope = NamespcScope->getParent();
1093
1094 if (II) {
1095 // C++ [namespace.def]p2:
1096 // The identifier in an original-namespace-definition shall not have been
1097 // previously defined in the declarative region in which the
1098 // original-namespace-definition appears. The identifier in an
1099 // original-namespace-definition is the name of the namespace. Subsequently
1100 // in that declarative region, it is treated as an original-namespace-name.
1101
1102 Decl *PrevDecl =
Argiris Kirtzidisda64ff42008-10-14 18:28:48 +00001103 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001104 /*enableLazyBuiltinCreation=*/false);
1105
Argiris Kirtzidisad9de132008-09-10 02:11:07 +00001106 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001107 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
1108 // This is an extended namespace definition.
1109 // Attach this namespace decl to the chain of extended namespace
1110 // definitions.
1111 NamespaceDecl *NextNS = OrigNS;
1112 while (NextNS->getNextNamespace())
1113 NextNS = NextNS->getNextNamespace();
1114
1115 NextNS->setNextNamespace(Namespc);
1116 Namespc->setOriginalNamespace(OrigNS);
1117
1118 // We won't add this decl to the current scope. We want the namespace
1119 // name to return the original namespace decl during a name lookup.
1120 } else {
1121 // This is an invalid name redefinition.
1122 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
1123 Namespc->getName());
1124 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1125 Namespc->setInvalidDecl();
1126 // Continue on to push Namespc as current DeclContext and return it.
1127 }
1128 } else {
1129 // This namespace name is declared for the first time.
1130 PushOnScopeChains(Namespc, DeclRegionScope);
1131 }
1132 }
1133 else {
1134 // FIXME: Handle anonymous namespaces
1135 }
1136
1137 // Although we could have an invalid decl (i.e. the namespace name is a
1138 // redefinition), push it as current DeclContext and try to continue parsing.
1139 PushDeclContext(Namespc->getOriginalNamespace());
1140 return Namespc;
1141}
1142
1143/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1144/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1145void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1146 Decl *Dcl = static_cast<Decl *>(D);
1147 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1148 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1149 Namespc->setRBracLoc(RBrace);
1150 PopDeclContext();
1151}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001152
1153
1154/// AddCXXDirectInitializerToDecl - This action is called immediately after
1155/// ActOnDeclarator, when a C++ direct initializer is present.
1156/// e.g: "int x(1);"
1157void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1158 ExprTy **ExprTys, unsigned NumExprs,
1159 SourceLocation *CommaLocs,
1160 SourceLocation RParenLoc) {
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001161 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001162 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001163
1164 // If there is no declaration, there was an error parsing it. Just ignore
1165 // the initializer.
1166 if (RealDecl == 0) {
Ted Kremenek85b4c492008-10-06 20:35:04 +00001167 for (unsigned i = 0; i != NumExprs; ++i)
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001168 delete static_cast<Expr *>(ExprTys[i]);
1169 return;
1170 }
1171
1172 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1173 if (!VDecl) {
1174 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1175 RealDecl->setInvalidDecl();
1176 return;
1177 }
1178
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001179 // We will treat direct-initialization as a copy-initialization:
1180 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001181 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1182 //
1183 // Clients that want to distinguish between the two forms, can check for
1184 // direct initializer using VarDecl::hasCXXDirectInitializer().
1185 // A major benefit is that clients that don't particularly care about which
1186 // exactly form was it (like the CodeGen) can handle both cases without
1187 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001188
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001189 // C++ 8.5p11:
1190 // The form of initialization (using parentheses or '=') is generally
1191 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001192 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +00001193 QualType DeclInitType = VDecl->getType();
1194 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1195 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001196
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001197 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001198 CXXConstructorDecl *Constructor
Douglas Gregor6428e762008-11-05 15:29:30 +00001199 = PerformInitializationByConstructor(DeclInitType,
1200 (Expr **)ExprTys, NumExprs,
1201 VDecl->getLocation(),
1202 SourceRange(VDecl->getLocation(),
1203 RParenLoc),
1204 VDecl->getName(),
1205 IK_Direct);
Douglas Gregor5870a952008-11-03 20:45:27 +00001206 if (!Constructor) {
1207 RealDecl->setInvalidDecl();
1208 }
Douglas Gregor6428e762008-11-05 15:29:30 +00001209
1210 // Let clients know that initialization was done with a direct
1211 // initializer.
1212 VDecl->setCXXDirectInitializer(true);
1213
1214 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1215 // the initializer.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001216 return;
1217 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001218
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001219 if (NumExprs > 1) {
1220 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
1221 SourceRange(VDecl->getLocation(), RParenLoc));
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001222 RealDecl->setInvalidDecl();
1223 return;
1224 }
1225
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001226 // Let clients know that initialization was done with a direct initializer.
1227 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001228
1229 assert(NumExprs == 1 && "Expected 1 expression");
1230 // Set the init expression, handles conversions.
1231 AddInitializerToDecl(Dcl, ExprTys[0]);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001232}
Douglas Gregor81c29152008-10-29 00:13:59 +00001233
Douglas Gregor6428e762008-11-05 15:29:30 +00001234/// PerformInitializationByConstructor - Perform initialization by
1235/// constructor (C++ [dcl.init]p14), which may occur as part of
1236/// direct-initialization or copy-initialization. We are initializing
1237/// an object of type @p ClassType with the given arguments @p
1238/// Args. @p Loc is the location in the source code where the
1239/// initializer occurs (e.g., a declaration, member initializer,
1240/// functional cast, etc.) while @p Range covers the whole
1241/// initialization. @p InitEntity is the entity being initialized,
1242/// which may by the name of a declaration or a type. @p Kind is the
1243/// kind of initialization we're performing, which affects whether
1244/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00001245/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00001246/// when the initialization fails, emits a diagnostic and returns
1247/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00001248CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00001249Sema::PerformInitializationByConstructor(QualType ClassType,
1250 Expr **Args, unsigned NumArgs,
1251 SourceLocation Loc, SourceRange Range,
1252 std::string InitEntity,
1253 InitializationKind Kind) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001254 const RecordType *ClassRec = ClassType->getAsRecordType();
1255 assert(ClassRec && "Can only initialize a class type here");
1256
1257 // C++ [dcl.init]p14:
1258 //
1259 // If the initialization is direct-initialization, or if it is
1260 // copy-initialization where the cv-unqualified version of the
1261 // source type is the same class as, or a derived class of, the
1262 // class of the destination, constructors are considered. The
1263 // applicable constructors are enumerated (13.3.1.3), and the
1264 // best one is chosen through overload resolution (13.3). The
1265 // constructor so selected is called to initialize the object,
1266 // with the initializer expression(s) as its argument(s). If no
1267 // constructor applies, or the overload resolution is ambiguous,
1268 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00001269 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1270 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00001271
1272 // Add constructors to the overload set.
1273 OverloadedFunctionDecl *Constructors
1274 = const_cast<OverloadedFunctionDecl *>(ClassDecl->getConstructors());
1275 for (OverloadedFunctionDecl::function_iterator Con
1276 = Constructors->function_begin();
1277 Con != Constructors->function_end(); ++Con) {
1278 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1279 if ((Kind == IK_Direct) ||
1280 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1281 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1282 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1283 }
1284
Douglas Gregor5870a952008-11-03 20:45:27 +00001285 OverloadCandidateSet::iterator Best;
Douglas Gregor5870a952008-11-03 20:45:27 +00001286 switch (BestViableFunction(CandidateSet, Best)) {
1287 case OR_Success:
1288 // We found a constructor. Return it.
1289 return cast<CXXConstructorDecl>(Best->Function);
1290
1291 case OR_No_Viable_Function:
1292 if (CandidateSet.empty())
1293 Diag(Loc, diag::err_ovl_no_viable_function_in_init,
1294 InitEntity, Range);
1295 else {
1296 Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands,
1297 InitEntity, Range);
1298 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1299 }
1300 return 0;
1301
1302 case OR_Ambiguous:
1303 Diag(Loc, diag::err_ovl_ambiguous_init,
1304 InitEntity, Range);
1305 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1306 return 0;
1307 }
1308
1309 return 0;
1310}
1311
Douglas Gregor81c29152008-10-29 00:13:59 +00001312/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1313/// determine whether they are reference-related,
1314/// reference-compatible, reference-compatible with added
1315/// qualification, or incompatible, for use in C++ initialization by
1316/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1317/// type, and the first type (T1) is the pointee type of the reference
1318/// type being initialized.
1319Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001320Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1321 bool& DerivedToBase) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001322 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1323 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1324
1325 T1 = Context.getCanonicalType(T1);
1326 T2 = Context.getCanonicalType(T2);
1327 QualType UnqualT1 = T1.getUnqualifiedType();
1328 QualType UnqualT2 = T2.getUnqualifiedType();
1329
1330 // C++ [dcl.init.ref]p4:
1331 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1332 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1333 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001334 if (UnqualT1 == UnqualT2)
1335 DerivedToBase = false;
1336 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1337 DerivedToBase = true;
1338 else
Douglas Gregor81c29152008-10-29 00:13:59 +00001339 return Ref_Incompatible;
1340
1341 // At this point, we know that T1 and T2 are reference-related (at
1342 // least).
1343
1344 // C++ [dcl.init.ref]p4:
1345 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1346 // reference-related to T2 and cv1 is the same cv-qualification
1347 // as, or greater cv-qualification than, cv2. For purposes of
1348 // overload resolution, cases for which cv1 is greater
1349 // cv-qualification than cv2 are identified as
1350 // reference-compatible with added qualification (see 13.3.3.2).
1351 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1352 return Ref_Compatible;
1353 else if (T1.isMoreQualifiedThan(T2))
1354 return Ref_Compatible_With_Added_Qualification;
1355 else
1356 return Ref_Related;
1357}
1358
1359/// CheckReferenceInit - Check the initialization of a reference
1360/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1361/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00001362/// list), and DeclType is the type of the declaration. When ICS is
1363/// non-null, this routine will compute the implicit conversion
1364/// sequence according to C++ [over.ics.ref] and will not produce any
1365/// diagnostics; when ICS is null, it will emit diagnostics when any
1366/// errors are found. Either way, a return value of true indicates
1367/// that there was a failure, a return value of false indicates that
1368/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001369///
1370/// When @p SuppressUserConversions, user-defined conversions are
1371/// suppressed.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001372bool
1373Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001374 ImplicitConversionSequence *ICS,
1375 bool SuppressUserConversions) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001376 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1377
1378 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1379 QualType T2 = Init->getType();
1380
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001381 // Compute some basic properties of the types and the initializer.
1382 bool DerivedToBase = false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001383 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001384 ReferenceCompareResult RefRelationship
1385 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1386
1387 // Most paths end in a failed conversion.
1388 if (ICS)
1389 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00001390
1391 // C++ [dcl.init.ref]p5:
1392 // A reference to type “cv1 T1” is initialized by an expression
1393 // of type “cv2 T2” as follows:
1394
1395 // -- If the initializer expression
1396
1397 bool BindsDirectly = false;
1398 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1399 // reference-compatible with “cv2 T2,” or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001400 //
1401 // Note that the bit-field check is skipped if we are just computing
1402 // the implicit conversion sequence (C++ [over.best.ics]p2).
1403 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1404 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001405 BindsDirectly = true;
1406
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001407 if (ICS) {
1408 // C++ [over.ics.ref]p1:
1409 // When a parameter of reference type binds directly (8.5.3)
1410 // to an argument expression, the implicit conversion sequence
1411 // is the identity conversion, unless the argument expression
1412 // has a type that is a derived class of the parameter type,
1413 // in which case the implicit conversion sequence is a
1414 // derived-to-base Conversion (13.3.3.1).
1415 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1416 ICS->Standard.First = ICK_Identity;
1417 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1418 ICS->Standard.Third = ICK_Identity;
1419 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1420 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001421 ICS->Standard.ReferenceBinding = true;
1422 ICS->Standard.DirectBinding = true;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001423
1424 // Nothing more to do: the inaccessibility/ambiguity check for
1425 // derived-to-base conversions is suppressed when we're
1426 // computing the implicit conversion sequence (C++
1427 // [over.best.ics]p2).
1428 return false;
1429 } else {
1430 // Perform the conversion.
Douglas Gregor81c29152008-10-29 00:13:59 +00001431 // FIXME: Binding to a subobject of the lvalue is going to require
1432 // more AST annotation than this.
1433 ImpCastExprToType(Init, T1);
1434 }
1435 }
1436
1437 // -- has a class type (i.e., T2 is a class type) and can be
1438 // implicitly converted to an lvalue of type “cv3 T3,”
1439 // where “cv1 T1” is reference-compatible with “cv3 T3”
1440 // 92) (this conversion is selected by enumerating the
1441 // applicable conversion functions (13.3.1.6) and choosing
1442 // the best one through overload resolution (13.3)),
1443 // FIXME: Implement this second bullet, once we have conversion
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001444 // functions. Also remember C++ [over.ics.ref]p1, second part.
Douglas Gregor81c29152008-10-29 00:13:59 +00001445
1446 if (BindsDirectly) {
1447 // C++ [dcl.init.ref]p4:
1448 // [...] In all cases where the reference-related or
1449 // reference-compatible relationship of two types is used to
1450 // establish the validity of a reference binding, and T1 is a
1451 // base class of T2, a program that necessitates such a binding
1452 // is ill-formed if T1 is an inaccessible (clause 11) or
1453 // ambiguous (10.2) base class of T2.
1454 //
1455 // Note that we only check this condition when we're allowed to
1456 // complain about errors, because we should not be checking for
1457 // ambiguity (or inaccessibility) unless the reference binding
1458 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001459 if (DerivedToBase)
1460 return CheckDerivedToBaseConversion(T2, T1,
1461 Init->getSourceRange().getBegin(),
1462 Init->getSourceRange());
1463 else
1464 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001465 }
1466
1467 // -- Otherwise, the reference shall be to a non-volatile const
1468 // type (i.e., cv1 shall be const).
1469 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001470 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001471 Diag(Init->getSourceRange().getBegin(),
1472 diag::err_not_reference_to_const_init,
1473 T1.getAsString(),
1474 InitLvalue != Expr::LV_Valid? "temporary" : "value",
1475 T2.getAsString(), Init->getSourceRange());
1476 return true;
1477 }
1478
1479 // -- If the initializer expression is an rvalue, with T2 a
1480 // class type, and “cv1 T1” is reference-compatible with
1481 // “cv2 T2,” the reference is bound in one of the
1482 // following ways (the choice is implementation-defined):
1483 //
1484 // -- The reference is bound to the object represented by
1485 // the rvalue (see 3.10) or to a sub-object within that
1486 // object.
1487 //
1488 // -- A temporary of type “cv1 T2” [sic] is created, and
1489 // a constructor is called to copy the entire rvalue
1490 // object into the temporary. The reference is bound to
1491 // the temporary or to a sub-object within the
1492 // temporary.
1493 //
1494 //
1495 // The constructor that would be used to make the copy
1496 // shall be callable whether or not the copy is actually
1497 // done.
1498 //
1499 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1500 // freedom, so we will always take the first option and never build
1501 // a temporary in this case. FIXME: We will, however, have to check
1502 // for the presence of a copy constructor in C++98/03 mode.
1503 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001504 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1505 if (ICS) {
1506 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1507 ICS->Standard.First = ICK_Identity;
1508 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1509 ICS->Standard.Third = ICK_Identity;
1510 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1511 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001512 ICS->Standard.ReferenceBinding = true;
1513 ICS->Standard.DirectBinding = false;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001514 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001515 // FIXME: Binding to a subobject of the rvalue is going to require
1516 // more AST annotation than this.
1517 ImpCastExprToType(Init, T1);
1518 }
1519 return false;
1520 }
1521
1522 // -- Otherwise, a temporary of type “cv1 T1” is created and
1523 // initialized from the initializer expression using the
1524 // rules for a non-reference copy initialization (8.5). The
1525 // reference is then bound to the temporary. If T1 is
1526 // reference-related to T2, cv1 must be the same
1527 // cv-qualification as, or greater cv-qualification than,
1528 // cv2; otherwise, the program is ill-formed.
1529 if (RefRelationship == Ref_Related) {
1530 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1531 // we would be reference-compatible or reference-compatible with
1532 // added qualification. But that wasn't the case, so the reference
1533 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001534 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001535 Diag(Init->getSourceRange().getBegin(),
1536 diag::err_reference_init_drops_quals,
1537 T1.getAsString(),
1538 InitLvalue != Expr::LV_Valid? "temporary" : "value",
1539 T2.getAsString(), Init->getSourceRange());
1540 return true;
1541 }
1542
1543 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001544 if (ICS) {
1545 /// C++ [over.ics.ref]p2:
1546 ///
1547 /// When a parameter of reference type is not bound directly to
1548 /// an argument expression, the conversion sequence is the one
1549 /// required to convert the argument expression to the
1550 /// underlying type of the reference according to
1551 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1552 /// to copy-initializing a temporary of the underlying type with
1553 /// the argument expression. Any difference in top-level
1554 /// cv-qualification is subsumed by the initialization itself
1555 /// and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001556 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001557 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1558 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001559 return PerformImplicitConversion(Init, T1);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001560 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001561}