SemaDeclCXX.cpp revision 10bd36882406cdf4805e35add1ce2f11ab9ae152
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        D.getMutableDeclSpec().ClearStorageClassSpecs();
451      } else {
452        QualType T = GetTypeForDeclarator(D, S);
453        diag::kind err = static_cast<diag::kind>(0);
454        if (T->isReferenceType())
455          err = diag::err_mutable_reference;
456        else if (T.isConstQualified())
457          err = diag::err_mutable_const;
458        if (err != 0) {
459          if (DS.getStorageClassSpecLoc().isValid())
460            Diag(DS.getStorageClassSpecLoc(), err);
461          else
462            Diag(DS.getThreadSpecLoc(), err);
463          D.getMutableDeclSpec().ClearStorageClassSpecs();
464        }
465      }
466      break;
467    default:
468      if (DS.getStorageClassSpecLoc().isValid())
469        Diag(DS.getStorageClassSpecLoc(),
470             diag::err_storageclass_invalid_for_member);
471      else
472        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
473      D.getMutableDeclSpec().ClearStorageClassSpecs();
474  }
475
476  if (!isFunc &&
477      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
478      D.getNumTypeObjects() == 0) {
479    // Check also for this case:
480    //
481    // typedef int f();
482    // f a;
483    //
484    Decl *TD = static_cast<Decl *>(DS.getTypeRep());
485    isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
486  }
487
488  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
489                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
490                      !isFunc);
491
492  Decl *Member;
493  bool InvalidDecl = false;
494
495  if (isInstField)
496    Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
497  else
498    Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
499
500  if (!Member) return LastInGroup;
501
502  assert((Name || isInstField) && "No identifier for non-field ?");
503
504  // set/getAccess is not part of Decl's interface to avoid bloating it with C++
505  // specific methods. Use a wrapper class that can be used with all C++ class
506  // member decls.
507  CXXClassMemberWrapper(Member).setAccess(AS);
508
509  // C++ [dcl.init.aggr]p1:
510  //   An aggregate is an array or a class (clause 9) with [...] no
511  //   private or protected non-static data members (clause 11).
512  if (isInstField && (AS == AS_private || AS == AS_protected))
513    cast<CXXRecordDecl>(CurContext)->setAggregate(false);
514
515  if (DS.isVirtualSpecified()) {
516    if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
517      Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
518      InvalidDecl = true;
519    } else {
520      CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
521      CurClass->setAggregate(false);
522      CurClass->setPolymorphic(true);
523    }
524  }
525
526  if (BitWidth) {
527    // C++ 9.6p2: Only when declaring an unnamed bit-field may the
528    // constant-expression be a value equal to zero.
529    // FIXME: Check this.
530
531    if (D.isFunctionDeclarator()) {
532      // FIXME: Emit diagnostic about only constructors taking base initializers
533      // or something similar, when constructor support is in place.
534      Diag(Loc, diag::err_not_bitfield_type,
535           Name.getAsString(), BitWidth->getSourceRange());
536      InvalidDecl = true;
537
538    } else if (isInstField) {
539      // C++ 9.6p3: A bit-field shall have integral or enumeration type.
540      if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
541        Diag(Loc, diag::err_not_integral_type_bitfield,
542             Name.getAsString(), BitWidth->getSourceRange());
543        InvalidDecl = true;
544      }
545
546    } else if (isa<FunctionDecl>(Member)) {
547      // A function typedef ("typedef int f(); f a;").
548      // C++ 9.6p3: A bit-field shall have integral or enumeration type.
549      Diag(Loc, diag::err_not_integral_type_bitfield,
550           Name.getAsString(), BitWidth->getSourceRange());
551      InvalidDecl = true;
552
553    } else if (isa<TypedefDecl>(Member)) {
554      // "cannot declare 'A' to be a bit-field type"
555      Diag(Loc, diag::err_not_bitfield_type, Name.getAsString(),
556           BitWidth->getSourceRange());
557      InvalidDecl = true;
558
559    } else {
560      assert(isa<CXXClassVarDecl>(Member) &&
561             "Didn't we cover all member kinds?");
562      // C++ 9.6p3: A bit-field shall not be a static member.
563      // "static member 'A' cannot be a bit-field"
564      Diag(Loc, diag::err_static_not_bitfield, Name.getAsString(),
565           BitWidth->getSourceRange());
566      InvalidDecl = true;
567    }
568  }
569
570  if (Init) {
571    // C++ 9.2p4: A member-declarator can contain a constant-initializer only
572    // if it declares a static member of const integral or const enumeration
573    // type.
574    if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
575      // ...static member of...
576      CVD->setInit(Init);
577      // ...const integral or const enumeration type.
578      if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
579          CVD->getType()->isIntegralType()) {
580        // constant-initializer
581        if (CheckForConstantInitializer(Init, CVD->getType()))
582          InvalidDecl = true;
583
584      } else {
585        // not const integral.
586        Diag(Loc, diag::err_member_initialization,
587             Name.getAsString(), Init->getSourceRange());
588        InvalidDecl = true;
589      }
590
591    } else {
592      // not static member.
593      Diag(Loc, diag::err_member_initialization,
594           Name.getAsString(), Init->getSourceRange());
595      InvalidDecl = true;
596    }
597  }
598
599  if (InvalidDecl)
600    Member->setInvalidDecl();
601
602  if (isInstField) {
603    FieldCollector->Add(cast<CXXFieldDecl>(Member));
604    return LastInGroup;
605  }
606  return Member;
607}
608
609/// ActOnMemInitializer - Handle a C++ member initializer.
610Sema::MemInitResult
611Sema::ActOnMemInitializer(DeclTy *ConstructorD,
612                          Scope *S,
613                          IdentifierInfo *MemberOrBase,
614                          SourceLocation IdLoc,
615                          SourceLocation LParenLoc,
616                          ExprTy **Args, unsigned NumArgs,
617                          SourceLocation *CommaLocs,
618                          SourceLocation RParenLoc) {
619  CXXConstructorDecl *Constructor
620    = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
621  if (!Constructor) {
622    // The user wrote a constructor initializer on a function that is
623    // not a C++ constructor. Ignore the error for now, because we may
624    // have more member initializers coming; we'll diagnose it just
625    // once in ActOnMemInitializers.
626    return true;
627  }
628
629  CXXRecordDecl *ClassDecl = Constructor->getParent();
630
631  // C++ [class.base.init]p2:
632  //   Names in a mem-initializer-id are looked up in the scope of the
633  //   constructor’s class and, if not found in that scope, are looked
634  //   up in the scope containing the constructor’s
635  //   definition. [Note: if the constructor’s class contains a member
636  //   with the same name as a direct or virtual base class of the
637  //   class, a mem-initializer-id naming the member or base class and
638  //   composed of a single identifier refers to the class member. A
639  //   mem-initializer-id for the hidden base class may be specified
640  //   using a qualified name. ]
641  // Look for a member, first.
642  CXXFieldDecl *Member = ClassDecl->getMember(MemberOrBase);
643
644  // FIXME: Handle members of an anonymous union.
645
646  if (Member) {
647    // FIXME: Perform direct initialization of the member.
648    return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
649  }
650
651  // It didn't name a member, so see if it names a class.
652  TypeTy *BaseTy = isTypeName(*MemberOrBase, S, 0/*SS*/);
653  if (!BaseTy)
654    return Diag(IdLoc, diag::err_mem_init_not_member_or_class,
655                MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
656
657  QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
658  if (!BaseType->isRecordType())
659    return Diag(IdLoc, diag::err_base_init_does_not_name_class,
660                BaseType.getAsString(), SourceRange(IdLoc, RParenLoc));
661
662  // C++ [class.base.init]p2:
663  //   [...] Unless the mem-initializer-id names a nonstatic data
664  //   member of the constructor’s class or a direct or virtual base
665  //   of that class, the mem-initializer is ill-formed. A
666  //   mem-initializer-list can initialize a base class using any
667  //   name that denotes that base class type.
668
669  // First, check for a direct base class.
670  const CXXBaseSpecifier *DirectBaseSpec = 0;
671  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
672       Base != ClassDecl->bases_end(); ++Base) {
673    if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
674        Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
675      // We found a direct base of this type. That's what we're
676      // initializing.
677      DirectBaseSpec = &*Base;
678      break;
679    }
680  }
681
682  // Check for a virtual base class.
683  // FIXME: We might be able to short-circuit this if we know in
684  // advance that there are no virtual bases.
685  const CXXBaseSpecifier *VirtualBaseSpec = 0;
686  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
687    // We haven't found a base yet; search the class hierarchy for a
688    // virtual base class.
689    BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
690                    /*DetectVirtual=*/false);
691    if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
692      for (BasePaths::paths_iterator Path = Paths.begin();
693           Path != Paths.end(); ++Path) {
694        if (Path->back().Base->isVirtual()) {
695          VirtualBaseSpec = Path->back().Base;
696          break;
697        }
698      }
699    }
700  }
701
702  // C++ [base.class.init]p2:
703  //   If a mem-initializer-id is ambiguous because it designates both
704  //   a direct non-virtual base class and an inherited virtual base
705  //   class, the mem-initializer is ill-formed.
706  if (DirectBaseSpec && VirtualBaseSpec)
707    return Diag(IdLoc, diag::err_base_init_direct_and_virtual,
708                MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
709
710  return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
711}
712
713
714void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
715                                             DeclTy *TagDecl,
716                                             SourceLocation LBrac,
717                                             SourceLocation RBrac) {
718  ActOnFields(S, RLoc, TagDecl,
719              (DeclTy**)FieldCollector->getCurFields(),
720              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
721}
722
723/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
724/// special functions, such as the default constructor, copy
725/// constructor, or destructor, to the given C++ class (C++
726/// [special]p1).  This routine can only be executed just before the
727/// definition of the class is complete.
728void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
729  QualType ClassType = Context.getTypeDeclType(ClassDecl);
730  ClassType = Context.getCanonicalType(ClassType);
731
732  if (!ClassDecl->hasUserDeclaredConstructor()) {
733    // C++ [class.ctor]p5:
734    //   A default constructor for a class X is a constructor of class X
735    //   that can be called without an argument. If there is no
736    //   user-declared constructor for class X, a default constructor is
737    //   implicitly declared. An implicitly-declared default constructor
738    //   is an inline public member of its class.
739    DeclarationName Name
740      = Context.DeclarationNames.getCXXConstructorName(ClassType);
741    CXXConstructorDecl *DefaultCon =
742      CXXConstructorDecl::Create(Context, ClassDecl,
743                                 ClassDecl->getLocation(), Name,
744                                 Context.getFunctionType(Context.VoidTy,
745                                                         0, 0, false, 0),
746                                 /*isExplicit=*/false,
747                                 /*isInline=*/true,
748                                 /*isImplicitlyDeclared=*/true);
749    DefaultCon->setAccess(AS_public);
750    ClassDecl->addConstructor(Context, DefaultCon);
751  }
752
753  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
754    // C++ [class.copy]p4:
755    //   If the class definition does not explicitly declare a copy
756    //   constructor, one is declared implicitly.
757
758    // C++ [class.copy]p5:
759    //   The implicitly-declared copy constructor for a class X will
760    //   have the form
761    //
762    //       X::X(const X&)
763    //
764    //   if
765    bool HasConstCopyConstructor = true;
766
767    //     -- each direct or virtual base class B of X has a copy
768    //        constructor whose first parameter is of type const B& or
769    //        const volatile B&, and
770    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
771         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
772      const CXXRecordDecl *BaseClassDecl
773        = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
774      HasConstCopyConstructor
775        = BaseClassDecl->hasConstCopyConstructor(Context);
776    }
777
778    //     -- for all the nonstatic data members of X that are of a
779    //        class type M (or array thereof), each such class type
780    //        has a copy constructor whose first parameter is of type
781    //        const M& or const volatile M&.
782    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
783         HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
784      QualType FieldType = (*Field)->getType();
785      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
786        FieldType = Array->getElementType();
787      if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
788        const CXXRecordDecl *FieldClassDecl
789          = cast<CXXRecordDecl>(FieldClassType->getDecl());
790        HasConstCopyConstructor
791          = FieldClassDecl->hasConstCopyConstructor(Context);
792      }
793    }
794
795    //  Otherwise, the implicitly declared copy constructor will have
796    //  the form
797    //
798    //       X::X(X&)
799    QualType ArgType = Context.getTypeDeclType(ClassDecl);
800    if (HasConstCopyConstructor)
801      ArgType = ArgType.withConst();
802    ArgType = Context.getReferenceType(ArgType);
803
804    //  An implicitly-declared copy constructor is an inline public
805    //  member of its class.
806    DeclarationName Name
807      = Context.DeclarationNames.getCXXConstructorName(ClassType);
808    CXXConstructorDecl *CopyConstructor
809      = CXXConstructorDecl::Create(Context, ClassDecl,
810                                   ClassDecl->getLocation(), Name,
811                                   Context.getFunctionType(Context.VoidTy,
812                                                           &ArgType, 1,
813                                                           false, 0),
814                                   /*isExplicit=*/false,
815                                   /*isInline=*/true,
816                                   /*isImplicitlyDeclared=*/true);
817    CopyConstructor->setAccess(AS_public);
818
819    // Add the parameter to the constructor.
820    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
821                                                 ClassDecl->getLocation(),
822                                                 /*IdentifierInfo=*/0,
823                                                 ArgType, VarDecl::None, 0, 0);
824    CopyConstructor->setParams(&FromParam, 1);
825
826    ClassDecl->addConstructor(Context, CopyConstructor);
827  }
828
829  if (!ClassDecl->getDestructor()) {
830    // C++ [class.dtor]p2:
831    //   If a class has no user-declared destructor, a destructor is
832    //   declared implicitly. An implicitly-declared destructor is an
833    //   inline public member of its class.
834    DeclarationName Name
835      = Context.DeclarationNames.getCXXDestructorName(ClassType);
836    CXXDestructorDecl *Destructor
837      = CXXDestructorDecl::Create(Context, ClassDecl,
838                                  ClassDecl->getLocation(), Name,
839                                  Context.getFunctionType(Context.VoidTy,
840                                                          0, 0, false, 0),
841                                  /*isInline=*/true,
842                                  /*isImplicitlyDeclared=*/true);
843    Destructor->setAccess(AS_public);
844    ClassDecl->setDestructor(Destructor);
845  }
846
847  // FIXME: Implicit copy assignment operator
848}
849
850void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
851  CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
852  FieldCollector->FinishClass();
853  AddImplicitlyDeclaredMembersToClass(Rec);
854  PopDeclContext();
855
856  // Everything, including inline method definitions, have been parsed.
857  // Let the consumer know of the new TagDecl definition.
858  Consumer.HandleTagDeclDefinition(Rec);
859}
860
861/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
862/// the well-formednes of the constructor declarator @p D with type @p
863/// R. If there are any errors in the declarator, this routine will
864/// emit diagnostics and return true. Otherwise, it will return
865/// false. Either way, the type @p R will be updated to reflect a
866/// well-formed type for the constructor.
867bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
868                                      FunctionDecl::StorageClass& SC) {
869  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
870  bool isInvalid = false;
871
872  // C++ [class.ctor]p3:
873  //   A constructor shall not be virtual (10.3) or static (9.4). A
874  //   constructor can be invoked for a const, volatile or const
875  //   volatile object. A constructor shall not be declared const,
876  //   volatile, or const volatile (9.3.2).
877  if (isVirtual) {
878    Diag(D.getIdentifierLoc(),
879         diag::err_constructor_cannot_be,
880         "virtual",
881         SourceRange(D.getDeclSpec().getVirtualSpecLoc()),
882         SourceRange(D.getIdentifierLoc()));
883    isInvalid = true;
884  }
885  if (SC == FunctionDecl::Static) {
886    Diag(D.getIdentifierLoc(),
887         diag::err_constructor_cannot_be,
888         "static",
889         SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
890         SourceRange(D.getIdentifierLoc()));
891    isInvalid = true;
892    SC = FunctionDecl::None;
893  }
894  if (D.getDeclSpec().hasTypeSpecifier()) {
895    // Constructors don't have return types, but the parser will
896    // happily parse something like:
897    //
898    //   class X {
899    //     float X(float);
900    //   };
901    //
902    // The return type will be eliminated later.
903    Diag(D.getIdentifierLoc(),
904         diag::err_constructor_return_type,
905         SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
906         SourceRange(D.getIdentifierLoc()));
907  }
908  if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
909    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
910    if (FTI.TypeQuals & QualType::Const)
911      Diag(D.getIdentifierLoc(),
912           diag::err_invalid_qualified_constructor,
913           "const",
914           SourceRange(D.getIdentifierLoc()));
915    if (FTI.TypeQuals & QualType::Volatile)
916      Diag(D.getIdentifierLoc(),
917           diag::err_invalid_qualified_constructor,
918           "volatile",
919           SourceRange(D.getIdentifierLoc()));
920    if (FTI.TypeQuals & QualType::Restrict)
921      Diag(D.getIdentifierLoc(),
922           diag::err_invalid_qualified_constructor,
923           "restrict",
924           SourceRange(D.getIdentifierLoc()));
925  }
926
927  // Rebuild the function type "R" without any type qualifiers (in
928  // case any of the errors above fired) and with "void" as the
929  // return type, since constructors don't have return types. We
930  // *always* have to do this, because GetTypeForDeclarator will
931  // put in a result type of "int" when none was specified.
932  const FunctionTypeProto *Proto = R->getAsFunctionTypeProto();
933  R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
934                              Proto->getNumArgs(),
935                              Proto->isVariadic(),
936                              0);
937
938  return isInvalid;
939}
940
941/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
942/// the well-formednes of the destructor declarator @p D with type @p
943/// R. If there are any errors in the declarator, this routine will
944/// emit diagnostics and return true. Otherwise, it will return
945/// false. Either way, the type @p R will be updated to reflect a
946/// well-formed type for the destructor.
947bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
948                                     FunctionDecl::StorageClass& SC) {
949  bool isInvalid = false;
950
951  // C++ [class.dtor]p1:
952  //   [...] A typedef-name that names a class is a class-name
953  //   (7.1.3); however, a typedef-name that names a class shall not
954  //   be used as the identifier in the declarator for a destructor
955  //   declaration.
956  TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType();
957  if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) {
958    Diag(D.getIdentifierLoc(),
959         diag::err_destructor_typedef_name,
960         TypedefD->getName());
961    isInvalid = true;
962  }
963
964  // C++ [class.dtor]p2:
965  //   A destructor is used to destroy objects of its class type. A
966  //   destructor takes no parameters, and no return type can be
967  //   specified for it (not even void). The address of a destructor
968  //   shall not be taken. A destructor shall not be static. A
969  //   destructor can be invoked for a const, volatile or const
970  //   volatile object. A destructor shall not be declared const,
971  //   volatile or const volatile (9.3.2).
972  if (SC == FunctionDecl::Static) {
973    Diag(D.getIdentifierLoc(),
974         diag::err_destructor_cannot_be,
975         "static",
976         SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
977         SourceRange(D.getIdentifierLoc()));
978    isInvalid = true;
979    SC = FunctionDecl::None;
980  }
981  if (D.getDeclSpec().hasTypeSpecifier()) {
982    // Destructors don't have return types, but the parser will
983    // happily parse something like:
984    //
985    //   class X {
986    //     float ~X();
987    //   };
988    //
989    // The return type will be eliminated later.
990    Diag(D.getIdentifierLoc(),
991         diag::err_destructor_return_type,
992         SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
993         SourceRange(D.getIdentifierLoc()));
994  }
995  if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
996    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
997    if (FTI.TypeQuals & QualType::Const)
998      Diag(D.getIdentifierLoc(),
999           diag::err_invalid_qualified_destructor,
1000           "const",
1001           SourceRange(D.getIdentifierLoc()));
1002    if (FTI.TypeQuals & QualType::Volatile)
1003      Diag(D.getIdentifierLoc(),
1004           diag::err_invalid_qualified_destructor,
1005           "volatile",
1006           SourceRange(D.getIdentifierLoc()));
1007    if (FTI.TypeQuals & QualType::Restrict)
1008      Diag(D.getIdentifierLoc(),
1009           diag::err_invalid_qualified_destructor,
1010           "restrict",
1011           SourceRange(D.getIdentifierLoc()));
1012  }
1013
1014  // Make sure we don't have any parameters.
1015  if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1016    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1017
1018    // Delete the parameters.
1019    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1020    if (FTI.NumArgs) {
1021      delete [] FTI.ArgInfo;
1022      FTI.NumArgs = 0;
1023      FTI.ArgInfo = 0;
1024    }
1025  }
1026
1027  // Make sure the destructor isn't variadic.
1028  if (R->getAsFunctionTypeProto()->isVariadic())
1029    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1030
1031  // Rebuild the function type "R" without any type qualifiers or
1032  // parameters (in case any of the errors above fired) and with
1033  // "void" as the return type, since destructors don't have return
1034  // types. We *always* have to do this, because GetTypeForDeclarator
1035  // will put in a result type of "int" when none was specified.
1036  R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1037
1038  return isInvalid;
1039}
1040
1041/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1042/// well-formednes of the conversion function declarator @p D with
1043/// type @p R. If there are any errors in the declarator, this routine
1044/// will emit diagnostics and return true. Otherwise, it will return
1045/// false. Either way, the type @p R will be updated to reflect a
1046/// well-formed type for the conversion operator.
1047bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1048                                     FunctionDecl::StorageClass& SC) {
1049  bool isInvalid = false;
1050
1051  // C++ [class.conv.fct]p1:
1052  //   Neither parameter types nor return type can be specified. The
1053  //   type of a conversion function (8.3.5) is “function taking no
1054  //   parameter returning conversion-type-id.”
1055  if (SC == FunctionDecl::Static) {
1056    Diag(D.getIdentifierLoc(),
1057         diag::err_conv_function_not_member,
1058         "static",
1059         SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
1060         SourceRange(D.getIdentifierLoc()));
1061    isInvalid = true;
1062    SC = FunctionDecl::None;
1063  }
1064  if (D.getDeclSpec().hasTypeSpecifier()) {
1065    // Conversion functions don't have return types, but the parser will
1066    // happily parse something like:
1067    //
1068    //   class X {
1069    //     float operator bool();
1070    //   };
1071    //
1072    // The return type will be changed later anyway.
1073    Diag(D.getIdentifierLoc(),
1074         diag::err_conv_function_return_type,
1075         SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
1076         SourceRange(D.getIdentifierLoc()));
1077  }
1078
1079  // Make sure we don't have any parameters.
1080  if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1081    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1082
1083    // Delete the parameters.
1084    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1085    if (FTI.NumArgs) {
1086      delete [] FTI.ArgInfo;
1087      FTI.NumArgs = 0;
1088      FTI.ArgInfo = 0;
1089    }
1090  }
1091
1092  // Make sure the conversion function isn't variadic.
1093  if (R->getAsFunctionTypeProto()->isVariadic())
1094    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1095
1096  // C++ [class.conv.fct]p4:
1097  //   The conversion-type-id shall not represent a function type nor
1098  //   an array type.
1099  QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1100  if (ConvType->isArrayType()) {
1101    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1102    ConvType = Context.getPointerType(ConvType);
1103  } else if (ConvType->isFunctionType()) {
1104    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1105    ConvType = Context.getPointerType(ConvType);
1106  }
1107
1108  // Rebuild the function type "R" without any parameters (in case any
1109  // of the errors above fired) and with the conversion type as the
1110  // return type.
1111  R = Context.getFunctionType(ConvType, 0, 0, false,
1112                              R->getAsFunctionTypeProto()->getTypeQuals());
1113
1114  return isInvalid;
1115}
1116
1117/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete
1118/// the declaration of the given C++ constructor ConDecl that was
1119/// built from declarator D. This routine is responsible for checking
1120/// that the newly-created constructor declaration is well-formed and
1121/// for recording it in the C++ class. Example:
1122///
1123/// @code
1124/// class X {
1125///   X(); // X::X() will be the ConDecl.
1126/// };
1127/// @endcode
1128Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) {
1129  assert(ConDecl && "Expected to receive a constructor declaration");
1130
1131  // Check default arguments on the constructor
1132  CheckCXXDefaultArguments(ConDecl);
1133
1134  CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1135  if (!ClassDecl) {
1136    ConDecl->setInvalidDecl();
1137    return ConDecl;
1138  }
1139
1140  // Make sure this constructor is an overload of the existing
1141  // constructors.
1142  OverloadedFunctionDecl::function_iterator MatchedDecl;
1143  if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) {
1144    Diag(ConDecl->getLocation(),
1145         diag::err_constructor_redeclared,
1146         SourceRange(ConDecl->getLocation()));
1147    Diag((*MatchedDecl)->getLocation(),
1148         diag::err_previous_declaration,
1149         SourceRange((*MatchedDecl)->getLocation()));
1150    ConDecl->setInvalidDecl();
1151    return ConDecl;
1152  }
1153
1154
1155  // C++ [class.copy]p3:
1156  //   A declaration of a constructor for a class X is ill-formed if
1157  //   its first parameter is of type (optionally cv-qualified) X and
1158  //   either there are no other parameters or else all other
1159  //   parameters have default arguments.
1160  if ((ConDecl->getNumParams() == 1) ||
1161      (ConDecl->getNumParams() > 1 &&
1162       ConDecl->getParamDecl(1)->getDefaultArg() != 0)) {
1163    QualType ParamType = ConDecl->getParamDecl(0)->getType();
1164    QualType ClassTy = Context.getTagDeclType(
1165                         const_cast<CXXRecordDecl*>(ConDecl->getParent()));
1166    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1167      Diag(ConDecl->getLocation(),
1168           diag::err_constructor_byvalue_arg,
1169           SourceRange(ConDecl->getParamDecl(0)->getLocation()));
1170      ConDecl->setInvalidDecl();
1171      return ConDecl;
1172    }
1173  }
1174
1175  // Add this constructor to the set of constructors of the current
1176  // class.
1177  ClassDecl->addConstructor(Context, ConDecl);
1178  return (DeclTy *)ConDecl;
1179}
1180
1181/// ActOnDestructorDeclarator - Called by ActOnDeclarator to complete
1182/// the declaration of the given C++ @p Destructor. This routine is
1183/// responsible for recording the destructor in the C++ class, if
1184/// possible.
1185Sema::DeclTy *Sema::ActOnDestructorDeclarator(CXXDestructorDecl *Destructor) {
1186  assert(Destructor && "Expected to receive a destructor declaration");
1187
1188  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext);
1189
1190  // Make sure we aren't redeclaring the destructor.
1191  if (CXXDestructorDecl *PrevDestructor = ClassDecl->getDestructor()) {
1192    Diag(Destructor->getLocation(), diag::err_destructor_redeclared);
1193    Diag(PrevDestructor->getLocation(),
1194         PrevDestructor->isThisDeclarationADefinition()?
1195             diag::err_previous_definition
1196           : diag::err_previous_declaration);
1197    Destructor->setInvalidDecl();
1198    return Destructor;
1199  }
1200
1201  ClassDecl->setDestructor(Destructor);
1202  return (DeclTy *)Destructor;
1203}
1204
1205/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1206/// the declaration of the given C++ conversion function. This routine
1207/// is responsible for recording the conversion function in the C++
1208/// class, if possible.
1209Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1210  assert(Conversion && "Expected to receive a conversion function declaration");
1211
1212  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext);
1213
1214  // Make sure we aren't redeclaring the conversion function.
1215  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
1216  OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1217  for (OverloadedFunctionDecl::function_iterator Func
1218         = Conversions->function_begin();
1219       Func != Conversions->function_end(); ++Func) {
1220    CXXConversionDecl *OtherConv = cast<CXXConversionDecl>(*Func);
1221    if (ConvType == Context.getCanonicalType(OtherConv->getConversionType())) {
1222      Diag(Conversion->getLocation(), diag::err_conv_function_redeclared);
1223      Diag(OtherConv->getLocation(),
1224           OtherConv->isThisDeclarationADefinition()?
1225              diag::err_previous_definition
1226            : diag::err_previous_declaration);
1227      Conversion->setInvalidDecl();
1228      return (DeclTy *)Conversion;
1229    }
1230  }
1231
1232  // C++ [class.conv.fct]p1:
1233  //   [...] A conversion function is never used to convert a
1234  //   (possibly cv-qualified) object to the (possibly cv-qualified)
1235  //   same object type (or a reference to it), to a (possibly
1236  //   cv-qualified) base class of that type (or a reference to it),
1237  //   or to (possibly cv-qualified) void.
1238  // FIXME: Suppress this warning if the conversion function ends up
1239  // being a virtual function that overrides a virtual function in a
1240  // base class.
1241  QualType ClassType
1242    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1243  if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1244    ConvType = ConvTypeRef->getPointeeType();
1245  if (ConvType->isRecordType()) {
1246    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1247    if (ConvType == ClassType)
1248      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used,
1249           ClassType.getAsString());
1250    else if (IsDerivedFrom(ClassType, ConvType))
1251      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used,
1252           ClassType.getAsString(),
1253           ConvType.getAsString());
1254  } else if (ConvType->isVoidType()) {
1255    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used,
1256         ClassType.getAsString(), ConvType.getAsString());
1257  }
1258
1259  ClassDecl->addConversionFunction(Context, Conversion);
1260
1261  return (DeclTy *)Conversion;
1262}
1263
1264//===----------------------------------------------------------------------===//
1265// Namespace Handling
1266//===----------------------------------------------------------------------===//
1267
1268/// ActOnStartNamespaceDef - This is called at the start of a namespace
1269/// definition.
1270Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1271                                           SourceLocation IdentLoc,
1272                                           IdentifierInfo *II,
1273                                           SourceLocation LBrace) {
1274  NamespaceDecl *Namespc =
1275      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1276  Namespc->setLBracLoc(LBrace);
1277
1278  Scope *DeclRegionScope = NamespcScope->getParent();
1279
1280  if (II) {
1281    // C++ [namespace.def]p2:
1282    // The identifier in an original-namespace-definition shall not have been
1283    // previously defined in the declarative region in which the
1284    // original-namespace-definition appears. The identifier in an
1285    // original-namespace-definition is the name of the namespace. Subsequently
1286    // in that declarative region, it is treated as an original-namespace-name.
1287
1288    Decl *PrevDecl =
1289        LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 0,
1290                   /*enableLazyBuiltinCreation=*/false);
1291
1292    if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
1293      if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
1294        // This is an extended namespace definition.
1295        // Attach this namespace decl to the chain of extended namespace
1296        // definitions.
1297        NamespaceDecl *NextNS = OrigNS;
1298        while (NextNS->getNextNamespace())
1299          NextNS = NextNS->getNextNamespace();
1300
1301        NextNS->setNextNamespace(Namespc);
1302        Namespc->setOriginalNamespace(OrigNS);
1303
1304        // We won't add this decl to the current scope. We want the namespace
1305        // name to return the original namespace decl during a name lookup.
1306      } else {
1307        // This is an invalid name redefinition.
1308        Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
1309          Namespc->getName());
1310        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1311        Namespc->setInvalidDecl();
1312        // Continue on to push Namespc as current DeclContext and return it.
1313      }
1314    } else {
1315      // This namespace name is declared for the first time.
1316      PushOnScopeChains(Namespc, DeclRegionScope);
1317    }
1318  }
1319  else {
1320    // FIXME: Handle anonymous namespaces
1321  }
1322
1323  // Although we could have an invalid decl (i.e. the namespace name is a
1324  // redefinition), push it as current DeclContext and try to continue parsing.
1325  PushDeclContext(Namespc->getOriginalNamespace());
1326  return Namespc;
1327}
1328
1329/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1330/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1331void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1332  Decl *Dcl = static_cast<Decl *>(D);
1333  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1334  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1335  Namespc->setRBracLoc(RBrace);
1336  PopDeclContext();
1337}
1338
1339
1340/// AddCXXDirectInitializerToDecl - This action is called immediately after
1341/// ActOnDeclarator, when a C++ direct initializer is present.
1342/// e.g: "int x(1);"
1343void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1344                                         ExprTy **ExprTys, unsigned NumExprs,
1345                                         SourceLocation *CommaLocs,
1346                                         SourceLocation RParenLoc) {
1347  assert(NumExprs != 0 && ExprTys && "missing expressions");
1348  Decl *RealDecl = static_cast<Decl *>(Dcl);
1349
1350  // If there is no declaration, there was an error parsing it.  Just ignore
1351  // the initializer.
1352  if (RealDecl == 0) {
1353    for (unsigned i = 0; i != NumExprs; ++i)
1354      delete static_cast<Expr *>(ExprTys[i]);
1355    return;
1356  }
1357
1358  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1359  if (!VDecl) {
1360    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1361    RealDecl->setInvalidDecl();
1362    return;
1363  }
1364
1365  // We will treat direct-initialization as a copy-initialization:
1366  //    int x(1);  -as-> int x = 1;
1367  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1368  //
1369  // Clients that want to distinguish between the two forms, can check for
1370  // direct initializer using VarDecl::hasCXXDirectInitializer().
1371  // A major benefit is that clients that don't particularly care about which
1372  // exactly form was it (like the CodeGen) can handle both cases without
1373  // special case code.
1374
1375  // C++ 8.5p11:
1376  // The form of initialization (using parentheses or '=') is generally
1377  // insignificant, but does matter when the entity being initialized has a
1378  // class type.
1379  QualType DeclInitType = VDecl->getType();
1380  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1381    DeclInitType = Array->getElementType();
1382
1383  if (VDecl->getType()->isRecordType()) {
1384    CXXConstructorDecl *Constructor
1385      = PerformInitializationByConstructor(DeclInitType,
1386                                           (Expr **)ExprTys, NumExprs,
1387                                           VDecl->getLocation(),
1388                                           SourceRange(VDecl->getLocation(),
1389                                                       RParenLoc),
1390                                           VDecl->getName(),
1391                                           IK_Direct);
1392    if (!Constructor) {
1393      RealDecl->setInvalidDecl();
1394    }
1395
1396    // Let clients know that initialization was done with a direct
1397    // initializer.
1398    VDecl->setCXXDirectInitializer(true);
1399
1400    // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1401    // the initializer.
1402    return;
1403  }
1404
1405  if (NumExprs > 1) {
1406    Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
1407         SourceRange(VDecl->getLocation(), RParenLoc));
1408    RealDecl->setInvalidDecl();
1409    return;
1410  }
1411
1412  // Let clients know that initialization was done with a direct initializer.
1413  VDecl->setCXXDirectInitializer(true);
1414
1415  assert(NumExprs == 1 && "Expected 1 expression");
1416  // Set the init expression, handles conversions.
1417  AddInitializerToDecl(Dcl, ExprTys[0]);
1418}
1419
1420/// PerformInitializationByConstructor - Perform initialization by
1421/// constructor (C++ [dcl.init]p14), which may occur as part of
1422/// direct-initialization or copy-initialization. We are initializing
1423/// an object of type @p ClassType with the given arguments @p
1424/// Args. @p Loc is the location in the source code where the
1425/// initializer occurs (e.g., a declaration, member initializer,
1426/// functional cast, etc.) while @p Range covers the whole
1427/// initialization. @p InitEntity is the entity being initialized,
1428/// which may by the name of a declaration or a type. @p Kind is the
1429/// kind of initialization we're performing, which affects whether
1430/// explicit constructors will be considered. When successful, returns
1431/// the constructor that will be used to perform the initialization;
1432/// when the initialization fails, emits a diagnostic and returns
1433/// null.
1434CXXConstructorDecl *
1435Sema::PerformInitializationByConstructor(QualType ClassType,
1436                                         Expr **Args, unsigned NumArgs,
1437                                         SourceLocation Loc, SourceRange Range,
1438                                         std::string InitEntity,
1439                                         InitializationKind Kind) {
1440  const RecordType *ClassRec = ClassType->getAsRecordType();
1441  assert(ClassRec && "Can only initialize a class type here");
1442
1443  // C++ [dcl.init]p14:
1444  //
1445  //   If the initialization is direct-initialization, or if it is
1446  //   copy-initialization where the cv-unqualified version of the
1447  //   source type is the same class as, or a derived class of, the
1448  //   class of the destination, constructors are considered. The
1449  //   applicable constructors are enumerated (13.3.1.3), and the
1450  //   best one is chosen through overload resolution (13.3). The
1451  //   constructor so selected is called to initialize the object,
1452  //   with the initializer expression(s) as its argument(s). If no
1453  //   constructor applies, or the overload resolution is ambiguous,
1454  //   the initialization is ill-formed.
1455  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1456  OverloadCandidateSet CandidateSet;
1457
1458  // Add constructors to the overload set.
1459  OverloadedFunctionDecl *Constructors
1460    = const_cast<OverloadedFunctionDecl *>(ClassDecl->getConstructors());
1461  for (OverloadedFunctionDecl::function_iterator Con
1462         = Constructors->function_begin();
1463       Con != Constructors->function_end(); ++Con) {
1464    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1465    if ((Kind == IK_Direct) ||
1466        (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1467        (Kind == IK_Default && Constructor->isDefaultConstructor()))
1468      AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1469  }
1470
1471  OverloadCandidateSet::iterator Best;
1472  switch (BestViableFunction(CandidateSet, Best)) {
1473  case OR_Success:
1474    // We found a constructor. Return it.
1475    return cast<CXXConstructorDecl>(Best->Function);
1476
1477  case OR_No_Viable_Function:
1478    if (CandidateSet.empty())
1479      Diag(Loc, diag::err_ovl_no_viable_function_in_init,
1480           InitEntity, Range);
1481    else {
1482      Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands,
1483           InitEntity, Range);
1484      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1485    }
1486    return 0;
1487
1488  case OR_Ambiguous:
1489    Diag(Loc, diag::err_ovl_ambiguous_init,
1490         InitEntity, Range);
1491    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1492    return 0;
1493  }
1494
1495  return 0;
1496}
1497
1498/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1499/// determine whether they are reference-related,
1500/// reference-compatible, reference-compatible with added
1501/// qualification, or incompatible, for use in C++ initialization by
1502/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1503/// type, and the first type (T1) is the pointee type of the reference
1504/// type being initialized.
1505Sema::ReferenceCompareResult
1506Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1507                                   bool& DerivedToBase) {
1508  assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1509  assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1510
1511  T1 = Context.getCanonicalType(T1);
1512  T2 = Context.getCanonicalType(T2);
1513  QualType UnqualT1 = T1.getUnqualifiedType();
1514  QualType UnqualT2 = T2.getUnqualifiedType();
1515
1516  // C++ [dcl.init.ref]p4:
1517  //   Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1518  //   reference-related to “cv2 T2” if T1 is the same type as T2, or
1519  //   T1 is a base class of T2.
1520  if (UnqualT1 == UnqualT2)
1521    DerivedToBase = false;
1522  else if (IsDerivedFrom(UnqualT2, UnqualT1))
1523    DerivedToBase = true;
1524  else
1525    return Ref_Incompatible;
1526
1527  // At this point, we know that T1 and T2 are reference-related (at
1528  // least).
1529
1530  // C++ [dcl.init.ref]p4:
1531  //   "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1532  //   reference-related to T2 and cv1 is the same cv-qualification
1533  //   as, or greater cv-qualification than, cv2. For purposes of
1534  //   overload resolution, cases for which cv1 is greater
1535  //   cv-qualification than cv2 are identified as
1536  //   reference-compatible with added qualification (see 13.3.3.2).
1537  if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1538    return Ref_Compatible;
1539  else if (T1.isMoreQualifiedThan(T2))
1540    return Ref_Compatible_With_Added_Qualification;
1541  else
1542    return Ref_Related;
1543}
1544
1545/// CheckReferenceInit - Check the initialization of a reference
1546/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1547/// the initializer (either a simple initializer or an initializer
1548/// list), and DeclType is the type of the declaration. When ICS is
1549/// non-null, this routine will compute the implicit conversion
1550/// sequence according to C++ [over.ics.ref] and will not produce any
1551/// diagnostics; when ICS is null, it will emit diagnostics when any
1552/// errors are found. Either way, a return value of true indicates
1553/// that there was a failure, a return value of false indicates that
1554/// the reference initialization succeeded.
1555///
1556/// When @p SuppressUserConversions, user-defined conversions are
1557/// suppressed.
1558bool
1559Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
1560                         ImplicitConversionSequence *ICS,
1561                         bool SuppressUserConversions) {
1562  assert(DeclType->isReferenceType() && "Reference init needs a reference");
1563
1564  QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1565  QualType T2 = Init->getType();
1566
1567  // If the initializer is the address of an overloaded function, try
1568  // to resolve the overloaded function. If all goes well, T2 is the
1569  // type of the resulting function.
1570  if (T2->isOverloadType()) {
1571    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1572                                                          ICS != 0);
1573    if (Fn) {
1574      // Since we're performing this reference-initialization for
1575      // real, update the initializer with the resulting function.
1576      if (!ICS)
1577        FixOverloadedFunctionReference(Init, Fn);
1578
1579      T2 = Fn->getType();
1580    }
1581  }
1582
1583  // Compute some basic properties of the types and the initializer.
1584  bool DerivedToBase = false;
1585  Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
1586  ReferenceCompareResult RefRelationship
1587    = CompareReferenceRelationship(T1, T2, DerivedToBase);
1588
1589  // Most paths end in a failed conversion.
1590  if (ICS)
1591    ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
1592
1593  // C++ [dcl.init.ref]p5:
1594  //   A reference to type “cv1 T1” is initialized by an expression
1595  //   of type “cv2 T2” as follows:
1596
1597  //     -- If the initializer expression
1598
1599  bool BindsDirectly = false;
1600  //       -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1601  //          reference-compatible with “cv2 T2,” or
1602  //
1603  // Note that the bit-field check is skipped if we are just computing
1604  // the implicit conversion sequence (C++ [over.best.ics]p2).
1605  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1606      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1607    BindsDirectly = true;
1608
1609    if (ICS) {
1610      // C++ [over.ics.ref]p1:
1611      //   When a parameter of reference type binds directly (8.5.3)
1612      //   to an argument expression, the implicit conversion sequence
1613      //   is the identity conversion, unless the argument expression
1614      //   has a type that is a derived class of the parameter type,
1615      //   in which case the implicit conversion sequence is a
1616      //   derived-to-base Conversion (13.3.3.1).
1617      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1618      ICS->Standard.First = ICK_Identity;
1619      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1620      ICS->Standard.Third = ICK_Identity;
1621      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1622      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
1623      ICS->Standard.ReferenceBinding = true;
1624      ICS->Standard.DirectBinding = true;
1625
1626      // Nothing more to do: the inaccessibility/ambiguity check for
1627      // derived-to-base conversions is suppressed when we're
1628      // computing the implicit conversion sequence (C++
1629      // [over.best.ics]p2).
1630      return false;
1631    } else {
1632      // Perform the conversion.
1633      // FIXME: Binding to a subobject of the lvalue is going to require
1634      // more AST annotation than this.
1635      ImpCastExprToType(Init, T1, /*isLvalue=*/true);
1636    }
1637  }
1638
1639  //       -- has a class type (i.e., T2 is a class type) and can be
1640  //          implicitly converted to an lvalue of type “cv3 T3,”
1641  //          where “cv1 T1” is reference-compatible with “cv3 T3”
1642  //          92) (this conversion is selected by enumerating the
1643  //          applicable conversion functions (13.3.1.6) and choosing
1644  //          the best one through overload resolution (13.3)),
1645  if (!SuppressUserConversions && T2->isRecordType()) {
1646    // FIXME: Look for conversions in base classes!
1647    CXXRecordDecl *T2RecordDecl
1648      = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
1649
1650    OverloadCandidateSet CandidateSet;
1651    OverloadedFunctionDecl *Conversions
1652      = T2RecordDecl->getConversionFunctions();
1653    for (OverloadedFunctionDecl::function_iterator Func
1654           = Conversions->function_begin();
1655         Func != Conversions->function_end(); ++Func) {
1656      CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1657
1658      // If the conversion function doesn't return a reference type,
1659      // it can't be considered for this conversion.
1660      // FIXME: This will change when we support rvalue references.
1661      if (Conv->getConversionType()->isReferenceType())
1662        AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1663    }
1664
1665    OverloadCandidateSet::iterator Best;
1666    switch (BestViableFunction(CandidateSet, Best)) {
1667    case OR_Success:
1668      // This is a direct binding.
1669      BindsDirectly = true;
1670
1671      if (ICS) {
1672        // C++ [over.ics.ref]p1:
1673        //
1674        //   [...] If the parameter binds directly to the result of
1675        //   applying a conversion function to the argument
1676        //   expression, the implicit conversion sequence is a
1677        //   user-defined conversion sequence (13.3.3.1.2), with the
1678        //   second standard conversion sequence either an identity
1679        //   conversion or, if the conversion function returns an
1680        //   entity of a type that is a derived class of the parameter
1681        //   type, a derived-to-base Conversion.
1682        ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1683        ICS->UserDefined.Before = Best->Conversions[0].Standard;
1684        ICS->UserDefined.After = Best->FinalConversion;
1685        ICS->UserDefined.ConversionFunction = Best->Function;
1686        assert(ICS->UserDefined.After.ReferenceBinding &&
1687               ICS->UserDefined.After.DirectBinding &&
1688               "Expected a direct reference binding!");
1689        return false;
1690      } else {
1691        // Perform the conversion.
1692        // FIXME: Binding to a subobject of the lvalue is going to require
1693        // more AST annotation than this.
1694        ImpCastExprToType(Init, T1, /*isLvalue=*/true);
1695      }
1696      break;
1697
1698    case OR_Ambiguous:
1699      assert(false && "Ambiguous reference binding conversions not implemented.");
1700      return true;
1701
1702    case OR_No_Viable_Function:
1703      // There was no suitable conversion; continue with other checks.
1704      break;
1705    }
1706  }
1707
1708  if (BindsDirectly) {
1709    // C++ [dcl.init.ref]p4:
1710    //   [...] In all cases where the reference-related or
1711    //   reference-compatible relationship of two types is used to
1712    //   establish the validity of a reference binding, and T1 is a
1713    //   base class of T2, a program that necessitates such a binding
1714    //   is ill-formed if T1 is an inaccessible (clause 11) or
1715    //   ambiguous (10.2) base class of T2.
1716    //
1717    // Note that we only check this condition when we're allowed to
1718    // complain about errors, because we should not be checking for
1719    // ambiguity (or inaccessibility) unless the reference binding
1720    // actually happens.
1721    if (DerivedToBase)
1722      return CheckDerivedToBaseConversion(T2, T1,
1723                                          Init->getSourceRange().getBegin(),
1724                                          Init->getSourceRange());
1725    else
1726      return false;
1727  }
1728
1729  //     -- Otherwise, the reference shall be to a non-volatile const
1730  //        type (i.e., cv1 shall be const).
1731  if (T1.getCVRQualifiers() != QualType::Const) {
1732    if (!ICS)
1733      Diag(Init->getSourceRange().getBegin(),
1734           diag::err_not_reference_to_const_init,
1735           T1.getAsString(),
1736           InitLvalue != Expr::LV_Valid? "temporary" : "value",
1737           T2.getAsString(), Init->getSourceRange());
1738    return true;
1739  }
1740
1741  //       -- If the initializer expression is an rvalue, with T2 a
1742  //          class type, and “cv1 T1” is reference-compatible with
1743  //          “cv2 T2,” the reference is bound in one of the
1744  //          following ways (the choice is implementation-defined):
1745  //
1746  //          -- The reference is bound to the object represented by
1747  //             the rvalue (see 3.10) or to a sub-object within that
1748  //             object.
1749  //
1750  //          -- A temporary of type “cv1 T2” [sic] is created, and
1751  //             a constructor is called to copy the entire rvalue
1752  //             object into the temporary. The reference is bound to
1753  //             the temporary or to a sub-object within the
1754  //             temporary.
1755  //
1756  //
1757  //          The constructor that would be used to make the copy
1758  //          shall be callable whether or not the copy is actually
1759  //          done.
1760  //
1761  // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1762  // freedom, so we will always take the first option and never build
1763  // a temporary in this case. FIXME: We will, however, have to check
1764  // for the presence of a copy constructor in C++98/03 mode.
1765  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
1766      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1767    if (ICS) {
1768      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1769      ICS->Standard.First = ICK_Identity;
1770      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1771      ICS->Standard.Third = ICK_Identity;
1772      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1773      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
1774      ICS->Standard.ReferenceBinding = true;
1775      ICS->Standard.DirectBinding = false;
1776    } else {
1777      // FIXME: Binding to a subobject of the rvalue is going to require
1778      // more AST annotation than this.
1779      ImpCastExprToType(Init, T1, /*isLvalue=*/true);
1780    }
1781    return false;
1782  }
1783
1784  //       -- Otherwise, a temporary of type “cv1 T1” is created and
1785  //          initialized from the initializer expression using the
1786  //          rules for a non-reference copy initialization (8.5). The
1787  //          reference is then bound to the temporary. If T1 is
1788  //          reference-related to T2, cv1 must be the same
1789  //          cv-qualification as, or greater cv-qualification than,
1790  //          cv2; otherwise, the program is ill-formed.
1791  if (RefRelationship == Ref_Related) {
1792    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1793    // we would be reference-compatible or reference-compatible with
1794    // added qualification. But that wasn't the case, so the reference
1795    // initialization fails.
1796    if (!ICS)
1797      Diag(Init->getSourceRange().getBegin(),
1798           diag::err_reference_init_drops_quals,
1799           T1.getAsString(),
1800           InitLvalue != Expr::LV_Valid? "temporary" : "value",
1801           T2.getAsString(), Init->getSourceRange());
1802    return true;
1803  }
1804
1805  // Actually try to convert the initializer to T1.
1806  if (ICS) {
1807    /// C++ [over.ics.ref]p2:
1808    ///
1809    ///   When a parameter of reference type is not bound directly to
1810    ///   an argument expression, the conversion sequence is the one
1811    ///   required to convert the argument expression to the
1812    ///   underlying type of the reference according to
1813    ///   13.3.3.1. Conceptually, this conversion sequence corresponds
1814    ///   to copy-initializing a temporary of the underlying type with
1815    ///   the argument expression. Any difference in top-level
1816    ///   cv-qualification is subsumed by the initialization itself
1817    ///   and does not constitute a conversion.
1818    *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
1819    return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1820  } else {
1821    return PerformImplicitConversion(Init, T1);
1822  }
1823}
1824
1825/// CheckOverloadedOperatorDeclaration - Check whether the declaration
1826/// of this overloaded operator is well-formed. If so, returns false;
1827/// otherwise, emits appropriate diagnostics and returns true.
1828bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
1829  assert(FnDecl && FnDecl->isOverloadedOperator() &&
1830         "Expected an overloaded operator declaration");
1831
1832  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
1833
1834  // C++ [over.oper]p5:
1835  //   The allocation and deallocation functions, operator new,
1836  //   operator new[], operator delete and operator delete[], are
1837  //   described completely in 3.7.3. The attributes and restrictions
1838  //   found in the rest of this subclause do not apply to them unless
1839  //   explicitly stated in 3.7.3.
1840  // FIXME: Write a separate routine for checking this. For now, just
1841  // allow it.
1842  if (Op == OO_New || Op == OO_Array_New ||
1843      Op == OO_Delete || Op == OO_Array_Delete)
1844    return false;
1845
1846  // C++ [over.oper]p6:
1847  //   An operator function shall either be a non-static member
1848  //   function or be a non-member function and have at least one
1849  //   parameter whose type is a class, a reference to a class, an
1850  //   enumeration, or a reference to an enumeration.
1851  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
1852    if (MethodDecl->isStatic())
1853      return Diag(FnDecl->getLocation(),
1854                  diag::err_operator_overload_static,
1855                  FnDecl->getName());
1856  } else {
1857    bool ClassOrEnumParam = false;
1858    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
1859                                   ParamEnd = FnDecl->param_end();
1860         Param != ParamEnd; ++Param) {
1861      QualType ParamType = (*Param)->getType().getNonReferenceType();
1862      if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
1863        ClassOrEnumParam = true;
1864        break;
1865      }
1866    }
1867
1868    if (!ClassOrEnumParam)
1869      return Diag(FnDecl->getLocation(),
1870                  diag::err_operator_overload_needs_class_or_enum,
1871                  FnDecl->getName());
1872  }
1873
1874  // C++ [over.oper]p8:
1875  //   An operator function cannot have default arguments (8.3.6),
1876  //   except where explicitly stated below.
1877  //
1878  // Only the function-call operator allows default arguments
1879  // (C++ [over.call]p1).
1880  if (Op != OO_Call) {
1881    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
1882         Param != FnDecl->param_end(); ++Param) {
1883      if (Expr *DefArg = (*Param)->getDefaultArg())
1884        return Diag((*Param)->getLocation(),
1885                    diag::err_operator_overload_default_arg,
1886                    FnDecl->getName(), DefArg->getSourceRange());
1887    }
1888  }
1889
1890  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
1891    { false, false, false }
1892#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1893    , { Unary, Binary, MemberOnly }
1894#include "clang/Basic/OperatorKinds.def"
1895  };
1896
1897  bool CanBeUnaryOperator = OperatorUses[Op][0];
1898  bool CanBeBinaryOperator = OperatorUses[Op][1];
1899  bool MustBeMemberOperator = OperatorUses[Op][2];
1900
1901  // C++ [over.oper]p8:
1902  //   [...] Operator functions cannot have more or fewer parameters
1903  //   than the number required for the corresponding operator, as
1904  //   described in the rest of this subclause.
1905  unsigned NumParams = FnDecl->getNumParams()
1906                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
1907  if (Op != OO_Call &&
1908      ((NumParams == 1 && !CanBeUnaryOperator) ||
1909       (NumParams == 2 && !CanBeBinaryOperator) ||
1910       (NumParams < 1) || (NumParams > 2))) {
1911    // We have the wrong number of parameters.
1912    std::string NumParamsStr = llvm::utostr(NumParams);
1913
1914    diag::kind DK;
1915
1916    if (CanBeUnaryOperator && CanBeBinaryOperator) {
1917      if (NumParams == 1)
1918        DK = diag::err_operator_overload_must_be_unary_or_binary;
1919      else
1920        DK = diag::err_operator_overload_must_be_unary_or_binary;
1921    } else if (CanBeUnaryOperator) {
1922      if (NumParams == 1)
1923        DK = diag::err_operator_overload_must_be_unary;
1924      else
1925        DK = diag::err_operator_overload_must_be_unary_plural;
1926    } else if (CanBeBinaryOperator) {
1927      if (NumParams == 1)
1928        DK = diag::err_operator_overload_must_be_binary;
1929      else
1930        DK = diag::err_operator_overload_must_be_binary_plural;
1931    } else {
1932      assert(false && "All non-call overloaded operators are unary or binary!");
1933    }
1934
1935    return Diag(FnDecl->getLocation(), DK,
1936                FnDecl->getName(), NumParamsStr);
1937  }
1938
1939  // Overloaded operators other than operator() cannot be variadic.
1940  if (Op != OO_Call &&
1941      FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) {
1942    return Diag(FnDecl->getLocation(),
1943                diag::err_operator_overload_variadic,
1944                FnDecl->getName());
1945  }
1946
1947  // Some operators must be non-static member functions.
1948  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
1949    return Diag(FnDecl->getLocation(),
1950                diag::err_operator_overload_must_be_member,
1951                FnDecl->getName());
1952  }
1953
1954  // C++ [over.inc]p1:
1955  //   The user-defined function called operator++ implements the
1956  //   prefix and postfix ++ operator. If this function is a member
1957  //   function with no parameters, or a non-member function with one
1958  //   parameter of class or enumeration type, it defines the prefix
1959  //   increment operator ++ for objects of that type. If the function
1960  //   is a member function with one parameter (which shall be of type
1961  //   int) or a non-member function with two parameters (the second
1962  //   of which shall be of type int), it defines the postfix
1963  //   increment operator ++ for objects of that type.
1964  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
1965    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
1966    bool ParamIsInt = false;
1967    if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
1968      ParamIsInt = BT->getKind() == BuiltinType::Int;
1969
1970    if (!ParamIsInt) {
1971      diag::kind DK;
1972      if (Op == OO_PlusPlus)
1973        DK = diag::err_operator_overload_post_inc_must_be_int;
1974      else
1975        DK = diag::err_operator_overload_post_dec_must_be_int;
1976      return Diag(LastParam->getLocation(), DK,
1977                  Context.getCanonicalType(LastParam->getType()).getAsString());
1978    }
1979  }
1980
1981  return false;
1982}
1983