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