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