blob: 33fc52b71dca6374586a430373dbb9b15832ebfc [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"
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregorec93f442008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregor05904022008-10-22 21:13:31 +000017#include "clang/AST/TypeOrdering.h"
Chris Lattner97316c02008-04-10 02:22:51 +000018#include "clang/AST/StmtVisitor.h"
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +000019#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000020#include "clang/Basic/Diagnostic.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000021#include "clang/Parse/DeclSpec.h"
Chris Lattner97316c02008-04-10 02:22:51 +000022#include "llvm/Support/Compiler.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000023#include <algorithm> // for std::equal
Douglas Gregorabed2172008-10-22 17:49:05 +000024#include <map>
Chris Lattnerac7b83a2008-04-08 05:04:30 +000025
26using namespace clang;
27
Chris Lattner97316c02008-04-10 02:22:51 +000028//===----------------------------------------------------------------------===//
29// CheckDefaultArgumentVisitor
30//===----------------------------------------------------------------------===//
31
Chris Lattnerb1856db2008-04-12 23:52:44 +000032namespace {
33 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
34 /// the default argument of a parameter to determine whether it
35 /// contains any ill-formed subexpressions. For example, this will
36 /// diagnose the use of local variables or parameters within the
37 /// default argument expression.
38 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000039 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb1856db2008-04-12 23:52:44 +000040 Expr *DefaultArg;
41 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000042
Chris Lattnerb1856db2008-04-12 23:52:44 +000043 public:
44 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
45 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000046
Chris Lattnerb1856db2008-04-12 23:52:44 +000047 bool VisitExpr(Expr *Node);
48 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor3c246952008-11-04 13:41:56 +000049 bool VisitPredefinedExpr(PredefinedExpr *PE);
Chris Lattnerb1856db2008-04-12 23:52:44 +000050 };
Chris Lattner97316c02008-04-10 02:22:51 +000051
Chris Lattnerb1856db2008-04-12 23:52:44 +000052 /// VisitExpr - Visit all of the children of this expression.
53 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
54 bool IsInvalid = false;
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000055 for (Stmt::child_iterator I = Node->child_begin(),
56 E = Node->child_end(); I != E; ++I)
57 IsInvalid |= Visit(*I);
Chris Lattnerb1856db2008-04-12 23:52:44 +000058 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000059 }
60
Chris Lattnerb1856db2008-04-12 23:52:44 +000061 /// VisitDeclRefExpr - Visit a reference to a declaration, to
62 /// determine whether this declaration can be used in the default
63 /// argument expression.
64 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregord2baafd2008-10-21 16:13:35 +000065 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb1856db2008-04-12 23:52:44 +000066 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
67 // C++ [dcl.fct.default]p9
68 // Default arguments are evaluated each time the function is
69 // called. The order of evaluation of function arguments is
70 // unspecified. Consequently, parameters of a function shall not
71 // be used in default argument expressions, even if they are not
72 // evaluated. Parameters of a function declared before a default
73 // argument expression are in scope and can hide namespace and
74 // class member names.
75 return S->Diag(DRE->getSourceRange().getBegin(),
76 diag::err_param_default_argument_references_param,
77 Param->getName(), DefaultArg->getSourceRange());
Steve Naroff72a6ebc2008-04-15 22:42:06 +000078 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000079 // C++ [dcl.fct.default]p7
80 // Local variables shall not be used in default argument
81 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000082 if (VDecl->isBlockVarDecl())
83 return S->Diag(DRE->getSourceRange().getBegin(),
84 diag::err_param_default_argument_references_local,
85 VDecl->getName(), DefaultArg->getSourceRange());
Chris Lattnerb1856db2008-04-12 23:52:44 +000086 }
Chris Lattner97316c02008-04-10 02:22:51 +000087
Douglas Gregor3c246952008-11-04 13:41:56 +000088 return false;
89 }
Chris Lattnerb1856db2008-04-12 23:52:44 +000090
Douglas Gregor3c246952008-11-04 13:41:56 +000091 /// VisitPredefinedExpr - Visit a predefined expression, which could
92 /// refer to "this".
93 bool CheckDefaultArgumentVisitor::VisitPredefinedExpr(PredefinedExpr *PE) {
94 if (PE->getIdentType() == PredefinedExpr::CXXThis) {
95 // C++ [dcl.fct.default]p8:
96 // The keyword this shall not be used in a default argument of a
97 // member function.
98 return S->Diag(PE->getSourceRange().getBegin(),
99 diag::err_param_default_argument_references_this,
100 PE->getSourceRange());
101 }
Chris Lattnerb1856db2008-04-12 23:52:44 +0000102 return false;
103 }
Chris Lattner97316c02008-04-10 02:22:51 +0000104}
105
106/// ActOnParamDefaultArgument - Check whether the default argument
107/// provided for a function parameter is well-formed. If so, attach it
108/// to the parameter declaration.
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000109void
110Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
111 ExprTy *defarg) {
112 ParmVarDecl *Param = (ParmVarDecl *)param;
113 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
114 QualType ParamType = Param->getType();
115
116 // Default arguments are only permitted in C++
117 if (!getLangOptions().CPlusPlus) {
118 Diag(EqualLoc, diag::err_param_default_argument,
119 DefaultArg->getSourceRange());
120 return;
121 }
122
123 // C++ [dcl.fct.default]p5
124 // A default argument expression is implicitly converted (clause
125 // 4) to the parameter type. The default argument expression has
126 // the same semantic constraints as the initializer expression in
127 // a declaration of a variable of the parameter type, using the
128 // copy-initialization semantics (8.5).
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000129 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor58c428c2008-11-04 13:57:51 +0000130 bool DefaultInitFailed = PerformCopyInitialization(DefaultArgPtr, ParamType,
131 "in default argument");
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000132 if (DefaultArgPtr != DefaultArg.get()) {
133 DefaultArg.take();
134 DefaultArg.reset(DefaultArgPtr);
135 }
Douglas Gregor58c428c2008-11-04 13:57:51 +0000136 if (DefaultInitFailed) {
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000137 return;
138 }
139
Chris Lattner97316c02008-04-10 02:22:51 +0000140 // Check that the default argument is well-formed
Chris Lattnerb1856db2008-04-12 23:52:44 +0000141 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Chris Lattner97316c02008-04-10 02:22:51 +0000142 if (DefaultArgChecker.Visit(DefaultArg.get()))
143 return;
144
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000145 // Okay: add the default argument to the parameter
146 Param->setDefaultArg(DefaultArg.take());
147}
148
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000149/// CheckExtraCXXDefaultArguments - Check for any extra default
150/// arguments in the declarator, which is not a function declaration
151/// or definition and therefore is not permitted to have default
152/// arguments. This routine should be invoked for every declarator
153/// that is not a function declaration or definition.
154void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
155 // C++ [dcl.fct.default]p3
156 // A default argument expression shall be specified only in the
157 // parameter-declaration-clause of a function declaration or in a
158 // template-parameter (14.1). It shall not be specified for a
159 // parameter pack. If it is specified in a
160 // parameter-declaration-clause, it shall not occur within a
161 // declarator or abstract-declarator of a parameter-declaration.
162 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
163 DeclaratorChunk &chunk = D.getTypeObject(i);
164 if (chunk.Kind == DeclaratorChunk::Function) {
165 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
166 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
167 if (Param->getDefaultArg()) {
168 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc,
169 Param->getDefaultArg()->getSourceRange());
170 Param->setDefaultArg(0);
171 }
172 }
173 }
174 }
175}
176
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000177// MergeCXXFunctionDecl - Merge two declarations of the same C++
178// function, once we already know that they have the same
179// type. Subroutine of MergeFunctionDecl.
180FunctionDecl *
181Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
182 // C++ [dcl.fct.default]p4:
183 //
184 // For non-template functions, default arguments can be added in
185 // later declarations of a function in the same
186 // scope. Declarations in different scopes have completely
187 // distinct sets of default arguments. That is, declarations in
188 // inner scopes do not acquire default arguments from
189 // declarations in outer scopes, and vice versa. In a given
190 // function declaration, all parameters subsequent to a
191 // parameter with a default argument shall have default
192 // arguments supplied in this or previous declarations. A
193 // default argument shall not be redefined by a later
194 // declaration (not even to the same value).
195 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
196 ParmVarDecl *OldParam = Old->getParamDecl(p);
197 ParmVarDecl *NewParam = New->getParamDecl(p);
198
199 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
200 Diag(NewParam->getLocation(),
201 diag::err_param_default_argument_redefinition,
202 NewParam->getDefaultArg()->getSourceRange());
203 Diag(OldParam->getLocation(), diag::err_previous_definition);
204 } else if (OldParam->getDefaultArg()) {
205 // Merge the old default argument into the new parameter
206 NewParam->setDefaultArg(OldParam->getDefaultArg());
207 }
208 }
209
210 return New;
211}
212
213/// CheckCXXDefaultArguments - Verify that the default arguments for a
214/// function declaration are well-formed according to C++
215/// [dcl.fct.default].
216void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
217 unsigned NumParams = FD->getNumParams();
218 unsigned p;
219
220 // Find first parameter with a default argument
221 for (p = 0; p < NumParams; ++p) {
222 ParmVarDecl *Param = FD->getParamDecl(p);
223 if (Param->getDefaultArg())
224 break;
225 }
226
227 // C++ [dcl.fct.default]p4:
228 // In a given function declaration, all parameters
229 // subsequent to a parameter with a default argument shall
230 // have default arguments supplied in this or previous
231 // declarations. A default argument shall not be redefined
232 // by a later declaration (not even to the same value).
233 unsigned LastMissingDefaultArg = 0;
234 for(; p < NumParams; ++p) {
235 ParmVarDecl *Param = FD->getParamDecl(p);
236 if (!Param->getDefaultArg()) {
237 if (Param->getIdentifier())
238 Diag(Param->getLocation(),
239 diag::err_param_default_argument_missing_name,
240 Param->getIdentifier()->getName());
241 else
242 Diag(Param->getLocation(),
243 diag::err_param_default_argument_missing);
244
245 LastMissingDefaultArg = p;
246 }
247 }
248
249 if (LastMissingDefaultArg > 0) {
250 // Some default arguments were missing. Clear out all of the
251 // default arguments up to (and including) the last missing
252 // default argument, so that we leave the function parameters
253 // in a semantically valid state.
254 for (p = 0; p <= LastMissingDefaultArg; ++p) {
255 ParmVarDecl *Param = FD->getParamDecl(p);
256 if (Param->getDefaultArg()) {
257 delete Param->getDefaultArg();
258 Param->setDefaultArg(0);
259 }
260 }
261 }
262}
Douglas Gregorec93f442008-04-13 21:30:24 +0000263
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000264/// isCurrentClassName - Determine whether the identifier II is the
265/// name of the class type currently being defined. In the case of
266/// nested classes, this will only return true if II is the name of
267/// the innermost class.
268bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *) {
269 if (CXXRecordDecl *CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext))
270 return &II == CurDecl->getIdentifier();
271 else
272 return false;
273}
274
Douglas Gregorec93f442008-04-13 21:30:24 +0000275/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
276/// one entry in the base class list of a class specifier, for
277/// example:
278/// class foo : public bar, virtual private baz {
279/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorabed2172008-10-22 17:49:05 +0000280Sema::BaseResult
281Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
282 bool Virtual, AccessSpecifier Access,
283 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000284 RecordDecl *Decl = (RecordDecl*)classdecl;
285 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
286
287 // Base specifiers must be record types.
288 if (!BaseType->isRecordType()) {
289 Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000290 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000291 }
292
293 // C++ [class.union]p1:
294 // A union shall not be used as a base class.
295 if (BaseType->isUnionType()) {
296 Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000297 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000298 }
299
300 // C++ [class.union]p1:
301 // A union shall not have base classes.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000302 if (Decl->isUnion()) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000303 Diag(Decl->getLocation(), diag::err_base_clause_on_union,
304 SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000305 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000306 }
307
308 // C++ [class.derived]p2:
309 // The class-name in a base-specifier shall not be an incompletely
310 // defined class.
311 if (BaseType->isIncompleteType()) {
312 Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000313 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000314 }
315
Douglas Gregorabed2172008-10-22 17:49:05 +0000316 // Create the base specifier.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000317 return new CXXBaseSpecifier(SpecifierRange, Virtual,
318 BaseType->isClassType(), Access, BaseType);
Douglas Gregorabed2172008-10-22 17:49:05 +0000319}
Douglas Gregorec93f442008-04-13 21:30:24 +0000320
Douglas Gregorabed2172008-10-22 17:49:05 +0000321/// ActOnBaseSpecifiers - Attach the given base specifiers to the
322/// class, after checking whether there are any duplicate base
323/// classes.
324void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
325 unsigned NumBases) {
326 if (NumBases == 0)
327 return;
328
329 // Used to keep track of which base types we have already seen, so
330 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000331 // that the key is always the unqualified canonical type of the base
332 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000333 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
334
335 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000336 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
337 unsigned NumGoodBases = 0;
338 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000339 QualType NewBaseType
Douglas Gregor4fd85902008-10-23 18:13:27 +0000340 = Context.getCanonicalType(BaseSpecs[idx]->getType());
341 NewBaseType = NewBaseType.getUnqualifiedType();
342
Douglas Gregorabed2172008-10-22 17:49:05 +0000343 if (KnownBaseTypes[NewBaseType]) {
344 // C++ [class.mi]p3:
345 // A class shall not be specified as a direct base class of a
346 // derived class more than once.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000347 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Douglas Gregorabed2172008-10-22 17:49:05 +0000348 diag::err_duplicate_base_class,
349 KnownBaseTypes[NewBaseType]->getType().getAsString(),
Douglas Gregor4fd85902008-10-23 18:13:27 +0000350 BaseSpecs[idx]->getSourceRange());
351
352 // Delete the duplicate base class specifier; we're going to
353 // overwrite its pointer later.
354 delete BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000355 } else {
356 // Okay, add this new base class.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000357 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
358 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000359 }
360 }
361
362 // Attach the remaining base class specifiers to the derived class.
363 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000364 Decl->setBases(BaseSpecs, NumGoodBases);
365
366 // Delete the remaining (good) base class specifiers, since their
367 // data has been copied into the CXXRecordDecl.
368 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
369 delete BaseSpecs[idx];
Douglas Gregorec93f442008-04-13 21:30:24 +0000370}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000371
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000372//===----------------------------------------------------------------------===//
373// C++ class member Handling
374//===----------------------------------------------------------------------===//
375
376/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
377/// definition, when on C++.
378void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000379 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
380 PushDeclContext(Dcl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000381 FieldCollector->StartClass();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000382
383 if (Dcl->getIdentifier()) {
384 // C++ [class]p2:
385 // [...] The class-name is also inserted into the scope of the
386 // class itself; this is known as the injected-class-name. For
387 // purposes of access checking, the injected-class-name is treated
388 // as if it were a public member name.
389 TypedefDecl *InjectedClassName
390 = TypedefDecl::Create(Context, Dcl, LBrace, Dcl->getIdentifier(),
391 Context.getTypeDeclType(Dcl), /*PrevDecl=*/0);
392 PushOnScopeChains(InjectedClassName, S);
393 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000394}
395
396/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
397/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
398/// bitfield width if there is one and 'InitExpr' specifies the initializer if
399/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
400/// declarators on it.
401///
402/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
403/// an instance field is declared, a new CXXFieldDecl is created but the method
404/// does *not* return it; it returns LastInGroup instead. The other C++ members
405/// (which are all ScopedDecls) are returned after appending them to
406/// LastInGroup.
407Sema::DeclTy *
408Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
409 ExprTy *BW, ExprTy *InitExpr,
410 DeclTy *LastInGroup) {
411 const DeclSpec &DS = D.getDeclSpec();
412 IdentifierInfo *II = D.getIdentifier();
413 Expr *BitWidth = static_cast<Expr*>(BW);
414 Expr *Init = static_cast<Expr*>(InitExpr);
415 SourceLocation Loc = D.getIdentifierLoc();
416
417 // C++ 9.2p6: A member shall not be declared to have automatic storage
418 // duration (auto, register) or with the extern storage-class-specifier.
419 switch (DS.getStorageClassSpec()) {
420 case DeclSpec::SCS_unspecified:
421 case DeclSpec::SCS_typedef:
422 case DeclSpec::SCS_static:
423 // FALL THROUGH.
424 break;
425 default:
426 if (DS.getStorageClassSpecLoc().isValid())
427 Diag(DS.getStorageClassSpecLoc(),
428 diag::err_storageclass_invalid_for_member);
429 else
430 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
431 D.getMutableDeclSpec().ClearStorageClassSpecs();
432 }
433
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000434 bool isFunc = D.isFunctionDeclarator();
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000435 if (!isFunc &&
436 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
437 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000438 // Check also for this case:
439 //
440 // typedef int f();
441 // f a;
442 //
443 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
444 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
445 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000446
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000447 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000448 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000449
450 Decl *Member;
451 bool InvalidDecl = false;
452
453 if (isInstField)
454 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
455 else
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000456 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000457
458 if (!Member) return LastInGroup;
459
Sanjiv Guptafa451432008-10-31 09:52:39 +0000460 assert((II || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000461
462 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
463 // specific methods. Use a wrapper class that can be used with all C++ class
464 // member decls.
465 CXXClassMemberWrapper(Member).setAccess(AS);
466
467 if (BitWidth) {
468 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
469 // constant-expression be a value equal to zero.
470 // FIXME: Check this.
471
472 if (D.isFunctionDeclarator()) {
473 // FIXME: Emit diagnostic about only constructors taking base initializers
474 // or something similar, when constructor support is in place.
475 Diag(Loc, diag::err_not_bitfield_type,
476 II->getName(), BitWidth->getSourceRange());
477 InvalidDecl = true;
478
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000479 } else if (isInstField) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000480 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000481 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000482 Diag(Loc, diag::err_not_integral_type_bitfield,
483 II->getName(), BitWidth->getSourceRange());
484 InvalidDecl = true;
485 }
486
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000487 } else if (isa<FunctionDecl>(Member)) {
488 // A function typedef ("typedef int f(); f a;").
489 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
490 Diag(Loc, diag::err_not_integral_type_bitfield,
491 II->getName(), BitWidth->getSourceRange());
492 InvalidDecl = true;
493
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000494 } else if (isa<TypedefDecl>(Member)) {
495 // "cannot declare 'A' to be a bit-field type"
496 Diag(Loc, diag::err_not_bitfield_type, II->getName(),
497 BitWidth->getSourceRange());
498 InvalidDecl = true;
499
500 } else {
501 assert(isa<CXXClassVarDecl>(Member) &&
502 "Didn't we cover all member kinds?");
503 // C++ 9.6p3: A bit-field shall not be a static member.
504 // "static member 'A' cannot be a bit-field"
505 Diag(Loc, diag::err_static_not_bitfield, II->getName(),
506 BitWidth->getSourceRange());
507 InvalidDecl = true;
508 }
509 }
510
511 if (Init) {
512 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
513 // if it declares a static member of const integral or const enumeration
514 // type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000515 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
516 // ...static member of...
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000517 CVD->setInit(Init);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000518 // ...const integral or const enumeration type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000519 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
520 CVD->getType()->isIntegralType()) {
521 // constant-initializer
522 if (CheckForConstantInitializer(Init, CVD->getType()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000523 InvalidDecl = true;
524
525 } else {
526 // not const integral.
527 Diag(Loc, diag::err_member_initialization,
528 II->getName(), Init->getSourceRange());
529 InvalidDecl = true;
530 }
531
532 } else {
533 // not static member.
534 Diag(Loc, diag::err_member_initialization,
535 II->getName(), Init->getSourceRange());
536 InvalidDecl = true;
537 }
538 }
539
540 if (InvalidDecl)
541 Member->setInvalidDecl();
542
543 if (isInstField) {
544 FieldCollector->Add(cast<CXXFieldDecl>(Member));
545 return LastInGroup;
546 }
547 return Member;
548}
549
550void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
551 DeclTy *TagDecl,
552 SourceLocation LBrac,
553 SourceLocation RBrac) {
554 ActOnFields(S, RLoc, TagDecl,
555 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +0000556 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000557}
558
Douglas Gregore640ab62008-11-03 17:51:48 +0000559/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
560/// special functions, such as the default constructor, copy
561/// constructor, or destructor, to the given C++ class (C++
562/// [special]p1). This routine can only be executed just before the
563/// definition of the class is complete.
564void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
565 if (!ClassDecl->hasUserDeclaredConstructor()) {
566 // C++ [class.ctor]p5:
567 // A default constructor for a class X is a constructor of class X
568 // that can be called without an argument. If there is no
569 // user-declared constructor for class X, a default constructor is
570 // implicitly declared. An implicitly-declared default constructor
571 // is an inline public member of its class.
572 CXXConstructorDecl *DefaultCon =
573 CXXConstructorDecl::Create(Context, ClassDecl,
574 ClassDecl->getLocation(),
575 ClassDecl->getIdentifier(),
576 Context.getFunctionType(Context.VoidTy,
577 0, 0, false, 0),
578 /*isExplicit=*/false,
579 /*isInline=*/true,
580 /*isImplicitlyDeclared=*/true);
581 DefaultCon->setAccess(AS_public);
582 ClassDecl->addConstructor(Context, DefaultCon);
583 }
584
585 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
586 // C++ [class.copy]p4:
587 // If the class definition does not explicitly declare a copy
588 // constructor, one is declared implicitly.
589
590 // C++ [class.copy]p5:
591 // The implicitly-declared copy constructor for a class X will
592 // have the form
593 //
594 // X::X(const X&)
595 //
596 // if
597 bool HasConstCopyConstructor = true;
598
599 // -- each direct or virtual base class B of X has a copy
600 // constructor whose first parameter is of type const B& or
601 // const volatile B&, and
602 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
603 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
604 const CXXRecordDecl *BaseClassDecl
605 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
606 HasConstCopyConstructor
607 = BaseClassDecl->hasConstCopyConstructor(Context);
608 }
609
610 // -- for all the nonstatic data members of X that are of a
611 // class type M (or array thereof), each such class type
612 // has a copy constructor whose first parameter is of type
613 // const M& or const volatile M&.
614 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
615 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
616 QualType FieldType = (*Field)->getType();
617 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
618 FieldType = Array->getElementType();
619 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
620 const CXXRecordDecl *FieldClassDecl
621 = cast<CXXRecordDecl>(FieldClassType->getDecl());
622 HasConstCopyConstructor
623 = FieldClassDecl->hasConstCopyConstructor(Context);
624 }
625 }
626
627 // Otherwise, the implicitly declared copy constructor will have
628 // the form
629 //
630 // X::X(X&)
631 QualType ArgType = Context.getTypeDeclType(ClassDecl);
632 if (HasConstCopyConstructor)
633 ArgType = ArgType.withConst();
634 ArgType = Context.getReferenceType(ArgType);
635
636 // An implicitly-declared copy constructor is an inline public
637 // member of its class.
638 CXXConstructorDecl *CopyConstructor
639 = CXXConstructorDecl::Create(Context, ClassDecl,
640 ClassDecl->getLocation(),
641 ClassDecl->getIdentifier(),
642 Context.getFunctionType(Context.VoidTy,
643 &ArgType, 1,
644 false, 0),
645 /*isExplicit=*/false,
646 /*isInline=*/true,
647 /*isImplicitlyDeclared=*/true);
648 CopyConstructor->setAccess(AS_public);
649
650 // Add the parameter to the constructor.
651 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
652 ClassDecl->getLocation(),
653 /*IdentifierInfo=*/0,
654 ArgType, VarDecl::None, 0, 0);
655 CopyConstructor->setParams(&FromParam, 1);
656
657 ClassDecl->addConstructor(Context, CopyConstructor);
658 }
659
660 // FIXME: Implicit destructor
661 // FIXME: Implicit copy assignment operator
662}
663
Argiris Kirtzidis448b4e42008-08-09 00:39:29 +0000664void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000665 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000666 FieldCollector->FinishClass();
Douglas Gregore640ab62008-11-03 17:51:48 +0000667 AddImplicitlyDeclaredMembersToClass(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000668 PopDeclContext();
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000669
670 // Everything, including inline method definitions, have been parsed.
671 // Let the consumer know of the new TagDecl definition.
672 Consumer.HandleTagDeclDefinition(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000673}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000674
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000675/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete
676/// the declaration of the given C++ constructor ConDecl that was
677/// built from declarator D. This routine is responsible for checking
678/// that the newly-created constructor declaration is well-formed and
679/// for recording it in the C++ class. Example:
680///
681/// @code
682/// class X {
683/// X(); // X::X() will be the ConDecl.
684/// };
685/// @endcode
686Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) {
687 assert(ConDecl && "Expected to receive a constructor declaration");
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000688
689 // Check default arguments on the constructor
690 CheckCXXDefaultArguments(ConDecl);
691
Douglas Gregorccabf082008-10-31 20:25:05 +0000692 CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
693 if (!ClassDecl) {
694 ConDecl->setInvalidDecl();
695 return ConDecl;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000696 }
697
Douglas Gregorccabf082008-10-31 20:25:05 +0000698 // Make sure this constructor is an overload of the existing
699 // constructors.
700 OverloadedFunctionDecl::function_iterator MatchedDecl;
701 if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) {
702 Diag(ConDecl->getLocation(),
703 diag::err_constructor_redeclared,
704 SourceRange(ConDecl->getLocation()));
705 Diag((*MatchedDecl)->getLocation(),
706 diag::err_previous_declaration,
707 SourceRange((*MatchedDecl)->getLocation()));
708 ConDecl->setInvalidDecl();
709 return ConDecl;
710 }
711
712
713 // C++ [class.copy]p3:
714 // A declaration of a constructor for a class X is ill-formed if
715 // its first parameter is of type (optionally cv-qualified) X and
716 // either there are no other parameters or else all other
717 // parameters have default arguments.
718 if ((ConDecl->getNumParams() == 1) ||
719 (ConDecl->getNumParams() > 1 &&
720 ConDecl->getParamDecl(1)->getDefaultArg() != 0)) {
721 QualType ParamType = ConDecl->getParamDecl(0)->getType();
722 QualType ClassTy = Context.getTagDeclType(
723 const_cast<CXXRecordDecl*>(ConDecl->getParent()));
724 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
725 Diag(ConDecl->getLocation(),
726 diag::err_constructor_byvalue_arg,
727 SourceRange(ConDecl->getParamDecl(0)->getLocation()));
728 ConDecl->setInvalidDecl();
729 return 0;
730 }
731 }
732
733 // Add this constructor to the set of constructors of the current
734 // class.
735 ClassDecl->addConstructor(Context, ConDecl);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000736
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000737 return (DeclTy *)ConDecl;
738}
739
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000740//===----------------------------------------------------------------------===//
741// Namespace Handling
742//===----------------------------------------------------------------------===//
743
744/// ActOnStartNamespaceDef - This is called at the start of a namespace
745/// definition.
746Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
747 SourceLocation IdentLoc,
748 IdentifierInfo *II,
749 SourceLocation LBrace) {
750 NamespaceDecl *Namespc =
751 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
752 Namespc->setLBracLoc(LBrace);
753
754 Scope *DeclRegionScope = NamespcScope->getParent();
755
756 if (II) {
757 // C++ [namespace.def]p2:
758 // The identifier in an original-namespace-definition shall not have been
759 // previously defined in the declarative region in which the
760 // original-namespace-definition appears. The identifier in an
761 // original-namespace-definition is the name of the namespace. Subsequently
762 // in that declarative region, it is treated as an original-namespace-name.
763
764 Decl *PrevDecl =
Argiris Kirtzidisda64ff42008-10-14 18:28:48 +0000765 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000766 /*enableLazyBuiltinCreation=*/false);
767
Argiris Kirtzidisad9de132008-09-10 02:11:07 +0000768 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000769 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
770 // This is an extended namespace definition.
771 // Attach this namespace decl to the chain of extended namespace
772 // definitions.
773 NamespaceDecl *NextNS = OrigNS;
774 while (NextNS->getNextNamespace())
775 NextNS = NextNS->getNextNamespace();
776
777 NextNS->setNextNamespace(Namespc);
778 Namespc->setOriginalNamespace(OrigNS);
779
780 // We won't add this decl to the current scope. We want the namespace
781 // name to return the original namespace decl during a name lookup.
782 } else {
783 // This is an invalid name redefinition.
784 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
785 Namespc->getName());
786 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
787 Namespc->setInvalidDecl();
788 // Continue on to push Namespc as current DeclContext and return it.
789 }
790 } else {
791 // This namespace name is declared for the first time.
792 PushOnScopeChains(Namespc, DeclRegionScope);
793 }
794 }
795 else {
796 // FIXME: Handle anonymous namespaces
797 }
798
799 // Although we could have an invalid decl (i.e. the namespace name is a
800 // redefinition), push it as current DeclContext and try to continue parsing.
801 PushDeclContext(Namespc->getOriginalNamespace());
802 return Namespc;
803}
804
805/// ActOnFinishNamespaceDef - This callback is called after a namespace is
806/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
807void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
808 Decl *Dcl = static_cast<Decl *>(D);
809 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
810 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
811 Namespc->setRBracLoc(RBrace);
812 PopDeclContext();
813}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000814
815
816/// AddCXXDirectInitializerToDecl - This action is called immediately after
817/// ActOnDeclarator, when a C++ direct initializer is present.
818/// e.g: "int x(1);"
819void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
820 ExprTy **ExprTys, unsigned NumExprs,
821 SourceLocation *CommaLocs,
822 SourceLocation RParenLoc) {
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000823 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +0000824 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000825
826 // If there is no declaration, there was an error parsing it. Just ignore
827 // the initializer.
828 if (RealDecl == 0) {
Ted Kremenek85b4c492008-10-06 20:35:04 +0000829 for (unsigned i = 0; i != NumExprs; ++i)
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000830 delete static_cast<Expr *>(ExprTys[i]);
831 return;
832 }
833
834 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
835 if (!VDecl) {
836 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
837 RealDecl->setInvalidDecl();
838 return;
839 }
840
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +0000841 // We will treat direct-initialization as a copy-initialization:
842 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000843 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
844 //
845 // Clients that want to distinguish between the two forms, can check for
846 // direct initializer using VarDecl::hasCXXDirectInitializer().
847 // A major benefit is that clients that don't particularly care about which
848 // exactly form was it (like the CodeGen) can handle both cases without
849 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000850
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000851 // C++ 8.5p11:
852 // The form of initialization (using parentheses or '=') is generally
853 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000854 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +0000855 QualType DeclInitType = VDecl->getType();
856 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
857 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000858
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000859 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +0000860 CXXConstructorDecl *Constructor
861 = PerformDirectInitForClassType(DeclInitType, (Expr **)ExprTys, NumExprs,
862 VDecl->getLocation(),
863 SourceRange(VDecl->getLocation(),
864 RParenLoc),
865 VDecl->getName(),
866 /*HasInitializer=*/true);
867 if (!Constructor) {
868 RealDecl->setInvalidDecl();
869 }
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000870 return;
871 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000872
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +0000873 if (NumExprs > 1) {
874 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
875 SourceRange(VDecl->getLocation(), RParenLoc));
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000876 RealDecl->setInvalidDecl();
877 return;
878 }
879
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000880 // Let clients know that initialization was done with a direct initializer.
881 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +0000882
883 assert(NumExprs == 1 && "Expected 1 expression");
884 // Set the init expression, handles conversions.
885 AddInitializerToDecl(Dcl, ExprTys[0]);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000886}
Douglas Gregor81c29152008-10-29 00:13:59 +0000887
Douglas Gregor5870a952008-11-03 20:45:27 +0000888/// PerformDirectInitForClassType - Perform direct-initialization (C++
889/// [dcl.init]) for a value of the given class type with the given set
890/// of arguments (@p Args). @p Loc is the location in the source code
891/// where the initializer occurs (e.g., a declaration, member
892/// initializer, functional cast, etc.) while @p Range covers the
893/// whole initialization. @p HasInitializer is true if the initializer
894/// was actually written in the source code. When successful, returns
895/// the constructor that will be used to perform the initialization;
896/// when the initialization fails, emits a diagnostic and returns null.
897CXXConstructorDecl *
898Sema::PerformDirectInitForClassType(QualType ClassType,
899 Expr **Args, unsigned NumArgs,
900 SourceLocation Loc, SourceRange Range,
901 std::string InitEntity,
902 bool HasInitializer) {
903 const RecordType *ClassRec = ClassType->getAsRecordType();
904 assert(ClassRec && "Can only initialize a class type here");
905
906 // C++ [dcl.init]p14:
907 //
908 // If the initialization is direct-initialization, or if it is
909 // copy-initialization where the cv-unqualified version of the
910 // source type is the same class as, or a derived class of, the
911 // class of the destination, constructors are considered. The
912 // applicable constructors are enumerated (13.3.1.3), and the
913 // best one is chosen through overload resolution (13.3). The
914 // constructor so selected is called to initialize the object,
915 // with the initializer expression(s) as its argument(s). If no
916 // constructor applies, or the overload resolution is ambiguous,
917 // the initialization is ill-formed.
918 //
919 // FIXME: We don't check cv-qualifiers on the class type, because we
920 // don't yet keep track of whether a class type is a POD class type
921 // (or a "trivial" class type, as is used in C++0x).
922 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
923 OverloadCandidateSet CandidateSet;
924 OverloadCandidateSet::iterator Best;
925 AddOverloadCandidates(ClassDecl->getConstructors(), Args, NumArgs,
926 CandidateSet);
927 switch (BestViableFunction(CandidateSet, Best)) {
928 case OR_Success:
929 // We found a constructor. Return it.
930 return cast<CXXConstructorDecl>(Best->Function);
931
932 case OR_No_Viable_Function:
933 if (CandidateSet.empty())
934 Diag(Loc, diag::err_ovl_no_viable_function_in_init,
935 InitEntity, Range);
936 else {
937 Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands,
938 InitEntity, Range);
939 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
940 }
941 return 0;
942
943 case OR_Ambiguous:
944 Diag(Loc, diag::err_ovl_ambiguous_init,
945 InitEntity, Range);
946 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
947 return 0;
948 }
949
950 return 0;
951}
952
Douglas Gregor81c29152008-10-29 00:13:59 +0000953/// CompareReferenceRelationship - Compare the two types T1 and T2 to
954/// determine whether they are reference-related,
955/// reference-compatible, reference-compatible with added
956/// qualification, or incompatible, for use in C++ initialization by
957/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
958/// type, and the first type (T1) is the pointee type of the reference
959/// type being initialized.
960Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000961Sema::CompareReferenceRelationship(QualType T1, QualType T2,
962 bool& DerivedToBase) {
Douglas Gregor81c29152008-10-29 00:13:59 +0000963 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
964 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
965
966 T1 = Context.getCanonicalType(T1);
967 T2 = Context.getCanonicalType(T2);
968 QualType UnqualT1 = T1.getUnqualifiedType();
969 QualType UnqualT2 = T2.getUnqualifiedType();
970
971 // C++ [dcl.init.ref]p4:
972 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
973 // reference-related to “cv2 T2” if T1 is the same type as T2, or
974 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000975 if (UnqualT1 == UnqualT2)
976 DerivedToBase = false;
977 else if (IsDerivedFrom(UnqualT2, UnqualT1))
978 DerivedToBase = true;
979 else
Douglas Gregor81c29152008-10-29 00:13:59 +0000980 return Ref_Incompatible;
981
982 // At this point, we know that T1 and T2 are reference-related (at
983 // least).
984
985 // C++ [dcl.init.ref]p4:
986 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
987 // reference-related to T2 and cv1 is the same cv-qualification
988 // as, or greater cv-qualification than, cv2. For purposes of
989 // overload resolution, cases for which cv1 is greater
990 // cv-qualification than cv2 are identified as
991 // reference-compatible with added qualification (see 13.3.3.2).
992 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
993 return Ref_Compatible;
994 else if (T1.isMoreQualifiedThan(T2))
995 return Ref_Compatible_With_Added_Qualification;
996 else
997 return Ref_Related;
998}
999
1000/// CheckReferenceInit - Check the initialization of a reference
1001/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1002/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00001003/// list), and DeclType is the type of the declaration. When ICS is
1004/// non-null, this routine will compute the implicit conversion
1005/// sequence according to C++ [over.ics.ref] and will not produce any
1006/// diagnostics; when ICS is null, it will emit diagnostics when any
1007/// errors are found. Either way, a return value of true indicates
1008/// that there was a failure, a return value of false indicates that
1009/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001010///
1011/// When @p SuppressUserConversions, user-defined conversions are
1012/// suppressed.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001013bool
1014Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001015 ImplicitConversionSequence *ICS,
1016 bool SuppressUserConversions) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001017 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1018
1019 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1020 QualType T2 = Init->getType();
1021
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001022 // Compute some basic properties of the types and the initializer.
1023 bool DerivedToBase = false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001024 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001025 ReferenceCompareResult RefRelationship
1026 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1027
1028 // Most paths end in a failed conversion.
1029 if (ICS)
1030 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00001031
1032 // C++ [dcl.init.ref]p5:
1033 // A reference to type “cv1 T1” is initialized by an expression
1034 // of type “cv2 T2” as follows:
1035
1036 // -- If the initializer expression
1037
1038 bool BindsDirectly = false;
1039 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1040 // reference-compatible with “cv2 T2,” or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001041 //
1042 // Note that the bit-field check is skipped if we are just computing
1043 // the implicit conversion sequence (C++ [over.best.ics]p2).
1044 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1045 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001046 BindsDirectly = true;
1047
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001048 if (ICS) {
1049 // C++ [over.ics.ref]p1:
1050 // When a parameter of reference type binds directly (8.5.3)
1051 // to an argument expression, the implicit conversion sequence
1052 // is the identity conversion, unless the argument expression
1053 // has a type that is a derived class of the parameter type,
1054 // in which case the implicit conversion sequence is a
1055 // derived-to-base Conversion (13.3.3.1).
1056 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1057 ICS->Standard.First = ICK_Identity;
1058 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1059 ICS->Standard.Third = ICK_Identity;
1060 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1061 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001062 ICS->Standard.ReferenceBinding = true;
1063 ICS->Standard.DirectBinding = true;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001064
1065 // Nothing more to do: the inaccessibility/ambiguity check for
1066 // derived-to-base conversions is suppressed when we're
1067 // computing the implicit conversion sequence (C++
1068 // [over.best.ics]p2).
1069 return false;
1070 } else {
1071 // Perform the conversion.
Douglas Gregor81c29152008-10-29 00:13:59 +00001072 // FIXME: Binding to a subobject of the lvalue is going to require
1073 // more AST annotation than this.
1074 ImpCastExprToType(Init, T1);
1075 }
1076 }
1077
1078 // -- has a class type (i.e., T2 is a class type) and can be
1079 // implicitly converted to an lvalue of type “cv3 T3,”
1080 // where “cv1 T1” is reference-compatible with “cv3 T3”
1081 // 92) (this conversion is selected by enumerating the
1082 // applicable conversion functions (13.3.1.6) and choosing
1083 // the best one through overload resolution (13.3)),
1084 // FIXME: Implement this second bullet, once we have conversion
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001085 // functions. Also remember C++ [over.ics.ref]p1, second part.
Douglas Gregor81c29152008-10-29 00:13:59 +00001086
1087 if (BindsDirectly) {
1088 // C++ [dcl.init.ref]p4:
1089 // [...] In all cases where the reference-related or
1090 // reference-compatible relationship of two types is used to
1091 // establish the validity of a reference binding, and T1 is a
1092 // base class of T2, a program that necessitates such a binding
1093 // is ill-formed if T1 is an inaccessible (clause 11) or
1094 // ambiguous (10.2) base class of T2.
1095 //
1096 // Note that we only check this condition when we're allowed to
1097 // complain about errors, because we should not be checking for
1098 // ambiguity (or inaccessibility) unless the reference binding
1099 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001100 if (DerivedToBase)
1101 return CheckDerivedToBaseConversion(T2, T1,
1102 Init->getSourceRange().getBegin(),
1103 Init->getSourceRange());
1104 else
1105 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001106 }
1107
1108 // -- Otherwise, the reference shall be to a non-volatile const
1109 // type (i.e., cv1 shall be const).
1110 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001111 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001112 Diag(Init->getSourceRange().getBegin(),
1113 diag::err_not_reference_to_const_init,
1114 T1.getAsString(),
1115 InitLvalue != Expr::LV_Valid? "temporary" : "value",
1116 T2.getAsString(), Init->getSourceRange());
1117 return true;
1118 }
1119
1120 // -- If the initializer expression is an rvalue, with T2 a
1121 // class type, and “cv1 T1” is reference-compatible with
1122 // “cv2 T2,” the reference is bound in one of the
1123 // following ways (the choice is implementation-defined):
1124 //
1125 // -- The reference is bound to the object represented by
1126 // the rvalue (see 3.10) or to a sub-object within that
1127 // object.
1128 //
1129 // -- A temporary of type “cv1 T2” [sic] is created, and
1130 // a constructor is called to copy the entire rvalue
1131 // object into the temporary. The reference is bound to
1132 // the temporary or to a sub-object within the
1133 // temporary.
1134 //
1135 //
1136 // The constructor that would be used to make the copy
1137 // shall be callable whether or not the copy is actually
1138 // done.
1139 //
1140 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1141 // freedom, so we will always take the first option and never build
1142 // a temporary in this case. FIXME: We will, however, have to check
1143 // for the presence of a copy constructor in C++98/03 mode.
1144 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001145 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1146 if (ICS) {
1147 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1148 ICS->Standard.First = ICK_Identity;
1149 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1150 ICS->Standard.Third = ICK_Identity;
1151 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1152 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001153 ICS->Standard.ReferenceBinding = true;
1154 ICS->Standard.DirectBinding = false;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001155 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001156 // FIXME: Binding to a subobject of the rvalue is going to require
1157 // more AST annotation than this.
1158 ImpCastExprToType(Init, T1);
1159 }
1160 return false;
1161 }
1162
1163 // -- Otherwise, a temporary of type “cv1 T1” is created and
1164 // initialized from the initializer expression using the
1165 // rules for a non-reference copy initialization (8.5). The
1166 // reference is then bound to the temporary. If T1 is
1167 // reference-related to T2, cv1 must be the same
1168 // cv-qualification as, or greater cv-qualification than,
1169 // cv2; otherwise, the program is ill-formed.
1170 if (RefRelationship == Ref_Related) {
1171 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1172 // we would be reference-compatible or reference-compatible with
1173 // added qualification. But that wasn't the case, so the reference
1174 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001175 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001176 Diag(Init->getSourceRange().getBegin(),
1177 diag::err_reference_init_drops_quals,
1178 T1.getAsString(),
1179 InitLvalue != Expr::LV_Valid? "temporary" : "value",
1180 T2.getAsString(), Init->getSourceRange());
1181 return true;
1182 }
1183
1184 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001185 if (ICS) {
1186 /// C++ [over.ics.ref]p2:
1187 ///
1188 /// When a parameter of reference type is not bound directly to
1189 /// an argument expression, the conversion sequence is the one
1190 /// required to convert the argument expression to the
1191 /// underlying type of the reference according to
1192 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1193 /// to copy-initializing a temporary of the underlying type with
1194 /// the argument expression. Any difference in top-level
1195 /// cv-qualification is subsumed by the initialization itself
1196 /// and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001197 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001198 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1199 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001200 return PerformImplicitConversion(Init, T1);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001201 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001202}