blob: b42a27cdcb2cf1369f8794051b4f4873890446f7 [file] [log] [blame]
Shih-wei Liaof8fd82b2010-02-10 11:10:31 -08001//===------ 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"
15#include "SemaInit.h"
16#include "Lookup.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/RecordLayout.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/DeclVisitor.h"
22#include "clang/AST/TypeLoc.h"
23#include "clang/AST/TypeOrdering.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Template.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Lex/Preprocessor.h"
29#include "llvm/ADT/STLExtras.h"
30#include <map>
31#include <set>
32
33using namespace clang;
34
35//===----------------------------------------------------------------------===//
36// CheckDefaultArgumentVisitor
37//===----------------------------------------------------------------------===//
38
39namespace {
40 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
41 /// the default argument of a parameter to determine whether it
42 /// contains any ill-formed subexpressions. For example, this will
43 /// diagnose the use of local variables or parameters within the
44 /// default argument expression.
45 class CheckDefaultArgumentVisitor
46 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
47 Expr *DefaultArg;
48 Sema *S;
49
50 public:
51 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
52 : DefaultArg(defarg), S(s) {}
53
54 bool VisitExpr(Expr *Node);
55 bool VisitDeclRefExpr(DeclRefExpr *DRE);
56 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
57 };
58
59 /// VisitExpr - Visit all of the children of this expression.
60 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
61 bool IsInvalid = false;
62 for (Stmt::child_iterator I = Node->child_begin(),
63 E = Node->child_end(); I != E; ++I)
64 IsInvalid |= Visit(*I);
65 return IsInvalid;
66 }
67
68 /// VisitDeclRefExpr - Visit a reference to a declaration, to
69 /// determine whether this declaration can be used in the default
70 /// argument expression.
71 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
72 NamedDecl *Decl = DRE->getDecl();
73 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
74 // C++ [dcl.fct.default]p9
75 // Default arguments are evaluated each time the function is
76 // called. The order of evaluation of function arguments is
77 // unspecified. Consequently, parameters of a function shall not
78 // be used in default argument expressions, even if they are not
79 // evaluated. Parameters of a function declared before a default
80 // argument expression are in scope and can hide namespace and
81 // class member names.
82 return S->Diag(DRE->getSourceRange().getBegin(),
83 diag::err_param_default_argument_references_param)
84 << Param->getDeclName() << DefaultArg->getSourceRange();
85 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
86 // C++ [dcl.fct.default]p7
87 // Local variables shall not be used in default argument
88 // expressions.
89 if (VDecl->isBlockVarDecl())
90 return S->Diag(DRE->getSourceRange().getBegin(),
91 diag::err_param_default_argument_references_local)
92 << VDecl->getDeclName() << DefaultArg->getSourceRange();
93 }
94
95 return false;
96 }
97
98 /// VisitCXXThisExpr - Visit a C++ "this" expression.
99 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
100 // C++ [dcl.fct.default]p8:
101 // The keyword this shall not be used in a default argument of a
102 // member function.
103 return S->Diag(ThisE->getSourceRange().getBegin(),
104 diag::err_param_default_argument_references_this)
105 << ThisE->getSourceRange();
106 }
107}
108
109bool
110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
111 SourceLocation EqualLoc) {
112 if (RequireCompleteType(Param->getLocation(), Param->getType(),
113 diag::err_typecheck_decl_incomplete_type)) {
114 Param->setInvalidDecl();
115 return true;
116 }
117
118 Expr *Arg = (Expr *)DefaultArg.get();
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).
126 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
127 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
128 EqualLoc);
129 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
130 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
131 MultiExprArg(*this, (void**)&Arg, 1));
132 if (Result.isInvalid())
133 return true;
134 Arg = Result.takeAs<Expr>();
135
136 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
137
138 // Okay: add the default argument to the parameter
139 Param->setDefaultArg(Arg);
140
141 DefaultArg.release();
142
143 return false;
144}
145
146/// ActOnParamDefaultArgument - Check whether the default argument
147/// provided for a function parameter is well-formed. If so, attach it
148/// to the parameter declaration.
149void
150Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
151 ExprArg defarg) {
152 if (!param || !defarg.get())
153 return;
154
155 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
156 UnparsedDefaultArgLocs.erase(Param);
157
158 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
159
160 // Default arguments are only permitted in C++
161 if (!getLangOptions().CPlusPlus) {
162 Diag(EqualLoc, diag::err_param_default_argument)
163 << DefaultArg->getSourceRange();
164 Param->setInvalidDecl();
165 return;
166 }
167
168 // Check that the default argument is well-formed
169 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
170 if (DefaultArgChecker.Visit(DefaultArg.get())) {
171 Param->setInvalidDecl();
172 return;
173 }
174
175 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
176}
177
178/// ActOnParamUnparsedDefaultArgument - We've seen a default
179/// argument for a function parameter, but we can't parse it yet
180/// because we're inside a class definition. Note that this default
181/// argument will be parsed later.
182void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
183 SourceLocation EqualLoc,
184 SourceLocation ArgLoc) {
185 if (!param)
186 return;
187
188 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
189 if (Param)
190 Param->setUnparsedDefaultArg();
191
192 UnparsedDefaultArgLocs[Param] = ArgLoc;
193}
194
195/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
196/// the default argument for the parameter param failed.
197void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
198 if (!param)
199 return;
200
201 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
202
203 Param->setInvalidDecl();
204
205 UnparsedDefaultArgLocs.erase(Param);
206}
207
208/// CheckExtraCXXDefaultArguments - Check for any extra default
209/// arguments in the declarator, which is not a function declaration
210/// or definition and therefore is not permitted to have default
211/// arguments. This routine should be invoked for every declarator
212/// that is not a function declaration or definition.
213void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
214 // C++ [dcl.fct.default]p3
215 // A default argument expression shall be specified only in the
216 // parameter-declaration-clause of a function declaration or in a
217 // template-parameter (14.1). It shall not be specified for a
218 // parameter pack. If it is specified in a
219 // parameter-declaration-clause, it shall not occur within a
220 // declarator or abstract-declarator of a parameter-declaration.
221 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
222 DeclaratorChunk &chunk = D.getTypeObject(i);
223 if (chunk.Kind == DeclaratorChunk::Function) {
224 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
225 ParmVarDecl *Param =
226 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
227 if (Param->hasUnparsedDefaultArg()) {
228 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
229 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
231 delete Toks;
232 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
233 } else if (Param->getDefaultArg()) {
234 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
235 << Param->getDefaultArg()->getSourceRange();
236 Param->setDefaultArg(0);
237 }
238 }
239 }
240 }
241}
242
243// MergeCXXFunctionDecl - Merge two declarations of the same C++
244// function, once we already know that they have the same
245// type. Subroutine of MergeFunctionDecl. Returns true if there was an
246// error, false otherwise.
247bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
248 bool Invalid = false;
249
250 // C++ [dcl.fct.default]p4:
251 // For non-template functions, default arguments can be added in
252 // later declarations of a function in the same
253 // scope. Declarations in different scopes have completely
254 // distinct sets of default arguments. That is, declarations in
255 // inner scopes do not acquire default arguments from
256 // declarations in outer scopes, and vice versa. In a given
257 // function declaration, all parameters subsequent to a
258 // parameter with a default argument shall have default
259 // arguments supplied in this or previous declarations. A
260 // default argument shall not be redefined by a later
261 // declaration (not even to the same value).
262 //
263 // C++ [dcl.fct.default]p6:
264 // Except for member functions of class templates, the default arguments
265 // in a member function definition that appears outside of the class
266 // definition are added to the set of default arguments provided by the
267 // member function declaration in the class definition.
268 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
269 ParmVarDecl *OldParam = Old->getParamDecl(p);
270 ParmVarDecl *NewParam = New->getParamDecl(p);
271
272 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
273 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
274 // hint here. Alternatively, we could walk the type-source information
275 // for NewParam to find the last source location in the type... but it
276 // isn't worth the effort right now. This is the kind of test case that
277 // is hard to get right:
278
279 // int f(int);
280 // void g(int (*fp)(int) = f);
281 // void g(int (*fp)(int) = &f);
282 Diag(NewParam->getLocation(),
283 diag::err_param_default_argument_redefinition)
284 << NewParam->getDefaultArgRange();
285
286 // Look for the function declaration where the default argument was
287 // actually written, which may be a declaration prior to Old.
288 for (FunctionDecl *Older = Old->getPreviousDeclaration();
289 Older; Older = Older->getPreviousDeclaration()) {
290 if (!Older->getParamDecl(p)->hasDefaultArg())
291 break;
292
293 OldParam = Older->getParamDecl(p);
294 }
295
296 Diag(OldParam->getLocation(), diag::note_previous_definition)
297 << OldParam->getDefaultArgRange();
298 Invalid = true;
299 } else if (OldParam->hasDefaultArg()) {
300 // Merge the old default argument into the new parameter
301 if (OldParam->hasUninstantiatedDefaultArg())
302 NewParam->setUninstantiatedDefaultArg(
303 OldParam->getUninstantiatedDefaultArg());
304 else
305 NewParam->setDefaultArg(OldParam->getDefaultArg());
306 } else if (NewParam->hasDefaultArg()) {
307 if (New->getDescribedFunctionTemplate()) {
308 // Paragraph 4, quoted above, only applies to non-template functions.
309 Diag(NewParam->getLocation(),
310 diag::err_param_default_argument_template_redecl)
311 << NewParam->getDefaultArgRange();
312 Diag(Old->getLocation(), diag::note_template_prev_declaration)
313 << false;
314 } else if (New->getTemplateSpecializationKind()
315 != TSK_ImplicitInstantiation &&
316 New->getTemplateSpecializationKind() != TSK_Undeclared) {
317 // C++ [temp.expr.spec]p21:
318 // Default function arguments shall not be specified in a declaration
319 // or a definition for one of the following explicit specializations:
320 // - the explicit specialization of a function template;
321 // - the explicit specialization of a member function template;
322 // - the explicit specialization of a member function of a class
323 // template where the class template specialization to which the
324 // member function specialization belongs is implicitly
325 // instantiated.
326 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
327 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
328 << New->getDeclName()
329 << NewParam->getDefaultArgRange();
330 } else if (New->getDeclContext()->isDependentContext()) {
331 // C++ [dcl.fct.default]p6 (DR217):
332 // Default arguments for a member function of a class template shall
333 // be specified on the initial declaration of the member function
334 // within the class template.
335 //
336 // Reading the tea leaves a bit in DR217 and its reference to DR205
337 // leads me to the conclusion that one cannot add default function
338 // arguments for an out-of-line definition of a member function of a
339 // dependent type.
340 int WhichKind = 2;
341 if (CXXRecordDecl *Record
342 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
343 if (Record->getDescribedClassTemplate())
344 WhichKind = 0;
345 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
346 WhichKind = 1;
347 else
348 WhichKind = 2;
349 }
350
351 Diag(NewParam->getLocation(),
352 diag::err_param_default_argument_member_template_redecl)
353 << WhichKind
354 << NewParam->getDefaultArgRange();
355 }
356 }
357 }
358
359 if (CheckEquivalentExceptionSpec(
360 Old->getType()->getAs<FunctionProtoType>(), Old->getLocation(),
361 New->getType()->getAs<FunctionProtoType>(), New->getLocation()))
362 Invalid = true;
363
364 return Invalid;
365}
366
367/// CheckCXXDefaultArguments - Verify that the default arguments for a
368/// function declaration are well-formed according to C++
369/// [dcl.fct.default].
370void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
371 unsigned NumParams = FD->getNumParams();
372 unsigned p;
373
374 // Find first parameter with a default argument
375 for (p = 0; p < NumParams; ++p) {
376 ParmVarDecl *Param = FD->getParamDecl(p);
377 if (Param->hasDefaultArg())
378 break;
379 }
380
381 // C++ [dcl.fct.default]p4:
382 // In a given function declaration, all parameters
383 // subsequent to a parameter with a default argument shall
384 // have default arguments supplied in this or previous
385 // declarations. A default argument shall not be redefined
386 // by a later declaration (not even to the same value).
387 unsigned LastMissingDefaultArg = 0;
388 for (; p < NumParams; ++p) {
389 ParmVarDecl *Param = FD->getParamDecl(p);
390 if (!Param->hasDefaultArg()) {
391 if (Param->isInvalidDecl())
392 /* We already complained about this parameter. */;
393 else if (Param->getIdentifier())
394 Diag(Param->getLocation(),
395 diag::err_param_default_argument_missing_name)
396 << Param->getIdentifier();
397 else
398 Diag(Param->getLocation(),
399 diag::err_param_default_argument_missing);
400
401 LastMissingDefaultArg = p;
402 }
403 }
404
405 if (LastMissingDefaultArg > 0) {
406 // Some default arguments were missing. Clear out all of the
407 // default arguments up to (and including) the last missing
408 // default argument, so that we leave the function parameters
409 // in a semantically valid state.
410 for (p = 0; p <= LastMissingDefaultArg; ++p) {
411 ParmVarDecl *Param = FD->getParamDecl(p);
412 if (Param->hasDefaultArg()) {
413 if (!Param->hasUnparsedDefaultArg())
414 Param->getDefaultArg()->Destroy(Context);
415 Param->setDefaultArg(0);
416 }
417 }
418 }
419}
420
421/// isCurrentClassName - Determine whether the identifier II is the
422/// name of the class type currently being defined. In the case of
423/// nested classes, this will only return true if II is the name of
424/// the innermost class.
425bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
426 const CXXScopeSpec *SS) {
427 assert(getLangOptions().CPlusPlus && "No class names in C!");
428
429 CXXRecordDecl *CurDecl;
430 if (SS && SS->isSet() && !SS->isInvalid()) {
431 DeclContext *DC = computeDeclContext(*SS, true);
432 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
433 } else
434 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
435
436 if (CurDecl && CurDecl->getIdentifier())
437 return &II == CurDecl->getIdentifier();
438 else
439 return false;
440}
441
442/// \brief Check the validity of a C++ base class specifier.
443///
444/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
445/// and returns NULL otherwise.
446CXXBaseSpecifier *
447Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
448 SourceRange SpecifierRange,
449 bool Virtual, AccessSpecifier Access,
450 QualType BaseType,
451 SourceLocation BaseLoc) {
452 // C++ [class.union]p1:
453 // A union shall not have base classes.
454 if (Class->isUnion()) {
455 Diag(Class->getLocation(), diag::err_base_clause_on_union)
456 << SpecifierRange;
457 return 0;
458 }
459
460 if (BaseType->isDependentType())
461 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
462 Class->getTagKind() == RecordDecl::TK_class,
463 Access, BaseType);
464
465 // Base specifiers must be record types.
466 if (!BaseType->isRecordType()) {
467 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
468 return 0;
469 }
470
471 // C++ [class.union]p1:
472 // A union shall not be used as a base class.
473 if (BaseType->isUnionType()) {
474 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
475 return 0;
476 }
477
478 // C++ [class.derived]p2:
479 // The class-name in a base-specifier shall not be an incompletely
480 // defined class.
481 if (RequireCompleteType(BaseLoc, BaseType,
482 PDiag(diag::err_incomplete_base_class)
483 << SpecifierRange))
484 return 0;
485
486 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
487 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
488 assert(BaseDecl && "Record type has no declaration");
489 BaseDecl = BaseDecl->getDefinition(Context);
490 assert(BaseDecl && "Base type is not incomplete, but has no definition");
491 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
492 assert(CXXBaseDecl && "Base type is not a C++ type");
493
494 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
495 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
496 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
497 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
498 << BaseType;
499 return 0;
500 }
501
502 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
503
504 // Create the base specifier.
505 // FIXME: Allocate via ASTContext?
506 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
507 Class->getTagKind() == RecordDecl::TK_class,
508 Access, BaseType);
509}
510
511void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
512 const CXXRecordDecl *BaseClass,
513 bool BaseIsVirtual) {
514 // A class with a non-empty base class is not empty.
515 // FIXME: Standard ref?
516 if (!BaseClass->isEmpty())
517 Class->setEmpty(false);
518
519 // C++ [class.virtual]p1:
520 // A class that [...] inherits a virtual function is called a polymorphic
521 // class.
522 if (BaseClass->isPolymorphic())
523 Class->setPolymorphic(true);
524
525 // C++ [dcl.init.aggr]p1:
526 // An aggregate is [...] a class with [...] no base classes [...].
527 Class->setAggregate(false);
528
529 // C++ [class]p4:
530 // A POD-struct is an aggregate class...
531 Class->setPOD(false);
532
533 if (BaseIsVirtual) {
534 // C++ [class.ctor]p5:
535 // A constructor is trivial if its class has no virtual base classes.
536 Class->setHasTrivialConstructor(false);
537
538 // C++ [class.copy]p6:
539 // A copy constructor is trivial if its class has no virtual base classes.
540 Class->setHasTrivialCopyConstructor(false);
541
542 // C++ [class.copy]p11:
543 // A copy assignment operator is trivial if its class has no virtual
544 // base classes.
545 Class->setHasTrivialCopyAssignment(false);
546
547 // C++0x [meta.unary.prop] is_empty:
548 // T is a class type, but not a union type, with ... no virtual base
549 // classes
550 Class->setEmpty(false);
551 } else {
552 // C++ [class.ctor]p5:
553 // A constructor is trivial if all the direct base classes of its
554 // class have trivial constructors.
555 if (!BaseClass->hasTrivialConstructor())
556 Class->setHasTrivialConstructor(false);
557
558 // C++ [class.copy]p6:
559 // A copy constructor is trivial if all the direct base classes of its
560 // class have trivial copy constructors.
561 if (!BaseClass->hasTrivialCopyConstructor())
562 Class->setHasTrivialCopyConstructor(false);
563
564 // C++ [class.copy]p11:
565 // A copy assignment operator is trivial if all the direct base classes
566 // of its class have trivial copy assignment operators.
567 if (!BaseClass->hasTrivialCopyAssignment())
568 Class->setHasTrivialCopyAssignment(false);
569 }
570
571 // C++ [class.ctor]p3:
572 // A destructor is trivial if all the direct base classes of its class
573 // have trivial destructors.
574 if (!BaseClass->hasTrivialDestructor())
575 Class->setHasTrivialDestructor(false);
576}
577
578/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
579/// one entry in the base class list of a class specifier, for
580/// example:
581/// class foo : public bar, virtual private baz {
582/// 'public bar' and 'virtual private baz' are each base-specifiers.
583Sema::BaseResult
584Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
585 bool Virtual, AccessSpecifier Access,
586 TypeTy *basetype, SourceLocation BaseLoc) {
587 if (!classdecl)
588 return true;
589
590 AdjustDeclIfTemplate(classdecl);
591 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
592 QualType BaseType = GetTypeFromParser(basetype);
593 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
594 Virtual, Access,
595 BaseType, BaseLoc))
596 return BaseSpec;
597
598 return true;
599}
600
601/// \brief Performs the actual work of attaching the given base class
602/// specifiers to a C++ class.
603bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
604 unsigned NumBases) {
605 if (NumBases == 0)
606 return false;
607
608 // Used to keep track of which base types we have already seen, so
609 // that we can properly diagnose redundant direct base types. Note
610 // that the key is always the unqualified canonical type of the base
611 // class.
612 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
613
614 // Copy non-redundant base specifiers into permanent storage.
615 unsigned NumGoodBases = 0;
616 bool Invalid = false;
617 for (unsigned idx = 0; idx < NumBases; ++idx) {
618 QualType NewBaseType
619 = Context.getCanonicalType(Bases[idx]->getType());
620 NewBaseType = NewBaseType.getLocalUnqualifiedType();
621
622 if (KnownBaseTypes[NewBaseType]) {
623 // C++ [class.mi]p3:
624 // A class shall not be specified as a direct base class of a
625 // derived class more than once.
626 Diag(Bases[idx]->getSourceRange().getBegin(),
627 diag::err_duplicate_base_class)
628 << KnownBaseTypes[NewBaseType]->getType()
629 << Bases[idx]->getSourceRange();
630
631 // Delete the duplicate base class specifier; we're going to
632 // overwrite its pointer later.
633 Context.Deallocate(Bases[idx]);
634
635 Invalid = true;
636 } else {
637 // Okay, add this new base class.
638 KnownBaseTypes[NewBaseType] = Bases[idx];
639 Bases[NumGoodBases++] = Bases[idx];
640 }
641 }
642
643 // Attach the remaining base class specifiers to the derived class.
644 Class->setBases(Context, Bases, NumGoodBases);
645
646 // Delete the remaining (good) base class specifiers, since their
647 // data has been copied into the CXXRecordDecl.
648 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
649 Context.Deallocate(Bases[idx]);
650
651 return Invalid;
652}
653
654/// ActOnBaseSpecifiers - Attach the given base specifiers to the
655/// class, after checking whether there are any duplicate base
656/// classes.
657void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
658 unsigned NumBases) {
659 if (!ClassDecl || !Bases || !NumBases)
660 return;
661
662 AdjustDeclIfTemplate(ClassDecl);
663 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
664 (CXXBaseSpecifier**)(Bases), NumBases);
665}
666
667/// \brief Determine whether the type \p Derived is a C++ class that is
668/// derived from the type \p Base.
669bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
670 if (!getLangOptions().CPlusPlus)
671 return false;
672
673 const RecordType *DerivedRT = Derived->getAs<RecordType>();
674 if (!DerivedRT)
675 return false;
676
677 const RecordType *BaseRT = Base->getAs<RecordType>();
678 if (!BaseRT)
679 return false;
680
681 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
682 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
683 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
684 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
685}
686
687/// \brief Determine whether the type \p Derived is a C++ class that is
688/// derived from the type \p Base.
689bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
690 if (!getLangOptions().CPlusPlus)
691 return false;
692
693 const RecordType *DerivedRT = Derived->getAs<RecordType>();
694 if (!DerivedRT)
695 return false;
696
697 const RecordType *BaseRT = Base->getAs<RecordType>();
698 if (!BaseRT)
699 return false;
700
701 CXXRecordDecl *DerivedRD = cast<CXXRecordDecl>(DerivedRT->getDecl());
702 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
703 return DerivedRD->isDerivedFrom(BaseRD, Paths);
704}
705
706/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
707/// conversion (where Derived and Base are class types) is
708/// well-formed, meaning that the conversion is unambiguous (and
709/// that all of the base classes are accessible). Returns true
710/// and emits a diagnostic if the code is ill-formed, returns false
711/// otherwise. Loc is the location where this routine should point to
712/// if there is an error, and Range is the source range to highlight
713/// if there is an error.
714bool
715Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
716 AccessDiagnosticsKind ADK,
717 unsigned AmbigiousBaseConvID,
718 SourceLocation Loc, SourceRange Range,
719 DeclarationName Name) {
720 // First, determine whether the path from Derived to Base is
721 // ambiguous. This is slightly more expensive than checking whether
722 // the Derived to Base conversion exists, because here we need to
723 // explore multiple paths to determine if there is an ambiguity.
724 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
725 /*DetectVirtual=*/false);
726 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
727 assert(DerivationOkay &&
728 "Can only be used with a derived-to-base conversion");
729 (void)DerivationOkay;
730
731 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
732 if (ADK == ADK_quiet)
733 return false;
734
735 // Check that the base class can be accessed.
736 switch (CheckBaseClassAccess(Loc, /*IsBaseToDerived*/ false,
737 Base, Derived, Paths.front(),
738 /*force*/ false,
739 /*unprivileged*/ false,
740 ADK)) {
741 case AR_accessible: return false;
742 case AR_inaccessible: return true;
743 case AR_dependent: return false;
744 case AR_delayed: return false;
745 }
746 }
747
748 // We know that the derived-to-base conversion is ambiguous, and
749 // we're going to produce a diagnostic. Perform the derived-to-base
750 // search just one more time to compute all of the possible paths so
751 // that we can print them out. This is more expensive than any of
752 // the previous derived-to-base checks we've done, but at this point
753 // performance isn't as much of an issue.
754 Paths.clear();
755 Paths.setRecordingPaths(true);
756 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
757 assert(StillOkay && "Can only be used with a derived-to-base conversion");
758 (void)StillOkay;
759
760 // Build up a textual representation of the ambiguous paths, e.g.,
761 // D -> B -> A, that will be used to illustrate the ambiguous
762 // conversions in the diagnostic. We only print one of the paths
763 // to each base class subobject.
764 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
765
766 Diag(Loc, AmbigiousBaseConvID)
767 << Derived << Base << PathDisplayStr << Range << Name;
768 return true;
769}
770
771bool
772Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
773 SourceLocation Loc, SourceRange Range,
774 bool IgnoreAccess) {
775 return CheckDerivedToBaseConversion(Derived, Base,
776 IgnoreAccess ? ADK_quiet : ADK_normal,
777 diag::err_ambiguous_derived_to_base_conv,
778 Loc, Range, DeclarationName());
779}
780
781
782/// @brief Builds a string representing ambiguous paths from a
783/// specific derived class to different subobjects of the same base
784/// class.
785///
786/// This function builds a string that can be used in error messages
787/// to show the different paths that one can take through the
788/// inheritance hierarchy to go from the derived class to different
789/// subobjects of a base class. The result looks something like this:
790/// @code
791/// struct D -> struct B -> struct A
792/// struct D -> struct C -> struct A
793/// @endcode
794std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
795 std::string PathDisplayStr;
796 std::set<unsigned> DisplayedPaths;
797 for (CXXBasePaths::paths_iterator Path = Paths.begin();
798 Path != Paths.end(); ++Path) {
799 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
800 // We haven't displayed a path to this particular base
801 // class subobject yet.
802 PathDisplayStr += "\n ";
803 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
804 for (CXXBasePath::const_iterator Element = Path->begin();
805 Element != Path->end(); ++Element)
806 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
807 }
808 }
809
810 return PathDisplayStr;
811}
812
813//===----------------------------------------------------------------------===//
814// C++ class member Handling
815//===----------------------------------------------------------------------===//
816
817/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
818/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
819/// bitfield width if there is one and 'InitExpr' specifies the initializer if
820/// any.
821Sema::DeclPtrTy
822Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
823 MultiTemplateParamsArg TemplateParameterLists,
824 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
825 bool Deleted) {
826 const DeclSpec &DS = D.getDeclSpec();
827 DeclarationName Name = GetNameForDeclarator(D);
828 Expr *BitWidth = static_cast<Expr*>(BW);
829 Expr *Init = static_cast<Expr*>(InitExpr);
830 SourceLocation Loc = D.getIdentifierLoc();
831
832 bool isFunc = D.isFunctionDeclarator();
833
834 assert(!DS.isFriendSpecified());
835
836 // C++ 9.2p6: A member shall not be declared to have automatic storage
837 // duration (auto, register) or with the extern storage-class-specifier.
838 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
839 // data members and cannot be applied to names declared const or static,
840 // and cannot be applied to reference members.
841 switch (DS.getStorageClassSpec()) {
842 case DeclSpec::SCS_unspecified:
843 case DeclSpec::SCS_typedef:
844 case DeclSpec::SCS_static:
845 // FALL THROUGH.
846 break;
847 case DeclSpec::SCS_mutable:
848 if (isFunc) {
849 if (DS.getStorageClassSpecLoc().isValid())
850 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
851 else
852 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
853
854 // FIXME: It would be nicer if the keyword was ignored only for this
855 // declarator. Otherwise we could get follow-up errors.
856 D.getMutableDeclSpec().ClearStorageClassSpecs();
857 } else {
858 QualType T = GetTypeForDeclarator(D, S);
859 diag::kind err = static_cast<diag::kind>(0);
860 if (T->isReferenceType())
861 err = diag::err_mutable_reference;
862 else if (T.isConstQualified())
863 err = diag::err_mutable_const;
864 if (err != 0) {
865 if (DS.getStorageClassSpecLoc().isValid())
866 Diag(DS.getStorageClassSpecLoc(), err);
867 else
868 Diag(DS.getThreadSpecLoc(), err);
869 // FIXME: It would be nicer if the keyword was ignored only for this
870 // declarator. Otherwise we could get follow-up errors.
871 D.getMutableDeclSpec().ClearStorageClassSpecs();
872 }
873 }
874 break;
875 default:
876 if (DS.getStorageClassSpecLoc().isValid())
877 Diag(DS.getStorageClassSpecLoc(),
878 diag::err_storageclass_invalid_for_member);
879 else
880 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
881 D.getMutableDeclSpec().ClearStorageClassSpecs();
882 }
883
884 if (!isFunc &&
885 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
886 D.getNumTypeObjects() == 0) {
887 // Check also for this case:
888 //
889 // typedef int f();
890 // f a;
891 //
892 QualType TDType = GetTypeFromParser(DS.getTypeRep());
893 isFunc = TDType->isFunctionType();
894 }
895
896 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
897 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
898 !isFunc);
899
900 Decl *Member;
901 if (isInstField) {
902 // FIXME: Check for template parameters!
903 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
904 AS);
905 assert(Member && "HandleField never returns null");
906 } else {
907 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
908 .getAs<Decl>();
909 if (!Member) {
910 if (BitWidth) DeleteExpr(BitWidth);
911 return DeclPtrTy();
912 }
913
914 // Non-instance-fields can't have a bitfield.
915 if (BitWidth) {
916 if (Member->isInvalidDecl()) {
917 // don't emit another diagnostic.
918 } else if (isa<VarDecl>(Member)) {
919 // C++ 9.6p3: A bit-field shall not be a static member.
920 // "static member 'A' cannot be a bit-field"
921 Diag(Loc, diag::err_static_not_bitfield)
922 << Name << BitWidth->getSourceRange();
923 } else if (isa<TypedefDecl>(Member)) {
924 // "typedef member 'x' cannot be a bit-field"
925 Diag(Loc, diag::err_typedef_not_bitfield)
926 << Name << BitWidth->getSourceRange();
927 } else {
928 // A function typedef ("typedef int f(); f a;").
929 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
930 Diag(Loc, diag::err_not_integral_type_bitfield)
931 << Name << cast<ValueDecl>(Member)->getType()
932 << BitWidth->getSourceRange();
933 }
934
935 DeleteExpr(BitWidth);
936 BitWidth = 0;
937 Member->setInvalidDecl();
938 }
939
940 Member->setAccess(AS);
941
942 // If we have declared a member function template, set the access of the
943 // templated declaration as well.
944 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
945 FunTmpl->getTemplatedDecl()->setAccess(AS);
946 }
947
948 assert((Name || isInstField) && "No identifier for non-field ?");
949
950 if (Init)
951 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
952 if (Deleted) // FIXME: Source location is not very good.
953 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
954
955 if (isInstField) {
956 FieldCollector->Add(cast<FieldDecl>(Member));
957 return DeclPtrTy();
958 }
959 return DeclPtrTy::make(Member);
960}
961
962/// \brief Find the direct and/or virtual base specifiers that
963/// correspond to the given base type, for use in base initialization
964/// within a constructor.
965static bool FindBaseInitializer(Sema &SemaRef,
966 CXXRecordDecl *ClassDecl,
967 QualType BaseType,
968 const CXXBaseSpecifier *&DirectBaseSpec,
969 const CXXBaseSpecifier *&VirtualBaseSpec) {
970 // First, check for a direct base class.
971 DirectBaseSpec = 0;
972 for (CXXRecordDecl::base_class_const_iterator Base
973 = ClassDecl->bases_begin();
974 Base != ClassDecl->bases_end(); ++Base) {
975 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
976 // We found a direct base of this type. That's what we're
977 // initializing.
978 DirectBaseSpec = &*Base;
979 break;
980 }
981 }
982
983 // Check for a virtual base class.
984 // FIXME: We might be able to short-circuit this if we know in advance that
985 // there are no virtual bases.
986 VirtualBaseSpec = 0;
987 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
988 // We haven't found a base yet; search the class hierarchy for a
989 // virtual base class.
990 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
991 /*DetectVirtual=*/false);
992 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
993 BaseType, Paths)) {
994 for (CXXBasePaths::paths_iterator Path = Paths.begin();
995 Path != Paths.end(); ++Path) {
996 if (Path->back().Base->isVirtual()) {
997 VirtualBaseSpec = Path->back().Base;
998 break;
999 }
1000 }
1001 }
1002 }
1003
1004 return DirectBaseSpec || VirtualBaseSpec;
1005}
1006
1007/// ActOnMemInitializer - Handle a C++ member initializer.
1008Sema::MemInitResult
1009Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
1010 Scope *S,
1011 const CXXScopeSpec &SS,
1012 IdentifierInfo *MemberOrBase,
1013 TypeTy *TemplateTypeTy,
1014 SourceLocation IdLoc,
1015 SourceLocation LParenLoc,
1016 ExprTy **Args, unsigned NumArgs,
1017 SourceLocation *CommaLocs,
1018 SourceLocation RParenLoc) {
1019 if (!ConstructorD)
1020 return true;
1021
1022 AdjustDeclIfTemplate(ConstructorD);
1023
1024 CXXConstructorDecl *Constructor
1025 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
1026 if (!Constructor) {
1027 // The user wrote a constructor initializer on a function that is
1028 // not a C++ constructor. Ignore the error for now, because we may
1029 // have more member initializers coming; we'll diagnose it just
1030 // once in ActOnMemInitializers.
1031 return true;
1032 }
1033
1034 CXXRecordDecl *ClassDecl = Constructor->getParent();
1035
1036 // C++ [class.base.init]p2:
1037 // Names in a mem-initializer-id are looked up in the scope of the
1038 // constructor’s class and, if not found in that scope, are looked
1039 // up in the scope containing the constructor’s
1040 // definition. [Note: if the constructor’s class contains a member
1041 // with the same name as a direct or virtual base class of the
1042 // class, a mem-initializer-id naming the member or base class and
1043 // composed of a single identifier refers to the class member. A
1044 // mem-initializer-id for the hidden base class may be specified
1045 // using a qualified name. ]
1046 if (!SS.getScopeRep() && !TemplateTypeTy) {
1047 // Look for a member, first.
1048 FieldDecl *Member = 0;
1049 DeclContext::lookup_result Result
1050 = ClassDecl->lookup(MemberOrBase);
1051 if (Result.first != Result.second)
1052 Member = dyn_cast<FieldDecl>(*Result.first);
1053
1054 // FIXME: Handle members of an anonymous union.
1055
1056 if (Member)
1057 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1058 LParenLoc, RParenLoc);
1059 }
1060 // It didn't name a member, so see if it names a class.
1061 QualType BaseType;
1062 TypeSourceInfo *TInfo = 0;
1063
1064 if (TemplateTypeTy) {
1065 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1066 } else {
1067 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1068 LookupParsedName(R, S, &SS);
1069
1070 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1071 if (!TyD) {
1072 if (R.isAmbiguous()) return true;
1073
1074 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1075 bool NotUnknownSpecialization = false;
1076 DeclContext *DC = computeDeclContext(SS, false);
1077 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1078 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1079
1080 if (!NotUnknownSpecialization) {
1081 // When the scope specifier can refer to a member of an unknown
1082 // specialization, we take it as a type name.
1083 BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
1084 *MemberOrBase, SS.getRange());
1085 R.clear();
1086 }
1087 }
1088
1089 // If no results were found, try to correct typos.
1090 if (R.empty() && BaseType.isNull() &&
1091 CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) {
1092 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1093 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1094 // We have found a non-static data member with a similar
1095 // name to what was typed; complain and initialize that
1096 // member.
1097 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1098 << MemberOrBase << true << R.getLookupName()
1099 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1100 R.getLookupName().getAsString());
1101 Diag(Member->getLocation(), diag::note_previous_decl)
1102 << Member->getDeclName();
1103
1104 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1105 LParenLoc, RParenLoc);
1106 }
1107 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1108 const CXXBaseSpecifier *DirectBaseSpec;
1109 const CXXBaseSpecifier *VirtualBaseSpec;
1110 if (FindBaseInitializer(*this, ClassDecl,
1111 Context.getTypeDeclType(Type),
1112 DirectBaseSpec, VirtualBaseSpec)) {
1113 // We have found a direct or virtual base class with a
1114 // similar name to what was typed; complain and initialize
1115 // that base class.
1116 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1117 << MemberOrBase << false << R.getLookupName()
1118 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1119 R.getLookupName().getAsString());
1120
1121 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1122 : VirtualBaseSpec;
1123 Diag(BaseSpec->getSourceRange().getBegin(),
1124 diag::note_base_class_specified_here)
1125 << BaseSpec->getType()
1126 << BaseSpec->getSourceRange();
1127
1128 TyD = Type;
1129 }
1130 }
1131 }
1132
1133 if (!TyD && BaseType.isNull()) {
1134 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1135 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1136 return true;
1137 }
1138 }
1139
1140 if (BaseType.isNull()) {
1141 BaseType = Context.getTypeDeclType(TyD);
1142 if (SS.isSet()) {
1143 NestedNameSpecifier *Qualifier =
1144 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1145
1146 // FIXME: preserve source range information
1147 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1148 }
1149 }
1150 }
1151
1152 if (!TInfo)
1153 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1154
1155 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
1156 LParenLoc, RParenLoc, ClassDecl);
1157}
1158
1159/// Checks an initializer expression for use of uninitialized fields, such as
1160/// containing the field that is being initialized. Returns true if there is an
1161/// uninitialized field was used an updates the SourceLocation parameter; false
1162/// otherwise.
1163static bool InitExprContainsUninitializedFields(const Stmt* S,
1164 const FieldDecl* LhsField,
1165 SourceLocation* L) {
1166 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1167 if (ME) {
1168 const NamedDecl* RhsField = ME->getMemberDecl();
1169 if (RhsField == LhsField) {
1170 // Initializing a field with itself. Throw a warning.
1171 // But wait; there are exceptions!
1172 // Exception #1: The field may not belong to this record.
1173 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1174 const Expr* base = ME->getBase();
1175 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1176 // Even though the field matches, it does not belong to this record.
1177 return false;
1178 }
1179 // None of the exceptions triggered; return true to indicate an
1180 // uninitialized field was used.
1181 *L = ME->getMemberLoc();
1182 return true;
1183 }
1184 }
1185 bool found = false;
1186 for (Stmt::const_child_iterator it = S->child_begin();
1187 it != S->child_end() && found == false;
1188 ++it) {
1189 if (isa<CallExpr>(S)) {
1190 // Do not descend into function calls or constructors, as the use
1191 // of an uninitialized field may be valid. One would have to inspect
1192 // the contents of the function/ctor to determine if it is safe or not.
1193 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1194 // may be safe, depending on what the function/ctor does.
1195 continue;
1196 }
1197 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1198 }
1199 return found;
1200}
1201
1202Sema::MemInitResult
1203Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1204 unsigned NumArgs, SourceLocation IdLoc,
1205 SourceLocation LParenLoc,
1206 SourceLocation RParenLoc) {
1207 // Diagnose value-uses of fields to initialize themselves, e.g.
1208 // foo(foo)
1209 // where foo is not also a parameter to the constructor.
1210 // TODO: implement -Wuninitialized and fold this into that framework.
1211 for (unsigned i = 0; i < NumArgs; ++i) {
1212 SourceLocation L;
1213 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1214 // FIXME: Return true in the case when other fields are used before being
1215 // uninitialized. For example, let this field be the i'th field. When
1216 // initializing the i'th field, throw a warning if any of the >= i'th
1217 // fields are used, as they are not yet initialized.
1218 // Right now we are only handling the case where the i'th field uses
1219 // itself in its initializer.
1220 Diag(L, diag::warn_field_is_uninit);
1221 }
1222 }
1223
1224 bool HasDependentArg = false;
1225 for (unsigned i = 0; i < NumArgs; i++)
1226 HasDependentArg |= Args[i]->isTypeDependent();
1227
1228 QualType FieldType = Member->getType();
1229 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1230 FieldType = Array->getElementType();
1231 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1232 if (FieldType->isDependentType() || HasDependentArg) {
1233 // Can't check initialization for a member of dependent type or when
1234 // any of the arguments are type-dependent expressions.
1235 OwningExprResult Init
1236 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1237 RParenLoc));
1238
1239 // Erase any temporaries within this evaluation context; we're not
1240 // going to track them in the AST, since we'll be rebuilding the
1241 // ASTs during template instantiation.
1242 ExprTemporaries.erase(
1243 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1244 ExprTemporaries.end());
1245
1246 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1247 LParenLoc,
1248 Init.takeAs<Expr>(),
1249 RParenLoc);
1250
1251 }
1252
1253 if (Member->isInvalidDecl())
1254 return true;
1255
1256 // Initialize the member.
1257 InitializedEntity MemberEntity =
1258 InitializedEntity::InitializeMember(Member, 0);
1259 InitializationKind Kind =
1260 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1261
1262 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1263
1264 OwningExprResult MemberInit =
1265 InitSeq.Perform(*this, MemberEntity, Kind,
1266 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1267 if (MemberInit.isInvalid())
1268 return true;
1269
1270 // C++0x [class.base.init]p7:
1271 // The initialization of each base and member constitutes a
1272 // full-expression.
1273 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1274 if (MemberInit.isInvalid())
1275 return true;
1276
1277 // If we are in a dependent context, template instantiation will
1278 // perform this type-checking again. Just save the arguments that we
1279 // received in a ParenListExpr.
1280 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1281 // of the information that we have about the member
1282 // initializer. However, deconstructing the ASTs is a dicey process,
1283 // and this approach is far more likely to get the corner cases right.
1284 if (CurContext->isDependentContext()) {
1285 // Bump the reference count of all of the arguments.
1286 for (unsigned I = 0; I != NumArgs; ++I)
1287 Args[I]->Retain();
1288
1289 OwningExprResult Init
1290 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1291 RParenLoc));
1292 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1293 LParenLoc,
1294 Init.takeAs<Expr>(),
1295 RParenLoc);
1296 }
1297
1298 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1299 LParenLoc,
1300 MemberInit.takeAs<Expr>(),
1301 RParenLoc);
1302}
1303
1304Sema::MemInitResult
1305Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
1306 Expr **Args, unsigned NumArgs,
1307 SourceLocation LParenLoc, SourceLocation RParenLoc,
1308 CXXRecordDecl *ClassDecl) {
1309 bool HasDependentArg = false;
1310 for (unsigned i = 0; i < NumArgs; i++)
1311 HasDependentArg |= Args[i]->isTypeDependent();
1312
1313 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
1314 if (BaseType->isDependentType() || HasDependentArg) {
1315 // Can't check initialization for a base of dependent type or when
1316 // any of the arguments are type-dependent expressions.
1317 OwningExprResult BaseInit
1318 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1319 RParenLoc));
1320
1321 // Erase any temporaries within this evaluation context; we're not
1322 // going to track them in the AST, since we'll be rebuilding the
1323 // ASTs during template instantiation.
1324 ExprTemporaries.erase(
1325 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1326 ExprTemporaries.end());
1327
1328 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1329 LParenLoc,
1330 BaseInit.takeAs<Expr>(),
1331 RParenLoc);
1332 }
1333
1334 if (!BaseType->isRecordType())
1335 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1336 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1337
1338 // C++ [class.base.init]p2:
1339 // [...] Unless the mem-initializer-id names a nonstatic data
1340 // member of the constructor’s class or a direct or virtual base
1341 // of that class, the mem-initializer is ill-formed. A
1342 // mem-initializer-list can initialize a base class using any
1343 // name that denotes that base class type.
1344
1345 // Check for direct and virtual base classes.
1346 const CXXBaseSpecifier *DirectBaseSpec = 0;
1347 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1348 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1349 VirtualBaseSpec);
1350
1351 // C++ [base.class.init]p2:
1352 // If a mem-initializer-id is ambiguous because it designates both
1353 // a direct non-virtual base class and an inherited virtual base
1354 // class, the mem-initializer is ill-formed.
1355 if (DirectBaseSpec && VirtualBaseSpec)
1356 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1357 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1358 // C++ [base.class.init]p2:
1359 // Unless the mem-initializer-id names a nonstatic data membeer of the
1360 // constructor's class ot a direst or virtual base of that class, the
1361 // mem-initializer is ill-formed.
1362 if (!DirectBaseSpec && !VirtualBaseSpec)
1363 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1364 << BaseType << ClassDecl->getNameAsCString()
1365 << BaseTInfo->getTypeLoc().getSourceRange();
1366
1367 CXXBaseSpecifier *BaseSpec
1368 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1369 if (!BaseSpec)
1370 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1371
1372 // Initialize the base.
1373 InitializedEntity BaseEntity =
1374 InitializedEntity::InitializeBase(Context, BaseSpec);
1375 InitializationKind Kind =
1376 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1377
1378 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1379
1380 OwningExprResult BaseInit =
1381 InitSeq.Perform(*this, BaseEntity, Kind,
1382 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1383 if (BaseInit.isInvalid())
1384 return true;
1385
1386 // C++0x [class.base.init]p7:
1387 // The initialization of each base and member constitutes a
1388 // full-expression.
1389 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1390 if (BaseInit.isInvalid())
1391 return true;
1392
1393 // If we are in a dependent context, template instantiation will
1394 // perform this type-checking again. Just save the arguments that we
1395 // received in a ParenListExpr.
1396 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1397 // of the information that we have about the base
1398 // initializer. However, deconstructing the ASTs is a dicey process,
1399 // and this approach is far more likely to get the corner cases right.
1400 if (CurContext->isDependentContext()) {
1401 // Bump the reference count of all of the arguments.
1402 for (unsigned I = 0; I != NumArgs; ++I)
1403 Args[I]->Retain();
1404
1405 OwningExprResult Init
1406 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1407 RParenLoc));
1408 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1409 LParenLoc,
1410 Init.takeAs<Expr>(),
1411 RParenLoc);
1412 }
1413
1414 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1415 LParenLoc,
1416 BaseInit.takeAs<Expr>(),
1417 RParenLoc);
1418}
1419
1420bool
1421Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
1422 CXXBaseOrMemberInitializer **Initializers,
1423 unsigned NumInitializers,
1424 bool IsImplicitConstructor,
1425 bool AnyErrors) {
1426 // We need to build the initializer AST according to order of construction
1427 // and not what user specified in the Initializers list.
1428 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1429 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1430 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1431 bool HasDependentBaseInit = false;
1432 bool HadError = false;
1433
1434 for (unsigned i = 0; i < NumInitializers; i++) {
1435 CXXBaseOrMemberInitializer *Member = Initializers[i];
1436 if (Member->isBaseInitializer()) {
1437 if (Member->getBaseClass()->isDependentType())
1438 HasDependentBaseInit = true;
1439 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1440 } else {
1441 AllBaseFields[Member->getMember()] = Member;
1442 }
1443 }
1444
1445 if (HasDependentBaseInit) {
1446 // FIXME. This does not preserve the ordering of the initializers.
1447 // Try (with -Wreorder)
1448 // template<class X> struct A {};
1449 // template<class X> struct B : A<X> {
1450 // B() : x1(10), A<X>() {}
1451 // int x1;
1452 // };
1453 // B<int> x;
1454 // On seeing one dependent type, we should essentially exit this routine
1455 // while preserving user-declared initializer list. When this routine is
1456 // called during instantiatiation process, this routine will rebuild the
1457 // ordered initializer list correctly.
1458
1459 // If we have a dependent base initialization, we can't determine the
1460 // association between initializers and bases; just dump the known
1461 // initializers into the list, and don't try to deal with other bases.
1462 for (unsigned i = 0; i < NumInitializers; i++) {
1463 CXXBaseOrMemberInitializer *Member = Initializers[i];
1464 if (Member->isBaseInitializer())
1465 AllToInit.push_back(Member);
1466 }
1467 } else {
1468 llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit;
1469
1470 // Push virtual bases before others.
1471 for (CXXRecordDecl::base_class_iterator VBase =
1472 ClassDecl->vbases_begin(),
1473 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1474 if (VBase->getType()->isDependentType())
1475 continue;
1476 if (CXXBaseOrMemberInitializer *Value
1477 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1478 AllToInit.push_back(Value);
1479 } else if (!AnyErrors) {
1480 InitializedEntity InitEntity
1481 = InitializedEntity::InitializeBase(Context, VBase);
1482 InitializationKind InitKind
1483 = InitializationKind::CreateDefault(Constructor->getLocation());
1484 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1485 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1486 MultiExprArg(*this, 0, 0));
1487 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1488 if (BaseInit.isInvalid()) {
1489 HadError = true;
1490 continue;
1491 }
1492
1493 // Don't attach synthesized base initializers in a dependent
1494 // context; they'll be checked again at template instantiation
1495 // time.
1496 if (CurContext->isDependentContext())
1497 continue;
1498
1499 CXXBaseOrMemberInitializer *CXXBaseInit =
1500 new (Context) CXXBaseOrMemberInitializer(Context,
1501 Context.getTrivialTypeSourceInfo(VBase->getType(),
1502 SourceLocation()),
1503 SourceLocation(),
1504 BaseInit.takeAs<Expr>(),
1505 SourceLocation());
1506 AllToInit.push_back(CXXBaseInit);
1507 }
1508 }
1509
1510 for (CXXRecordDecl::base_class_iterator Base =
1511 ClassDecl->bases_begin(),
1512 E = ClassDecl->bases_end(); Base != E; ++Base) {
1513 // Virtuals are in the virtual base list and already constructed.
1514 if (Base->isVirtual())
1515 continue;
1516 // Skip dependent types.
1517 if (Base->getType()->isDependentType())
1518 continue;
1519 if (CXXBaseOrMemberInitializer *Value
1520 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1521 AllToInit.push_back(Value);
1522 }
1523 else if (!AnyErrors) {
1524 InitializedEntity InitEntity
1525 = InitializedEntity::InitializeBase(Context, Base);
1526 InitializationKind InitKind
1527 = InitializationKind::CreateDefault(Constructor->getLocation());
1528 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1529 OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1530 MultiExprArg(*this, 0, 0));
1531 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1532 if (BaseInit.isInvalid()) {
1533 HadError = true;
1534 continue;
1535 }
1536
1537 // Don't attach synthesized base initializers in a dependent
1538 // context; they'll be regenerated at template instantiation
1539 // time.
1540 if (CurContext->isDependentContext())
1541 continue;
1542
1543 CXXBaseOrMemberInitializer *CXXBaseInit =
1544 new (Context) CXXBaseOrMemberInitializer(Context,
1545 Context.getTrivialTypeSourceInfo(Base->getType(),
1546 SourceLocation()),
1547 SourceLocation(),
1548 BaseInit.takeAs<Expr>(),
1549 SourceLocation());
1550 AllToInit.push_back(CXXBaseInit);
1551 }
1552 }
1553 }
1554
1555 // non-static data members.
1556 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1557 E = ClassDecl->field_end(); Field != E; ++Field) {
1558 if ((*Field)->isAnonymousStructOrUnion()) {
1559 if (const RecordType *FieldClassType =
1560 Field->getType()->getAs<RecordType>()) {
1561 CXXRecordDecl *FieldClassDecl
1562 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1563 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1564 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1565 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1566 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1567 // set to the anonymous union data member used in the initializer
1568 // list.
1569 Value->setMember(*Field);
1570 Value->setAnonUnionMember(*FA);
1571 AllToInit.push_back(Value);
1572 break;
1573 }
1574 }
1575 }
1576 continue;
1577 }
1578 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1579 AllToInit.push_back(Value);
1580 continue;
1581 }
1582
1583 if ((*Field)->getType()->isDependentType() || AnyErrors)
1584 continue;
1585
1586 QualType FT = Context.getBaseElementType((*Field)->getType());
1587 if (FT->getAs<RecordType>()) {
1588 InitializedEntity InitEntity
1589 = InitializedEntity::InitializeMember(*Field);
1590 InitializationKind InitKind
1591 = InitializationKind::CreateDefault(Constructor->getLocation());
1592
1593 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1594 OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind,
1595 MultiExprArg(*this, 0, 0));
1596 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1597 if (MemberInit.isInvalid()) {
1598 HadError = true;
1599 continue;
1600 }
1601
1602 // Don't attach synthesized member initializers in a dependent
1603 // context; they'll be regenerated a template instantiation
1604 // time.
1605 if (CurContext->isDependentContext())
1606 continue;
1607
1608 CXXBaseOrMemberInitializer *Member =
1609 new (Context) CXXBaseOrMemberInitializer(Context,
1610 *Field, SourceLocation(),
1611 SourceLocation(),
1612 MemberInit.takeAs<Expr>(),
1613 SourceLocation());
1614
1615 AllToInit.push_back(Member);
1616 }
1617 else if (FT->isReferenceType()) {
1618 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
1619 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1620 << 0 << (*Field)->getDeclName();
1621 Diag((*Field)->getLocation(), diag::note_declared_at);
1622 HadError = true;
1623 }
1624 else if (FT.isConstQualified()) {
1625 Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
1626 << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1627 << 1 << (*Field)->getDeclName();
1628 Diag((*Field)->getLocation(), diag::note_declared_at);
1629 HadError = true;
1630 }
1631 }
1632
1633 NumInitializers = AllToInit.size();
1634 if (NumInitializers > 0) {
1635 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1636 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1637 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1638
1639 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1640 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx)
1641 baseOrMemberInitializers[Idx] = AllToInit[Idx];
1642 }
1643
1644 return HadError;
1645}
1646
1647static void *GetKeyForTopLevelField(FieldDecl *Field) {
1648 // For anonymous unions, use the class declaration as the key.
1649 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
1650 if (RT->getDecl()->isAnonymousStructOrUnion())
1651 return static_cast<void *>(RT->getDecl());
1652 }
1653 return static_cast<void *>(Field);
1654}
1655
1656static void *GetKeyForBase(QualType BaseType) {
1657 if (const RecordType *RT = BaseType->getAs<RecordType>())
1658 return (void *)RT;
1659
1660 assert(0 && "Unexpected base type!");
1661 return 0;
1662}
1663
1664static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
1665 bool MemberMaybeAnon = false) {
1666 // For fields injected into the class via declaration of an anonymous union,
1667 // use its anonymous union class declaration as the unique key.
1668 if (Member->isMemberInitializer()) {
1669 FieldDecl *Field = Member->getMember();
1670
1671 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1672 // data member of the class. Data member used in the initializer list is
1673 // in AnonUnionMember field.
1674 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1675 Field = Member->getAnonUnionMember();
1676 if (Field->getDeclContext()->isRecord()) {
1677 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1678 if (RD->isAnonymousStructOrUnion())
1679 return static_cast<void *>(RD);
1680 }
1681 return static_cast<void *>(Field);
1682 }
1683
1684 return GetKeyForBase(QualType(Member->getBaseClass(), 0));
1685}
1686
1687/// ActOnMemInitializers - Handle the member initializers for a constructor.
1688void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
1689 SourceLocation ColonLoc,
1690 MemInitTy **MemInits, unsigned NumMemInits,
1691 bool AnyErrors) {
1692 if (!ConstructorDecl)
1693 return;
1694
1695 AdjustDeclIfTemplate(ConstructorDecl);
1696
1697 CXXConstructorDecl *Constructor
1698 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
1699
1700 if (!Constructor) {
1701 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1702 return;
1703 }
1704
1705 if (!Constructor->isDependentContext()) {
1706 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1707 bool err = false;
1708 for (unsigned i = 0; i < NumMemInits; i++) {
1709 CXXBaseOrMemberInitializer *Member =
1710 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1711 void *KeyToMember = GetKeyForMember(Member);
1712 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1713 if (!PrevMember) {
1714 PrevMember = Member;
1715 continue;
1716 }
1717 if (FieldDecl *Field = Member->getMember())
1718 Diag(Member->getSourceLocation(),
1719 diag::error_multiple_mem_initialization)
1720 << Field->getNameAsString()
1721 << Member->getSourceRange();
1722 else {
1723 Type *BaseClass = Member->getBaseClass();
1724 assert(BaseClass && "ActOnMemInitializers - neither field or base");
1725 Diag(Member->getSourceLocation(),
1726 diag::error_multiple_base_initialization)
1727 << QualType(BaseClass, 0)
1728 << Member->getSourceRange();
1729 }
1730 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1731 << 0;
1732 err = true;
1733 }
1734
1735 if (err)
1736 return;
1737 }
1738
1739 SetBaseOrMemberInitializers(Constructor,
1740 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
1741 NumMemInits, false, AnyErrors);
1742
1743 if (Constructor->isDependentContext())
1744 return;
1745
1746 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
1747 Diagnostic::Ignored &&
1748 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
1749 Diagnostic::Ignored)
1750 return;
1751
1752 // Also issue warning if order of ctor-initializer list does not match order
1753 // of 1) base class declarations and 2) order of non-static data members.
1754 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
1755
1756 CXXRecordDecl *ClassDecl
1757 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1758 // Push virtual bases before others.
1759 for (CXXRecordDecl::base_class_iterator VBase =
1760 ClassDecl->vbases_begin(),
1761 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
1762 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
1763
1764 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1765 E = ClassDecl->bases_end(); Base != E; ++Base) {
1766 // Virtuals are alread in the virtual base list and are constructed
1767 // first.
1768 if (Base->isVirtual())
1769 continue;
1770 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
1771 }
1772
1773 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1774 E = ClassDecl->field_end(); Field != E; ++Field)
1775 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
1776
1777 int Last = AllBaseOrMembers.size();
1778 int curIndex = 0;
1779 CXXBaseOrMemberInitializer *PrevMember = 0;
1780 for (unsigned i = 0; i < NumMemInits; i++) {
1781 CXXBaseOrMemberInitializer *Member =
1782 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1783 void *MemberInCtorList = GetKeyForMember(Member, true);
1784
1785 for (; curIndex < Last; curIndex++)
1786 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1787 break;
1788 if (curIndex == Last) {
1789 assert(PrevMember && "Member not in member list?!");
1790 // Initializer as specified in ctor-initializer list is out of order.
1791 // Issue a warning diagnostic.
1792 if (PrevMember->isBaseInitializer()) {
1793 // Diagnostics is for an initialized base class.
1794 Type *BaseClass = PrevMember->getBaseClass();
1795 Diag(PrevMember->getSourceLocation(),
1796 diag::warn_base_initialized)
1797 << QualType(BaseClass, 0);
1798 } else {
1799 FieldDecl *Field = PrevMember->getMember();
1800 Diag(PrevMember->getSourceLocation(),
1801 diag::warn_field_initialized)
1802 << Field->getNameAsString();
1803 }
1804 // Also the note!
1805 if (FieldDecl *Field = Member->getMember())
1806 Diag(Member->getSourceLocation(),
1807 diag::note_fieldorbase_initialized_here) << 0
1808 << Field->getNameAsString();
1809 else {
1810 Type *BaseClass = Member->getBaseClass();
1811 Diag(Member->getSourceLocation(),
1812 diag::note_fieldorbase_initialized_here) << 1
1813 << QualType(BaseClass, 0);
1814 }
1815 for (curIndex = 0; curIndex < Last; curIndex++)
1816 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1817 break;
1818 }
1819 PrevMember = Member;
1820 }
1821}
1822
1823void
1824Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1825 // Ignore dependent destructors.
1826 if (Destructor->isDependentContext())
1827 return;
1828
1829 CXXRecordDecl *ClassDecl = Destructor->getParent();
1830
1831 // Non-static data members.
1832 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1833 E = ClassDecl->field_end(); I != E; ++I) {
1834 FieldDecl *Field = *I;
1835
1836 QualType FieldType = Context.getBaseElementType(Field->getType());
1837
1838 const RecordType* RT = FieldType->getAs<RecordType>();
1839 if (!RT)
1840 continue;
1841
1842 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1843 if (FieldClassDecl->hasTrivialDestructor())
1844 continue;
1845
1846 const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1847 MarkDeclarationReferenced(Destructor->getLocation(),
1848 const_cast<CXXDestructorDecl*>(Dtor));
1849 }
1850
1851 // Bases.
1852 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1853 E = ClassDecl->bases_end(); Base != E; ++Base) {
1854 // Ignore virtual bases.
1855 if (Base->isVirtual())
1856 continue;
1857
1858 // Ignore trivial destructors.
1859 CXXRecordDecl *BaseClassDecl
1860 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1861 if (BaseClassDecl->hasTrivialDestructor())
1862 continue;
1863
1864 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1865 MarkDeclarationReferenced(Destructor->getLocation(),
1866 const_cast<CXXDestructorDecl*>(Dtor));
1867 }
1868
1869 // Virtual bases.
1870 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1871 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1872 // Ignore trivial destructors.
1873 CXXRecordDecl *BaseClassDecl
1874 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1875 if (BaseClassDecl->hasTrivialDestructor())
1876 continue;
1877
1878 const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1879 MarkDeclarationReferenced(Destructor->getLocation(),
1880 const_cast<CXXDestructorDecl*>(Dtor));
1881 }
1882}
1883
1884void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
1885 if (!CDtorDecl)
1886 return;
1887
1888 AdjustDeclIfTemplate(CDtorDecl);
1889
1890 if (CXXConstructorDecl *Constructor
1891 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
1892 SetBaseOrMemberInitializers(Constructor, 0, 0, false, false);
1893}
1894
1895namespace {
1896 /// PureVirtualMethodCollector - traverses a class and its superclasses
1897 /// and determines if it has any pure virtual methods.
1898 class PureVirtualMethodCollector {
1899 ASTContext &Context;
1900
1901 public:
1902 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
1903
1904 private:
1905 MethodList Methods;
1906
1907 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
1908
1909 public:
1910 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
1911 : Context(Ctx) {
1912
1913 MethodList List;
1914 Collect(RD, List);
1915
1916 // Copy the temporary list to methods, and make sure to ignore any
1917 // null entries.
1918 for (size_t i = 0, e = List.size(); i != e; ++i) {
1919 if (List[i])
1920 Methods.push_back(List[i]);
1921 }
1922 }
1923
1924 bool empty() const { return Methods.empty(); }
1925
1926 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1927 MethodList::const_iterator methods_end() { return Methods.end(); }
1928 };
1929
1930 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
1931 MethodList& Methods) {
1932 // First, collect the pure virtual methods for the base classes.
1933 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1934 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
1935 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
1936 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
1937 if (BaseDecl && BaseDecl->isAbstract())
1938 Collect(BaseDecl, Methods);
1939 }
1940 }
1941
1942 // Next, zero out any pure virtual methods that this class overrides.
1943 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
1944
1945 MethodSetTy OverriddenMethods;
1946 size_t MethodsSize = Methods.size();
1947
1948 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
1949 i != e; ++i) {
1950 // Traverse the record, looking for methods.
1951 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
1952 // If the method is pure virtual, add it to the methods vector.
1953 if (MD->isPure())
1954 Methods.push_back(MD);
1955
1956 // Record all the overridden methods in our set.
1957 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1958 E = MD->end_overridden_methods(); I != E; ++I) {
1959 // Keep track of the overridden methods.
1960 OverriddenMethods.insert(*I);
1961 }
1962 }
1963 }
1964
1965 // Now go through the methods and zero out all the ones we know are
1966 // overridden.
1967 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1968 if (OverriddenMethods.count(Methods[i]))
1969 Methods[i] = 0;
1970 }
1971
1972 }
1973}
1974
1975
1976bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1977 unsigned DiagID, AbstractDiagSelID SelID,
1978 const CXXRecordDecl *CurrentRD) {
1979 if (SelID == -1)
1980 return RequireNonAbstractType(Loc, T,
1981 PDiag(DiagID), CurrentRD);
1982 else
1983 return RequireNonAbstractType(Loc, T,
1984 PDiag(DiagID) << SelID, CurrentRD);
1985}
1986
1987bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1988 const PartialDiagnostic &PD,
1989 const CXXRecordDecl *CurrentRD) {
1990 if (!getLangOptions().CPlusPlus)
1991 return false;
1992
1993 if (const ArrayType *AT = Context.getAsArrayType(T))
1994 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
1995 CurrentRD);
1996
1997 if (const PointerType *PT = T->getAs<PointerType>()) {
1998 // Find the innermost pointer type.
1999 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
2000 PT = T;
2001
2002 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
2003 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
2004 }
2005
2006 const RecordType *RT = T->getAs<RecordType>();
2007 if (!RT)
2008 return false;
2009
2010 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2011
2012 if (CurrentRD && CurrentRD != RD)
2013 return false;
2014
2015 // FIXME: is this reasonable? It matches current behavior, but....
2016 if (!RD->getDefinition(Context))
2017 return false;
2018
2019 if (!RD->isAbstract())
2020 return false;
2021
2022 Diag(Loc, PD) << RD->getDeclName();
2023
2024 // Check if we've already emitted the list of pure virtual functions for this
2025 // class.
2026 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2027 return true;
2028
2029 PureVirtualMethodCollector Collector(Context, RD);
2030
2031 for (PureVirtualMethodCollector::MethodList::const_iterator I =
2032 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
2033 const CXXMethodDecl *MD = *I;
2034
2035 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
2036 MD->getDeclName();
2037 }
2038
2039 if (!PureVirtualClassDiagSet)
2040 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2041 PureVirtualClassDiagSet->insert(RD);
2042
2043 return true;
2044}
2045
2046namespace {
2047 class AbstractClassUsageDiagnoser
2048 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2049 Sema &SemaRef;
2050 CXXRecordDecl *AbstractClass;
2051
2052 bool VisitDeclContext(const DeclContext *DC) {
2053 bool Invalid = false;
2054
2055 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2056 E = DC->decls_end(); I != E; ++I)
2057 Invalid |= Visit(*I);
2058
2059 return Invalid;
2060 }
2061
2062 public:
2063 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2064 : SemaRef(SemaRef), AbstractClass(ac) {
2065 Visit(SemaRef.Context.getTranslationUnitDecl());
2066 }
2067
2068 bool VisitFunctionDecl(const FunctionDecl *FD) {
2069 if (FD->isThisDeclarationADefinition()) {
2070 // No need to do the check if we're in a definition, because it requires
2071 // that the return/param types are complete.
2072 // because that requires
2073 return VisitDeclContext(FD);
2074 }
2075
2076 // Check the return type.
2077 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
2078 bool Invalid =
2079 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2080 diag::err_abstract_type_in_decl,
2081 Sema::AbstractReturnType,
2082 AbstractClass);
2083
2084 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
2085 E = FD->param_end(); I != E; ++I) {
2086 const ParmVarDecl *VD = *I;
2087 Invalid |=
2088 SemaRef.RequireNonAbstractType(VD->getLocation(),
2089 VD->getOriginalType(),
2090 diag::err_abstract_type_in_decl,
2091 Sema::AbstractParamType,
2092 AbstractClass);
2093 }
2094
2095 return Invalid;
2096 }
2097
2098 bool VisitDecl(const Decl* D) {
2099 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2100 return VisitDeclContext(DC);
2101
2102 return false;
2103 }
2104 };
2105}
2106
2107/// \brief Perform semantic checks on a class definition that has been
2108/// completing, introducing implicitly-declared members, checking for
2109/// abstract types, etc.
2110void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2111 if (!Record || Record->isInvalidDecl())
2112 return;
2113
2114 if (!Record->isDependentType())
2115 AddImplicitlyDeclaredMembersToClass(Record);
2116
2117 if (Record->isInvalidDecl())
2118 return;
2119
2120 // Set access bits correctly on the directly-declared conversions.
2121 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2122 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2123 Convs->setAccess(I, (*I)->getAccess());
2124
2125 if (!Record->isAbstract()) {
2126 // Collect all the pure virtual methods and see if this is an abstract
2127 // class after all.
2128 PureVirtualMethodCollector Collector(Context, Record);
2129 if (!Collector.empty())
2130 Record->setAbstract(true);
2131 }
2132
2133 if (Record->isAbstract())
2134 (void)AbstractClassUsageDiagnoser(*this, Record);
2135}
2136
2137void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
2138 DeclPtrTy TagDecl,
2139 SourceLocation LBrac,
2140 SourceLocation RBrac) {
2141 if (!TagDecl)
2142 return;
2143
2144 AdjustDeclIfTemplate(TagDecl);
2145
2146 ActOnFields(S, RLoc, TagDecl,
2147 (DeclPtrTy*)FieldCollector->getCurFields(),
2148 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
2149
2150 CheckCompletedCXXClass(
2151 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
2152}
2153
2154/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2155/// special functions, such as the default constructor, copy
2156/// constructor, or destructor, to the given C++ class (C++
2157/// [special]p1). This routine can only be executed just before the
2158/// definition of the class is complete.
2159void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
2160 CanQualType ClassType
2161 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
2162
2163 // FIXME: Implicit declarations have exception specifications, which are
2164 // the union of the specifications of the implicitly called functions.
2165
2166 if (!ClassDecl->hasUserDeclaredConstructor()) {
2167 // C++ [class.ctor]p5:
2168 // A default constructor for a class X is a constructor of class X
2169 // that can be called without an argument. If there is no
2170 // user-declared constructor for class X, a default constructor is
2171 // implicitly declared. An implicitly-declared default constructor
2172 // is an inline public member of its class.
2173 DeclarationName Name
2174 = Context.DeclarationNames.getCXXConstructorName(ClassType);
2175 CXXConstructorDecl *DefaultCon =
2176 CXXConstructorDecl::Create(Context, ClassDecl,
2177 ClassDecl->getLocation(), Name,
2178 Context.getFunctionType(Context.VoidTy,
2179 0, 0, false, 0),
2180 /*TInfo=*/0,
2181 /*isExplicit=*/false,
2182 /*isInline=*/true,
2183 /*isImplicitlyDeclared=*/true);
2184 DefaultCon->setAccess(AS_public);
2185 DefaultCon->setImplicit();
2186 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
2187 ClassDecl->addDecl(DefaultCon);
2188 }
2189
2190 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2191 // C++ [class.copy]p4:
2192 // If the class definition does not explicitly declare a copy
2193 // constructor, one is declared implicitly.
2194
2195 // C++ [class.copy]p5:
2196 // The implicitly-declared copy constructor for a class X will
2197 // have the form
2198 //
2199 // X::X(const X&)
2200 //
2201 // if
2202 bool HasConstCopyConstructor = true;
2203
2204 // -- each direct or virtual base class B of X has a copy
2205 // constructor whose first parameter is of type const B& or
2206 // const volatile B&, and
2207 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2208 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2209 const CXXRecordDecl *BaseClassDecl
2210 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2211 HasConstCopyConstructor
2212 = BaseClassDecl->hasConstCopyConstructor(Context);
2213 }
2214
2215 // -- for all the nonstatic data members of X that are of a
2216 // class type M (or array thereof), each such class type
2217 // has a copy constructor whose first parameter is of type
2218 // const M& or const volatile M&.
2219 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2220 HasConstCopyConstructor && Field != ClassDecl->field_end();
2221 ++Field) {
2222 QualType FieldType = (*Field)->getType();
2223 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2224 FieldType = Array->getElementType();
2225 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2226 const CXXRecordDecl *FieldClassDecl
2227 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2228 HasConstCopyConstructor
2229 = FieldClassDecl->hasConstCopyConstructor(Context);
2230 }
2231 }
2232
2233 // Otherwise, the implicitly declared copy constructor will have
2234 // the form
2235 //
2236 // X::X(X&)
2237 QualType ArgType = ClassType;
2238 if (HasConstCopyConstructor)
2239 ArgType = ArgType.withConst();
2240 ArgType = Context.getLValueReferenceType(ArgType);
2241
2242 // An implicitly-declared copy constructor is an inline public
2243 // member of its class.
2244 DeclarationName Name
2245 = Context.DeclarationNames.getCXXConstructorName(ClassType);
2246 CXXConstructorDecl *CopyConstructor
2247 = CXXConstructorDecl::Create(Context, ClassDecl,
2248 ClassDecl->getLocation(), Name,
2249 Context.getFunctionType(Context.VoidTy,
2250 &ArgType, 1,
2251 false, 0),
2252 /*TInfo=*/0,
2253 /*isExplicit=*/false,
2254 /*isInline=*/true,
2255 /*isImplicitlyDeclared=*/true);
2256 CopyConstructor->setAccess(AS_public);
2257 CopyConstructor->setImplicit();
2258 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
2259
2260 // Add the parameter to the constructor.
2261 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2262 ClassDecl->getLocation(),
2263 /*IdentifierInfo=*/0,
2264 ArgType, /*TInfo=*/0,
2265 VarDecl::None, 0);
2266 CopyConstructor->setParams(Context, &FromParam, 1);
2267 ClassDecl->addDecl(CopyConstructor);
2268 }
2269
2270 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2271 // Note: The following rules are largely analoguous to the copy
2272 // constructor rules. Note that virtual bases are not taken into account
2273 // for determining the argument type of the operator. Note also that
2274 // operators taking an object instead of a reference are allowed.
2275 //
2276 // C++ [class.copy]p10:
2277 // If the class definition does not explicitly declare a copy
2278 // assignment operator, one is declared implicitly.
2279 // The implicitly-defined copy assignment operator for a class X
2280 // will have the form
2281 //
2282 // X& X::operator=(const X&)
2283 //
2284 // if
2285 bool HasConstCopyAssignment = true;
2286
2287 // -- each direct base class B of X has a copy assignment operator
2288 // whose parameter is of type const B&, const volatile B& or B,
2289 // and
2290 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2291 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
2292 assert(!Base->getType()->isDependentType() &&
2293 "Cannot generate implicit members for class with dependent bases.");
2294 const CXXRecordDecl *BaseClassDecl
2295 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2296 const CXXMethodDecl *MD = 0;
2297 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
2298 MD);
2299 }
2300
2301 // -- for all the nonstatic data members of X that are of a class
2302 // type M (or array thereof), each such class type has a copy
2303 // assignment operator whose parameter is of type const M&,
2304 // const volatile M& or M.
2305 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2306 HasConstCopyAssignment && Field != ClassDecl->field_end();
2307 ++Field) {
2308 QualType FieldType = (*Field)->getType();
2309 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2310 FieldType = Array->getElementType();
2311 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2312 const CXXRecordDecl *FieldClassDecl
2313 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2314 const CXXMethodDecl *MD = 0;
2315 HasConstCopyAssignment
2316 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
2317 }
2318 }
2319
2320 // Otherwise, the implicitly declared copy assignment operator will
2321 // have the form
2322 //
2323 // X& X::operator=(X&)
2324 QualType ArgType = ClassType;
2325 QualType RetType = Context.getLValueReferenceType(ArgType);
2326 if (HasConstCopyAssignment)
2327 ArgType = ArgType.withConst();
2328 ArgType = Context.getLValueReferenceType(ArgType);
2329
2330 // An implicitly-declared copy assignment operator is an inline public
2331 // member of its class.
2332 DeclarationName Name =
2333 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2334 CXXMethodDecl *CopyAssignment =
2335 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2336 Context.getFunctionType(RetType, &ArgType, 1,
2337 false, 0),
2338 /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
2339 CopyAssignment->setAccess(AS_public);
2340 CopyAssignment->setImplicit();
2341 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
2342 CopyAssignment->setCopyAssignment(true);
2343
2344 // Add the parameter to the operator.
2345 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2346 ClassDecl->getLocation(),
2347 /*IdentifierInfo=*/0,
2348 ArgType, /*TInfo=*/0,
2349 VarDecl::None, 0);
2350 CopyAssignment->setParams(Context, &FromParam, 1);
2351
2352 // Don't call addedAssignmentOperator. There is no way to distinguish an
2353 // implicit from an explicit assignment operator.
2354 ClassDecl->addDecl(CopyAssignment);
2355 AddOverriddenMethods(ClassDecl, CopyAssignment);
2356 }
2357
2358 if (!ClassDecl->hasUserDeclaredDestructor()) {
2359 // C++ [class.dtor]p2:
2360 // If a class has no user-declared destructor, a destructor is
2361 // declared implicitly. An implicitly-declared destructor is an
2362 // inline public member of its class.
2363 DeclarationName Name
2364 = Context.DeclarationNames.getCXXDestructorName(ClassType);
2365 CXXDestructorDecl *Destructor
2366 = CXXDestructorDecl::Create(Context, ClassDecl,
2367 ClassDecl->getLocation(), Name,
2368 Context.getFunctionType(Context.VoidTy,
2369 0, 0, false, 0),
2370 /*isInline=*/true,
2371 /*isImplicitlyDeclared=*/true);
2372 Destructor->setAccess(AS_public);
2373 Destructor->setImplicit();
2374 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
2375 ClassDecl->addDecl(Destructor);
2376
2377 AddOverriddenMethods(ClassDecl, Destructor);
2378 }
2379}
2380
2381void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
2382 Decl *D = TemplateD.getAs<Decl>();
2383 if (!D)
2384 return;
2385
2386 TemplateParameterList *Params = 0;
2387 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2388 Params = Template->getTemplateParameters();
2389 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2390 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2391 Params = PartialSpec->getTemplateParameters();
2392 else
2393 return;
2394
2395 for (TemplateParameterList::iterator Param = Params->begin(),
2396 ParamEnd = Params->end();
2397 Param != ParamEnd; ++Param) {
2398 NamedDecl *Named = cast<NamedDecl>(*Param);
2399 if (Named->getDeclName()) {
2400 S->AddDecl(DeclPtrTy::make(Named));
2401 IdResolver.AddDecl(Named);
2402 }
2403 }
2404}
2405
2406void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2407 if (!RecordD) return;
2408 AdjustDeclIfTemplate(RecordD);
2409 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2410 PushDeclContext(S, Record);
2411}
2412
2413void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2414 if (!RecordD) return;
2415 PopDeclContext();
2416}
2417
2418/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2419/// parsing a top-level (non-nested) C++ class, and we are now
2420/// parsing those parts of the given Method declaration that could
2421/// not be parsed earlier (C++ [class.mem]p2), such as default
2422/// arguments. This action should enter the scope of the given
2423/// Method declaration as if we had just parsed the qualified method
2424/// name. However, it should not bring the parameters into scope;
2425/// that will be performed by ActOnDelayedCXXMethodParameter.
2426void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2427}
2428
2429/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2430/// C++ method declaration. We're (re-)introducing the given
2431/// function parameter into scope for use in parsing later parts of
2432/// the method declaration. For example, we could see an
2433/// ActOnParamDefaultArgument event for this parameter.
2434void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
2435 if (!ParamD)
2436 return;
2437
2438 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
2439
2440 // If this parameter has an unparsed default argument, clear it out
2441 // to make way for the parsed default argument.
2442 if (Param->hasUnparsedDefaultArg())
2443 Param->setDefaultArg(0);
2444
2445 S->AddDecl(DeclPtrTy::make(Param));
2446 if (Param->getDeclName())
2447 IdResolver.AddDecl(Param);
2448}
2449
2450/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2451/// processing the delayed method declaration for Method. The method
2452/// declaration is now considered finished. There may be a separate
2453/// ActOnStartOfFunctionDef action later (not necessarily
2454/// immediately!) for this method, if it was also defined inside the
2455/// class body.
2456void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2457 if (!MethodD)
2458 return;
2459
2460 AdjustDeclIfTemplate(MethodD);
2461
2462 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
2463
2464 // Now that we have our default arguments, check the constructor
2465 // again. It could produce additional diagnostics or affect whether
2466 // the class has implicitly-declared destructors, among other
2467 // things.
2468 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2469 CheckConstructor(Constructor);
2470
2471 // Check the default arguments, which we may have added.
2472 if (!Method->isInvalidDecl())
2473 CheckCXXDefaultArguments(Method);
2474}
2475
2476/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
2477/// the well-formedness of the constructor declarator @p D with type @p
2478/// R. If there are any errors in the declarator, this routine will
2479/// emit diagnostics and set the invalid bit to true. In any case, the type
2480/// will be updated to reflect a well-formed type for the constructor and
2481/// returned.
2482QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2483 FunctionDecl::StorageClass &SC) {
2484 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2485
2486 // C++ [class.ctor]p3:
2487 // A constructor shall not be virtual (10.3) or static (9.4). A
2488 // constructor can be invoked for a const, volatile or const
2489 // volatile object. A constructor shall not be declared const,
2490 // volatile, or const volatile (9.3.2).
2491 if (isVirtual) {
2492 if (!D.isInvalidType())
2493 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2494 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2495 << SourceRange(D.getIdentifierLoc());
2496 D.setInvalidType();
2497 }
2498 if (SC == FunctionDecl::Static) {
2499 if (!D.isInvalidType())
2500 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2501 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2502 << SourceRange(D.getIdentifierLoc());
2503 D.setInvalidType();
2504 SC = FunctionDecl::None;
2505 }
2506
2507 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2508 if (FTI.TypeQuals != 0) {
2509 if (FTI.TypeQuals & Qualifiers::Const)
2510 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2511 << "const" << SourceRange(D.getIdentifierLoc());
2512 if (FTI.TypeQuals & Qualifiers::Volatile)
2513 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2514 << "volatile" << SourceRange(D.getIdentifierLoc());
2515 if (FTI.TypeQuals & Qualifiers::Restrict)
2516 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2517 << "restrict" << SourceRange(D.getIdentifierLoc());
2518 }
2519
2520 // Rebuild the function type "R" without any type qualifiers (in
2521 // case any of the errors above fired) and with "void" as the
2522 // return type, since constructors don't have return types. We
2523 // *always* have to do this, because GetTypeForDeclarator will
2524 // put in a result type of "int" when none was specified.
2525 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
2526 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2527 Proto->getNumArgs(),
2528 Proto->isVariadic(), 0);
2529}
2530
2531/// CheckConstructor - Checks a fully-formed constructor for
2532/// well-formedness, issuing any diagnostics required. Returns true if
2533/// the constructor declarator is invalid.
2534void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
2535 CXXRecordDecl *ClassDecl
2536 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2537 if (!ClassDecl)
2538 return Constructor->setInvalidDecl();
2539
2540 // C++ [class.copy]p3:
2541 // A declaration of a constructor for a class X is ill-formed if
2542 // its first parameter is of type (optionally cv-qualified) X and
2543 // either there are no other parameters or else all other
2544 // parameters have default arguments.
2545 if (!Constructor->isInvalidDecl() &&
2546 ((Constructor->getNumParams() == 1) ||
2547 (Constructor->getNumParams() > 1 &&
2548 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2549 Constructor->getTemplateSpecializationKind()
2550 != TSK_ImplicitInstantiation) {
2551 QualType ParamType = Constructor->getParamDecl(0)->getType();
2552 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2553 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
2554 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2555 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
2556 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
2557
2558 // FIXME: Rather that making the constructor invalid, we should endeavor
2559 // to fix the type.
2560 Constructor->setInvalidDecl();
2561 }
2562 }
2563
2564 // Notify the class that we've added a constructor.
2565 ClassDecl->addedConstructor(Context, Constructor);
2566}
2567
2568/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2569/// issuing any diagnostics required. Returns true on error.
2570bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
2571 CXXRecordDecl *RD = Destructor->getParent();
2572
2573 if (Destructor->isVirtual()) {
2574 SourceLocation Loc;
2575
2576 if (!Destructor->isImplicit())
2577 Loc = Destructor->getLocation();
2578 else
2579 Loc = RD->getLocation();
2580
2581 // If we have a virtual destructor, look up the deallocation function
2582 FunctionDecl *OperatorDelete = 0;
2583 DeclarationName Name =
2584 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2585 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2586 return true;
2587
2588 Destructor->setOperatorDelete(OperatorDelete);
2589 }
2590
2591 return false;
2592}
2593
2594static inline bool
2595FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2596 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2597 FTI.ArgInfo[0].Param &&
2598 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2599}
2600
2601/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2602/// the well-formednes of the destructor declarator @p D with type @p
2603/// R. If there are any errors in the declarator, this routine will
2604/// emit diagnostics and set the declarator to invalid. Even if this happens,
2605/// will be updated to reflect a well-formed type for the destructor and
2606/// returned.
2607QualType Sema::CheckDestructorDeclarator(Declarator &D,
2608 FunctionDecl::StorageClass& SC) {
2609 // C++ [class.dtor]p1:
2610 // [...] A typedef-name that names a class is a class-name
2611 // (7.1.3); however, a typedef-name that names a class shall not
2612 // be used as the identifier in the declarator for a destructor
2613 // declaration.
2614 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
2615 if (isa<TypedefType>(DeclaratorType)) {
2616 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
2617 << DeclaratorType;
2618 D.setInvalidType();
2619 }
2620
2621 // C++ [class.dtor]p2:
2622 // A destructor is used to destroy objects of its class type. A
2623 // destructor takes no parameters, and no return type can be
2624 // specified for it (not even void). The address of a destructor
2625 // shall not be taken. A destructor shall not be static. A
2626 // destructor can be invoked for a const, volatile or const
2627 // volatile object. A destructor shall not be declared const,
2628 // volatile or const volatile (9.3.2).
2629 if (SC == FunctionDecl::Static) {
2630 if (!D.isInvalidType())
2631 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2632 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2633 << SourceRange(D.getIdentifierLoc());
2634 SC = FunctionDecl::None;
2635 D.setInvalidType();
2636 }
2637 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
2638 // Destructors don't have return types, but the parser will
2639 // happily parse something like:
2640 //
2641 // class X {
2642 // float ~X();
2643 // };
2644 //
2645 // The return type will be eliminated later.
2646 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2647 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2648 << SourceRange(D.getIdentifierLoc());
2649 }
2650
2651 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2652 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
2653 if (FTI.TypeQuals & Qualifiers::Const)
2654 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2655 << "const" << SourceRange(D.getIdentifierLoc());
2656 if (FTI.TypeQuals & Qualifiers::Volatile)
2657 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2658 << "volatile" << SourceRange(D.getIdentifierLoc());
2659 if (FTI.TypeQuals & Qualifiers::Restrict)
2660 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2661 << "restrict" << SourceRange(D.getIdentifierLoc());
2662 D.setInvalidType();
2663 }
2664
2665 // Make sure we don't have any parameters.
2666 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
2667 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2668
2669 // Delete the parameters.
2670 FTI.freeArgs();
2671 D.setInvalidType();
2672 }
2673
2674 // Make sure the destructor isn't variadic.
2675 if (FTI.isVariadic) {
2676 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
2677 D.setInvalidType();
2678 }
2679
2680 // Rebuild the function type "R" without any type qualifiers or
2681 // parameters (in case any of the errors above fired) and with
2682 // "void" as the return type, since destructors don't have return
2683 // types. We *always* have to do this, because GetTypeForDeclarator
2684 // will put in a result type of "int" when none was specified.
2685 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
2686}
2687
2688/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2689/// well-formednes of the conversion function declarator @p D with
2690/// type @p R. If there are any errors in the declarator, this routine
2691/// will emit diagnostics and return true. Otherwise, it will return
2692/// false. Either way, the type @p R will be updated to reflect a
2693/// well-formed type for the conversion operator.
2694void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
2695 FunctionDecl::StorageClass& SC) {
2696 // C++ [class.conv.fct]p1:
2697 // Neither parameter types nor return type can be specified. The
2698 // type of a conversion function (8.3.5) is "function taking no
2699 // parameter returning conversion-type-id."
2700 if (SC == FunctionDecl::Static) {
2701 if (!D.isInvalidType())
2702 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2703 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2704 << SourceRange(D.getIdentifierLoc());
2705 D.setInvalidType();
2706 SC = FunctionDecl::None;
2707 }
2708 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
2709 // Conversion functions don't have return types, but the parser will
2710 // happily parse something like:
2711 //
2712 // class X {
2713 // float operator bool();
2714 // };
2715 //
2716 // The return type will be changed later anyway.
2717 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2718 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2719 << SourceRange(D.getIdentifierLoc());
2720 }
2721
2722 // Make sure we don't have any parameters.
2723 if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
2724 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2725
2726 // Delete the parameters.
2727 D.getTypeObject(0).Fun.freeArgs();
2728 D.setInvalidType();
2729 }
2730
2731 // Make sure the conversion function isn't variadic.
2732 if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
2733 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
2734 D.setInvalidType();
2735 }
2736
2737 // C++ [class.conv.fct]p4:
2738 // The conversion-type-id shall not represent a function type nor
2739 // an array type.
2740 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
2741 if (ConvType->isArrayType()) {
2742 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2743 ConvType = Context.getPointerType(ConvType);
2744 D.setInvalidType();
2745 } else if (ConvType->isFunctionType()) {
2746 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2747 ConvType = Context.getPointerType(ConvType);
2748 D.setInvalidType();
2749 }
2750
2751 // Rebuild the function type "R" without any parameters (in case any
2752 // of the errors above fired) and with the conversion type as the
2753 // return type.
2754 R = Context.getFunctionType(ConvType, 0, 0, false,
2755 R->getAs<FunctionProtoType>()->getTypeQuals());
2756
2757 // C++0x explicit conversion operators.
2758 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
2759 Diag(D.getDeclSpec().getExplicitSpecLoc(),
2760 diag::warn_explicit_conversion_functions)
2761 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
2762}
2763
2764/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2765/// the declaration of the given C++ conversion function. This routine
2766/// is responsible for recording the conversion function in the C++
2767/// class, if possible.
2768Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
2769 assert(Conversion && "Expected to receive a conversion function declaration");
2770
2771 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
2772
2773 // Make sure we aren't redeclaring the conversion function.
2774 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
2775
2776 // C++ [class.conv.fct]p1:
2777 // [...] A conversion function is never used to convert a
2778 // (possibly cv-qualified) object to the (possibly cv-qualified)
2779 // same object type (or a reference to it), to a (possibly
2780 // cv-qualified) base class of that type (or a reference to it),
2781 // or to (possibly cv-qualified) void.
2782 // FIXME: Suppress this warning if the conversion function ends up being a
2783 // virtual function that overrides a virtual function in a base class.
2784 QualType ClassType
2785 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
2786 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
2787 ConvType = ConvTypeRef->getPointeeType();
2788 if (ConvType->isRecordType()) {
2789 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2790 if (ConvType == ClassType)
2791 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
2792 << ClassType;
2793 else if (IsDerivedFrom(ClassType, ConvType))
2794 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
2795 << ClassType << ConvType;
2796 } else if (ConvType->isVoidType()) {
2797 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
2798 << ClassType << ConvType;
2799 }
2800
2801 if (Conversion->getPrimaryTemplate()) {
2802 // ignore specializations
2803 } else if (Conversion->getPreviousDeclaration()) {
2804 if (FunctionTemplateDecl *ConversionTemplate
2805 = Conversion->getDescribedFunctionTemplate()) {
2806 if (ClassDecl->replaceConversion(
2807 ConversionTemplate->getPreviousDeclaration(),
2808 ConversionTemplate))
2809 return DeclPtrTy::make(ConversionTemplate);
2810 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
2811 Conversion))
2812 return DeclPtrTy::make(Conversion);
2813 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
2814 } else if (FunctionTemplateDecl *ConversionTemplate
2815 = Conversion->getDescribedFunctionTemplate())
2816 ClassDecl->addConversionFunction(ConversionTemplate);
2817 else
2818 ClassDecl->addConversionFunction(Conversion);
2819
2820 return DeclPtrTy::make(Conversion);
2821}
2822
2823//===----------------------------------------------------------------------===//
2824// Namespace Handling
2825//===----------------------------------------------------------------------===//
2826
2827/// ActOnStartNamespaceDef - This is called at the start of a namespace
2828/// definition.
2829Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2830 SourceLocation IdentLoc,
2831 IdentifierInfo *II,
2832 SourceLocation LBrace,
2833 AttributeList *AttrList) {
2834 NamespaceDecl *Namespc =
2835 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2836 Namespc->setLBracLoc(LBrace);
2837
2838 Scope *DeclRegionScope = NamespcScope->getParent();
2839
2840 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
2841
2842 if (II) {
2843 // C++ [namespace.def]p2:
2844 // The identifier in an original-namespace-definition shall not have been
2845 // previously defined in the declarative region in which the
2846 // original-namespace-definition appears. The identifier in an
2847 // original-namespace-definition is the name of the namespace. Subsequently
2848 // in that declarative region, it is treated as an original-namespace-name.
2849
2850 NamedDecl *PrevDecl
2851 = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
2852 ForRedeclaration);
2853
2854 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2855 // This is an extended namespace definition.
2856 // Attach this namespace decl to the chain of extended namespace
2857 // definitions.
2858 OrigNS->setNextNamespace(Namespc);
2859 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
2860
2861 // Remove the previous declaration from the scope.
2862 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
2863 IdResolver.RemoveDecl(OrigNS);
2864 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
2865 }
2866 } else if (PrevDecl) {
2867 // This is an invalid name redefinition.
2868 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2869 << Namespc->getDeclName();
2870 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2871 Namespc->setInvalidDecl();
2872 // Continue on to push Namespc as current DeclContext and return it.
2873 } else if (II->isStr("std") &&
2874 CurContext->getLookupContext()->isTranslationUnit()) {
2875 // This is the first "real" definition of the namespace "std", so update
2876 // our cache of the "std" namespace to point at this definition.
2877 if (StdNamespace) {
2878 // We had already defined a dummy namespace "std". Link this new
2879 // namespace definition to the dummy namespace "std".
2880 StdNamespace->setNextNamespace(Namespc);
2881 StdNamespace->setLocation(IdentLoc);
2882 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2883 }
2884
2885 // Make our StdNamespace cache point at the first real definition of the
2886 // "std" namespace.
2887 StdNamespace = Namespc;
2888 }
2889
2890 PushOnScopeChains(Namespc, DeclRegionScope);
2891 } else {
2892 // Anonymous namespaces.
2893 assert(Namespc->isAnonymousNamespace());
2894 CurContext->addDecl(Namespc);
2895
2896 // Link the anonymous namespace into its parent.
2897 NamespaceDecl *PrevDecl;
2898 DeclContext *Parent = CurContext->getLookupContext();
2899 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2900 PrevDecl = TU->getAnonymousNamespace();
2901 TU->setAnonymousNamespace(Namespc);
2902 } else {
2903 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2904 PrevDecl = ND->getAnonymousNamespace();
2905 ND->setAnonymousNamespace(Namespc);
2906 }
2907
2908 // Link the anonymous namespace with its previous declaration.
2909 if (PrevDecl) {
2910 assert(PrevDecl->isAnonymousNamespace());
2911 assert(!PrevDecl->getNextNamespace());
2912 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2913 PrevDecl->setNextNamespace(Namespc);
2914 }
2915
2916 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
2917 // behaves as if it were replaced by
2918 // namespace unique { /* empty body */ }
2919 // using namespace unique;
2920 // namespace unique { namespace-body }
2921 // where all occurrences of 'unique' in a translation unit are
2922 // replaced by the same identifier and this identifier differs
2923 // from all other identifiers in the entire program.
2924
2925 // We just create the namespace with an empty name and then add an
2926 // implicit using declaration, just like the standard suggests.
2927 //
2928 // CodeGen enforces the "universally unique" aspect by giving all
2929 // declarations semantically contained within an anonymous
2930 // namespace internal linkage.
2931
2932 if (!PrevDecl) {
2933 UsingDirectiveDecl* UD
2934 = UsingDirectiveDecl::Create(Context, CurContext,
2935 /* 'using' */ LBrace,
2936 /* 'namespace' */ SourceLocation(),
2937 /* qualifier */ SourceRange(),
2938 /* NNS */ NULL,
2939 /* identifier */ SourceLocation(),
2940 Namespc,
2941 /* Ancestor */ CurContext);
2942 UD->setImplicit();
2943 CurContext->addDecl(UD);
2944 }
2945 }
2946
2947 // Although we could have an invalid decl (i.e. the namespace name is a
2948 // redefinition), push it as current DeclContext and try to continue parsing.
2949 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2950 // for the namespace has the declarations that showed up in that particular
2951 // namespace definition.
2952 PushDeclContext(NamespcScope, Namespc);
2953 return DeclPtrTy::make(Namespc);
2954}
2955
2956/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2957/// is a namespace alias, returns the namespace it points to.
2958static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2959 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2960 return AD->getNamespace();
2961 return dyn_cast_or_null<NamespaceDecl>(D);
2962}
2963
2964/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2965/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
2966void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2967 Decl *Dcl = D.getAs<Decl>();
2968 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2969 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2970 Namespc->setRBracLoc(RBrace);
2971 PopDeclContext();
2972}
2973
2974Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2975 SourceLocation UsingLoc,
2976 SourceLocation NamespcLoc,
2977 const CXXScopeSpec &SS,
2978 SourceLocation IdentLoc,
2979 IdentifierInfo *NamespcName,
2980 AttributeList *AttrList) {
2981 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2982 assert(NamespcName && "Invalid NamespcName.");
2983 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
2984 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
2985
2986 UsingDirectiveDecl *UDir = 0;
2987
2988 // Lookup namespace name.
2989 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
2990 LookupParsedName(R, S, &SS);
2991 if (R.isAmbiguous())
2992 return DeclPtrTy();
2993
2994 if (!R.empty()) {
2995 NamedDecl *Named = R.getFoundDecl();
2996 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
2997 && "expected namespace decl");
2998 // C++ [namespace.udir]p1:
2999 // A using-directive specifies that the names in the nominated
3000 // namespace can be used in the scope in which the
3001 // using-directive appears after the using-directive. During
3002 // unqualified name lookup (3.4.1), the names appear as if they
3003 // were declared in the nearest enclosing namespace which
3004 // contains both the using-directive and the nominated
3005 // namespace. [Note: in this context, "contains" means "contains
3006 // directly or indirectly". ]
3007
3008 // Find enclosing context containing both using-directive and
3009 // nominated namespace.
3010 NamespaceDecl *NS = getNamespaceDecl(Named);
3011 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3012 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3013 CommonAncestor = CommonAncestor->getParent();
3014
3015 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
3016 SS.getRange(),
3017 (NestedNameSpecifier *)SS.getScopeRep(),
3018 IdentLoc, Named, CommonAncestor);
3019 PushUsingDirective(S, UDir);
3020 } else {
3021 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
3022 }
3023
3024 // FIXME: We ignore attributes for now.
3025 delete AttrList;
3026 return DeclPtrTy::make(UDir);
3027}
3028
3029void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3030 // If scope has associated entity, then using directive is at namespace
3031 // or translation unit scope. We add UsingDirectiveDecls, into
3032 // it's lookup structure.
3033 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
3034 Ctx->addDecl(UDir);
3035 else
3036 // Otherwise it is block-sope. using-directives will affect lookup
3037 // only to the end of scope.
3038 S->PushUsingDirective(DeclPtrTy::make(UDir));
3039}
3040
3041
3042Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
3043 AccessSpecifier AS,
3044 bool HasUsingKeyword,
3045 SourceLocation UsingLoc,
3046 const CXXScopeSpec &SS,
3047 UnqualifiedId &Name,
3048 AttributeList *AttrList,
3049 bool IsTypeName,
3050 SourceLocation TypenameLoc) {
3051 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
3052
3053 switch (Name.getKind()) {
3054 case UnqualifiedId::IK_Identifier:
3055 case UnqualifiedId::IK_OperatorFunctionId:
3056 case UnqualifiedId::IK_LiteralOperatorId:
3057 case UnqualifiedId::IK_ConversionFunctionId:
3058 break;
3059
3060 case UnqualifiedId::IK_ConstructorName:
3061 case UnqualifiedId::IK_ConstructorTemplateId:
3062 // C++0x inherited constructors.
3063 if (getLangOptions().CPlusPlus0x) break;
3064
3065 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3066 << SS.getRange();
3067 return DeclPtrTy();
3068
3069 case UnqualifiedId::IK_DestructorName:
3070 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3071 << SS.getRange();
3072 return DeclPtrTy();
3073
3074 case UnqualifiedId::IK_TemplateId:
3075 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3076 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3077 return DeclPtrTy();
3078 }
3079
3080 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
3081 if (!TargetName)
3082 return DeclPtrTy();
3083
3084 // Warn about using declarations.
3085 // TODO: store that the declaration was written without 'using' and
3086 // talk about access decls instead of using decls in the
3087 // diagnostics.
3088 if (!HasUsingKeyword) {
3089 UsingLoc = Name.getSourceRange().getBegin();
3090
3091 Diag(UsingLoc, diag::warn_access_decl_deprecated)
3092 << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
3093 "using ");
3094 }
3095
3096 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
3097 Name.getSourceRange().getBegin(),
3098 TargetName, AttrList,
3099 /* IsInstantiation */ false,
3100 IsTypeName, TypenameLoc);
3101 if (UD)
3102 PushOnScopeChains(UD, S, /*AddToContext*/ false);
3103
3104 return DeclPtrTy::make(UD);
3105}
3106
3107/// Determines whether to create a using shadow decl for a particular
3108/// decl, given the set of decls existing prior to this using lookup.
3109bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3110 const LookupResult &Previous) {
3111 // Diagnose finding a decl which is not from a base class of the
3112 // current class. We do this now because there are cases where this
3113 // function will silently decide not to build a shadow decl, which
3114 // will pre-empt further diagnostics.
3115 //
3116 // We don't need to do this in C++0x because we do the check once on
3117 // the qualifier.
3118 //
3119 // FIXME: diagnose the following if we care enough:
3120 // struct A { int foo; };
3121 // struct B : A { using A::foo; };
3122 // template <class T> struct C : A {};
3123 // template <class T> struct D : C<T> { using B::foo; } // <---
3124 // This is invalid (during instantiation) in C++03 because B::foo
3125 // resolves to the using decl in B, which is not a base class of D<T>.
3126 // We can't diagnose it immediately because C<T> is an unknown
3127 // specialization. The UsingShadowDecl in D<T> then points directly
3128 // to A::foo, which will look well-formed when we instantiate.
3129 // The right solution is to not collapse the shadow-decl chain.
3130 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3131 DeclContext *OrigDC = Orig->getDeclContext();
3132
3133 // Handle enums and anonymous structs.
3134 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3135 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3136 while (OrigRec->isAnonymousStructOrUnion())
3137 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3138
3139 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3140 if (OrigDC == CurContext) {
3141 Diag(Using->getLocation(),
3142 diag::err_using_decl_nested_name_specifier_is_current_class)
3143 << Using->getNestedNameRange();
3144 Diag(Orig->getLocation(), diag::note_using_decl_target);
3145 return true;
3146 }
3147
3148 Diag(Using->getNestedNameRange().getBegin(),
3149 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3150 << Using->getTargetNestedNameDecl()
3151 << cast<CXXRecordDecl>(CurContext)
3152 << Using->getNestedNameRange();
3153 Diag(Orig->getLocation(), diag::note_using_decl_target);
3154 return true;
3155 }
3156 }
3157
3158 if (Previous.empty()) return false;
3159
3160 NamedDecl *Target = Orig;
3161 if (isa<UsingShadowDecl>(Target))
3162 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3163
3164 // If the target happens to be one of the previous declarations, we
3165 // don't have a conflict.
3166 //
3167 // FIXME: but we might be increasing its access, in which case we
3168 // should redeclare it.
3169 NamedDecl *NonTag = 0, *Tag = 0;
3170 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3171 I != E; ++I) {
3172 NamedDecl *D = (*I)->getUnderlyingDecl();
3173 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3174 return false;
3175
3176 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3177 }
3178
3179 if (Target->isFunctionOrFunctionTemplate()) {
3180 FunctionDecl *FD;
3181 if (isa<FunctionTemplateDecl>(Target))
3182 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3183 else
3184 FD = cast<FunctionDecl>(Target);
3185
3186 NamedDecl *OldDecl = 0;
3187 switch (CheckOverload(FD, Previous, OldDecl)) {
3188 case Ovl_Overload:
3189 return false;
3190
3191 case Ovl_NonFunction:
3192 Diag(Using->getLocation(), diag::err_using_decl_conflict);
3193 break;
3194
3195 // We found a decl with the exact signature.
3196 case Ovl_Match:
3197 if (isa<UsingShadowDecl>(OldDecl)) {
3198 // Silently ignore the possible conflict.
3199 return false;
3200 }
3201
3202 // If we're in a record, we want to hide the target, so we
3203 // return true (without a diagnostic) to tell the caller not to
3204 // build a shadow decl.
3205 if (CurContext->isRecord())
3206 return true;
3207
3208 // If we're not in a record, this is an error.
3209 Diag(Using->getLocation(), diag::err_using_decl_conflict);
3210 break;
3211 }
3212
3213 Diag(Target->getLocation(), diag::note_using_decl_target);
3214 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3215 return true;
3216 }
3217
3218 // Target is not a function.
3219
3220 if (isa<TagDecl>(Target)) {
3221 // No conflict between a tag and a non-tag.
3222 if (!Tag) return false;
3223
3224 Diag(Using->getLocation(), diag::err_using_decl_conflict);
3225 Diag(Target->getLocation(), diag::note_using_decl_target);
3226 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3227 return true;
3228 }
3229
3230 // No conflict between a tag and a non-tag.
3231 if (!NonTag) return false;
3232
3233 Diag(Using->getLocation(), diag::err_using_decl_conflict);
3234 Diag(Target->getLocation(), diag::note_using_decl_target);
3235 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3236 return true;
3237}
3238
3239/// Builds a shadow declaration corresponding to a 'using' declaration.
3240UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
3241 UsingDecl *UD,
3242 NamedDecl *Orig) {
3243
3244 // If we resolved to another shadow declaration, just coalesce them.
3245 NamedDecl *Target = Orig;
3246 if (isa<UsingShadowDecl>(Target)) {
3247 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3248 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
3249 }
3250
3251 UsingShadowDecl *Shadow
3252 = UsingShadowDecl::Create(Context, CurContext,
3253 UD->getLocation(), UD, Target);
3254 UD->addShadowDecl(Shadow);
3255
3256 if (S)
3257 PushOnScopeChains(Shadow, S);
3258 else
3259 CurContext->addDecl(Shadow);
3260 Shadow->setAccess(UD->getAccess());
3261
3262 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3263 Shadow->setInvalidDecl();
3264
3265 return Shadow;
3266}
3267
3268/// Hides a using shadow declaration. This is required by the current
3269/// using-decl implementation when a resolvable using declaration in a
3270/// class is followed by a declaration which would hide or override
3271/// one or more of the using decl's targets; for example:
3272///
3273/// struct Base { void foo(int); };
3274/// struct Derived : Base {
3275/// using Base::foo;
3276/// void foo(int);
3277/// };
3278///
3279/// The governing language is C++03 [namespace.udecl]p12:
3280///
3281/// When a using-declaration brings names from a base class into a
3282/// derived class scope, member functions in the derived class
3283/// override and/or hide member functions with the same name and
3284/// parameter types in a base class (rather than conflicting).
3285///
3286/// There are two ways to implement this:
3287/// (1) optimistically create shadow decls when they're not hidden
3288/// by existing declarations, or
3289/// (2) don't create any shadow decls (or at least don't make them
3290/// visible) until we've fully parsed/instantiated the class.
3291/// The problem with (1) is that we might have to retroactively remove
3292/// a shadow decl, which requires several O(n) operations because the
3293/// decl structures are (very reasonably) not designed for removal.
3294/// (2) avoids this but is very fiddly and phase-dependent.
3295void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3296 // Remove it from the DeclContext...
3297 Shadow->getDeclContext()->removeDecl(Shadow);
3298
3299 // ...and the scope, if applicable...
3300 if (S) {
3301 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3302 IdResolver.RemoveDecl(Shadow);
3303 }
3304
3305 // ...and the using decl.
3306 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3307
3308 // TODO: complain somehow if Shadow was used. It shouldn't
3309 // be possible for this to happen, because
3310}
3311
3312/// Builds a using declaration.
3313///
3314/// \param IsInstantiation - Whether this call arises from an
3315/// instantiation of an unresolved using declaration. We treat
3316/// the lookup differently for these declarations.
3317NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3318 SourceLocation UsingLoc,
3319 const CXXScopeSpec &SS,
3320 SourceLocation IdentLoc,
3321 DeclarationName Name,
3322 AttributeList *AttrList,
3323 bool IsInstantiation,
3324 bool IsTypeName,
3325 SourceLocation TypenameLoc) {
3326 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3327 assert(IdentLoc.isValid() && "Invalid TargetName location.");
3328
3329 // FIXME: We ignore attributes for now.
3330 delete AttrList;
3331
3332 if (SS.isEmpty()) {
3333 Diag(IdentLoc, diag::err_using_requires_qualname);
3334 return 0;
3335 }
3336
3337 // Do the redeclaration lookup in the current scope.
3338 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3339 ForRedeclaration);
3340 Previous.setHideTags(false);
3341 if (S) {
3342 LookupName(Previous, S);
3343
3344 // It is really dumb that we have to do this.
3345 LookupResult::Filter F = Previous.makeFilter();
3346 while (F.hasNext()) {
3347 NamedDecl *D = F.next();
3348 if (!isDeclInScope(D, CurContext, S))
3349 F.erase();
3350 }
3351 F.done();
3352 } else {
3353 assert(IsInstantiation && "no scope in non-instantiation");
3354 assert(CurContext->isRecord() && "scope not record in instantiation");
3355 LookupQualifiedName(Previous, CurContext);
3356 }
3357
3358 NestedNameSpecifier *NNS =
3359 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3360
3361 // Check for invalid redeclarations.
3362 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3363 return 0;
3364
3365 // Check for bad qualifiers.
3366 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3367 return 0;
3368
3369 DeclContext *LookupContext = computeDeclContext(SS);
3370 NamedDecl *D;
3371 if (!LookupContext) {
3372 if (IsTypeName) {
3373 // FIXME: not all declaration name kinds are legal here
3374 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3375 UsingLoc, TypenameLoc,
3376 SS.getRange(), NNS,
3377 IdentLoc, Name);
3378 } else {
3379 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3380 UsingLoc, SS.getRange(), NNS,
3381 IdentLoc, Name);
3382 }
3383 } else {
3384 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3385 SS.getRange(), UsingLoc, NNS, Name,
3386 IsTypeName);
3387 }
3388 D->setAccess(AS);
3389 CurContext->addDecl(D);
3390
3391 if (!LookupContext) return D;
3392 UsingDecl *UD = cast<UsingDecl>(D);
3393
3394 if (RequireCompleteDeclContext(SS)) {
3395 UD->setInvalidDecl();
3396 return UD;
3397 }
3398
3399 // Look up the target name.
3400
3401 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
3402
3403 // Unlike most lookups, we don't always want to hide tag
3404 // declarations: tag names are visible through the using declaration
3405 // even if hidden by ordinary names, *except* in a dependent context
3406 // where it's important for the sanity of two-phase lookup.
3407 if (!IsInstantiation)
3408 R.setHideTags(false);
3409
3410 LookupQualifiedName(R, LookupContext);
3411
3412 if (R.empty()) {
3413 Diag(IdentLoc, diag::err_no_member)
3414 << Name << LookupContext << SS.getRange();
3415 UD->setInvalidDecl();
3416 return UD;
3417 }
3418
3419 if (R.isAmbiguous()) {
3420 UD->setInvalidDecl();
3421 return UD;
3422 }
3423
3424 if (IsTypeName) {
3425 // If we asked for a typename and got a non-type decl, error out.
3426 if (!R.getAsSingle<TypeDecl>()) {
3427 Diag(IdentLoc, diag::err_using_typename_non_type);
3428 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3429 Diag((*I)->getUnderlyingDecl()->getLocation(),
3430 diag::note_using_decl_target);
3431 UD->setInvalidDecl();
3432 return UD;
3433 }
3434 } else {
3435 // If we asked for a non-typename and we got a type, error out,
3436 // but only if this is an instantiation of an unresolved using
3437 // decl. Otherwise just silently find the type name.
3438 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
3439 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3440 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
3441 UD->setInvalidDecl();
3442 return UD;
3443 }
3444 }
3445
3446 // C++0x N2914 [namespace.udecl]p6:
3447 // A using-declaration shall not name a namespace.
3448 if (R.getAsSingle<NamespaceDecl>()) {
3449 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3450 << SS.getRange();
3451 UD->setInvalidDecl();
3452 return UD;
3453 }
3454
3455 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3456 if (!CheckUsingShadowDecl(UD, *I, Previous))
3457 BuildUsingShadowDecl(S, UD, *I);
3458 }
3459
3460 return UD;
3461}
3462
3463/// Checks that the given using declaration is not an invalid
3464/// redeclaration. Note that this is checking only for the using decl
3465/// itself, not for any ill-formedness among the UsingShadowDecls.
3466bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3467 bool isTypeName,
3468 const CXXScopeSpec &SS,
3469 SourceLocation NameLoc,
3470 const LookupResult &Prev) {
3471 // C++03 [namespace.udecl]p8:
3472 // C++0x [namespace.udecl]p10:
3473 // A using-declaration is a declaration and can therefore be used
3474 // repeatedly where (and only where) multiple declarations are
3475 // allowed.
3476 // That's only in file contexts.
3477 if (CurContext->getLookupContext()->isFileContext())
3478 return false;
3479
3480 NestedNameSpecifier *Qual
3481 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3482
3483 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3484 NamedDecl *D = *I;
3485
3486 bool DTypename;
3487 NestedNameSpecifier *DQual;
3488 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3489 DTypename = UD->isTypeName();
3490 DQual = UD->getTargetNestedNameDecl();
3491 } else if (UnresolvedUsingValueDecl *UD
3492 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3493 DTypename = false;
3494 DQual = UD->getTargetNestedNameSpecifier();
3495 } else if (UnresolvedUsingTypenameDecl *UD
3496 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3497 DTypename = true;
3498 DQual = UD->getTargetNestedNameSpecifier();
3499 } else continue;
3500
3501 // using decls differ if one says 'typename' and the other doesn't.
3502 // FIXME: non-dependent using decls?
3503 if (isTypeName != DTypename) continue;
3504
3505 // using decls differ if they name different scopes (but note that
3506 // template instantiation can cause this check to trigger when it
3507 // didn't before instantiation).
3508 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3509 Context.getCanonicalNestedNameSpecifier(DQual))
3510 continue;
3511
3512 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
3513 Diag(D->getLocation(), diag::note_using_decl) << 1;
3514 return true;
3515 }
3516
3517 return false;
3518}
3519
3520
3521/// Checks that the given nested-name qualifier used in a using decl
3522/// in the current context is appropriately related to the current
3523/// scope. If an error is found, diagnoses it and returns true.
3524bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3525 const CXXScopeSpec &SS,
3526 SourceLocation NameLoc) {
3527 DeclContext *NamedContext = computeDeclContext(SS);
3528
3529 if (!CurContext->isRecord()) {
3530 // C++03 [namespace.udecl]p3:
3531 // C++0x [namespace.udecl]p8:
3532 // A using-declaration for a class member shall be a member-declaration.
3533
3534 // If we weren't able to compute a valid scope, it must be a
3535 // dependent class scope.
3536 if (!NamedContext || NamedContext->isRecord()) {
3537 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3538 << SS.getRange();
3539 return true;
3540 }
3541
3542 // Otherwise, everything is known to be fine.
3543 return false;
3544 }
3545
3546 // The current scope is a record.
3547
3548 // If the named context is dependent, we can't decide much.
3549 if (!NamedContext) {
3550 // FIXME: in C++0x, we can diagnose if we can prove that the
3551 // nested-name-specifier does not refer to a base class, which is
3552 // still possible in some cases.
3553
3554 // Otherwise we have to conservatively report that things might be
3555 // okay.
3556 return false;
3557 }
3558
3559 if (!NamedContext->isRecord()) {
3560 // Ideally this would point at the last name in the specifier,
3561 // but we don't have that level of source info.
3562 Diag(SS.getRange().getBegin(),
3563 diag::err_using_decl_nested_name_specifier_is_not_class)
3564 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3565 return true;
3566 }
3567
3568 if (getLangOptions().CPlusPlus0x) {
3569 // C++0x [namespace.udecl]p3:
3570 // In a using-declaration used as a member-declaration, the
3571 // nested-name-specifier shall name a base class of the class
3572 // being defined.
3573
3574 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3575 cast<CXXRecordDecl>(NamedContext))) {
3576 if (CurContext == NamedContext) {
3577 Diag(NameLoc,
3578 diag::err_using_decl_nested_name_specifier_is_current_class)
3579 << SS.getRange();
3580 return true;
3581 }
3582
3583 Diag(SS.getRange().getBegin(),
3584 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3585 << (NestedNameSpecifier*) SS.getScopeRep()
3586 << cast<CXXRecordDecl>(CurContext)
3587 << SS.getRange();
3588 return true;
3589 }
3590
3591 return false;
3592 }
3593
3594 // C++03 [namespace.udecl]p4:
3595 // A using-declaration used as a member-declaration shall refer
3596 // to a member of a base class of the class being defined [etc.].
3597
3598 // Salient point: SS doesn't have to name a base class as long as
3599 // lookup only finds members from base classes. Therefore we can
3600 // diagnose here only if we can prove that that can't happen,
3601 // i.e. if the class hierarchies provably don't intersect.
3602
3603 // TODO: it would be nice if "definitely valid" results were cached
3604 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3605 // need to be repeated.
3606
3607 struct UserData {
3608 llvm::DenseSet<const CXXRecordDecl*> Bases;
3609
3610 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3611 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3612 Data->Bases.insert(Base);
3613 return true;
3614 }
3615
3616 bool hasDependentBases(const CXXRecordDecl *Class) {
3617 return !Class->forallBases(collect, this);
3618 }
3619
3620 /// Returns true if the base is dependent or is one of the
3621 /// accumulated base classes.
3622 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3623 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3624 return !Data->Bases.count(Base);
3625 }
3626
3627 bool mightShareBases(const CXXRecordDecl *Class) {
3628 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3629 }
3630 };
3631
3632 UserData Data;
3633
3634 // Returns false if we find a dependent base.
3635 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3636 return false;
3637
3638 // Returns false if the class has a dependent base or if it or one
3639 // of its bases is present in the base set of the current context.
3640 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3641 return false;
3642
3643 Diag(SS.getRange().getBegin(),
3644 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3645 << (NestedNameSpecifier*) SS.getScopeRep()
3646 << cast<CXXRecordDecl>(CurContext)
3647 << SS.getRange();
3648
3649 return true;
3650}
3651
3652Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
3653 SourceLocation NamespaceLoc,
3654 SourceLocation AliasLoc,
3655 IdentifierInfo *Alias,
3656 const CXXScopeSpec &SS,
3657 SourceLocation IdentLoc,
3658 IdentifierInfo *Ident) {
3659
3660 // Lookup the namespace name.
3661 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3662 LookupParsedName(R, S, &SS);
3663
3664 // Check if we have a previous declaration with the same name.
3665 if (NamedDecl *PrevDecl
3666 = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
3667 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
3668 // We already have an alias with the same name that points to the same
3669 // namespace, so don't create a new one.
3670 if (!R.isAmbiguous() && !R.empty() &&
3671 AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
3672 return DeclPtrTy();
3673 }
3674
3675 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3676 diag::err_redefinition_different_kind;
3677 Diag(AliasLoc, DiagID) << Alias;
3678 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3679 return DeclPtrTy();
3680 }
3681
3682 if (R.isAmbiguous())
3683 return DeclPtrTy();
3684
3685 if (R.empty()) {
3686 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
3687 return DeclPtrTy();
3688 }
3689
3690 NamespaceAliasDecl *AliasDecl =
3691 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3692 Alias, SS.getRange(),
3693 (NestedNameSpecifier *)SS.getScopeRep(),
3694 IdentLoc, R.getFoundDecl());
3695
3696 CurContext->addDecl(AliasDecl);
3697 return DeclPtrTy::make(AliasDecl);
3698}
3699
3700void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3701 CXXConstructorDecl *Constructor) {
3702 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3703 !Constructor->isUsed()) &&
3704 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
3705
3706 CXXRecordDecl *ClassDecl
3707 = cast<CXXRecordDecl>(Constructor->getDeclContext());
3708 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
3709
3710 DeclContext *PreviousContext = CurContext;
3711 CurContext = Constructor;
3712 if (SetBaseOrMemberInitializers(Constructor, 0, 0, true, false)) {
3713 Diag(CurrentLocation, diag::note_member_synthesized_at)
3714 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
3715 Constructor->setInvalidDecl();
3716 } else {
3717 Constructor->setUsed();
3718 }
3719 CurContext = PreviousContext;
3720}
3721
3722void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
3723 CXXDestructorDecl *Destructor) {
3724 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3725 "DefineImplicitDestructor - call it for implicit default dtor");
3726 CXXRecordDecl *ClassDecl = Destructor->getParent();
3727 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3728
3729 DeclContext *PreviousContext = CurContext;
3730 CurContext = Destructor;
3731
3732 // C++ [class.dtor] p5
3733 // Before the implicitly-declared default destructor for a class is
3734 // implicitly defined, all the implicitly-declared default destructors
3735 // for its base class and its non-static data members shall have been
3736 // implicitly defined.
3737 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3738 E = ClassDecl->bases_end(); Base != E; ++Base) {
3739 CXXRecordDecl *BaseClassDecl
3740 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3741 if (!BaseClassDecl->hasTrivialDestructor()) {
3742 if (CXXDestructorDecl *BaseDtor =
3743 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3744 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3745 else
3746 assert(false &&
3747 "DefineImplicitDestructor - missing dtor in a base class");
3748 }
3749 }
3750
3751 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3752 E = ClassDecl->field_end(); Field != E; ++Field) {
3753 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3754 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3755 FieldType = Array->getElementType();
3756 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
3757 CXXRecordDecl *FieldClassDecl
3758 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3759 if (!FieldClassDecl->hasTrivialDestructor()) {
3760 if (CXXDestructorDecl *FieldDtor =
3761 const_cast<CXXDestructorDecl*>(
3762 FieldClassDecl->getDestructor(Context)))
3763 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3764 else
3765 assert(false &&
3766 "DefineImplicitDestructor - missing dtor in class of a data member");
3767 }
3768 }
3769 }
3770
3771 // FIXME: If CheckDestructor fails, we should emit a note about where the
3772 // implicit destructor was needed.
3773 if (CheckDestructor(Destructor)) {
3774 Diag(CurrentLocation, diag::note_member_synthesized_at)
3775 << CXXDestructor << Context.getTagDeclType(ClassDecl);
3776
3777 Destructor->setInvalidDecl();
3778 CurContext = PreviousContext;
3779
3780 return;
3781 }
3782 CurContext = PreviousContext;
3783
3784 Destructor->setUsed();
3785}
3786
3787void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3788 CXXMethodDecl *MethodDecl) {
3789 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3790 MethodDecl->getOverloadedOperator() == OO_Equal &&
3791 !MethodDecl->isUsed()) &&
3792 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
3793
3794 CXXRecordDecl *ClassDecl
3795 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
3796
3797 DeclContext *PreviousContext = CurContext;
3798 CurContext = MethodDecl;
3799
3800 // C++[class.copy] p12
3801 // Before the implicitly-declared copy assignment operator for a class is
3802 // implicitly defined, all implicitly-declared copy assignment operators
3803 // for its direct base classes and its nonstatic data members shall have
3804 // been implicitly defined.
3805 bool err = false;
3806 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3807 E = ClassDecl->bases_end(); Base != E; ++Base) {
3808 CXXRecordDecl *BaseClassDecl
3809 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3810 if (CXXMethodDecl *BaseAssignOpMethod =
3811 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3812 BaseClassDecl))
3813 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3814 }
3815 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3816 E = ClassDecl->field_end(); Field != E; ++Field) {
3817 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3818 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3819 FieldType = Array->getElementType();
3820 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
3821 CXXRecordDecl *FieldClassDecl
3822 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3823 if (CXXMethodDecl *FieldAssignOpMethod =
3824 getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3825 FieldClassDecl))
3826 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
3827 } else if (FieldType->isReferenceType()) {
3828 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
3829 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3830 Diag(Field->getLocation(), diag::note_declared_at);
3831 Diag(CurrentLocation, diag::note_first_required_here);
3832 err = true;
3833 } else if (FieldType.isConstQualified()) {
3834 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
3835 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3836 Diag(Field->getLocation(), diag::note_declared_at);
3837 Diag(CurrentLocation, diag::note_first_required_here);
3838 err = true;
3839 }
3840 }
3841 if (!err)
3842 MethodDecl->setUsed();
3843
3844 CurContext = PreviousContext;
3845}
3846
3847CXXMethodDecl *
3848Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3849 ParmVarDecl *ParmDecl,
3850 CXXRecordDecl *ClassDecl) {
3851 QualType LHSType = Context.getTypeDeclType(ClassDecl);
3852 QualType RHSType(LHSType);
3853 // If class's assignment operator argument is const/volatile qualified,
3854 // look for operator = (const/volatile B&). Otherwise, look for
3855 // operator = (B&).
3856 RHSType = Context.getCVRQualifiedType(RHSType,
3857 ParmDecl->getType().getCVRQualifiers());
3858 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
3859 LHSType,
3860 SourceLocation()));
3861 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
3862 RHSType,
3863 CurrentLocation));
3864 Expr *Args[2] = { &*LHS, &*RHS };
3865 OverloadCandidateSet CandidateSet(CurrentLocation);
3866 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
3867 CandidateSet);
3868 OverloadCandidateSet::iterator Best;
3869 if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
3870 return cast<CXXMethodDecl>(Best->Function);
3871 assert(false &&
3872 "getAssignOperatorMethod - copy assignment operator method not found");
3873 return 0;
3874}
3875
3876void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3877 CXXConstructorDecl *CopyConstructor,
3878 unsigned TypeQuals) {
3879 assert((CopyConstructor->isImplicit() &&
3880 CopyConstructor->isCopyConstructor(TypeQuals) &&
3881 !CopyConstructor->isUsed()) &&
3882 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
3883
3884 CXXRecordDecl *ClassDecl
3885 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3886 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
3887
3888 DeclContext *PreviousContext = CurContext;
3889 CurContext = CopyConstructor;
3890
3891 // C++ [class.copy] p209
3892 // Before the implicitly-declared copy constructor for a class is
3893 // implicitly defined, all the implicitly-declared copy constructors
3894 // for its base class and its non-static data members shall have been
3895 // implicitly defined.
3896 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3897 Base != ClassDecl->bases_end(); ++Base) {
3898 CXXRecordDecl *BaseClassDecl
3899 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3900 if (CXXConstructorDecl *BaseCopyCtor =
3901 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
3902 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
3903 }
3904 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3905 FieldEnd = ClassDecl->field_end();
3906 Field != FieldEnd; ++Field) {
3907 QualType FieldType = Context.getCanonicalType((*Field)->getType());
3908 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3909 FieldType = Array->getElementType();
3910 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
3911 CXXRecordDecl *FieldClassDecl
3912 = cast<CXXRecordDecl>(FieldClassType->getDecl());
3913 if (CXXConstructorDecl *FieldCopyCtor =
3914 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
3915 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
3916 }
3917 }
3918 CopyConstructor->setUsed();
3919
3920 CurContext = PreviousContext;
3921}
3922
3923Sema::OwningExprResult
3924Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3925 CXXConstructorDecl *Constructor,
3926 MultiExprArg ExprArgs,
3927 bool RequiresZeroInit,
3928 bool BaseInitialization) {
3929 bool Elidable = false;
3930
3931 // C++ [class.copy]p15:
3932 // Whenever a temporary class object is copied using a copy constructor, and
3933 // this object and the copy have the same cv-unqualified type, an
3934 // implementation is permitted to treat the original and the copy as two
3935 // different ways of referring to the same object and not perform a copy at
3936 // all, even if the class copy constructor or destructor have side effects.
3937
3938 // FIXME: Is this enough?
3939 if (Constructor->isCopyConstructor()) {
3940 Expr *E = ((Expr **)ExprArgs.get())[0];
3941 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3942 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3943 E = ICE->getSubExpr();
3944 if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
3945 E = FCE->getSubExpr();
3946 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3947 E = BE->getSubExpr();
3948 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3949 if (ICE->getCastKind() == CastExpr::CK_NoOp)
3950 E = ICE->getSubExpr();
3951
3952 if (CallExpr *CE = dyn_cast<CallExpr>(E))
3953 Elidable = !CE->getCallReturnType()->isReferenceType();
3954 else if (isa<CXXTemporaryObjectExpr>(E))
3955 Elidable = true;
3956 else if (isa<CXXConstructExpr>(E))
3957 Elidable = true;
3958 }
3959
3960 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
3961 Elidable, move(ExprArgs), RequiresZeroInit,
3962 BaseInitialization);
3963}
3964
3965/// BuildCXXConstructExpr - Creates a complete call to a constructor,
3966/// including handling of its default argument expressions.
3967Sema::OwningExprResult
3968Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3969 CXXConstructorDecl *Constructor, bool Elidable,
3970 MultiExprArg ExprArgs,
3971 bool RequiresZeroInit,
3972 bool BaseInitialization) {
3973 unsigned NumExprs = ExprArgs.size();
3974 Expr **Exprs = (Expr **)ExprArgs.release();
3975
3976 MarkDeclarationReferenced(ConstructLoc, Constructor);
3977 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
3978 Constructor, Elidable, Exprs, NumExprs,
3979 RequiresZeroInit, BaseInitialization));
3980}
3981
3982bool Sema::InitializeVarWithConstructor(VarDecl *VD,
3983 CXXConstructorDecl *Constructor,
3984 MultiExprArg Exprs) {
3985 OwningExprResult TempResult =
3986 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
3987 move(Exprs));
3988 if (TempResult.isInvalid())
3989 return true;
3990
3991 Expr *Temp = TempResult.takeAs<Expr>();
3992 MarkDeclarationReferenced(VD->getLocation(), Constructor);
3993 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
3994 VD->setInit(Context, Temp);
3995
3996 return false;
3997}
3998
3999void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4000 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
4001 if (!ClassDecl->hasTrivialDestructor()) {
4002 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4003 MarkDeclarationReferenced(VD->getLocation(), Destructor);
4004 CheckDestructorAccess(VD->getLocation(), Record);
4005 }
4006}
4007
4008/// AddCXXDirectInitializerToDecl - This action is called immediately after
4009/// ActOnDeclarator, when a C++ direct initializer is present.
4010/// e.g: "int x(1);"
4011void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4012 SourceLocation LParenLoc,
4013 MultiExprArg Exprs,
4014 SourceLocation *CommaLocs,
4015 SourceLocation RParenLoc) {
4016 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
4017 Decl *RealDecl = Dcl.getAs<Decl>();
4018
4019 // If there is no declaration, there was an error parsing it. Just ignore
4020 // the initializer.
4021 if (RealDecl == 0)
4022 return;
4023
4024 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4025 if (!VDecl) {
4026 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4027 RealDecl->setInvalidDecl();
4028 return;
4029 }
4030
4031 // We will represent direct-initialization similarly to copy-initialization:
4032 // int x(1); -as-> int x = 1;
4033 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4034 //
4035 // Clients that want to distinguish between the two forms, can check for
4036 // direct initializer using VarDecl::hasCXXDirectInitializer().
4037 // A major benefit is that clients that don't particularly care about which
4038 // exactly form was it (like the CodeGen) can handle both cases without
4039 // special case code.
4040
4041 // If either the declaration has a dependent type or if any of the expressions
4042 // is type-dependent, we represent the initialization via a ParenListExpr for
4043 // later use during template instantiation.
4044 if (VDecl->getType()->isDependentType() ||
4045 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4046 // Let clients know that initialization was done with a direct initializer.
4047 VDecl->setCXXDirectInitializer(true);
4048
4049 // Store the initialization expressions as a ParenListExpr.
4050 unsigned NumExprs = Exprs.size();
4051 VDecl->setInit(Context,
4052 new (Context) ParenListExpr(Context, LParenLoc,
4053 (Expr **)Exprs.release(),
4054 NumExprs, RParenLoc));
4055 return;
4056 }
4057
4058
4059 // C++ 8.5p11:
4060 // The form of initialization (using parentheses or '=') is generally
4061 // insignificant, but does matter when the entity being initialized has a
4062 // class type.
4063 QualType DeclInitType = VDecl->getType();
4064 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
4065 DeclInitType = Context.getBaseElementType(Array);
4066
4067 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
4068 diag::err_typecheck_decl_incomplete_type)) {
4069 VDecl->setInvalidDecl();
4070 return;
4071 }
4072
4073 // The variable can not have an abstract class type.
4074 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4075 diag::err_abstract_type_in_decl,
4076 AbstractVariableType))
4077 VDecl->setInvalidDecl();
4078
4079 const VarDecl *Def;
4080 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
4081 Diag(VDecl->getLocation(), diag::err_redefinition)
4082 << VDecl->getDeclName();
4083 Diag(Def->getLocation(), diag::note_previous_definition);
4084 VDecl->setInvalidDecl();
4085 return;
4086 }
4087
4088 // Capture the variable that is being initialized and the style of
4089 // initialization.
4090 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4091
4092 // FIXME: Poor source location information.
4093 InitializationKind Kind
4094 = InitializationKind::CreateDirect(VDecl->getLocation(),
4095 LParenLoc, RParenLoc);
4096
4097 InitializationSequence InitSeq(*this, Entity, Kind,
4098 (Expr**)Exprs.get(), Exprs.size());
4099 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4100 if (Result.isInvalid()) {
4101 VDecl->setInvalidDecl();
4102 return;
4103 }
4104
4105 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
4106 VDecl->setInit(Context, Result.takeAs<Expr>());
4107 VDecl->setCXXDirectInitializer(true);
4108
4109 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4110 FinalizeVarWithDestructor(VDecl, Record);
4111}
4112
4113/// \brief Add the applicable constructor candidates for an initialization
4114/// by constructor.
4115static void AddConstructorInitializationCandidates(Sema &SemaRef,
4116 QualType ClassType,
4117 Expr **Args,
4118 unsigned NumArgs,
4119 InitializationKind Kind,
4120 OverloadCandidateSet &CandidateSet) {
4121 // C++ [dcl.init]p14:
4122 // If the initialization is direct-initialization, or if it is
4123 // copy-initialization where the cv-unqualified version of the
4124 // source type is the same class as, or a derived class of, the
4125 // class of the destination, constructors are considered. The
4126 // applicable constructors are enumerated (13.3.1.3), and the
4127 // best one is chosen through overload resolution (13.3). The
4128 // constructor so selected is called to initialize the object,
4129 // with the initializer expression(s) as its argument(s). If no
4130 // constructor applies, or the overload resolution is ambiguous,
4131 // the initialization is ill-formed.
4132 const RecordType *ClassRec = ClassType->getAs<RecordType>();
4133 assert(ClassRec && "Can only initialize a class type here");
4134
4135 // FIXME: When we decide not to synthesize the implicitly-declared
4136 // constructors, we'll need to make them appear here.
4137
4138 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4139 DeclarationName ConstructorName
4140 = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4141 SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4142 DeclContext::lookup_const_iterator Con, ConEnd;
4143 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4144 Con != ConEnd; ++Con) {
4145 // Find the constructor (which may be a template).
4146 CXXConstructorDecl *Constructor = 0;
4147 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4148 if (ConstructorTmpl)
4149 Constructor
4150 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4151 else
4152 Constructor = cast<CXXConstructorDecl>(*Con);
4153
4154 if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4155 (Kind.getKind() == InitializationKind::IK_Value) ||
4156 (Kind.getKind() == InitializationKind::IK_Copy &&
4157 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
4158 ((Kind.getKind() == InitializationKind::IK_Default) &&
4159 Constructor->isDefaultConstructor())) {
4160 if (ConstructorTmpl)
4161 SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
4162 ConstructorTmpl->getAccess(),
4163 /*ExplicitArgs*/ 0,
4164 Args, NumArgs, CandidateSet);
4165 else
4166 SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(),
4167 Args, NumArgs, CandidateSet);
4168 }
4169 }
4170}
4171
4172/// \brief Attempt to perform initialization by constructor
4173/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4174/// copy-initialization.
4175///
4176/// This routine determines whether initialization by constructor is possible,
4177/// but it does not emit any diagnostics in the case where the initialization
4178/// is ill-formed.
4179///
4180/// \param ClassType the type of the object being initialized, which must have
4181/// class type.
4182///
4183/// \param Args the arguments provided to initialize the object
4184///
4185/// \param NumArgs the number of arguments provided to initialize the object
4186///
4187/// \param Kind the type of initialization being performed
4188///
4189/// \returns the constructor used to initialize the object, if successful.
4190/// Otherwise, emits a diagnostic and returns NULL.
4191CXXConstructorDecl *
4192Sema::TryInitializationByConstructor(QualType ClassType,
4193 Expr **Args, unsigned NumArgs,
4194 SourceLocation Loc,
4195 InitializationKind Kind) {
4196 // Build the overload candidate set
4197 OverloadCandidateSet CandidateSet(Loc);
4198 AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4199 CandidateSet);
4200
4201 // Determine whether we found a constructor we can use.
4202 OverloadCandidateSet::iterator Best;
4203 switch (BestViableFunction(CandidateSet, Loc, Best)) {
4204 case OR_Success:
4205 case OR_Deleted:
4206 // We found a constructor. Return it.
4207 return cast<CXXConstructorDecl>(Best->Function);
4208
4209 case OR_No_Viable_Function:
4210 case OR_Ambiguous:
4211 // Overload resolution failed. Return nothing.
4212 return 0;
4213 }
4214
4215 // Silence GCC warning
4216 return 0;
4217}
4218
4219/// \brief Given a constructor and the set of arguments provided for the
4220/// constructor, convert the arguments and add any required default arguments
4221/// to form a proper call to this constructor.
4222///
4223/// \returns true if an error occurred, false otherwise.
4224bool
4225Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4226 MultiExprArg ArgsPtr,
4227 SourceLocation Loc,
4228 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4229 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4230 unsigned NumArgs = ArgsPtr.size();
4231 Expr **Args = (Expr **)ArgsPtr.get();
4232
4233 const FunctionProtoType *Proto
4234 = Constructor->getType()->getAs<FunctionProtoType>();
4235 assert(Proto && "Constructor without a prototype?");
4236 unsigned NumArgsInProto = Proto->getNumArgs();
4237
4238 // If too few arguments are available, we'll fill in the rest with defaults.
4239 if (NumArgs < NumArgsInProto)
4240 ConvertedArgs.reserve(NumArgsInProto);
4241 else
4242 ConvertedArgs.reserve(NumArgs);
4243
4244 VariadicCallType CallType =
4245 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4246 llvm::SmallVector<Expr *, 8> AllArgs;
4247 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4248 Proto, 0, Args, NumArgs, AllArgs,
4249 CallType);
4250 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4251 ConvertedArgs.push_back(AllArgs[i]);
4252 return Invalid;
4253}
4254
4255/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4256/// determine whether they are reference-related,
4257/// reference-compatible, reference-compatible with added
4258/// qualification, or incompatible, for use in C++ initialization by
4259/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4260/// type, and the first type (T1) is the pointee type of the reference
4261/// type being initialized.
4262Sema::ReferenceCompareResult
4263Sema::CompareReferenceRelationship(SourceLocation Loc,
4264 QualType OrigT1, QualType OrigT2,
4265 bool& DerivedToBase) {
4266 assert(!OrigT1->isReferenceType() &&
4267 "T1 must be the pointee type of the reference type");
4268 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4269
4270 QualType T1 = Context.getCanonicalType(OrigT1);
4271 QualType T2 = Context.getCanonicalType(OrigT2);
4272 Qualifiers T1Quals, T2Quals;
4273 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4274 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4275
4276 // C++ [dcl.init.ref]p4:
4277 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4278 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4279 // T1 is a base class of T2.
4280 if (UnqualT1 == UnqualT2)
4281 DerivedToBase = false;
4282 else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4283 !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4284 IsDerivedFrom(UnqualT2, UnqualT1))
4285 DerivedToBase = true;
4286 else
4287 return Ref_Incompatible;
4288
4289 // At this point, we know that T1 and T2 are reference-related (at
4290 // least).
4291
4292 // If the type is an array type, promote the element qualifiers to the type
4293 // for comparison.
4294 if (isa<ArrayType>(T1) && T1Quals)
4295 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4296 if (isa<ArrayType>(T2) && T2Quals)
4297 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4298
4299 // C++ [dcl.init.ref]p4:
4300 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4301 // reference-related to T2 and cv1 is the same cv-qualification
4302 // as, or greater cv-qualification than, cv2. For purposes of
4303 // overload resolution, cases for which cv1 is greater
4304 // cv-qualification than cv2 are identified as
4305 // reference-compatible with added qualification (see 13.3.3.2).
4306 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
4307 return Ref_Compatible;
4308 else if (T1.isMoreQualifiedThan(T2))
4309 return Ref_Compatible_With_Added_Qualification;
4310 else
4311 return Ref_Related;
4312}
4313
4314/// CheckReferenceInit - Check the initialization of a reference
4315/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4316/// the initializer (either a simple initializer or an initializer
4317/// list), and DeclType is the type of the declaration. When ICS is
4318/// non-null, this routine will compute the implicit conversion
4319/// sequence according to C++ [over.ics.ref] and will not produce any
4320/// diagnostics; when ICS is null, it will emit diagnostics when any
4321/// errors are found. Either way, a return value of true indicates
4322/// that there was a failure, a return value of false indicates that
4323/// the reference initialization succeeded.
4324///
4325/// When @p SuppressUserConversions, user-defined conversions are
4326/// suppressed.
4327/// When @p AllowExplicit, we also permit explicit user-defined
4328/// conversion functions.
4329/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
4330/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4331/// This is used when this is called from a C-style cast.
4332bool
4333Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
4334 SourceLocation DeclLoc,
4335 bool SuppressUserConversions,
4336 bool AllowExplicit, bool ForceRValue,
4337 ImplicitConversionSequence *ICS,
4338 bool IgnoreBaseAccess) {
4339 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4340
4341 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4342 QualType T2 = Init->getType();
4343
4344 // If the initializer is the address of an overloaded function, try
4345 // to resolve the overloaded function. If all goes well, T2 is the
4346 // type of the resulting function.
4347 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
4348 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
4349 ICS != 0);
4350 if (Fn) {
4351 // Since we're performing this reference-initialization for
4352 // real, update the initializer with the resulting function.
4353 if (!ICS) {
4354 if (DiagnoseUseOfDecl(Fn, DeclLoc))
4355 return true;
4356
4357 Init = FixOverloadedFunctionReference(Init, Fn);
4358 }
4359
4360 T2 = Fn->getType();
4361 }
4362 }
4363
4364 // Compute some basic properties of the types and the initializer.
4365 bool isRValRef = DeclType->isRValueReferenceType();
4366 bool DerivedToBase = false;
4367 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4368 Init->isLvalue(Context);
4369 ReferenceCompareResult RefRelationship
4370 = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
4371
4372 // Most paths end in a failed conversion.
4373 if (ICS) {
4374 ICS->setBad();
4375 ICS->Bad.init(BadConversionSequence::no_conversion, Init, DeclType);
4376 }
4377
4378 // C++ [dcl.init.ref]p5:
4379 // A reference to type "cv1 T1" is initialized by an expression
4380 // of type "cv2 T2" as follows:
4381
4382 // -- If the initializer expression
4383
4384 // Rvalue references cannot bind to lvalues (N2812).
4385 // There is absolutely no situation where they can. In particular, note that
4386 // this is ill-formed, even if B has a user-defined conversion to A&&:
4387 // B b;
4388 // A&& r = b;
4389 if (isRValRef && InitLvalue == Expr::LV_Valid) {
4390 if (!ICS)
4391 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4392 << Init->getSourceRange();
4393 return true;
4394 }
4395
4396 bool BindsDirectly = false;
4397 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4398 // reference-compatible with "cv2 T2," or
4399 //
4400 // Note that the bit-field check is skipped if we are just computing
4401 // the implicit conversion sequence (C++ [over.best.ics]p2).
4402 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
4403 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4404 BindsDirectly = true;
4405
4406 if (ICS) {
4407 // C++ [over.ics.ref]p1:
4408 // When a parameter of reference type binds directly (8.5.3)
4409 // to an argument expression, the implicit conversion sequence
4410 // is the identity conversion, unless the argument expression
4411 // has a type that is a derived class of the parameter type,
4412 // in which case the implicit conversion sequence is a
4413 // derived-to-base Conversion (13.3.3.1).
4414 ICS->setStandard();
4415 ICS->Standard.First = ICK_Identity;
4416 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4417 ICS->Standard.Third = ICK_Identity;
4418 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4419 ICS->Standard.setToType(0, T2);
4420 ICS->Standard.setToType(1, T1);
4421 ICS->Standard.setToType(2, T1);
4422 ICS->Standard.ReferenceBinding = true;
4423 ICS->Standard.DirectBinding = true;
4424 ICS->Standard.RRefBinding = false;
4425 ICS->Standard.CopyConstructor = 0;
4426
4427 // Nothing more to do: the inaccessibility/ambiguity check for
4428 // derived-to-base conversions is suppressed when we're
4429 // computing the implicit conversion sequence (C++
4430 // [over.best.ics]p2).
4431 return false;
4432 } else {
4433 // Perform the conversion.
4434 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4435 if (DerivedToBase)
4436 CK = CastExpr::CK_DerivedToBase;
4437 else if(CheckExceptionSpecCompatibility(Init, T1))
4438 return true;
4439 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
4440 }
4441 }
4442
4443 // -- has a class type (i.e., T2 is a class type) and can be
4444 // implicitly converted to an lvalue of type "cv3 T3,"
4445 // where "cv1 T1" is reference-compatible with "cv3 T3"
4446 // 92) (this conversion is selected by enumerating the
4447 // applicable conversion functions (13.3.1.6) and choosing
4448 // the best one through overload resolution (13.3)),
4449 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
4450 !RequireCompleteType(DeclLoc, T2, 0)) {
4451 CXXRecordDecl *T2RecordDecl
4452 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4453
4454 OverloadCandidateSet CandidateSet(DeclLoc);
4455 const UnresolvedSetImpl *Conversions
4456 = T2RecordDecl->getVisibleConversionFunctions();
4457 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4458 E = Conversions->end(); I != E; ++I) {
4459 NamedDecl *D = *I;
4460 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4461 if (isa<UsingShadowDecl>(D))
4462 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4463
4464 FunctionTemplateDecl *ConvTemplate
4465 = dyn_cast<FunctionTemplateDecl>(D);
4466 CXXConversionDecl *Conv;
4467 if (ConvTemplate)
4468 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4469 else
4470 Conv = cast<CXXConversionDecl>(D);
4471
4472 // If the conversion function doesn't return a reference type,
4473 // it can't be considered for this conversion.
4474 if (Conv->getConversionType()->isLValueReferenceType() &&
4475 (AllowExplicit || !Conv->isExplicit())) {
4476 if (ConvTemplate)
4477 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC,
4478 Init, DeclType, CandidateSet);
4479 else
4480 AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init,
4481 DeclType, CandidateSet);
4482 }
4483 }
4484
4485 OverloadCandidateSet::iterator Best;
4486 switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
4487 case OR_Success:
4488 // This is a direct binding.
4489 BindsDirectly = true;
4490
4491 if (ICS) {
4492 // C++ [over.ics.ref]p1:
4493 //
4494 // [...] If the parameter binds directly to the result of
4495 // applying a conversion function to the argument
4496 // expression, the implicit conversion sequence is a
4497 // user-defined conversion sequence (13.3.3.1.2), with the
4498 // second standard conversion sequence either an identity
4499 // conversion or, if the conversion function returns an
4500 // entity of a type that is a derived class of the parameter
4501 // type, a derived-to-base Conversion.
4502 ICS->setUserDefined();
4503 ICS->UserDefined.Before = Best->Conversions[0].Standard;
4504 ICS->UserDefined.After = Best->FinalConversion;
4505 ICS->UserDefined.ConversionFunction = Best->Function;
4506 ICS->UserDefined.EllipsisConversion = false;
4507 assert(ICS->UserDefined.After.ReferenceBinding &&
4508 ICS->UserDefined.After.DirectBinding &&
4509 "Expected a direct reference binding!");
4510 return false;
4511 } else {
4512 OwningExprResult InitConversion =
4513 BuildCXXCastArgument(DeclLoc, QualType(),
4514 CastExpr::CK_UserDefinedConversion,
4515 cast<CXXMethodDecl>(Best->Function),
4516 Owned(Init));
4517 Init = InitConversion.takeAs<Expr>();
4518
4519 if (CheckExceptionSpecCompatibility(Init, T1))
4520 return true;
4521 ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4522 /*isLvalue=*/true);
4523 }
4524 break;
4525
4526 case OR_Ambiguous:
4527 if (ICS) {
4528 ICS->setAmbiguous();
4529 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4530 Cand != CandidateSet.end(); ++Cand)
4531 if (Cand->Viable)
4532 ICS->Ambiguous.addConversion(Cand->Function);
4533 break;
4534 }
4535 Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4536 << Init->getSourceRange();
4537 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1);
4538 return true;
4539
4540 case OR_No_Viable_Function:
4541 case OR_Deleted:
4542 // There was no suitable conversion, or we found a deleted
4543 // conversion; continue with other checks.
4544 break;
4545 }
4546 }
4547
4548 if (BindsDirectly) {
4549 // C++ [dcl.init.ref]p4:
4550 // [...] In all cases where the reference-related or
4551 // reference-compatible relationship of two types is used to
4552 // establish the validity of a reference binding, and T1 is a
4553 // base class of T2, a program that necessitates such a binding
4554 // is ill-formed if T1 is an inaccessible (clause 11) or
4555 // ambiguous (10.2) base class of T2.
4556 //
4557 // Note that we only check this condition when we're allowed to
4558 // complain about errors, because we should not be checking for
4559 // ambiguity (or inaccessibility) unless the reference binding
4560 // actually happens.
4561 if (DerivedToBase)
4562 return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
4563 Init->getSourceRange(),
4564 IgnoreBaseAccess);
4565 else
4566 return false;
4567 }
4568
4569 // -- Otherwise, the reference shall be to a non-volatile const
4570 // type (i.e., cv1 shall be const), or the reference shall be an
4571 // rvalue reference and the initializer expression shall be an rvalue.
4572 if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
4573 if (!ICS)
4574 Diag(DeclLoc, diag::err_not_reference_to_const_init)
4575 << T1.isVolatileQualified()
4576 << T1 << int(InitLvalue != Expr::LV_Valid)
4577 << T2 << Init->getSourceRange();
4578 return true;
4579 }
4580
4581 // -- If the initializer expression is an rvalue, with T2 a
4582 // class type, and "cv1 T1" is reference-compatible with
4583 // "cv2 T2," the reference is bound in one of the
4584 // following ways (the choice is implementation-defined):
4585 //
4586 // -- The reference is bound to the object represented by
4587 // the rvalue (see 3.10) or to a sub-object within that
4588 // object.
4589 //
4590 // -- A temporary of type "cv1 T2" [sic] is created, and
4591 // a constructor is called to copy the entire rvalue
4592 // object into the temporary. The reference is bound to
4593 // the temporary or to a sub-object within the
4594 // temporary.
4595 //
4596 // The constructor that would be used to make the copy
4597 // shall be callable whether or not the copy is actually
4598 // done.
4599 //
4600 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
4601 // freedom, so we will always take the first option and never build
4602 // a temporary in this case. FIXME: We will, however, have to check
4603 // for the presence of a copy constructor in C++98/03 mode.
4604 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
4605 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4606 if (ICS) {
4607 ICS->setStandard();
4608 ICS->Standard.First = ICK_Identity;
4609 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4610 ICS->Standard.Third = ICK_Identity;
4611 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4612 ICS->Standard.setToType(0, T2);
4613 ICS->Standard.setToType(1, T1);
4614 ICS->Standard.setToType(2, T1);
4615 ICS->Standard.ReferenceBinding = true;
4616 ICS->Standard.DirectBinding = false;
4617 ICS->Standard.RRefBinding = isRValRef;
4618 ICS->Standard.CopyConstructor = 0;
4619 } else {
4620 CastExpr::CastKind CK = CastExpr::CK_NoOp;
4621 if (DerivedToBase)
4622 CK = CastExpr::CK_DerivedToBase;
4623 else if(CheckExceptionSpecCompatibility(Init, T1))
4624 return true;
4625 ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
4626 }
4627 return false;
4628 }
4629
4630 // -- Otherwise, a temporary of type "cv1 T1" is created and
4631 // initialized from the initializer expression using the
4632 // rules for a non-reference copy initialization (8.5). The
4633 // reference is then bound to the temporary. If T1 is
4634 // reference-related to T2, cv1 must be the same
4635 // cv-qualification as, or greater cv-qualification than,
4636 // cv2; otherwise, the program is ill-formed.
4637 if (RefRelationship == Ref_Related) {
4638 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4639 // we would be reference-compatible or reference-compatible with
4640 // added qualification. But that wasn't the case, so the reference
4641 // initialization fails.
4642 if (!ICS)
4643 Diag(DeclLoc, diag::err_reference_init_drops_quals)
4644 << T1 << int(InitLvalue != Expr::LV_Valid)
4645 << T2 << Init->getSourceRange();
4646 return true;
4647 }
4648
4649 // If at least one of the types is a class type, the types are not
4650 // related, and we aren't allowed any user conversions, the
4651 // reference binding fails. This case is important for breaking
4652 // recursion, since TryImplicitConversion below will attempt to
4653 // create a temporary through the use of a copy constructor.
4654 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4655 (T1->isRecordType() || T2->isRecordType())) {
4656 if (!ICS)
4657 Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
4658 << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
4659 return true;
4660 }
4661
4662 // Actually try to convert the initializer to T1.
4663 if (ICS) {
4664 // C++ [over.ics.ref]p2:
4665 //
4666 // When a parameter of reference type is not bound directly to
4667 // an argument expression, the conversion sequence is the one
4668 // required to convert the argument expression to the
4669 // underlying type of the reference according to
4670 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4671 // to copy-initializing a temporary of the underlying type with
4672 // the argument expression. Any difference in top-level
4673 // cv-qualification is subsumed by the initialization itself
4674 // and does not constitute a conversion.
4675 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4676 /*AllowExplicit=*/false,
4677 /*ForceRValue=*/false,
4678 /*InOverloadResolution=*/false);
4679
4680 // Of course, that's still a reference binding.
4681 if (ICS->isStandard()) {
4682 ICS->Standard.ReferenceBinding = true;
4683 ICS->Standard.RRefBinding = isRValRef;
4684 } else if (ICS->isUserDefined()) {
4685 ICS->UserDefined.After.ReferenceBinding = true;
4686 ICS->UserDefined.After.RRefBinding = isRValRef;
4687 }
4688 return ICS->isBad();
4689 } else {
4690 ImplicitConversionSequence Conversions;
4691 bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
4692 false, false,
4693 Conversions);
4694 if (badConversion) {
4695 if (Conversions.isAmbiguous()) {
4696 Diag(DeclLoc,
4697 diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4698 for (int j = Conversions.Ambiguous.conversions().size()-1;
4699 j >= 0; j--) {
4700 FunctionDecl *Func = Conversions.Ambiguous.conversions()[j];
4701 NoteOverloadCandidate(Func);
4702 }
4703 }
4704 else {
4705 if (isRValRef)
4706 Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4707 << Init->getSourceRange();
4708 else
4709 Diag(DeclLoc, diag::err_invalid_initialization)
4710 << DeclType << Init->getType() << Init->getSourceRange();
4711 }
4712 }
4713 return badConversion;
4714 }
4715}
4716
4717static inline bool
4718CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4719 const FunctionDecl *FnDecl) {
4720 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4721 if (isa<NamespaceDecl>(DC)) {
4722 return SemaRef.Diag(FnDecl->getLocation(),
4723 diag::err_operator_new_delete_declared_in_namespace)
4724 << FnDecl->getDeclName();
4725 }
4726
4727 if (isa<TranslationUnitDecl>(DC) &&
4728 FnDecl->getStorageClass() == FunctionDecl::Static) {
4729 return SemaRef.Diag(FnDecl->getLocation(),
4730 diag::err_operator_new_delete_declared_static)
4731 << FnDecl->getDeclName();
4732 }
4733
4734 return false;
4735}
4736
4737static inline bool
4738CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4739 CanQualType ExpectedResultType,
4740 CanQualType ExpectedFirstParamType,
4741 unsigned DependentParamTypeDiag,
4742 unsigned InvalidParamTypeDiag) {
4743 QualType ResultType =
4744 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4745
4746 // Check that the result type is not dependent.
4747 if (ResultType->isDependentType())
4748 return SemaRef.Diag(FnDecl->getLocation(),
4749 diag::err_operator_new_delete_dependent_result_type)
4750 << FnDecl->getDeclName() << ExpectedResultType;
4751
4752 // Check that the result type is what we expect.
4753 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4754 return SemaRef.Diag(FnDecl->getLocation(),
4755 diag::err_operator_new_delete_invalid_result_type)
4756 << FnDecl->getDeclName() << ExpectedResultType;
4757
4758 // A function template must have at least 2 parameters.
4759 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4760 return SemaRef.Diag(FnDecl->getLocation(),
4761 diag::err_operator_new_delete_template_too_few_parameters)
4762 << FnDecl->getDeclName();
4763
4764 // The function decl must have at least 1 parameter.
4765 if (FnDecl->getNumParams() == 0)
4766 return SemaRef.Diag(FnDecl->getLocation(),
4767 diag::err_operator_new_delete_too_few_parameters)
4768 << FnDecl->getDeclName();
4769
4770 // Check the the first parameter type is not dependent.
4771 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4772 if (FirstParamType->isDependentType())
4773 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4774 << FnDecl->getDeclName() << ExpectedFirstParamType;
4775
4776 // Check that the first parameter type is what we expect.
4777 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
4778 ExpectedFirstParamType)
4779 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4780 << FnDecl->getDeclName() << ExpectedFirstParamType;
4781
4782 return false;
4783}
4784
4785static bool
4786CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4787 // C++ [basic.stc.dynamic.allocation]p1:
4788 // A program is ill-formed if an allocation function is declared in a
4789 // namespace scope other than global scope or declared static in global
4790 // scope.
4791 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4792 return true;
4793
4794 CanQualType SizeTy =
4795 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4796
4797 // C++ [basic.stc.dynamic.allocation]p1:
4798 // The return type shall be void*. The first parameter shall have type
4799 // std::size_t.
4800 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4801 SizeTy,
4802 diag::err_operator_new_dependent_param_type,
4803 diag::err_operator_new_param_type))
4804 return true;
4805
4806 // C++ [basic.stc.dynamic.allocation]p1:
4807 // The first parameter shall not have an associated default argument.
4808 if (FnDecl->getParamDecl(0)->hasDefaultArg())
4809 return SemaRef.Diag(FnDecl->getLocation(),
4810 diag::err_operator_new_default_arg)
4811 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4812
4813 return false;
4814}
4815
4816static bool
4817CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4818 // C++ [basic.stc.dynamic.deallocation]p1:
4819 // A program is ill-formed if deallocation functions are declared in a
4820 // namespace scope other than global scope or declared static in global
4821 // scope.
4822 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4823 return true;
4824
4825 // C++ [basic.stc.dynamic.deallocation]p2:
4826 // Each deallocation function shall return void and its first parameter
4827 // shall be void*.
4828 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4829 SemaRef.Context.VoidPtrTy,
4830 diag::err_operator_delete_dependent_param_type,
4831 diag::err_operator_delete_param_type))
4832 return true;
4833
4834 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4835 if (FirstParamType->isDependentType())
4836 return SemaRef.Diag(FnDecl->getLocation(),
4837 diag::err_operator_delete_dependent_param_type)
4838 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4839
4840 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4841 SemaRef.Context.VoidPtrTy)
4842 return SemaRef.Diag(FnDecl->getLocation(),
4843 diag::err_operator_delete_param_type)
4844 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4845
4846 return false;
4847}
4848
4849/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4850/// of this overloaded operator is well-formed. If so, returns false;
4851/// otherwise, emits appropriate diagnostics and returns true.
4852bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
4853 assert(FnDecl && FnDecl->isOverloadedOperator() &&
4854 "Expected an overloaded operator declaration");
4855
4856 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4857
4858 // C++ [over.oper]p5:
4859 // The allocation and deallocation functions, operator new,
4860 // operator new[], operator delete and operator delete[], are
4861 // described completely in 3.7.3. The attributes and restrictions
4862 // found in the rest of this subclause do not apply to them unless
4863 // explicitly stated in 3.7.3.
4864 if (Op == OO_Delete || Op == OO_Array_Delete)
4865 return CheckOperatorDeleteDeclaration(*this, FnDecl);
4866
4867 if (Op == OO_New || Op == OO_Array_New)
4868 return CheckOperatorNewDeclaration(*this, FnDecl);
4869
4870 // C++ [over.oper]p6:
4871 // An operator function shall either be a non-static member
4872 // function or be a non-member function and have at least one
4873 // parameter whose type is a class, a reference to a class, an
4874 // enumeration, or a reference to an enumeration.
4875 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4876 if (MethodDecl->isStatic())
4877 return Diag(FnDecl->getLocation(),
4878 diag::err_operator_overload_static) << FnDecl->getDeclName();
4879 } else {
4880 bool ClassOrEnumParam = false;
4881 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4882 ParamEnd = FnDecl->param_end();
4883 Param != ParamEnd; ++Param) {
4884 QualType ParamType = (*Param)->getType().getNonReferenceType();
4885 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4886 ParamType->isEnumeralType()) {
4887 ClassOrEnumParam = true;
4888 break;
4889 }
4890 }
4891
4892 if (!ClassOrEnumParam)
4893 return Diag(FnDecl->getLocation(),
4894 diag::err_operator_overload_needs_class_or_enum)
4895 << FnDecl->getDeclName();
4896 }
4897
4898 // C++ [over.oper]p8:
4899 // An operator function cannot have default arguments (8.3.6),
4900 // except where explicitly stated below.
4901 //
4902 // Only the function-call operator allows default arguments
4903 // (C++ [over.call]p1).
4904 if (Op != OO_Call) {
4905 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4906 Param != FnDecl->param_end(); ++Param) {
4907 if ((*Param)->hasDefaultArg())
4908 return Diag((*Param)->getLocation(),
4909 diag::err_operator_overload_default_arg)
4910 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
4911 }
4912 }
4913
4914 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4915 { false, false, false }
4916#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4917 , { Unary, Binary, MemberOnly }
4918#include "clang/Basic/OperatorKinds.def"
4919 };
4920
4921 bool CanBeUnaryOperator = OperatorUses[Op][0];
4922 bool CanBeBinaryOperator = OperatorUses[Op][1];
4923 bool MustBeMemberOperator = OperatorUses[Op][2];
4924
4925 // C++ [over.oper]p8:
4926 // [...] Operator functions cannot have more or fewer parameters
4927 // than the number required for the corresponding operator, as
4928 // described in the rest of this subclause.
4929 unsigned NumParams = FnDecl->getNumParams()
4930 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
4931 if (Op != OO_Call &&
4932 ((NumParams == 1 && !CanBeUnaryOperator) ||
4933 (NumParams == 2 && !CanBeBinaryOperator) ||
4934 (NumParams < 1) || (NumParams > 2))) {
4935 // We have the wrong number of parameters.
4936 unsigned ErrorKind;
4937 if (CanBeUnaryOperator && CanBeBinaryOperator) {
4938 ErrorKind = 2; // 2 -> unary or binary.
4939 } else if (CanBeUnaryOperator) {
4940 ErrorKind = 0; // 0 -> unary
4941 } else {
4942 assert(CanBeBinaryOperator &&
4943 "All non-call overloaded operators are unary or binary!");
4944 ErrorKind = 1; // 1 -> binary
4945 }
4946
4947 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
4948 << FnDecl->getDeclName() << NumParams << ErrorKind;
4949 }
4950
4951 // Overloaded operators other than operator() cannot be variadic.
4952 if (Op != OO_Call &&
4953 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
4954 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
4955 << FnDecl->getDeclName();
4956 }
4957
4958 // Some operators must be non-static member functions.
4959 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4960 return Diag(FnDecl->getLocation(),
4961 diag::err_operator_overload_must_be_member)
4962 << FnDecl->getDeclName();
4963 }
4964
4965 // C++ [over.inc]p1:
4966 // The user-defined function called operator++ implements the
4967 // prefix and postfix ++ operator. If this function is a member
4968 // function with no parameters, or a non-member function with one
4969 // parameter of class or enumeration type, it defines the prefix
4970 // increment operator ++ for objects of that type. If the function
4971 // is a member function with one parameter (which shall be of type
4972 // int) or a non-member function with two parameters (the second
4973 // of which shall be of type int), it defines the postfix
4974 // increment operator ++ for objects of that type.
4975 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4976 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4977 bool ParamIsInt = false;
4978 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
4979 ParamIsInt = BT->getKind() == BuiltinType::Int;
4980
4981 if (!ParamIsInt)
4982 return Diag(LastParam->getLocation(),
4983 diag::err_operator_overload_post_incdec_must_be_int)
4984 << LastParam->getType() << (Op == OO_MinusMinus);
4985 }
4986
4987 // Notify the class if it got an assignment operator.
4988 if (Op == OO_Equal) {
4989 // Would have returned earlier otherwise.
4990 assert(isa<CXXMethodDecl>(FnDecl) &&
4991 "Overloaded = not member, but not filtered.");
4992 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4993 Method->getParent()->addedAssignmentOperator(Context, Method);
4994 }
4995
4996 return false;
4997}
4998
4999/// CheckLiteralOperatorDeclaration - Check whether the declaration
5000/// of this literal operator function is well-formed. If so, returns
5001/// false; otherwise, emits appropriate diagnostics and returns true.
5002bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5003 DeclContext *DC = FnDecl->getDeclContext();
5004 Decl::Kind Kind = DC->getDeclKind();
5005 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5006 Kind != Decl::LinkageSpec) {
5007 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5008 << FnDecl->getDeclName();
5009 return true;
5010 }
5011
5012 bool Valid = false;
5013
5014 // FIXME: Check for the one valid template signature
5015 // template <char...> type operator "" name();
5016
5017 if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
5018 // Check the first parameter
5019 QualType T = (*Param)->getType();
5020
5021 // unsigned long long int and long double are allowed, but only
5022 // alone.
5023 // We also allow any character type; their omission seems to be a bug
5024 // in n3000
5025 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5026 Context.hasSameType(T, Context.LongDoubleTy) ||
5027 Context.hasSameType(T, Context.CharTy) ||
5028 Context.hasSameType(T, Context.WCharTy) ||
5029 Context.hasSameType(T, Context.Char16Ty) ||
5030 Context.hasSameType(T, Context.Char32Ty)) {
5031 if (++Param == FnDecl->param_end())
5032 Valid = true;
5033 goto FinishedParams;
5034 }
5035
5036 // Otherwise it must be a pointer to const; let's strip those.
5037 const PointerType *PT = T->getAs<PointerType>();
5038 if (!PT)
5039 goto FinishedParams;
5040 T = PT->getPointeeType();
5041 if (!T.isConstQualified())
5042 goto FinishedParams;
5043 T = T.getUnqualifiedType();
5044
5045 // Move on to the second parameter;
5046 ++Param;
5047
5048 // If there is no second parameter, the first must be a const char *
5049 if (Param == FnDecl->param_end()) {
5050 if (Context.hasSameType(T, Context.CharTy))
5051 Valid = true;
5052 goto FinishedParams;
5053 }
5054
5055 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5056 // are allowed as the first parameter to a two-parameter function
5057 if (!(Context.hasSameType(T, Context.CharTy) ||
5058 Context.hasSameType(T, Context.WCharTy) ||
5059 Context.hasSameType(T, Context.Char16Ty) ||
5060 Context.hasSameType(T, Context.Char32Ty)))
5061 goto FinishedParams;
5062
5063 // The second and final parameter must be an std::size_t
5064 T = (*Param)->getType().getUnqualifiedType();
5065 if (Context.hasSameType(T, Context.getSizeType()) &&
5066 ++Param == FnDecl->param_end())
5067 Valid = true;
5068 }
5069
5070 // FIXME: This diagnostic is absolutely terrible.
5071FinishedParams:
5072 if (!Valid) {
5073 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5074 << FnDecl->getDeclName();
5075 return true;
5076 }
5077
5078 return false;
5079}
5080
5081/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5082/// linkage specification, including the language and (if present)
5083/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5084/// the location of the language string literal, which is provided
5085/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5086/// the '{' brace. Otherwise, this linkage specification does not
5087/// have any braces.
5088Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5089 SourceLocation ExternLoc,
5090 SourceLocation LangLoc,
5091 const char *Lang,
5092 unsigned StrSize,
5093 SourceLocation LBraceLoc) {
5094 LinkageSpecDecl::LanguageIDs Language;
5095 if (strncmp(Lang, "\"C\"", StrSize) == 0)
5096 Language = LinkageSpecDecl::lang_c;
5097 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
5098 Language = LinkageSpecDecl::lang_cxx;
5099 else {
5100 Diag(LangLoc, diag::err_bad_language);
5101 return DeclPtrTy();
5102 }
5103
5104 // FIXME: Add all the various semantics of linkage specifications
5105
5106 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
5107 LangLoc, Language,
5108 LBraceLoc.isValid());
5109 CurContext->addDecl(D);
5110 PushDeclContext(S, D);
5111 return DeclPtrTy::make(D);
5112}
5113
5114/// ActOnFinishLinkageSpecification - Completely the definition of
5115/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5116/// valid, it's the position of the closing '}' brace in a linkage
5117/// specification that uses braces.
5118Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5119 DeclPtrTy LinkageSpec,
5120 SourceLocation RBraceLoc) {
5121 if (LinkageSpec)
5122 PopDeclContext();
5123 return LinkageSpec;
5124}
5125
5126/// \brief Perform semantic analysis for the variable declaration that
5127/// occurs within a C++ catch clause, returning the newly-created
5128/// variable.
5129VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
5130 TypeSourceInfo *TInfo,
5131 IdentifierInfo *Name,
5132 SourceLocation Loc,
5133 SourceRange Range) {
5134 bool Invalid = false;
5135
5136 // Arrays and functions decay.
5137 if (ExDeclType->isArrayType())
5138 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5139 else if (ExDeclType->isFunctionType())
5140 ExDeclType = Context.getPointerType(ExDeclType);
5141
5142 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5143 // The exception-declaration shall not denote a pointer or reference to an
5144 // incomplete type, other than [cv] void*.
5145 // N2844 forbids rvalue references.
5146 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
5147 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
5148 Invalid = true;
5149 }
5150
5151 QualType BaseType = ExDeclType;
5152 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
5153 unsigned DK = diag::err_catch_incomplete;
5154 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
5155 BaseType = Ptr->getPointeeType();
5156 Mode = 1;
5157 DK = diag::err_catch_incomplete_ptr;
5158 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
5159 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
5160 BaseType = Ref->getPointeeType();
5161 Mode = 2;
5162 DK = diag::err_catch_incomplete_ref;
5163 }
5164 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
5165 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
5166 Invalid = true;
5167
5168 if (!Invalid && !ExDeclType->isDependentType() &&
5169 RequireNonAbstractType(Loc, ExDeclType,
5170 diag::err_abstract_type_in_decl,
5171 AbstractVariableType))
5172 Invalid = true;
5173
5174 // FIXME: Need to test for ability to copy-construct and destroy the
5175 // exception variable.
5176
5177 // FIXME: Need to check for abstract classes.
5178
5179 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
5180 Name, ExDeclType, TInfo, VarDecl::None);
5181
5182 if (Invalid)
5183 ExDecl->setInvalidDecl();
5184
5185 return ExDecl;
5186}
5187
5188/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5189/// handler.
5190Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
5191 TypeSourceInfo *TInfo = 0;
5192 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
5193
5194 bool Invalid = D.isInvalidType();
5195 IdentifierInfo *II = D.getIdentifier();
5196 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
5197 // The scope should be freshly made just for us. There is just no way
5198 // it contains any previous declaration.
5199 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
5200 if (PrevDecl->isTemplateParameter()) {
5201 // Maybe we will complain about the shadowed template parameter.
5202 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5203 }
5204 }
5205
5206 if (D.getCXXScopeSpec().isSet() && !Invalid) {
5207 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5208 << D.getCXXScopeSpec().getRange();
5209 Invalid = true;
5210 }
5211
5212 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
5213 D.getIdentifier(),
5214 D.getIdentifierLoc(),
5215 D.getDeclSpec().getSourceRange());
5216
5217 if (Invalid)
5218 ExDecl->setInvalidDecl();
5219
5220 // Add the exception declaration into this scope.
5221 if (II)
5222 PushOnScopeChains(ExDecl, S);
5223 else
5224 CurContext->addDecl(ExDecl);
5225
5226 ProcessDeclAttributes(S, ExDecl, D);
5227 return DeclPtrTy::make(ExDecl);
5228}
5229
5230Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
5231 ExprArg assertexpr,
5232 ExprArg assertmessageexpr) {
5233 Expr *AssertExpr = (Expr *)assertexpr.get();
5234 StringLiteral *AssertMessage =
5235 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5236
5237 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5238 llvm::APSInt Value(32);
5239 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5240 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5241 AssertExpr->getSourceRange();
5242 return DeclPtrTy();
5243 }
5244
5245 if (Value == 0) {
5246 Diag(AssertLoc, diag::err_static_assert_failed)
5247 << AssertMessage->getString() << AssertExpr->getSourceRange();
5248 }
5249 }
5250
5251 assertexpr.release();
5252 assertmessageexpr.release();
5253 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
5254 AssertExpr, AssertMessage);
5255
5256 CurContext->addDecl(Decl);
5257 return DeclPtrTy::make(Decl);
5258}
5259
5260/// Handle a friend type declaration. This works in tandem with
5261/// ActOnTag.
5262///
5263/// Notes on friend class templates:
5264///
5265/// We generally treat friend class declarations as if they were
5266/// declaring a class. So, for example, the elaborated type specifier
5267/// in a friend declaration is required to obey the restrictions of a
5268/// class-head (i.e. no typedefs in the scope chain), template
5269/// parameters are required to match up with simple template-ids, &c.
5270/// However, unlike when declaring a template specialization, it's
5271/// okay to refer to a template specialization without an empty
5272/// template parameter declaration, e.g.
5273/// friend class A<T>::B<unsigned>;
5274/// We permit this as a special case; if there are any template
5275/// parameters present at all, require proper matching, i.e.
5276/// template <> template <class T> friend class A<int>::B;
5277Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5278 MultiTemplateParamsArg TempParams) {
5279 SourceLocation Loc = DS.getSourceRange().getBegin();
5280
5281 assert(DS.isFriendSpecified());
5282 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5283
5284 // Try to convert the decl specifier to a type. This works for
5285 // friend templates because ActOnTag never produces a ClassTemplateDecl
5286 // for a TUK_Friend.
5287 Declarator TheDeclarator(DS, Declarator::MemberContext);
5288 QualType T = GetTypeForDeclarator(TheDeclarator, S);
5289 if (TheDeclarator.isInvalidType())
5290 return DeclPtrTy();
5291
5292 // This is definitely an error in C++98. It's probably meant to
5293 // be forbidden in C++0x, too, but the specification is just
5294 // poorly written.
5295 //
5296 // The problem is with declarations like the following:
5297 // template <T> friend A<T>::foo;
5298 // where deciding whether a class C is a friend or not now hinges
5299 // on whether there exists an instantiation of A that causes
5300 // 'foo' to equal C. There are restrictions on class-heads
5301 // (which we declare (by fiat) elaborated friend declarations to
5302 // be) that makes this tractable.
5303 //
5304 // FIXME: handle "template <> friend class A<T>;", which
5305 // is possibly well-formed? Who even knows?
5306 if (TempParams.size() && !isa<ElaboratedType>(T)) {
5307 Diag(Loc, diag::err_tagless_friend_type_template)
5308 << DS.getSourceRange();
5309 return DeclPtrTy();
5310 }
5311
5312 // C++ [class.friend]p2:
5313 // An elaborated-type-specifier shall be used in a friend declaration
5314 // for a class.*
5315 // * The class-key of the elaborated-type-specifier is required.
5316 // This is one of the rare places in Clang where it's legitimate to
5317 // ask about the "spelling" of the type.
5318 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5319 // If we evaluated the type to a record type, suggest putting
5320 // a tag in front.
5321 if (const RecordType *RT = T->getAs<RecordType>()) {
5322 RecordDecl *RD = RT->getDecl();
5323
5324 std::string InsertionText = std::string(" ") + RD->getKindName();
5325
5326 Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5327 << (unsigned) RD->getTagKind()
5328 << T
5329 << SourceRange(DS.getFriendSpecLoc())
5330 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5331 InsertionText);
5332 return DeclPtrTy();
5333 }else {
5334 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5335 << DS.getSourceRange();
5336 return DeclPtrTy();
5337 }
5338 }
5339
5340 // Enum types cannot be friends.
5341 if (T->getAs<EnumType>()) {
5342 Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5343 << SourceRange(DS.getFriendSpecLoc());
5344 return DeclPtrTy();
5345 }
5346
5347 // C++98 [class.friend]p1: A friend of a class is a function
5348 // or class that is not a member of the class . . .
5349 // This is fixed in DR77, which just barely didn't make the C++03
5350 // deadline. It's also a very silly restriction that seriously
5351 // affects inner classes and which nobody else seems to implement;
5352 // thus we never diagnose it, not even in -pedantic.
5353
5354 Decl *D;
5355 if (TempParams.size())
5356 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5357 TempParams.size(),
5358 (TemplateParameterList**) TempParams.release(),
5359 T.getTypePtr(),
5360 DS.getFriendSpecLoc());
5361 else
5362 D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5363 DS.getFriendSpecLoc());
5364 D->setAccess(AS_public);
5365 CurContext->addDecl(D);
5366
5367 return DeclPtrTy::make(D);
5368}
5369
5370Sema::DeclPtrTy
5371Sema::ActOnFriendFunctionDecl(Scope *S,
5372 Declarator &D,
5373 bool IsDefinition,
5374 MultiTemplateParamsArg TemplateParams) {
5375 const DeclSpec &DS = D.getDeclSpec();
5376
5377 assert(DS.isFriendSpecified());
5378 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5379
5380 SourceLocation Loc = D.getIdentifierLoc();
5381 TypeSourceInfo *TInfo = 0;
5382 QualType T = GetTypeForDeclarator(D, S, &TInfo);
5383
5384 // C++ [class.friend]p1
5385 // A friend of a class is a function or class....
5386 // Note that this sees through typedefs, which is intended.
5387 // It *doesn't* see through dependent types, which is correct
5388 // according to [temp.arg.type]p3:
5389 // If a declaration acquires a function type through a
5390 // type dependent on a template-parameter and this causes
5391 // a declaration that does not use the syntactic form of a
5392 // function declarator to have a function type, the program
5393 // is ill-formed.
5394 if (!T->isFunctionType()) {
5395 Diag(Loc, diag::err_unexpected_friend);
5396
5397 // It might be worthwhile to try to recover by creating an
5398 // appropriate declaration.
5399 return DeclPtrTy();
5400 }
5401
5402 // C++ [namespace.memdef]p3
5403 // - If a friend declaration in a non-local class first declares a
5404 // class or function, the friend class or function is a member
5405 // of the innermost enclosing namespace.
5406 // - The name of the friend is not found by simple name lookup
5407 // until a matching declaration is provided in that namespace
5408 // scope (either before or after the class declaration granting
5409 // friendship).
5410 // - If a friend function is called, its name may be found by the
5411 // name lookup that considers functions from namespaces and
5412 // classes associated with the types of the function arguments.
5413 // - When looking for a prior declaration of a class or a function
5414 // declared as a friend, scopes outside the innermost enclosing
5415 // namespace scope are not considered.
5416
5417 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5418 DeclarationName Name = GetNameForDeclarator(D);
5419 assert(Name);
5420
5421 // The context we found the declaration in, or in which we should
5422 // create the declaration.
5423 DeclContext *DC;
5424
5425 // FIXME: handle local classes
5426
5427 // Recover from invalid scope qualifiers as if they just weren't there.
5428 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5429 ForRedeclaration);
5430 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
5431 // FIXME: RequireCompleteDeclContext
5432 DC = computeDeclContext(ScopeQual);
5433
5434 // FIXME: handle dependent contexts
5435 if (!DC) return DeclPtrTy();
5436
5437 LookupQualifiedName(Previous, DC);
5438
5439 // If searching in that context implicitly found a declaration in
5440 // a different context, treat it like it wasn't found at all.
5441 // TODO: better diagnostics for this case. Suggesting the right
5442 // qualified scope would be nice...
5443 // FIXME: getRepresentativeDecl() is not right here at all
5444 if (Previous.empty() ||
5445 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
5446 D.setInvalidType();
5447 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5448 return DeclPtrTy();
5449 }
5450
5451 // C++ [class.friend]p1: A friend of a class is a function or
5452 // class that is not a member of the class . . .
5453 if (DC->Equals(CurContext))
5454 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5455
5456 // Otherwise walk out to the nearest namespace scope looking for matches.
5457 } else {
5458 // TODO: handle local class contexts.
5459
5460 DC = CurContext;
5461 while (true) {
5462 // Skip class contexts. If someone can cite chapter and verse
5463 // for this behavior, that would be nice --- it's what GCC and
5464 // EDG do, and it seems like a reasonable intent, but the spec
5465 // really only says that checks for unqualified existing
5466 // declarations should stop at the nearest enclosing namespace,
5467 // not that they should only consider the nearest enclosing
5468 // namespace.
5469 while (DC->isRecord())
5470 DC = DC->getParent();
5471
5472 LookupQualifiedName(Previous, DC);
5473
5474 // TODO: decide what we think about using declarations.
5475 if (!Previous.empty())
5476 break;
5477
5478 if (DC->isFileContext()) break;
5479 DC = DC->getParent();
5480 }
5481
5482 // C++ [class.friend]p1: A friend of a class is a function or
5483 // class that is not a member of the class . . .
5484 // C++0x changes this for both friend types and functions.
5485 // Most C++ 98 compilers do seem to give an error here, so
5486 // we do, too.
5487 if (!Previous.empty() && DC->Equals(CurContext)
5488 && !getLangOptions().CPlusPlus0x)
5489 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5490 }
5491
5492 if (DC->isFileContext()) {
5493 // This implies that it has to be an operator or function.
5494 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5495 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5496 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
5497 Diag(Loc, diag::err_introducing_special_friend) <<
5498 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5499 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
5500 return DeclPtrTy();
5501 }
5502 }
5503
5504 bool Redeclaration = false;
5505 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
5506 move(TemplateParams),
5507 IsDefinition,
5508 Redeclaration);
5509 if (!ND) return DeclPtrTy();
5510
5511 assert(ND->getDeclContext() == DC);
5512 assert(ND->getLexicalDeclContext() == CurContext);
5513
5514 // Add the function declaration to the appropriate lookup tables,
5515 // adjusting the redeclarations list as necessary. We don't
5516 // want to do this yet if the friending class is dependent.
5517 //
5518 // Also update the scope-based lookup if the target context's
5519 // lookup context is in lexical scope.
5520 if (!CurContext->isDependentContext()) {
5521 DC = DC->getLookupContext();
5522 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
5523 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
5524 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
5525 }
5526
5527 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
5528 D.getIdentifierLoc(), ND,
5529 DS.getFriendSpecLoc());
5530 FrD->setAccess(AS_public);
5531 CurContext->addDecl(FrD);
5532
5533 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5534 FrD->setSpecialization(true);
5535
5536 return DeclPtrTy::make(ND);
5537}
5538
5539void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
5540 AdjustDeclIfTemplate(dcl);
5541
5542 Decl *Dcl = dcl.getAs<Decl>();
5543 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5544 if (!Fn) {
5545 Diag(DelLoc, diag::err_deleted_non_function);
5546 return;
5547 }
5548 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5549 Diag(DelLoc, diag::err_deleted_decl_not_first);
5550 Diag(Prev->getLocation(), diag::note_previous_declaration);
5551 // If the declaration wasn't the first, we delete the function anyway for
5552 // recovery.
5553 }
5554 Fn->setDeleted();
5555}
5556
5557static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5558 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5559 ++CI) {
5560 Stmt *SubStmt = *CI;
5561 if (!SubStmt)
5562 continue;
5563 if (isa<ReturnStmt>(SubStmt))
5564 Self.Diag(SubStmt->getSourceRange().getBegin(),
5565 diag::err_return_in_constructor_handler);
5566 if (!isa<Expr>(SubStmt))
5567 SearchForReturnInStmt(Self, SubStmt);
5568 }
5569}
5570
5571void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5572 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5573 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5574 SearchForReturnInStmt(*this, Handler);
5575 }
5576}
5577
5578bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5579 const CXXMethodDecl *Old) {
5580 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5581 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
5582
5583 if (Context.hasSameType(NewTy, OldTy))
5584 return false;
5585
5586 // Check if the return types are covariant
5587 QualType NewClassTy, OldClassTy;
5588
5589 /// Both types must be pointers or references to classes.
5590 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5591 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
5592 NewClassTy = NewPT->getPointeeType();
5593 OldClassTy = OldPT->getPointeeType();
5594 }
5595 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5596 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5597 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5598 NewClassTy = NewRT->getPointeeType();
5599 OldClassTy = OldRT->getPointeeType();
5600 }
5601 }
5602 }
5603
5604 // The return types aren't either both pointers or references to a class type.
5605 if (NewClassTy.isNull()) {
5606 Diag(New->getLocation(),
5607 diag::err_different_return_type_for_overriding_virtual_function)
5608 << New->getDeclName() << NewTy << OldTy;
5609 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5610
5611 return true;
5612 }
5613
5614 // C++ [class.virtual]p6:
5615 // If the return type of D::f differs from the return type of B::f, the
5616 // class type in the return type of D::f shall be complete at the point of
5617 // declaration of D::f or shall be the class type D.
5618 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5619 if (!RT->isBeingDefined() &&
5620 RequireCompleteType(New->getLocation(), NewClassTy,
5621 PDiag(diag::err_covariant_return_incomplete)
5622 << New->getDeclName()))
5623 return true;
5624 }
5625
5626 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
5627 // Check if the new class derives from the old class.
5628 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5629 Diag(New->getLocation(),
5630 diag::err_covariant_return_not_derived)
5631 << New->getDeclName() << NewTy << OldTy;
5632 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5633 return true;
5634 }
5635
5636 // Check if we the conversion from derived to base is valid.
5637 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, ADK_covariance,
5638 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5639 // FIXME: Should this point to the return type?
5640 New->getLocation(), SourceRange(), New->getDeclName())) {
5641 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5642 return true;
5643 }
5644 }
5645
5646 // The qualifiers of the return types must be the same.
5647 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
5648 Diag(New->getLocation(),
5649 diag::err_covariant_return_type_different_qualifications)
5650 << New->getDeclName() << NewTy << OldTy;
5651 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5652 return true;
5653 };
5654
5655
5656 // The new class type must have the same or less qualifiers as the old type.
5657 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5658 Diag(New->getLocation(),
5659 diag::err_covariant_return_type_class_type_more_qualified)
5660 << New->getDeclName() << NewTy << OldTy;
5661 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5662 return true;
5663 };
5664
5665 return false;
5666}
5667
5668bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5669 const CXXMethodDecl *Old)
5670{
5671 if (Old->hasAttr<FinalAttr>()) {
5672 Diag(New->getLocation(), diag::err_final_function_overridden)
5673 << New->getDeclName();
5674 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5675 return true;
5676 }
5677
5678 return false;
5679}
5680
5681/// \brief Mark the given method pure.
5682///
5683/// \param Method the method to be marked pure.
5684///
5685/// \param InitRange the source range that covers the "0" initializer.
5686bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5687 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5688 Method->setPure();
5689
5690 // A class is abstract if at least one function is pure virtual.
5691 Method->getParent()->setAbstract(true);
5692 return false;
5693 }
5694
5695 if (!Method->isInvalidDecl())
5696 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5697 << Method->getDeclName() << InitRange;
5698 return true;
5699}
5700
5701/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5702/// an initializer for the out-of-line declaration 'Dcl'. The scope
5703/// is a fresh scope pushed for just this purpose.
5704///
5705/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5706/// static data member of class X, names should be looked up in the scope of
5707/// class X.
5708void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
5709 // If there is no declaration, there was an error parsing it.
5710 Decl *D = Dcl.getAs<Decl>();
5711 if (D == 0) return;
5712
5713 // We should only get called for declarations with scope specifiers, like:
5714 // int foo::bar;
5715 assert(D->isOutOfLine());
5716 EnterDeclaratorContext(S, D->getDeclContext());
5717}
5718
5719/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5720/// initializer for the out-of-line declaration 'Dcl'.
5721void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
5722 // If there is no declaration, there was an error parsing it.
5723 Decl *D = Dcl.getAs<Decl>();
5724 if (D == 0) return;
5725
5726 assert(D->isOutOfLine());
5727 ExitDeclaratorContext(S);
5728}
5729
5730/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5731/// C++ if/switch/while/for statement.
5732/// e.g: "if (int x = f()) {...}"
5733Action::DeclResult
5734Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5735 // C++ 6.4p2:
5736 // The declarator shall not specify a function or an array.
5737 // The type-specifier-seq shall not contain typedef and shall not declare a
5738 // new class or enumeration.
5739 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5740 "Parser allowed 'typedef' as storage class of condition decl.");
5741
5742 TypeSourceInfo *TInfo = 0;
5743 TagDecl *OwnedTag = 0;
5744 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
5745
5746 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5747 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5748 // would be created and CXXConditionDeclExpr wants a VarDecl.
5749 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5750 << D.getSourceRange();
5751 return DeclResult();
5752 } else if (OwnedTag && OwnedTag->isDefinition()) {
5753 // The type-specifier-seq shall not declare a new class or enumeration.
5754 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5755 }
5756
5757 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5758 if (!Dcl)
5759 return DeclResult();
5760
5761 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5762 VD->setDeclaredInCondition(true);
5763 return Dcl;
5764}
5765
5766void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5767 CXXMethodDecl *MD) {
5768 // Ignore dependent types.
5769 if (MD->isDependentContext())
5770 return;
5771
5772 CXXRecordDecl *RD = MD->getParent();
5773
5774 // Ignore classes without a vtable.
5775 if (!RD->isDynamicClass())
5776 return;
5777
5778 // Ignore declarations that are not definitions.
5779 if (!MD->isThisDeclarationADefinition())
5780 return;
5781
5782 if (isa<CXXConstructorDecl>(MD)) {
5783 switch (MD->getParent()->getTemplateSpecializationKind()) {
5784 case TSK_Undeclared:
5785 case TSK_ExplicitSpecialization:
5786 // Classes that aren't instantiations of templates don't need their
5787 // virtual methods marked until we see the definition of the key
5788 // function.
5789 return;
5790
5791 case TSK_ImplicitInstantiation:
5792 case TSK_ExplicitInstantiationDeclaration:
5793 case TSK_ExplicitInstantiationDefinition:
5794 // This is a constructor of a class template; mark all of the virtual
5795 // members as referenced to ensure that they get instantiatied.
5796 break;
5797 }
5798 } else if (!MD->isOutOfLine()) {
5799 // Consider only out-of-line definitions of member functions. When we see
5800 // an inline definition, it's too early to compute the key function.
5801 return;
5802 } else if (const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD)) {
5803 // If this is not the key function, we don't need to mark virtual members.
5804 if (KeyFunction->getCanonicalDecl() != MD->getCanonicalDecl())
5805 return;
5806 } else {
5807 // The class has no key function, so we've already noted that we need to
5808 // mark the virtual members of this class.
5809 return;
5810 }
5811
5812 // We will need to mark all of the virtual members as referenced to build the
5813 // vtable.
5814 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
5815}
5816
5817bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5818 if (ClassesWithUnmarkedVirtualMembers.empty())
5819 return false;
5820
5821 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5822 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5823 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5824 ClassesWithUnmarkedVirtualMembers.pop_back();
5825 MarkVirtualMembersReferenced(Loc, RD);
5826 }
5827
5828 return true;
5829}
5830
5831void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5832 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5833 e = RD->method_end(); i != e; ++i) {
5834 CXXMethodDecl *MD = *i;
5835
5836 // C++ [basic.def.odr]p2:
5837 // [...] A virtual member function is used if it is not pure. [...]
5838 if (MD->isVirtual() && !MD->isPure())
5839 MarkDeclarationReferenced(Loc, MD);
5840 }
5841}
5842