SemaDeclCXX.cpp revision 4dd55f511d1fba732f2968f430ce999fc8293896
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/Parse/DeclSpec.h"
22#include "llvm/ADT/STLExtras.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->getDeclName() << 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->getDeclName() << 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  ExprOwningPtr<Expr> DefaultArg(this, (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    Param->setInvalidDecl();
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 = CheckInitializerTypes(DefaultArgPtr, ParamType,
129                                                 EqualLoc,
130                                                 Param->getDeclName(),
131                                                 /*DirectInit=*/false);
132  if (DefaultArgPtr != DefaultArg.get()) {
133    DefaultArg.take();
134    DefaultArg.reset(DefaultArgPtr);
135  }
136  if (DefaultInitFailed) {
137    return;
138  }
139
140  // Check that the default argument is well-formed
141  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
142  if (DefaultArgChecker.Visit(DefaultArg.get())) {
143    Param->setInvalidDecl();
144    return;
145  }
146
147  // Okay: add the default argument to the parameter
148  Param->setDefaultArg(DefaultArg.take());
149}
150
151/// ActOnParamUnparsedDefaultArgument - We've seen a default
152/// argument for a function parameter, but we can't parse it yet
153/// because we're inside a class definition. Note that this default
154/// argument will be parsed later.
155void Sema::ActOnParamUnparsedDefaultArgument(DeclTy *param,
156                                             SourceLocation EqualLoc) {
157  ParmVarDecl *Param = (ParmVarDecl*)param;
158  if (Param)
159    Param->setUnparsedDefaultArg();
160}
161
162/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
163/// the default argument for the parameter param failed.
164void Sema::ActOnParamDefaultArgumentError(DeclTy *param) {
165  ((ParmVarDecl*)param)->setInvalidDecl();
166}
167
168/// CheckExtraCXXDefaultArguments - Check for any extra default
169/// arguments in the declarator, which is not a function declaration
170/// or definition and therefore is not permitted to have default
171/// arguments. This routine should be invoked for every declarator
172/// that is not a function declaration or definition.
173void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
174  // C++ [dcl.fct.default]p3
175  //   A default argument expression shall be specified only in the
176  //   parameter-declaration-clause of a function declaration or in a
177  //   template-parameter (14.1). It shall not be specified for a
178  //   parameter pack. If it is specified in a
179  //   parameter-declaration-clause, it shall not occur within a
180  //   declarator or abstract-declarator of a parameter-declaration.
181  for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
182    DeclaratorChunk &chunk = D.getTypeObject(i);
183    if (chunk.Kind == DeclaratorChunk::Function) {
184      for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
185        ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
186        if (Param->hasUnparsedDefaultArg()) {
187          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
188          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
189            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
190          delete Toks;
191          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
192        } else if (Param->getDefaultArg()) {
193          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
194            << Param->getDefaultArg()->getSourceRange();
195          Param->setDefaultArg(0);
196        }
197      }
198    }
199  }
200}
201
202// MergeCXXFunctionDecl - Merge two declarations of the same C++
203// function, once we already know that they have the same
204// type. Subroutine of MergeFunctionDecl. Returns true if there was an
205// error, false otherwise.
206bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
207  bool Invalid = false;
208
209  // C++ [dcl.fct.default]p4:
210  //
211  //   For non-template functions, default arguments can be added in
212  //   later declarations of a function in the same
213  //   scope. Declarations in different scopes have completely
214  //   distinct sets of default arguments. That is, declarations in
215  //   inner scopes do not acquire default arguments from
216  //   declarations in outer scopes, and vice versa. In a given
217  //   function declaration, all parameters subsequent to a
218  //   parameter with a default argument shall have default
219  //   arguments supplied in this or previous declarations. A
220  //   default argument shall not be redefined by a later
221  //   declaration (not even to the same value).
222  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
223    ParmVarDecl *OldParam = Old->getParamDecl(p);
224    ParmVarDecl *NewParam = New->getParamDecl(p);
225
226    if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
227      Diag(NewParam->getLocation(),
228           diag::err_param_default_argument_redefinition)
229        << NewParam->getDefaultArg()->getSourceRange();
230      Diag(OldParam->getLocation(), diag::note_previous_definition);
231      Invalid = true;
232    } else if (OldParam->getDefaultArg()) {
233      // Merge the old default argument into the new parameter
234      NewParam->setDefaultArg(OldParam->getDefaultArg());
235    }
236  }
237
238  return Invalid;
239}
240
241/// CheckCXXDefaultArguments - Verify that the default arguments for a
242/// function declaration are well-formed according to C++
243/// [dcl.fct.default].
244void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
245  unsigned NumParams = FD->getNumParams();
246  unsigned p;
247
248  // Find first parameter with a default argument
249  for (p = 0; p < NumParams; ++p) {
250    ParmVarDecl *Param = FD->getParamDecl(p);
251    if (Param->getDefaultArg())
252      break;
253  }
254
255  // C++ [dcl.fct.default]p4:
256  //   In a given function declaration, all parameters
257  //   subsequent to a parameter with a default argument shall
258  //   have default arguments supplied in this or previous
259  //   declarations. A default argument shall not be redefined
260  //   by a later declaration (not even to the same value).
261  unsigned LastMissingDefaultArg = 0;
262  for(; p < NumParams; ++p) {
263    ParmVarDecl *Param = FD->getParamDecl(p);
264    if (!Param->getDefaultArg()) {
265      if (Param->isInvalidDecl())
266        /* We already complained about this parameter. */;
267      else if (Param->getIdentifier())
268        Diag(Param->getLocation(),
269             diag::err_param_default_argument_missing_name)
270          << Param->getIdentifier();
271      else
272        Diag(Param->getLocation(),
273             diag::err_param_default_argument_missing);
274
275      LastMissingDefaultArg = p;
276    }
277  }
278
279  if (LastMissingDefaultArg > 0) {
280    // Some default arguments were missing. Clear out all of the
281    // default arguments up to (and including) the last missing
282    // default argument, so that we leave the function parameters
283    // in a semantically valid state.
284    for (p = 0; p <= LastMissingDefaultArg; ++p) {
285      ParmVarDecl *Param = FD->getParamDecl(p);
286      if (Param->getDefaultArg()) {
287        if (!Param->hasUnparsedDefaultArg())
288          Param->getDefaultArg()->Destroy(Context);
289        Param->setDefaultArg(0);
290      }
291    }
292  }
293}
294
295/// isCurrentClassName - Determine whether the identifier II is the
296/// name of the class type currently being defined. In the case of
297/// nested classes, this will only return true if II is the name of
298/// the innermost class.
299bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
300                              const CXXScopeSpec *SS) {
301  CXXRecordDecl *CurDecl;
302  if (SS) {
303    DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
304    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
305  } else
306    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
307
308  if (CurDecl)
309    return &II == CurDecl->getIdentifier();
310  else
311    return false;
312}
313
314/// \brief Check the validity of a C++ base class specifier.
315///
316/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
317/// and returns NULL otherwise.
318CXXBaseSpecifier *
319Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
320                         SourceRange SpecifierRange,
321                         bool Virtual, AccessSpecifier Access,
322                         QualType BaseType,
323                         SourceLocation BaseLoc) {
324  // C++ [class.union]p1:
325  //   A union shall not have base classes.
326  if (Class->isUnion()) {
327    Diag(Class->getLocation(), diag::err_base_clause_on_union)
328      << SpecifierRange;
329    return 0;
330  }
331
332  if (BaseType->isDependentType())
333    return new CXXBaseSpecifier(SpecifierRange, Virtual,
334                                Class->getTagKind() == RecordDecl::TK_class,
335                                Access, BaseType);
336
337  // Base specifiers must be record types.
338  if (!BaseType->isRecordType()) {
339    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
340    return 0;
341  }
342
343  // C++ [class.union]p1:
344  //   A union shall not be used as a base class.
345  if (BaseType->isUnionType()) {
346    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
347    return 0;
348  }
349
350  // C++ [class.derived]p2:
351  //   The class-name in a base-specifier shall not be an incompletely
352  //   defined class.
353  if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
354                          SpecifierRange))
355    return 0;
356
357  // If the base class is polymorphic, the new one is, too.
358  RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
359  assert(BaseDecl && "Record type has no declaration");
360  BaseDecl = BaseDecl->getDefinition(Context);
361  assert(BaseDecl && "Base type is not incomplete, but has no definition");
362  if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
363    Class->setPolymorphic(true);
364
365  // C++ [dcl.init.aggr]p1:
366  //   An aggregate is [...] a class with [...] no base classes [...].
367  Class->setAggregate(false);
368  Class->setPOD(false);
369
370  // Create the base specifier.
371  // FIXME: Allocate via ASTContext?
372  return new CXXBaseSpecifier(SpecifierRange, Virtual,
373                              Class->getTagKind() == RecordDecl::TK_class,
374                              Access, BaseType);
375}
376
377/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
378/// one entry in the base class list of a class specifier, for
379/// example:
380///    class foo : public bar, virtual private baz {
381/// 'public bar' and 'virtual private baz' are each base-specifiers.
382Sema::BaseResult
383Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
384                         bool Virtual, AccessSpecifier Access,
385                         TypeTy *basetype, SourceLocation BaseLoc) {
386  AdjustDeclIfTemplate(classdecl);
387  CXXRecordDecl *Class = cast<CXXRecordDecl>((Decl*)classdecl);
388  QualType BaseType = QualType::getFromOpaquePtr(basetype);
389  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
390                                                      Virtual, Access,
391                                                      BaseType, BaseLoc))
392    return BaseSpec;
393
394  return true;
395}
396
397/// \brief Performs the actual work of attaching the given base class
398/// specifiers to a C++ class.
399bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
400                                unsigned NumBases) {
401 if (NumBases == 0)
402    return false;
403
404  // Used to keep track of which base types we have already seen, so
405  // that we can properly diagnose redundant direct base types. Note
406  // that the key is always the unqualified canonical type of the base
407  // class.
408  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
409
410  // Copy non-redundant base specifiers into permanent storage.
411  unsigned NumGoodBases = 0;
412  bool Invalid = false;
413  for (unsigned idx = 0; idx < NumBases; ++idx) {
414    QualType NewBaseType
415      = Context.getCanonicalType(Bases[idx]->getType());
416    NewBaseType = NewBaseType.getUnqualifiedType();
417
418    if (KnownBaseTypes[NewBaseType]) {
419      // C++ [class.mi]p3:
420      //   A class shall not be specified as a direct base class of a
421      //   derived class more than once.
422      Diag(Bases[idx]->getSourceRange().getBegin(),
423           diag::err_duplicate_base_class)
424        << KnownBaseTypes[NewBaseType]->getType()
425        << Bases[idx]->getSourceRange();
426
427      // Delete the duplicate base class specifier; we're going to
428      // overwrite its pointer later.
429      delete Bases[idx];
430
431      Invalid = true;
432    } else {
433      // Okay, add this new base class.
434      KnownBaseTypes[NewBaseType] = Bases[idx];
435      Bases[NumGoodBases++] = Bases[idx];
436    }
437  }
438
439  // Attach the remaining base class specifiers to the derived class.
440  Class->setBases(Bases, NumGoodBases);
441
442  // Delete the remaining (good) base class specifiers, since their
443  // data has been copied into the CXXRecordDecl.
444  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
445    delete Bases[idx];
446
447  return Invalid;
448}
449
450/// ActOnBaseSpecifiers - Attach the given base specifiers to the
451/// class, after checking whether there are any duplicate base
452/// classes.
453void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
454                               unsigned NumBases) {
455  if (!ClassDecl || !Bases || !NumBases)
456    return;
457
458  AdjustDeclIfTemplate(ClassDecl);
459  AttachBaseSpecifiers(cast<CXXRecordDecl>((Decl*)ClassDecl),
460                       (CXXBaseSpecifier**)(Bases), NumBases);
461}
462
463//===----------------------------------------------------------------------===//
464// C++ class member Handling
465//===----------------------------------------------------------------------===//
466
467/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
468/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
469/// bitfield width if there is one and 'InitExpr' specifies the initializer if
470/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
471/// declarators on it.
472Sema::DeclTy *
473Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
474                               ExprTy *BW, ExprTy *InitExpr,
475                               DeclTy *LastInGroup) {
476  const DeclSpec &DS = D.getDeclSpec();
477  DeclarationName Name = GetNameForDeclarator(D);
478  Expr *BitWidth = static_cast<Expr*>(BW);
479  Expr *Init = static_cast<Expr*>(InitExpr);
480  SourceLocation Loc = D.getIdentifierLoc();
481
482  bool isFunc = D.isFunctionDeclarator();
483
484  // C++ 9.2p6: A member shall not be declared to have automatic storage
485  // duration (auto, register) or with the extern storage-class-specifier.
486  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
487  // data members and cannot be applied to names declared const or static,
488  // and cannot be applied to reference members.
489  switch (DS.getStorageClassSpec()) {
490    case DeclSpec::SCS_unspecified:
491    case DeclSpec::SCS_typedef:
492    case DeclSpec::SCS_static:
493      // FALL THROUGH.
494      break;
495    case DeclSpec::SCS_mutable:
496      if (isFunc) {
497        if (DS.getStorageClassSpecLoc().isValid())
498          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
499        else
500          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
501
502        // FIXME: It would be nicer if the keyword was ignored only for this
503        // declarator. Otherwise we could get follow-up errors.
504        D.getMutableDeclSpec().ClearStorageClassSpecs();
505      } else {
506        QualType T = GetTypeForDeclarator(D, S);
507        diag::kind err = static_cast<diag::kind>(0);
508        if (T->isReferenceType())
509          err = diag::err_mutable_reference;
510        else if (T.isConstQualified())
511          err = diag::err_mutable_const;
512        if (err != 0) {
513          if (DS.getStorageClassSpecLoc().isValid())
514            Diag(DS.getStorageClassSpecLoc(), err);
515          else
516            Diag(DS.getThreadSpecLoc(), err);
517          // FIXME: It would be nicer if the keyword was ignored only for this
518          // declarator. Otherwise we could get follow-up errors.
519          D.getMutableDeclSpec().ClearStorageClassSpecs();
520        }
521      }
522      break;
523    default:
524      if (DS.getStorageClassSpecLoc().isValid())
525        Diag(DS.getStorageClassSpecLoc(),
526             diag::err_storageclass_invalid_for_member);
527      else
528        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
529      D.getMutableDeclSpec().ClearStorageClassSpecs();
530  }
531
532  if (!isFunc &&
533      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
534      D.getNumTypeObjects() == 0) {
535    // Check also for this case:
536    //
537    // typedef int f();
538    // f a;
539    //
540    QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep());
541    isFunc = TDType->isFunctionType();
542  }
543
544  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
545                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
546                      !isFunc);
547
548  Decl *Member;
549  if (isInstField) {
550    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
551                         AS);
552    assert(Member && "HandleField never returns null");
553  } else {
554    Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
555    if (!Member) {
556      if (BitWidth) DeleteExpr(BitWidth);
557      return LastInGroup;
558    }
559
560    // Non-instance-fields can't have a bitfield.
561    if (BitWidth) {
562      if (Member->isInvalidDecl()) {
563        // don't emit another diagnostic.
564      } else if (isa<VarDecl>(Member)) {
565        // C++ 9.6p3: A bit-field shall not be a static member.
566        // "static member 'A' cannot be a bit-field"
567        Diag(Loc, diag::err_static_not_bitfield)
568          << Name << BitWidth->getSourceRange();
569      } else if (isa<TypedefDecl>(Member)) {
570        // "typedef member 'x' cannot be a bit-field"
571        Diag(Loc, diag::err_typedef_not_bitfield)
572          << Name << BitWidth->getSourceRange();
573      } else {
574        // A function typedef ("typedef int f(); f a;").
575        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
576        Diag(Loc, diag::err_not_integral_type_bitfield)
577          << Name << cast<ValueDecl>(Member)->getType()
578          << BitWidth->getSourceRange();
579      }
580
581      DeleteExpr(BitWidth);
582      BitWidth = 0;
583      Member->setInvalidDecl();
584    }
585
586    Member->setAccess(AS);
587  }
588
589  assert((Name || isInstField) && "No identifier for non-field ?");
590
591  if (DS.isVirtualSpecified()) {
592    if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
593      Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
594      Member->setInvalidDecl();
595    } else {
596      cast<CXXMethodDecl>(Member)->setVirtual();
597      CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
598      CurClass->setAggregate(false);
599      CurClass->setPOD(false);
600      CurClass->setPolymorphic(true);
601    }
602  }
603
604  // FIXME: The above definition of virtual is not sufficient. A function is
605  // also virtual if it overrides an already virtual function. This is important
606  // to do here because it decides the validity of a pure specifier.
607
608  if (Init) {
609    // C++ 9.2p4: A member-declarator can contain a constant-initializer only
610    // if it declares a static member of const integral or const enumeration
611    // type.
612    if (VarDecl *CVD = dyn_cast<VarDecl>(Member)) {
613      // ...static member of...
614      CVD->setInit(Init);
615      // ...const integral or const enumeration type.
616      if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
617          CVD->getType()->isIntegralType()) {
618        // constant-initializer
619        if (CheckForConstantInitializer(Init, CVD->getType()))
620          Member->setInvalidDecl();
621
622      } else {
623        // not const integral.
624        Diag(Loc, diag::err_member_initialization)
625          << Name << Init->getSourceRange();
626        Member->setInvalidDecl();
627      }
628
629    } else {
630      // not static member. perhaps virtual function?
631      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
632        // With declarators parsed the way they are, the parser cannot
633        // distinguish between a normal initializer and a pure-specifier.
634        // Thus this grotesque test.
635        IntegerLiteral *IL;
636        if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
637            Context.getCanonicalType(IL->getType()) == Context.IntTy) {
638          if (MD->isVirtual())
639            MD->setPure();
640          else {
641            Diag(Loc, diag::err_non_virtual_pure)
642              << Name << Init->getSourceRange();
643            Member->setInvalidDecl();
644          }
645        } else {
646          Diag(Loc, diag::err_member_function_initialization)
647            << Name << Init->getSourceRange();
648          Member->setInvalidDecl();
649        }
650      } else {
651        Diag(Loc, diag::err_member_initialization)
652          << Name << Init->getSourceRange();
653        Member->setInvalidDecl();
654      }
655    }
656  }
657
658  if (isInstField) {
659    FieldCollector->Add(cast<FieldDecl>(Member));
660    return LastInGroup;
661  }
662  return Member;
663}
664
665/// ActOnMemInitializer - Handle a C++ member initializer.
666Sema::MemInitResult
667Sema::ActOnMemInitializer(DeclTy *ConstructorD,
668                          Scope *S,
669                          IdentifierInfo *MemberOrBase,
670                          SourceLocation IdLoc,
671                          SourceLocation LParenLoc,
672                          ExprTy **Args, unsigned NumArgs,
673                          SourceLocation *CommaLocs,
674                          SourceLocation RParenLoc) {
675  CXXConstructorDecl *Constructor
676    = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
677  if (!Constructor) {
678    // The user wrote a constructor initializer on a function that is
679    // not a C++ constructor. Ignore the error for now, because we may
680    // have more member initializers coming; we'll diagnose it just
681    // once in ActOnMemInitializers.
682    return true;
683  }
684
685  CXXRecordDecl *ClassDecl = Constructor->getParent();
686
687  // C++ [class.base.init]p2:
688  //   Names in a mem-initializer-id are looked up in the scope of the
689  //   constructor’s class and, if not found in that scope, are looked
690  //   up in the scope containing the constructor’s
691  //   definition. [Note: if the constructor’s class contains a member
692  //   with the same name as a direct or virtual base class of the
693  //   class, a mem-initializer-id naming the member or base class and
694  //   composed of a single identifier refers to the class member. A
695  //   mem-initializer-id for the hidden base class may be specified
696  //   using a qualified name. ]
697  // Look for a member, first.
698  FieldDecl *Member = 0;
699  DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
700  if (Result.first != Result.second)
701    Member = dyn_cast<FieldDecl>(*Result.first);
702
703  // FIXME: Handle members of an anonymous union.
704
705  if (Member) {
706    // FIXME: Perform direct initialization of the member.
707    return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
708  }
709
710  // It didn't name a member, so see if it names a class.
711  TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, 0/*SS*/);
712  if (!BaseTy)
713    return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
714      << MemberOrBase << SourceRange(IdLoc, RParenLoc);
715
716  QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
717  if (!BaseType->isRecordType())
718    return Diag(IdLoc, diag::err_base_init_does_not_name_class)
719      << BaseType << SourceRange(IdLoc, RParenLoc);
720
721  // C++ [class.base.init]p2:
722  //   [...] Unless the mem-initializer-id names a nonstatic data
723  //   member of the constructor’s class or a direct or virtual base
724  //   of that class, the mem-initializer is ill-formed. A
725  //   mem-initializer-list can initialize a base class using any
726  //   name that denotes that base class type.
727
728  // First, check for a direct base class.
729  const CXXBaseSpecifier *DirectBaseSpec = 0;
730  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
731       Base != ClassDecl->bases_end(); ++Base) {
732    if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
733        Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
734      // We found a direct base of this type. That's what we're
735      // initializing.
736      DirectBaseSpec = &*Base;
737      break;
738    }
739  }
740
741  // Check for a virtual base class.
742  // FIXME: We might be able to short-circuit this if we know in
743  // advance that there are no virtual bases.
744  const CXXBaseSpecifier *VirtualBaseSpec = 0;
745  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
746    // We haven't found a base yet; search the class hierarchy for a
747    // virtual base class.
748    BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
749                    /*DetectVirtual=*/false);
750    if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
751      for (BasePaths::paths_iterator Path = Paths.begin();
752           Path != Paths.end(); ++Path) {
753        if (Path->back().Base->isVirtual()) {
754          VirtualBaseSpec = Path->back().Base;
755          break;
756        }
757      }
758    }
759  }
760
761  // C++ [base.class.init]p2:
762  //   If a mem-initializer-id is ambiguous because it designates both
763  //   a direct non-virtual base class and an inherited virtual base
764  //   class, the mem-initializer is ill-formed.
765  if (DirectBaseSpec && VirtualBaseSpec)
766    return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
767      << MemberOrBase << SourceRange(IdLoc, RParenLoc);
768
769  return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
770}
771
772
773void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
774                                             DeclTy *TagDecl,
775                                             SourceLocation LBrac,
776                                             SourceLocation RBrac) {
777  TemplateDecl *Template = AdjustDeclIfTemplate(TagDecl);
778  ActOnFields(S, RLoc, TagDecl,
779              (DeclTy**)FieldCollector->getCurFields(),
780              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
781
782  if (!Template)
783    AddImplicitlyDeclaredMembersToClass(cast<CXXRecordDecl>((Decl*)TagDecl));
784}
785
786/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
787/// special functions, such as the default constructor, copy
788/// constructor, or destructor, to the given C++ class (C++
789/// [special]p1).  This routine can only be executed just before the
790/// definition of the class is complete.
791void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
792  QualType ClassType = Context.getTypeDeclType(ClassDecl);
793  ClassType = Context.getCanonicalType(ClassType);
794
795  if (!ClassDecl->hasUserDeclaredConstructor()) {
796    // C++ [class.ctor]p5:
797    //   A default constructor for a class X is a constructor of class X
798    //   that can be called without an argument. If there is no
799    //   user-declared constructor for class X, a default constructor is
800    //   implicitly declared. An implicitly-declared default constructor
801    //   is an inline public member of its class.
802    DeclarationName Name
803      = Context.DeclarationNames.getCXXConstructorName(ClassType);
804    CXXConstructorDecl *DefaultCon =
805      CXXConstructorDecl::Create(Context, ClassDecl,
806                                 ClassDecl->getLocation(), Name,
807                                 Context.getFunctionType(Context.VoidTy,
808                                                         0, 0, false, 0),
809                                 /*isExplicit=*/false,
810                                 /*isInline=*/true,
811                                 /*isImplicitlyDeclared=*/true);
812    DefaultCon->setAccess(AS_public);
813    DefaultCon->setImplicit();
814    ClassDecl->addDecl(DefaultCon);
815
816    // Notify the class that we've added a constructor.
817    ClassDecl->addedConstructor(Context, DefaultCon);
818  }
819
820  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
821    // C++ [class.copy]p4:
822    //   If the class definition does not explicitly declare a copy
823    //   constructor, one is declared implicitly.
824
825    // C++ [class.copy]p5:
826    //   The implicitly-declared copy constructor for a class X will
827    //   have the form
828    //
829    //       X::X(const X&)
830    //
831    //   if
832    bool HasConstCopyConstructor = true;
833
834    //     -- each direct or virtual base class B of X has a copy
835    //        constructor whose first parameter is of type const B& or
836    //        const volatile B&, and
837    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
838         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
839      const CXXRecordDecl *BaseClassDecl
840        = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
841      HasConstCopyConstructor
842        = BaseClassDecl->hasConstCopyConstructor(Context);
843    }
844
845    //     -- for all the nonstatic data members of X that are of a
846    //        class type M (or array thereof), each such class type
847    //        has a copy constructor whose first parameter is of type
848    //        const M& or const volatile M&.
849    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
850         HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
851      QualType FieldType = (*Field)->getType();
852      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
853        FieldType = Array->getElementType();
854      if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
855        const CXXRecordDecl *FieldClassDecl
856          = cast<CXXRecordDecl>(FieldClassType->getDecl());
857        HasConstCopyConstructor
858          = FieldClassDecl->hasConstCopyConstructor(Context);
859      }
860    }
861
862    //   Otherwise, the implicitly declared copy constructor will have
863    //   the form
864    //
865    //       X::X(X&)
866    QualType ArgType = ClassType;
867    if (HasConstCopyConstructor)
868      ArgType = ArgType.withConst();
869    ArgType = Context.getReferenceType(ArgType);
870
871    //   An implicitly-declared copy constructor is an inline public
872    //   member of its class.
873    DeclarationName Name
874      = Context.DeclarationNames.getCXXConstructorName(ClassType);
875    CXXConstructorDecl *CopyConstructor
876      = CXXConstructorDecl::Create(Context, ClassDecl,
877                                   ClassDecl->getLocation(), Name,
878                                   Context.getFunctionType(Context.VoidTy,
879                                                           &ArgType, 1,
880                                                           false, 0),
881                                   /*isExplicit=*/false,
882                                   /*isInline=*/true,
883                                   /*isImplicitlyDeclared=*/true);
884    CopyConstructor->setAccess(AS_public);
885    CopyConstructor->setImplicit();
886
887    // Add the parameter to the constructor.
888    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
889                                                 ClassDecl->getLocation(),
890                                                 /*IdentifierInfo=*/0,
891                                                 ArgType, VarDecl::None, 0);
892    CopyConstructor->setParams(Context, &FromParam, 1);
893
894    ClassDecl->addedConstructor(Context, CopyConstructor);
895    ClassDecl->addDecl(CopyConstructor);
896  }
897
898  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
899    // Note: The following rules are largely analoguous to the copy
900    // constructor rules. Note that virtual bases are not taken into account
901    // for determining the argument type of the operator. Note also that
902    // operators taking an object instead of a reference are allowed.
903    //
904    // C++ [class.copy]p10:
905    //   If the class definition does not explicitly declare a copy
906    //   assignment operator, one is declared implicitly.
907    //   The implicitly-defined copy assignment operator for a class X
908    //   will have the form
909    //
910    //       X& X::operator=(const X&)
911    //
912    //   if
913    bool HasConstCopyAssignment = true;
914
915    //       -- each direct base class B of X has a copy assignment operator
916    //          whose parameter is of type const B&, const volatile B& or B,
917    //          and
918    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
919         HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
920      const CXXRecordDecl *BaseClassDecl
921        = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
922      HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
923    }
924
925    //       -- for all the nonstatic data members of X that are of a class
926    //          type M (or array thereof), each such class type has a copy
927    //          assignment operator whose parameter is of type const M&,
928    //          const volatile M& or M.
929    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
930         HasConstCopyAssignment && Field != ClassDecl->field_end(); ++Field) {
931      QualType FieldType = (*Field)->getType();
932      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
933        FieldType = Array->getElementType();
934      if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
935        const CXXRecordDecl *FieldClassDecl
936          = cast<CXXRecordDecl>(FieldClassType->getDecl());
937        HasConstCopyAssignment
938          = FieldClassDecl->hasConstCopyAssignment(Context);
939      }
940    }
941
942    //   Otherwise, the implicitly declared copy assignment operator will
943    //   have the form
944    //
945    //       X& X::operator=(X&)
946    QualType ArgType = ClassType;
947    QualType RetType = Context.getReferenceType(ArgType);
948    if (HasConstCopyAssignment)
949      ArgType = ArgType.withConst();
950    ArgType = Context.getReferenceType(ArgType);
951
952    //   An implicitly-declared copy assignment operator is an inline public
953    //   member of its class.
954    DeclarationName Name =
955      Context.DeclarationNames.getCXXOperatorName(OO_Equal);
956    CXXMethodDecl *CopyAssignment =
957      CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
958                            Context.getFunctionType(RetType, &ArgType, 1,
959                                                    false, 0),
960                            /*isStatic=*/false, /*isInline=*/true);
961    CopyAssignment->setAccess(AS_public);
962    CopyAssignment->setImplicit();
963
964    // Add the parameter to the operator.
965    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
966                                                 ClassDecl->getLocation(),
967                                                 /*IdentifierInfo=*/0,
968                                                 ArgType, VarDecl::None, 0);
969    CopyAssignment->setParams(Context, &FromParam, 1);
970
971    // Don't call addedAssignmentOperator. There is no way to distinguish an
972    // implicit from an explicit assignment operator.
973    ClassDecl->addDecl(CopyAssignment);
974  }
975
976  if (!ClassDecl->hasUserDeclaredDestructor()) {
977    // C++ [class.dtor]p2:
978    //   If a class has no user-declared destructor, a destructor is
979    //   declared implicitly. An implicitly-declared destructor is an
980    //   inline public member of its class.
981    DeclarationName Name
982      = Context.DeclarationNames.getCXXDestructorName(ClassType);
983    CXXDestructorDecl *Destructor
984      = CXXDestructorDecl::Create(Context, ClassDecl,
985                                  ClassDecl->getLocation(), Name,
986                                  Context.getFunctionType(Context.VoidTy,
987                                                          0, 0, false, 0),
988                                  /*isInline=*/true,
989                                  /*isImplicitlyDeclared=*/true);
990    Destructor->setAccess(AS_public);
991    Destructor->setImplicit();
992    ClassDecl->addDecl(Destructor);
993  }
994}
995
996/// ActOnStartDelayedCXXMethodDeclaration - We have completed
997/// parsing a top-level (non-nested) C++ class, and we are now
998/// parsing those parts of the given Method declaration that could
999/// not be parsed earlier (C++ [class.mem]p2), such as default
1000/// arguments. This action should enter the scope of the given
1001/// Method declaration as if we had just parsed the qualified method
1002/// name. However, it should not bring the parameters into scope;
1003/// that will be performed by ActOnDelayedCXXMethodParameter.
1004void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) {
1005  CXXScopeSpec SS;
1006  SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext());
1007  ActOnCXXEnterDeclaratorScope(S, SS);
1008}
1009
1010/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1011/// C++ method declaration. We're (re-)introducing the given
1012/// function parameter into scope for use in parsing later parts of
1013/// the method declaration. For example, we could see an
1014/// ActOnParamDefaultArgument event for this parameter.
1015void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
1016  ParmVarDecl *Param = (ParmVarDecl*)ParamD;
1017
1018  // If this parameter has an unparsed default argument, clear it out
1019  // to make way for the parsed default argument.
1020  if (Param->hasUnparsedDefaultArg())
1021    Param->setDefaultArg(0);
1022
1023  S->AddDecl(Param);
1024  if (Param->getDeclName())
1025    IdResolver.AddDecl(Param);
1026}
1027
1028/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1029/// processing the delayed method declaration for Method. The method
1030/// declaration is now considered finished. There may be a separate
1031/// ActOnStartOfFunctionDef action later (not necessarily
1032/// immediately!) for this method, if it was also defined inside the
1033/// class body.
1034void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
1035  FunctionDecl *Method = (FunctionDecl*)MethodD;
1036  CXXScopeSpec SS;
1037  SS.setScopeRep(Method->getDeclContext());
1038  ActOnCXXExitDeclaratorScope(S, SS);
1039
1040  // Now that we have our default arguments, check the constructor
1041  // again. It could produce additional diagnostics or affect whether
1042  // the class has implicitly-declared destructors, among other
1043  // things.
1044  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
1045    if (CheckConstructor(Constructor))
1046      Constructor->setInvalidDecl();
1047  }
1048
1049  // Check the default arguments, which we may have added.
1050  if (!Method->isInvalidDecl())
1051    CheckCXXDefaultArguments(Method);
1052}
1053
1054/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
1055/// the well-formedness of the constructor declarator @p D with type @p
1056/// R. If there are any errors in the declarator, this routine will
1057/// emit diagnostics and return true. Otherwise, it will return
1058/// false. Either way, the type @p R will be updated to reflect a
1059/// well-formed type for the constructor.
1060bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
1061                                      FunctionDecl::StorageClass& SC) {
1062  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1063  bool isInvalid = false;
1064
1065  // C++ [class.ctor]p3:
1066  //   A constructor shall not be virtual (10.3) or static (9.4). A
1067  //   constructor can be invoked for a const, volatile or const
1068  //   volatile object. A constructor shall not be declared const,
1069  //   volatile, or const volatile (9.3.2).
1070  if (isVirtual) {
1071    Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1072      << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1073      << SourceRange(D.getIdentifierLoc());
1074    isInvalid = true;
1075  }
1076  if (SC == FunctionDecl::Static) {
1077    Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1078      << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1079      << SourceRange(D.getIdentifierLoc());
1080    isInvalid = true;
1081    SC = FunctionDecl::None;
1082  }
1083  if (D.getDeclSpec().hasTypeSpecifier()) {
1084    // Constructors don't have return types, but the parser will
1085    // happily parse something like:
1086    //
1087    //   class X {
1088    //     float X(float);
1089    //   };
1090    //
1091    // The return type will be eliminated later.
1092    Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
1093      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1094      << SourceRange(D.getIdentifierLoc());
1095  }
1096  if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
1097    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1098    if (FTI.TypeQuals & QualType::Const)
1099      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1100        << "const" << SourceRange(D.getIdentifierLoc());
1101    if (FTI.TypeQuals & QualType::Volatile)
1102      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1103        << "volatile" << SourceRange(D.getIdentifierLoc());
1104    if (FTI.TypeQuals & QualType::Restrict)
1105      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1106        << "restrict" << SourceRange(D.getIdentifierLoc());
1107  }
1108
1109  // Rebuild the function type "R" without any type qualifiers (in
1110  // case any of the errors above fired) and with "void" as the
1111  // return type, since constructors don't have return types. We
1112  // *always* have to do this, because GetTypeForDeclarator will
1113  // put in a result type of "int" when none was specified.
1114  const FunctionProtoType *Proto = R->getAsFunctionProtoType();
1115  R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1116                              Proto->getNumArgs(),
1117                              Proto->isVariadic(),
1118                              0);
1119
1120  return isInvalid;
1121}
1122
1123/// CheckConstructor - Checks a fully-formed constructor for
1124/// well-formedness, issuing any diagnostics required. Returns true if
1125/// the constructor declarator is invalid.
1126bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1127  if (Constructor->isInvalidDecl())
1128    return true;
1129
1130  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1131  bool Invalid = false;
1132
1133  // C++ [class.copy]p3:
1134  //   A declaration of a constructor for a class X is ill-formed if
1135  //   its first parameter is of type (optionally cv-qualified) X and
1136  //   either there are no other parameters or else all other
1137  //   parameters have default arguments.
1138  if ((Constructor->getNumParams() == 1) ||
1139      (Constructor->getNumParams() > 1 &&
1140       Constructor->getParamDecl(1)->getDefaultArg() != 0)) {
1141    QualType ParamType = Constructor->getParamDecl(0)->getType();
1142    QualType ClassTy = Context.getTagDeclType(ClassDecl);
1143    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1144      Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1145        << SourceRange(Constructor->getParamDecl(0)->getLocation());
1146      Invalid = true;
1147    }
1148  }
1149
1150  // Notify the class that we've added a constructor.
1151  ClassDecl->addedConstructor(Context, Constructor);
1152
1153  return Invalid;
1154}
1155
1156/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1157/// the well-formednes of the destructor declarator @p D with type @p
1158/// R. If there are any errors in the declarator, this routine will
1159/// emit diagnostics and return true. Otherwise, it will return
1160/// false. Either way, the type @p R will be updated to reflect a
1161/// well-formed type for the destructor.
1162bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1163                                     FunctionDecl::StorageClass& SC) {
1164  bool isInvalid = false;
1165
1166  // C++ [class.dtor]p1:
1167  //   [...] A typedef-name that names a class is a class-name
1168  //   (7.1.3); however, a typedef-name that names a class shall not
1169  //   be used as the identifier in the declarator for a destructor
1170  //   declaration.
1171  QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1172  if (DeclaratorType->getAsTypedefType()) {
1173    Diag(D.getIdentifierLoc(),  diag::err_destructor_typedef_name)
1174      << DeclaratorType;
1175    isInvalid = true;
1176  }
1177
1178  // C++ [class.dtor]p2:
1179  //   A destructor is used to destroy objects of its class type. A
1180  //   destructor takes no parameters, and no return type can be
1181  //   specified for it (not even void). The address of a destructor
1182  //   shall not be taken. A destructor shall not be static. A
1183  //   destructor can be invoked for a const, volatile or const
1184  //   volatile object. A destructor shall not be declared const,
1185  //   volatile or const volatile (9.3.2).
1186  if (SC == FunctionDecl::Static) {
1187    Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1188      << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1189      << SourceRange(D.getIdentifierLoc());
1190    isInvalid = true;
1191    SC = FunctionDecl::None;
1192  }
1193  if (D.getDeclSpec().hasTypeSpecifier()) {
1194    // Destructors don't have return types, but the parser will
1195    // happily parse something like:
1196    //
1197    //   class X {
1198    //     float ~X();
1199    //   };
1200    //
1201    // The return type will be eliminated later.
1202    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1203      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1204      << SourceRange(D.getIdentifierLoc());
1205  }
1206  if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
1207    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1208    if (FTI.TypeQuals & QualType::Const)
1209      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1210        << "const" << SourceRange(D.getIdentifierLoc());
1211    if (FTI.TypeQuals & QualType::Volatile)
1212      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1213        << "volatile" << SourceRange(D.getIdentifierLoc());
1214    if (FTI.TypeQuals & QualType::Restrict)
1215      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1216        << "restrict" << SourceRange(D.getIdentifierLoc());
1217  }
1218
1219  // Make sure we don't have any parameters.
1220  if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
1221    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1222
1223    // Delete the parameters.
1224    D.getTypeObject(0).Fun.freeArgs();
1225  }
1226
1227  // Make sure the destructor isn't variadic.
1228  if (R->getAsFunctionProtoType()->isVariadic())
1229    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1230
1231  // Rebuild the function type "R" without any type qualifiers or
1232  // parameters (in case any of the errors above fired) and with
1233  // "void" as the return type, since destructors don't have return
1234  // types. We *always* have to do this, because GetTypeForDeclarator
1235  // will put in a result type of "int" when none was specified.
1236  R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1237
1238  return isInvalid;
1239}
1240
1241/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1242/// well-formednes of the conversion function declarator @p D with
1243/// type @p R. If there are any errors in the declarator, this routine
1244/// will emit diagnostics and return true. Otherwise, it will return
1245/// false. Either way, the type @p R will be updated to reflect a
1246/// well-formed type for the conversion operator.
1247bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1248                                     FunctionDecl::StorageClass& SC) {
1249  bool isInvalid = false;
1250
1251  // C++ [class.conv.fct]p1:
1252  //   Neither parameter types nor return type can be specified. The
1253  //   type of a conversion function (8.3.5) is “function taking no
1254  //   parameter returning conversion-type-id.”
1255  if (SC == FunctionDecl::Static) {
1256    Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1257      << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1258      << SourceRange(D.getIdentifierLoc());
1259    isInvalid = true;
1260    SC = FunctionDecl::None;
1261  }
1262  if (D.getDeclSpec().hasTypeSpecifier()) {
1263    // Conversion functions don't have return types, but the parser will
1264    // happily parse something like:
1265    //
1266    //   class X {
1267    //     float operator bool();
1268    //   };
1269    //
1270    // The return type will be changed later anyway.
1271    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1272      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1273      << SourceRange(D.getIdentifierLoc());
1274  }
1275
1276  // Make sure we don't have any parameters.
1277  if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
1278    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1279
1280    // Delete the parameters.
1281    D.getTypeObject(0).Fun.freeArgs();
1282  }
1283
1284  // Make sure the conversion function isn't variadic.
1285  if (R->getAsFunctionProtoType()->isVariadic())
1286    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1287
1288  // C++ [class.conv.fct]p4:
1289  //   The conversion-type-id shall not represent a function type nor
1290  //   an array type.
1291  QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1292  if (ConvType->isArrayType()) {
1293    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1294    ConvType = Context.getPointerType(ConvType);
1295  } else if (ConvType->isFunctionType()) {
1296    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1297    ConvType = Context.getPointerType(ConvType);
1298  }
1299
1300  // Rebuild the function type "R" without any parameters (in case any
1301  // of the errors above fired) and with the conversion type as the
1302  // return type.
1303  R = Context.getFunctionType(ConvType, 0, 0, false,
1304                              R->getAsFunctionProtoType()->getTypeQuals());
1305
1306  // C++0x explicit conversion operators.
1307  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1308    Diag(D.getDeclSpec().getExplicitSpecLoc(),
1309         diag::warn_explicit_conversion_functions)
1310      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1311
1312  return isInvalid;
1313}
1314
1315/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1316/// the declaration of the given C++ conversion function. This routine
1317/// is responsible for recording the conversion function in the C++
1318/// class, if possible.
1319Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1320  assert(Conversion && "Expected to receive a conversion function declaration");
1321
1322  // Set the lexical context of this conversion function
1323  Conversion->setLexicalDeclContext(CurContext);
1324
1325  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
1326
1327  // Make sure we aren't redeclaring the conversion function.
1328  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
1329
1330  // C++ [class.conv.fct]p1:
1331  //   [...] A conversion function is never used to convert a
1332  //   (possibly cv-qualified) object to the (possibly cv-qualified)
1333  //   same object type (or a reference to it), to a (possibly
1334  //   cv-qualified) base class of that type (or a reference to it),
1335  //   or to (possibly cv-qualified) void.
1336  // FIXME: Suppress this warning if the conversion function ends up
1337  // being a virtual function that overrides a virtual function in a
1338  // base class.
1339  QualType ClassType
1340    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1341  if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1342    ConvType = ConvTypeRef->getPointeeType();
1343  if (ConvType->isRecordType()) {
1344    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1345    if (ConvType == ClassType)
1346      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
1347        << ClassType;
1348    else if (IsDerivedFrom(ClassType, ConvType))
1349      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
1350        <<  ClassType << ConvType;
1351  } else if (ConvType->isVoidType()) {
1352    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
1353      << ClassType << ConvType;
1354  }
1355
1356  if (Conversion->getPreviousDeclaration()) {
1357    OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1358    for (OverloadedFunctionDecl::function_iterator
1359           Conv = Conversions->function_begin(),
1360           ConvEnd = Conversions->function_end();
1361         Conv != ConvEnd; ++Conv) {
1362      if (*Conv == Conversion->getPreviousDeclaration()) {
1363        *Conv = Conversion;
1364        return (DeclTy *)Conversion;
1365      }
1366    }
1367    assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1368  } else
1369    ClassDecl->addConversionFunction(Context, Conversion);
1370
1371  return (DeclTy *)Conversion;
1372}
1373
1374//===----------------------------------------------------------------------===//
1375// Namespace Handling
1376//===----------------------------------------------------------------------===//
1377
1378/// ActOnStartNamespaceDef - This is called at the start of a namespace
1379/// definition.
1380Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1381                                           SourceLocation IdentLoc,
1382                                           IdentifierInfo *II,
1383                                           SourceLocation LBrace) {
1384  NamespaceDecl *Namespc =
1385      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1386  Namespc->setLBracLoc(LBrace);
1387
1388  Scope *DeclRegionScope = NamespcScope->getParent();
1389
1390  if (II) {
1391    // C++ [namespace.def]p2:
1392    // The identifier in an original-namespace-definition shall not have been
1393    // previously defined in the declarative region in which the
1394    // original-namespace-definition appears. The identifier in an
1395    // original-namespace-definition is the name of the namespace. Subsequently
1396    // in that declarative region, it is treated as an original-namespace-name.
1397
1398    NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1399                                     true);
1400
1401    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1402      // This is an extended namespace definition.
1403      // Attach this namespace decl to the chain of extended namespace
1404      // definitions.
1405      OrigNS->setNextNamespace(Namespc);
1406      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
1407
1408      // Remove the previous declaration from the scope.
1409      if (DeclRegionScope->isDeclScope(OrigNS)) {
1410        IdResolver.RemoveDecl(OrigNS);
1411        DeclRegionScope->RemoveDecl(OrigNS);
1412      }
1413    } else if (PrevDecl) {
1414      // This is an invalid name redefinition.
1415      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1416       << Namespc->getDeclName();
1417      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1418      Namespc->setInvalidDecl();
1419      // Continue on to push Namespc as current DeclContext and return it.
1420    }
1421
1422    PushOnScopeChains(Namespc, DeclRegionScope);
1423  } else {
1424    // FIXME: Handle anonymous namespaces
1425  }
1426
1427  // Although we could have an invalid decl (i.e. the namespace name is a
1428  // redefinition), push it as current DeclContext and try to continue parsing.
1429  // FIXME: We should be able to push Namespc here, so that the
1430  // each DeclContext for the namespace has the declarations
1431  // that showed up in that particular namespace definition.
1432  PushDeclContext(NamespcScope, Namespc);
1433  return Namespc;
1434}
1435
1436/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1437/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1438void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1439  Decl *Dcl = static_cast<Decl *>(D);
1440  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1441  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1442  Namespc->setRBracLoc(RBrace);
1443  PopDeclContext();
1444}
1445
1446Sema::DeclTy *Sema::ActOnUsingDirective(Scope *S,
1447                                        SourceLocation UsingLoc,
1448                                        SourceLocation NamespcLoc,
1449                                        const CXXScopeSpec &SS,
1450                                        SourceLocation IdentLoc,
1451                                        IdentifierInfo *NamespcName,
1452                                        AttributeList *AttrList) {
1453  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1454  assert(NamespcName && "Invalid NamespcName.");
1455  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
1456  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
1457
1458  UsingDirectiveDecl *UDir = 0;
1459
1460  // Lookup namespace name.
1461  LookupResult R = LookupParsedName(S, &SS, NamespcName,
1462                                    LookupNamespaceName, false);
1463  if (R.isAmbiguous()) {
1464    DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
1465    return 0;
1466  }
1467  if (NamedDecl *NS = R) {
1468    assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
1469    // C++ [namespace.udir]p1:
1470    //   A using-directive specifies that the names in the nominated
1471    //   namespace can be used in the scope in which the
1472    //   using-directive appears after the using-directive. During
1473    //   unqualified name lookup (3.4.1), the names appear as if they
1474    //   were declared in the nearest enclosing namespace which
1475    //   contains both the using-directive and the nominated
1476    //   namespace. [Note: in this context, “contains” means “contains
1477    //   directly or indirectly”. ]
1478
1479    // Find enclosing context containing both using-directive and
1480    // nominated namespace.
1481    DeclContext *CommonAncestor = cast<DeclContext>(NS);
1482    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1483      CommonAncestor = CommonAncestor->getParent();
1484
1485    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc,
1486                                      NamespcLoc, IdentLoc,
1487                                      cast<NamespaceDecl>(NS),
1488                                      CommonAncestor);
1489    PushUsingDirective(S, UDir);
1490  } else {
1491    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
1492  }
1493
1494  // FIXME: We ignore attributes for now.
1495  delete AttrList;
1496  return UDir;
1497}
1498
1499void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1500  // If scope has associated entity, then using directive is at namespace
1501  // or translation unit scope. We add UsingDirectiveDecls, into
1502  // it's lookup structure.
1503  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
1504    Ctx->addDecl(UDir);
1505  else
1506    // Otherwise it is block-sope. using-directives will affect lookup
1507    // only to the end of scope.
1508    S->PushUsingDirective(UDir);
1509}
1510
1511/// AddCXXDirectInitializerToDecl - This action is called immediately after
1512/// ActOnDeclarator, when a C++ direct initializer is present.
1513/// e.g: "int x(1);"
1514void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1515                                         ExprTy **ExprTys, unsigned NumExprs,
1516                                         SourceLocation *CommaLocs,
1517                                         SourceLocation RParenLoc) {
1518  assert(NumExprs != 0 && ExprTys && "missing expressions");
1519  Decl *RealDecl = static_cast<Decl *>(Dcl);
1520
1521  // If there is no declaration, there was an error parsing it.  Just ignore
1522  // the initializer.
1523  if (RealDecl == 0) {
1524    for (unsigned i = 0; i != NumExprs; ++i)
1525      static_cast<Expr *>(ExprTys[i])->Destroy(Context);
1526    return;
1527  }
1528
1529  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1530  if (!VDecl) {
1531    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1532    RealDecl->setInvalidDecl();
1533    return;
1534  }
1535
1536  // We will treat direct-initialization as a copy-initialization:
1537  //    int x(1);  -as-> int x = 1;
1538  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1539  //
1540  // Clients that want to distinguish between the two forms, can check for
1541  // direct initializer using VarDecl::hasCXXDirectInitializer().
1542  // A major benefit is that clients that don't particularly care about which
1543  // exactly form was it (like the CodeGen) can handle both cases without
1544  // special case code.
1545
1546  // C++ 8.5p11:
1547  // The form of initialization (using parentheses or '=') is generally
1548  // insignificant, but does matter when the entity being initialized has a
1549  // class type.
1550  QualType DeclInitType = VDecl->getType();
1551  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1552    DeclInitType = Array->getElementType();
1553
1554  if (VDecl->getType()->isRecordType()) {
1555    CXXConstructorDecl *Constructor
1556      = PerformInitializationByConstructor(DeclInitType,
1557                                           (Expr **)ExprTys, NumExprs,
1558                                           VDecl->getLocation(),
1559                                           SourceRange(VDecl->getLocation(),
1560                                                       RParenLoc),
1561                                           VDecl->getDeclName(),
1562                                           IK_Direct);
1563    if (!Constructor) {
1564      RealDecl->setInvalidDecl();
1565    }
1566
1567    // Let clients know that initialization was done with a direct
1568    // initializer.
1569    VDecl->setCXXDirectInitializer(true);
1570
1571    // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1572    // the initializer.
1573    return;
1574  }
1575
1576  if (NumExprs > 1) {
1577    Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1578      << SourceRange(VDecl->getLocation(), RParenLoc);
1579    RealDecl->setInvalidDecl();
1580    return;
1581  }
1582
1583  // Let clients know that initialization was done with a direct initializer.
1584  VDecl->setCXXDirectInitializer(true);
1585
1586  assert(NumExprs == 1 && "Expected 1 expression");
1587  // Set the init expression, handles conversions.
1588  AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]), /*DirectInit=*/true);
1589}
1590
1591/// PerformInitializationByConstructor - Perform initialization by
1592/// constructor (C++ [dcl.init]p14), which may occur as part of
1593/// direct-initialization or copy-initialization. We are initializing
1594/// an object of type @p ClassType with the given arguments @p
1595/// Args. @p Loc is the location in the source code where the
1596/// initializer occurs (e.g., a declaration, member initializer,
1597/// functional cast, etc.) while @p Range covers the whole
1598/// initialization. @p InitEntity is the entity being initialized,
1599/// which may by the name of a declaration or a type. @p Kind is the
1600/// kind of initialization we're performing, which affects whether
1601/// explicit constructors will be considered. When successful, returns
1602/// the constructor that will be used to perform the initialization;
1603/// when the initialization fails, emits a diagnostic and returns
1604/// null.
1605CXXConstructorDecl *
1606Sema::PerformInitializationByConstructor(QualType ClassType,
1607                                         Expr **Args, unsigned NumArgs,
1608                                         SourceLocation Loc, SourceRange Range,
1609                                         DeclarationName InitEntity,
1610                                         InitializationKind Kind) {
1611  const RecordType *ClassRec = ClassType->getAsRecordType();
1612  assert(ClassRec && "Can only initialize a class type here");
1613
1614  // C++ [dcl.init]p14:
1615  //
1616  //   If the initialization is direct-initialization, or if it is
1617  //   copy-initialization where the cv-unqualified version of the
1618  //   source type is the same class as, or a derived class of, the
1619  //   class of the destination, constructors are considered. The
1620  //   applicable constructors are enumerated (13.3.1.3), and the
1621  //   best one is chosen through overload resolution (13.3). The
1622  //   constructor so selected is called to initialize the object,
1623  //   with the initializer expression(s) as its argument(s). If no
1624  //   constructor applies, or the overload resolution is ambiguous,
1625  //   the initialization is ill-formed.
1626  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1627  OverloadCandidateSet CandidateSet;
1628
1629  // Add constructors to the overload set.
1630  DeclarationName ConstructorName
1631    = Context.DeclarationNames.getCXXConstructorName(
1632                       Context.getCanonicalType(ClassType.getUnqualifiedType()));
1633  DeclContext::lookup_const_iterator Con, ConEnd;
1634  for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
1635       Con != ConEnd; ++Con) {
1636    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1637    if ((Kind == IK_Direct) ||
1638        (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1639        (Kind == IK_Default && Constructor->isDefaultConstructor()))
1640      AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1641  }
1642
1643  // FIXME: When we decide not to synthesize the implicitly-declared
1644  // constructors, we'll need to make them appear here.
1645
1646  OverloadCandidateSet::iterator Best;
1647  switch (BestViableFunction(CandidateSet, Best)) {
1648  case OR_Success:
1649    // We found a constructor. Return it.
1650    return cast<CXXConstructorDecl>(Best->Function);
1651
1652  case OR_No_Viable_Function:
1653    if (InitEntity)
1654      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1655        << InitEntity << Range;
1656    else
1657      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1658        << ClassType << Range;
1659    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1660    return 0;
1661
1662  case OR_Ambiguous:
1663    if (InitEntity)
1664      Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
1665    else
1666      Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
1667    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1668    return 0;
1669
1670  case OR_Deleted:
1671    if (InitEntity)
1672      Diag(Loc, diag::err_ovl_deleted_init)
1673        << Best->Function->isDeleted()
1674        << InitEntity << Range;
1675    else
1676      Diag(Loc, diag::err_ovl_deleted_init)
1677        << Best->Function->isDeleted()
1678        << InitEntity << Range;
1679    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1680    return 0;
1681  }
1682
1683  return 0;
1684}
1685
1686/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1687/// determine whether they are reference-related,
1688/// reference-compatible, reference-compatible with added
1689/// qualification, or incompatible, for use in C++ initialization by
1690/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1691/// type, and the first type (T1) is the pointee type of the reference
1692/// type being initialized.
1693Sema::ReferenceCompareResult
1694Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1695                                   bool& DerivedToBase) {
1696  assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1697  assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1698
1699  T1 = Context.getCanonicalType(T1);
1700  T2 = Context.getCanonicalType(T2);
1701  QualType UnqualT1 = T1.getUnqualifiedType();
1702  QualType UnqualT2 = T2.getUnqualifiedType();
1703
1704  // C++ [dcl.init.ref]p4:
1705  //   Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1706  //   reference-related to “cv2 T2” if T1 is the same type as T2, or
1707  //   T1 is a base class of T2.
1708  if (UnqualT1 == UnqualT2)
1709    DerivedToBase = false;
1710  else if (IsDerivedFrom(UnqualT2, UnqualT1))
1711    DerivedToBase = true;
1712  else
1713    return Ref_Incompatible;
1714
1715  // At this point, we know that T1 and T2 are reference-related (at
1716  // least).
1717
1718  // C++ [dcl.init.ref]p4:
1719  //   "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1720  //   reference-related to T2 and cv1 is the same cv-qualification
1721  //   as, or greater cv-qualification than, cv2. For purposes of
1722  //   overload resolution, cases for which cv1 is greater
1723  //   cv-qualification than cv2 are identified as
1724  //   reference-compatible with added qualification (see 13.3.3.2).
1725  if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1726    return Ref_Compatible;
1727  else if (T1.isMoreQualifiedThan(T2))
1728    return Ref_Compatible_With_Added_Qualification;
1729  else
1730    return Ref_Related;
1731}
1732
1733/// CheckReferenceInit - Check the initialization of a reference
1734/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1735/// the initializer (either a simple initializer or an initializer
1736/// list), and DeclType is the type of the declaration. When ICS is
1737/// non-null, this routine will compute the implicit conversion
1738/// sequence according to C++ [over.ics.ref] and will not produce any
1739/// diagnostics; when ICS is null, it will emit diagnostics when any
1740/// errors are found. Either way, a return value of true indicates
1741/// that there was a failure, a return value of false indicates that
1742/// the reference initialization succeeded.
1743///
1744/// When @p SuppressUserConversions, user-defined conversions are
1745/// suppressed.
1746/// When @p AllowExplicit, we also permit explicit user-defined
1747/// conversion functions.
1748bool
1749Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
1750                         ImplicitConversionSequence *ICS,
1751                         bool SuppressUserConversions,
1752                         bool AllowExplicit) {
1753  assert(DeclType->isReferenceType() && "Reference init needs a reference");
1754
1755  QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1756  QualType T2 = Init->getType();
1757
1758  // If the initializer is the address of an overloaded function, try
1759  // to resolve the overloaded function. If all goes well, T2 is the
1760  // type of the resulting function.
1761  if (T2->isOverloadType()) {
1762    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1763                                                          ICS != 0);
1764    if (Fn) {
1765      // Since we're performing this reference-initialization for
1766      // real, update the initializer with the resulting function.
1767      if (!ICS) {
1768        if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
1769          return true;
1770
1771        FixOverloadedFunctionReference(Init, Fn);
1772      }
1773
1774      T2 = Fn->getType();
1775    }
1776  }
1777
1778  // Compute some basic properties of the types and the initializer.
1779  bool DerivedToBase = false;
1780  Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
1781  ReferenceCompareResult RefRelationship
1782    = CompareReferenceRelationship(T1, T2, DerivedToBase);
1783
1784  // Most paths end in a failed conversion.
1785  if (ICS)
1786    ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
1787
1788  // C++ [dcl.init.ref]p5:
1789  //   A reference to type “cv1 T1” is initialized by an expression
1790  //   of type “cv2 T2” as follows:
1791
1792  //     -- If the initializer expression
1793
1794  bool BindsDirectly = false;
1795  //       -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1796  //          reference-compatible with “cv2 T2,” or
1797  //
1798  // Note that the bit-field check is skipped if we are just computing
1799  // the implicit conversion sequence (C++ [over.best.ics]p2).
1800  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1801      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1802    BindsDirectly = true;
1803
1804    if (ICS) {
1805      // C++ [over.ics.ref]p1:
1806      //   When a parameter of reference type binds directly (8.5.3)
1807      //   to an argument expression, the implicit conversion sequence
1808      //   is the identity conversion, unless the argument expression
1809      //   has a type that is a derived class of the parameter type,
1810      //   in which case the implicit conversion sequence is a
1811      //   derived-to-base Conversion (13.3.3.1).
1812      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1813      ICS->Standard.First = ICK_Identity;
1814      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1815      ICS->Standard.Third = ICK_Identity;
1816      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1817      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
1818      ICS->Standard.ReferenceBinding = true;
1819      ICS->Standard.DirectBinding = true;
1820
1821      // Nothing more to do: the inaccessibility/ambiguity check for
1822      // derived-to-base conversions is suppressed when we're
1823      // computing the implicit conversion sequence (C++
1824      // [over.best.ics]p2).
1825      return false;
1826    } else {
1827      // Perform the conversion.
1828      // FIXME: Binding to a subobject of the lvalue is going to require
1829      // more AST annotation than this.
1830      ImpCastExprToType(Init, T1, /*isLvalue=*/true);
1831    }
1832  }
1833
1834  //       -- has a class type (i.e., T2 is a class type) and can be
1835  //          implicitly converted to an lvalue of type “cv3 T3,”
1836  //          where “cv1 T1” is reference-compatible with “cv3 T3”
1837  //          92) (this conversion is selected by enumerating the
1838  //          applicable conversion functions (13.3.1.6) and choosing
1839  //          the best one through overload resolution (13.3)),
1840  if (!SuppressUserConversions && T2->isRecordType()) {
1841    // FIXME: Look for conversions in base classes!
1842    CXXRecordDecl *T2RecordDecl
1843      = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
1844
1845    OverloadCandidateSet CandidateSet;
1846    OverloadedFunctionDecl *Conversions
1847      = T2RecordDecl->getConversionFunctions();
1848    for (OverloadedFunctionDecl::function_iterator Func
1849           = Conversions->function_begin();
1850         Func != Conversions->function_end(); ++Func) {
1851      CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1852
1853      // If the conversion function doesn't return a reference type,
1854      // it can't be considered for this conversion.
1855      // FIXME: This will change when we support rvalue references.
1856      if (Conv->getConversionType()->isReferenceType() &&
1857          (AllowExplicit || !Conv->isExplicit()))
1858        AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1859    }
1860
1861    OverloadCandidateSet::iterator Best;
1862    switch (BestViableFunction(CandidateSet, Best)) {
1863    case OR_Success:
1864      // This is a direct binding.
1865      BindsDirectly = true;
1866
1867      if (ICS) {
1868        // C++ [over.ics.ref]p1:
1869        //
1870        //   [...] If the parameter binds directly to the result of
1871        //   applying a conversion function to the argument
1872        //   expression, the implicit conversion sequence is a
1873        //   user-defined conversion sequence (13.3.3.1.2), with the
1874        //   second standard conversion sequence either an identity
1875        //   conversion or, if the conversion function returns an
1876        //   entity of a type that is a derived class of the parameter
1877        //   type, a derived-to-base Conversion.
1878        ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1879        ICS->UserDefined.Before = Best->Conversions[0].Standard;
1880        ICS->UserDefined.After = Best->FinalConversion;
1881        ICS->UserDefined.ConversionFunction = Best->Function;
1882        assert(ICS->UserDefined.After.ReferenceBinding &&
1883               ICS->UserDefined.After.DirectBinding &&
1884               "Expected a direct reference binding!");
1885        return false;
1886      } else {
1887        // Perform the conversion.
1888        // FIXME: Binding to a subobject of the lvalue is going to require
1889        // more AST annotation than this.
1890        ImpCastExprToType(Init, T1, /*isLvalue=*/true);
1891      }
1892      break;
1893
1894    case OR_Ambiguous:
1895      assert(false && "Ambiguous reference binding conversions not implemented.");
1896      return true;
1897
1898    case OR_No_Viable_Function:
1899    case OR_Deleted:
1900      // There was no suitable conversion, or we found a deleted
1901      // conversion; continue with other checks.
1902      break;
1903    }
1904  }
1905
1906  if (BindsDirectly) {
1907    // C++ [dcl.init.ref]p4:
1908    //   [...] In all cases where the reference-related or
1909    //   reference-compatible relationship of two types is used to
1910    //   establish the validity of a reference binding, and T1 is a
1911    //   base class of T2, a program that necessitates such a binding
1912    //   is ill-formed if T1 is an inaccessible (clause 11) or
1913    //   ambiguous (10.2) base class of T2.
1914    //
1915    // Note that we only check this condition when we're allowed to
1916    // complain about errors, because we should not be checking for
1917    // ambiguity (or inaccessibility) unless the reference binding
1918    // actually happens.
1919    if (DerivedToBase)
1920      return CheckDerivedToBaseConversion(T2, T1,
1921                                          Init->getSourceRange().getBegin(),
1922                                          Init->getSourceRange());
1923    else
1924      return false;
1925  }
1926
1927  //     -- Otherwise, the reference shall be to a non-volatile const
1928  //        type (i.e., cv1 shall be const).
1929  if (T1.getCVRQualifiers() != QualType::Const) {
1930    if (!ICS)
1931      Diag(Init->getSourceRange().getBegin(),
1932           diag::err_not_reference_to_const_init)
1933        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1934        << T2 << Init->getSourceRange();
1935    return true;
1936  }
1937
1938  //       -- If the initializer expression is an rvalue, with T2 a
1939  //          class type, and “cv1 T1” is reference-compatible with
1940  //          “cv2 T2,” the reference is bound in one of the
1941  //          following ways (the choice is implementation-defined):
1942  //
1943  //          -- The reference is bound to the object represented by
1944  //             the rvalue (see 3.10) or to a sub-object within that
1945  //             object.
1946  //
1947  //          -- A temporary of type “cv1 T2” [sic] is created, and
1948  //             a constructor is called to copy the entire rvalue
1949  //             object into the temporary. The reference is bound to
1950  //             the temporary or to a sub-object within the
1951  //             temporary.
1952  //
1953  //          The constructor that would be used to make the copy
1954  //          shall be callable whether or not the copy is actually
1955  //          done.
1956  //
1957  // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1958  // freedom, so we will always take the first option and never build
1959  // a temporary in this case. FIXME: We will, however, have to check
1960  // for the presence of a copy constructor in C++98/03 mode.
1961  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
1962      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1963    if (ICS) {
1964      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1965      ICS->Standard.First = ICK_Identity;
1966      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1967      ICS->Standard.Third = ICK_Identity;
1968      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1969      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
1970      ICS->Standard.ReferenceBinding = true;
1971      ICS->Standard.DirectBinding = false;
1972    } else {
1973      // FIXME: Binding to a subobject of the rvalue is going to require
1974      // more AST annotation than this.
1975      ImpCastExprToType(Init, T1, /*isLvalue=*/true);
1976    }
1977    return false;
1978  }
1979
1980  //       -- Otherwise, a temporary of type “cv1 T1” is created and
1981  //          initialized from the initializer expression using the
1982  //          rules for a non-reference copy initialization (8.5). The
1983  //          reference is then bound to the temporary. If T1 is
1984  //          reference-related to T2, cv1 must be the same
1985  //          cv-qualification as, or greater cv-qualification than,
1986  //          cv2; otherwise, the program is ill-formed.
1987  if (RefRelationship == Ref_Related) {
1988    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1989    // we would be reference-compatible or reference-compatible with
1990    // added qualification. But that wasn't the case, so the reference
1991    // initialization fails.
1992    if (!ICS)
1993      Diag(Init->getSourceRange().getBegin(),
1994           diag::err_reference_init_drops_quals)
1995        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1996        << T2 << Init->getSourceRange();
1997    return true;
1998  }
1999
2000  // If at least one of the types is a class type, the types are not
2001  // related, and we aren't allowed any user conversions, the
2002  // reference binding fails. This case is important for breaking
2003  // recursion, since TryImplicitConversion below will attempt to
2004  // create a temporary through the use of a copy constructor.
2005  if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
2006      (T1->isRecordType() || T2->isRecordType())) {
2007    if (!ICS)
2008      Diag(Init->getSourceRange().getBegin(),
2009           diag::err_typecheck_convert_incompatible)
2010        << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
2011    return true;
2012  }
2013
2014  // Actually try to convert the initializer to T1.
2015  if (ICS) {
2016    /// C++ [over.ics.ref]p2:
2017    ///
2018    ///   When a parameter of reference type is not bound directly to
2019    ///   an argument expression, the conversion sequence is the one
2020    ///   required to convert the argument expression to the
2021    ///   underlying type of the reference according to
2022    ///   13.3.3.1. Conceptually, this conversion sequence corresponds
2023    ///   to copy-initializing a temporary of the underlying type with
2024    ///   the argument expression. Any difference in top-level
2025    ///   cv-qualification is subsumed by the initialization itself
2026    ///   and does not constitute a conversion.
2027    *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
2028    return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
2029  } else {
2030    return PerformImplicitConversion(Init, T1, "initializing");
2031  }
2032}
2033
2034/// CheckOverloadedOperatorDeclaration - Check whether the declaration
2035/// of this overloaded operator is well-formed. If so, returns false;
2036/// otherwise, emits appropriate diagnostics and returns true.
2037bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
2038  assert(FnDecl && FnDecl->isOverloadedOperator() &&
2039         "Expected an overloaded operator declaration");
2040
2041  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
2042
2043  // C++ [over.oper]p5:
2044  //   The allocation and deallocation functions, operator new,
2045  //   operator new[], operator delete and operator delete[], are
2046  //   described completely in 3.7.3. The attributes and restrictions
2047  //   found in the rest of this subclause do not apply to them unless
2048  //   explicitly stated in 3.7.3.
2049  // FIXME: Write a separate routine for checking this. For now, just
2050  // allow it.
2051  if (Op == OO_New || Op == OO_Array_New ||
2052      Op == OO_Delete || Op == OO_Array_Delete)
2053    return false;
2054
2055  // C++ [over.oper]p6:
2056  //   An operator function shall either be a non-static member
2057  //   function or be a non-member function and have at least one
2058  //   parameter whose type is a class, a reference to a class, an
2059  //   enumeration, or a reference to an enumeration.
2060  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
2061    if (MethodDecl->isStatic())
2062      return Diag(FnDecl->getLocation(),
2063                  diag::err_operator_overload_static) << FnDecl->getDeclName();
2064  } else {
2065    bool ClassOrEnumParam = false;
2066    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2067                                   ParamEnd = FnDecl->param_end();
2068         Param != ParamEnd; ++Param) {
2069      QualType ParamType = (*Param)->getType().getNonReferenceType();
2070      if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
2071        ClassOrEnumParam = true;
2072        break;
2073      }
2074    }
2075
2076    if (!ClassOrEnumParam)
2077      return Diag(FnDecl->getLocation(),
2078                  diag::err_operator_overload_needs_class_or_enum)
2079        << FnDecl->getDeclName();
2080  }
2081
2082  // C++ [over.oper]p8:
2083  //   An operator function cannot have default arguments (8.3.6),
2084  //   except where explicitly stated below.
2085  //
2086  // Only the function-call operator allows default arguments
2087  // (C++ [over.call]p1).
2088  if (Op != OO_Call) {
2089    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2090         Param != FnDecl->param_end(); ++Param) {
2091      if ((*Param)->hasUnparsedDefaultArg())
2092        return Diag((*Param)->getLocation(),
2093                    diag::err_operator_overload_default_arg)
2094          << FnDecl->getDeclName();
2095      else if (Expr *DefArg = (*Param)->getDefaultArg())
2096        return Diag((*Param)->getLocation(),
2097                    diag::err_operator_overload_default_arg)
2098          << FnDecl->getDeclName() << DefArg->getSourceRange();
2099    }
2100  }
2101
2102  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2103    { false, false, false }
2104#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2105    , { Unary, Binary, MemberOnly }
2106#include "clang/Basic/OperatorKinds.def"
2107  };
2108
2109  bool CanBeUnaryOperator = OperatorUses[Op][0];
2110  bool CanBeBinaryOperator = OperatorUses[Op][1];
2111  bool MustBeMemberOperator = OperatorUses[Op][2];
2112
2113  // C++ [over.oper]p8:
2114  //   [...] Operator functions cannot have more or fewer parameters
2115  //   than the number required for the corresponding operator, as
2116  //   described in the rest of this subclause.
2117  unsigned NumParams = FnDecl->getNumParams()
2118                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
2119  if (Op != OO_Call &&
2120      ((NumParams == 1 && !CanBeUnaryOperator) ||
2121       (NumParams == 2 && !CanBeBinaryOperator) ||
2122       (NumParams < 1) || (NumParams > 2))) {
2123    // We have the wrong number of parameters.
2124    unsigned ErrorKind;
2125    if (CanBeUnaryOperator && CanBeBinaryOperator) {
2126      ErrorKind = 2;  // 2 -> unary or binary.
2127    } else if (CanBeUnaryOperator) {
2128      ErrorKind = 0;  // 0 -> unary
2129    } else {
2130      assert(CanBeBinaryOperator &&
2131             "All non-call overloaded operators are unary or binary!");
2132      ErrorKind = 1;  // 1 -> binary
2133    }
2134
2135    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
2136      << FnDecl->getDeclName() << NumParams << ErrorKind;
2137  }
2138
2139  // Overloaded operators other than operator() cannot be variadic.
2140  if (Op != OO_Call &&
2141      FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
2142    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
2143      << FnDecl->getDeclName();
2144  }
2145
2146  // Some operators must be non-static member functions.
2147  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2148    return Diag(FnDecl->getLocation(),
2149                diag::err_operator_overload_must_be_member)
2150      << FnDecl->getDeclName();
2151  }
2152
2153  // C++ [over.inc]p1:
2154  //   The user-defined function called operator++ implements the
2155  //   prefix and postfix ++ operator. If this function is a member
2156  //   function with no parameters, or a non-member function with one
2157  //   parameter of class or enumeration type, it defines the prefix
2158  //   increment operator ++ for objects of that type. If the function
2159  //   is a member function with one parameter (which shall be of type
2160  //   int) or a non-member function with two parameters (the second
2161  //   of which shall be of type int), it defines the postfix
2162  //   increment operator ++ for objects of that type.
2163  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2164    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2165    bool ParamIsInt = false;
2166    if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2167      ParamIsInt = BT->getKind() == BuiltinType::Int;
2168
2169    if (!ParamIsInt)
2170      return Diag(LastParam->getLocation(),
2171                  diag::err_operator_overload_post_incdec_must_be_int)
2172        << LastParam->getType() << (Op == OO_MinusMinus);
2173  }
2174
2175  // Notify the class if it got an assignment operator.
2176  if (Op == OO_Equal) {
2177    // Would have returned earlier otherwise.
2178    assert(isa<CXXMethodDecl>(FnDecl) &&
2179      "Overloaded = not member, but not filtered.");
2180    CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2181    Method->getParent()->addedAssignmentOperator(Context, Method);
2182  }
2183
2184  return false;
2185}
2186
2187/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2188/// linkage specification, including the language and (if present)
2189/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2190/// the location of the language string literal, which is provided
2191/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2192/// the '{' brace. Otherwise, this linkage specification does not
2193/// have any braces.
2194Sema::DeclTy *Sema::ActOnStartLinkageSpecification(Scope *S,
2195                                                   SourceLocation ExternLoc,
2196                                                   SourceLocation LangLoc,
2197                                                   const char *Lang,
2198                                                   unsigned StrSize,
2199                                                   SourceLocation LBraceLoc) {
2200  LinkageSpecDecl::LanguageIDs Language;
2201  if (strncmp(Lang, "\"C\"", StrSize) == 0)
2202    Language = LinkageSpecDecl::lang_c;
2203  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2204    Language = LinkageSpecDecl::lang_cxx;
2205  else {
2206    Diag(LangLoc, diag::err_bad_language);
2207    return 0;
2208  }
2209
2210  // FIXME: Add all the various semantics of linkage specifications
2211
2212  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2213                                               LangLoc, Language,
2214                                               LBraceLoc.isValid());
2215  CurContext->addDecl(D);
2216  PushDeclContext(S, D);
2217  return D;
2218}
2219
2220/// ActOnFinishLinkageSpecification - Completely the definition of
2221/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2222/// valid, it's the position of the closing '}' brace in a linkage
2223/// specification that uses braces.
2224Sema::DeclTy *Sema::ActOnFinishLinkageSpecification(Scope *S,
2225                                                    DeclTy *LinkageSpec,
2226                                                    SourceLocation RBraceLoc) {
2227  if (LinkageSpec)
2228    PopDeclContext();
2229  return LinkageSpec;
2230}
2231
2232/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2233/// handler.
2234Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D)
2235{
2236  QualType ExDeclType = GetTypeForDeclarator(D, S);
2237  SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin();
2238
2239  bool Invalid = false;
2240
2241  // Arrays and functions decay.
2242  if (ExDeclType->isArrayType())
2243    ExDeclType = Context.getArrayDecayedType(ExDeclType);
2244  else if (ExDeclType->isFunctionType())
2245    ExDeclType = Context.getPointerType(ExDeclType);
2246
2247  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2248  // The exception-declaration shall not denote a pointer or reference to an
2249  // incomplete type, other than [cv] void*.
2250  QualType BaseType = ExDeclType;
2251  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
2252  unsigned DK = diag::err_catch_incomplete;
2253  if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2254    BaseType = Ptr->getPointeeType();
2255    Mode = 1;
2256    DK = diag::err_catch_incomplete_ptr;
2257  } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2258    BaseType = Ref->getPointeeType();
2259    Mode = 2;
2260    DK = diag::err_catch_incomplete_ref;
2261  }
2262  if ((Mode == 0 || !BaseType->isVoidType()) &&
2263      RequireCompleteType(Begin, BaseType, DK))
2264    Invalid = true;
2265
2266  // FIXME: Need to test for ability to copy-construct and destroy the
2267  // exception variable.
2268  // FIXME: Need to check for abstract classes.
2269
2270  IdentifierInfo *II = D.getIdentifier();
2271  if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
2272    // The scope should be freshly made just for us. There is just no way
2273    // it contains any previous declaration.
2274    assert(!S->isDeclScope(PrevDecl));
2275    if (PrevDecl->isTemplateParameter()) {
2276      // Maybe we will complain about the shadowed template parameter.
2277      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2278
2279    }
2280  }
2281
2282  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
2283                                    II, ExDeclType, VarDecl::None, Begin);
2284  if (D.getInvalidType() || Invalid)
2285    ExDecl->setInvalidDecl();
2286
2287  if (D.getCXXScopeSpec().isSet()) {
2288    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2289      << D.getCXXScopeSpec().getRange();
2290    ExDecl->setInvalidDecl();
2291  }
2292
2293  // Add the exception declaration into this scope.
2294  S->AddDecl(ExDecl);
2295  if (II)
2296    IdResolver.AddDecl(ExDecl);
2297
2298  ProcessDeclAttributes(ExDecl, D);
2299  return ExDecl;
2300}
2301