SemaDeclCXX.cpp revision 4681ebd429846ed98e7beaf49934fa347ff22152
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                                ExprArg defarg) {
109  ParmVarDecl *Param = (ParmVarDecl *)param;
110  ExprOwningPtr<Expr> DefaultArg(this, (Expr *)defarg.release());
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 && SS->isSet() && !SS->isInvalid()) {
303    DeclContext *DC = computeDeclContext(*SS);
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 (Init)
592    AddInitializerToDecl(Member, ExprArg(*this, Init), false);
593
594  if (isInstField) {
595    FieldCollector->Add(cast<FieldDecl>(Member));
596    return LastInGroup;
597  }
598  return Member;
599}
600
601/// ActOnMemInitializer - Handle a C++ member initializer.
602Sema::MemInitResult
603Sema::ActOnMemInitializer(DeclTy *ConstructorD,
604                          Scope *S,
605                          IdentifierInfo *MemberOrBase,
606                          SourceLocation IdLoc,
607                          SourceLocation LParenLoc,
608                          ExprTy **Args, unsigned NumArgs,
609                          SourceLocation *CommaLocs,
610                          SourceLocation RParenLoc) {
611  CXXConstructorDecl *Constructor
612    = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
613  if (!Constructor) {
614    // The user wrote a constructor initializer on a function that is
615    // not a C++ constructor. Ignore the error for now, because we may
616    // have more member initializers coming; we'll diagnose it just
617    // once in ActOnMemInitializers.
618    return true;
619  }
620
621  CXXRecordDecl *ClassDecl = Constructor->getParent();
622
623  // C++ [class.base.init]p2:
624  //   Names in a mem-initializer-id are looked up in the scope of the
625  //   constructor’s class and, if not found in that scope, are looked
626  //   up in the scope containing the constructor’s
627  //   definition. [Note: if the constructor’s class contains a member
628  //   with the same name as a direct or virtual base class of the
629  //   class, a mem-initializer-id naming the member or base class and
630  //   composed of a single identifier refers to the class member. A
631  //   mem-initializer-id for the hidden base class may be specified
632  //   using a qualified name. ]
633  // Look for a member, first.
634  FieldDecl *Member = 0;
635  DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
636  if (Result.first != Result.second)
637    Member = dyn_cast<FieldDecl>(*Result.first);
638
639  // FIXME: Handle members of an anonymous union.
640
641  if (Member) {
642    // FIXME: Perform direct initialization of the member.
643    return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
644  }
645
646  // It didn't name a member, so see if it names a class.
647  TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, 0/*SS*/);
648  if (!BaseTy)
649    return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
650      << MemberOrBase << SourceRange(IdLoc, RParenLoc);
651
652  QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
653  if (!BaseType->isRecordType())
654    return Diag(IdLoc, diag::err_base_init_does_not_name_class)
655      << BaseType << SourceRange(IdLoc, RParenLoc);
656
657  // C++ [class.base.init]p2:
658  //   [...] Unless the mem-initializer-id names a nonstatic data
659  //   member of the constructor’s class or a direct or virtual base
660  //   of that class, the mem-initializer is ill-formed. A
661  //   mem-initializer-list can initialize a base class using any
662  //   name that denotes that base class type.
663
664  // First, check for a direct base class.
665  const CXXBaseSpecifier *DirectBaseSpec = 0;
666  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
667       Base != ClassDecl->bases_end(); ++Base) {
668    if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
669        Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
670      // We found a direct base of this type. That's what we're
671      // initializing.
672      DirectBaseSpec = &*Base;
673      break;
674    }
675  }
676
677  // Check for a virtual base class.
678  // FIXME: We might be able to short-circuit this if we know in
679  // advance that there are no virtual bases.
680  const CXXBaseSpecifier *VirtualBaseSpec = 0;
681  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
682    // We haven't found a base yet; search the class hierarchy for a
683    // virtual base class.
684    BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
685                    /*DetectVirtual=*/false);
686    if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
687      for (BasePaths::paths_iterator Path = Paths.begin();
688           Path != Paths.end(); ++Path) {
689        if (Path->back().Base->isVirtual()) {
690          VirtualBaseSpec = Path->back().Base;
691          break;
692        }
693      }
694    }
695  }
696
697  // C++ [base.class.init]p2:
698  //   If a mem-initializer-id is ambiguous because it designates both
699  //   a direct non-virtual base class and an inherited virtual base
700  //   class, the mem-initializer is ill-formed.
701  if (DirectBaseSpec && VirtualBaseSpec)
702    return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
703      << MemberOrBase << SourceRange(IdLoc, RParenLoc);
704
705  return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
706}
707
708namespace {
709  /// PureVirtualMethodCollector - traverses a class and its superclasses
710  /// and determines if it has any pure virtual methods.
711  class VISIBILITY_HIDDEN PureVirtualMethodCollector {
712    ASTContext &Context;
713
714    typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
715    MethodList Methods;
716
717    void Collect(const CXXRecordDecl* RD, MethodList& Methods);
718
719  public:
720    PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
721      : Context(Ctx) {
722
723      MethodList List;
724      Collect(RD, List);
725
726      // Copy the temporary list to methods, and make sure to ignore any
727      // null entries.
728      for (size_t i = 0, e = List.size(); i != e; ++i) {
729        if (List[i])
730          Methods.push_back(List[i]);
731      }
732    }
733
734    bool empty() const { return Methods.empty(); }
735
736    MethodList::const_iterator methods_begin() { return Methods.begin(); }
737    MethodList::const_iterator methods_end() { return Methods.end(); }
738  };
739
740  void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
741                                           MethodList& Methods) {
742    // First, collect the pure virtual methods for the base classes.
743    for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
744         BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
745      if (const RecordType *RT = Base->getType()->getAsRecordType()) {
746        const CXXRecordDecl *BaseDecl
747          = cast<CXXRecordDecl>(RT->getDecl());
748        if (BaseDecl && BaseDecl->isAbstract())
749          Collect(BaseDecl, Methods);
750      }
751    }
752
753    // Next, zero out any pure virtual methods that this class overrides.
754    for (size_t i = 0, e = Methods.size(); i != e; ++i) {
755      const CXXMethodDecl *VMD = dyn_cast_or_null<CXXMethodDecl>(Methods[i]);
756      if (!VMD)
757        continue;
758
759      DeclContext::lookup_const_iterator I, E;
760      for (llvm::tie(I, E) = RD->lookup(VMD->getDeclName()); I != E; ++I) {
761        if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*I)) {
762          if (Context.getCanonicalType(MD->getType()) ==
763              Context.getCanonicalType(VMD->getType())) {
764            // We did find a matching method, which means that this is not a
765            // pure virtual method in the current class. Zero it out.
766            Methods[i] = 0;
767          }
768        }
769      }
770    }
771
772    // Finally, add pure virtual methods from this class.
773    for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
774         i != e; ++i) {
775      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
776        if (MD->isPure())
777          Methods.push_back(MD);
778      }
779    }
780  }
781}
782
783bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
784                                  unsigned SelID) {
785
786  if (!getLangOptions().CPlusPlus)
787    return false;
788
789  const RecordType *RT = T->getAsRecordType();
790  if (!RT)
791    return false;
792
793  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
794  if (!RD)
795    return false;
796
797  if (!RD->isAbstract())
798    return false;
799
800  Diag(Loc, diag::err_abstract_type_in_decl) << SelID << RD->getDeclName();
801
802  // Check if we've already emitted the list of pure virtual functions for this
803  // class.
804  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
805    return true;
806
807  PureVirtualMethodCollector Collector(Context, RD);
808
809  for (PureVirtualMethodCollector::MethodList::const_iterator I =
810       Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
811    const CXXMethodDecl *MD = *I;
812
813    Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
814      MD->getDeclName();
815  }
816
817  if (!PureVirtualClassDiagSet)
818    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
819  PureVirtualClassDiagSet->insert(RD);
820
821  return true;
822}
823
824void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
825                                             DeclTy *TagDecl,
826                                             SourceLocation LBrac,
827                                             SourceLocation RBrac) {
828  TemplateDecl *Template = AdjustDeclIfTemplate(TagDecl);
829  ActOnFields(S, RLoc, TagDecl,
830              (DeclTy**)FieldCollector->getCurFields(),
831              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
832
833  CXXRecordDecl *RD = cast<CXXRecordDecl>((Decl*)TagDecl);
834  if (!RD->isAbstract()) {
835    // Collect all the pure virtual methods and see if this is an abstract
836    // class after all.
837    PureVirtualMethodCollector Collector(Context, RD);
838    if (!Collector.empty())
839      RD->setAbstract(true);
840  }
841
842  if (!Template)
843    AddImplicitlyDeclaredMembersToClass(RD);
844}
845
846/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
847/// special functions, such as the default constructor, copy
848/// constructor, or destructor, to the given C++ class (C++
849/// [special]p1).  This routine can only be executed just before the
850/// definition of the class is complete.
851void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
852  QualType ClassType = Context.getTypeDeclType(ClassDecl);
853  ClassType = Context.getCanonicalType(ClassType);
854
855  if (!ClassDecl->hasUserDeclaredConstructor()) {
856    // C++ [class.ctor]p5:
857    //   A default constructor for a class X is a constructor of class X
858    //   that can be called without an argument. If there is no
859    //   user-declared constructor for class X, a default constructor is
860    //   implicitly declared. An implicitly-declared default constructor
861    //   is an inline public member of its class.
862    DeclarationName Name
863      = Context.DeclarationNames.getCXXConstructorName(ClassType);
864    CXXConstructorDecl *DefaultCon =
865      CXXConstructorDecl::Create(Context, ClassDecl,
866                                 ClassDecl->getLocation(), Name,
867                                 Context.getFunctionType(Context.VoidTy,
868                                                         0, 0, false, 0),
869                                 /*isExplicit=*/false,
870                                 /*isInline=*/true,
871                                 /*isImplicitlyDeclared=*/true);
872    DefaultCon->setAccess(AS_public);
873    DefaultCon->setImplicit();
874    ClassDecl->addDecl(DefaultCon);
875
876    // Notify the class that we've added a constructor.
877    ClassDecl->addedConstructor(Context, DefaultCon);
878  }
879
880  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
881    // C++ [class.copy]p4:
882    //   If the class definition does not explicitly declare a copy
883    //   constructor, one is declared implicitly.
884
885    // C++ [class.copy]p5:
886    //   The implicitly-declared copy constructor for a class X will
887    //   have the form
888    //
889    //       X::X(const X&)
890    //
891    //   if
892    bool HasConstCopyConstructor = true;
893
894    //     -- each direct or virtual base class B of X has a copy
895    //        constructor whose first parameter is of type const B& or
896    //        const volatile B&, and
897    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
898         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
899      const CXXRecordDecl *BaseClassDecl
900        = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
901      HasConstCopyConstructor
902        = BaseClassDecl->hasConstCopyConstructor(Context);
903    }
904
905    //     -- for all the nonstatic data members of X that are of a
906    //        class type M (or array thereof), each such class type
907    //        has a copy constructor whose first parameter is of type
908    //        const M& or const volatile M&.
909    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
910         HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
911      QualType FieldType = (*Field)->getType();
912      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
913        FieldType = Array->getElementType();
914      if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
915        const CXXRecordDecl *FieldClassDecl
916          = cast<CXXRecordDecl>(FieldClassType->getDecl());
917        HasConstCopyConstructor
918          = FieldClassDecl->hasConstCopyConstructor(Context);
919      }
920    }
921
922    //   Otherwise, the implicitly declared copy constructor will have
923    //   the form
924    //
925    //       X::X(X&)
926    QualType ArgType = ClassType;
927    if (HasConstCopyConstructor)
928      ArgType = ArgType.withConst();
929    ArgType = Context.getLValueReferenceType(ArgType);
930
931    //   An implicitly-declared copy constructor is an inline public
932    //   member of its class.
933    DeclarationName Name
934      = Context.DeclarationNames.getCXXConstructorName(ClassType);
935    CXXConstructorDecl *CopyConstructor
936      = CXXConstructorDecl::Create(Context, ClassDecl,
937                                   ClassDecl->getLocation(), Name,
938                                   Context.getFunctionType(Context.VoidTy,
939                                                           &ArgType, 1,
940                                                           false, 0),
941                                   /*isExplicit=*/false,
942                                   /*isInline=*/true,
943                                   /*isImplicitlyDeclared=*/true);
944    CopyConstructor->setAccess(AS_public);
945    CopyConstructor->setImplicit();
946
947    // Add the parameter to the constructor.
948    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
949                                                 ClassDecl->getLocation(),
950                                                 /*IdentifierInfo=*/0,
951                                                 ArgType, VarDecl::None, 0);
952    CopyConstructor->setParams(Context, &FromParam, 1);
953
954    ClassDecl->addedConstructor(Context, CopyConstructor);
955    ClassDecl->addDecl(CopyConstructor);
956  }
957
958  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
959    // Note: The following rules are largely analoguous to the copy
960    // constructor rules. Note that virtual bases are not taken into account
961    // for determining the argument type of the operator. Note also that
962    // operators taking an object instead of a reference are allowed.
963    //
964    // C++ [class.copy]p10:
965    //   If the class definition does not explicitly declare a copy
966    //   assignment operator, one is declared implicitly.
967    //   The implicitly-defined copy assignment operator for a class X
968    //   will have the form
969    //
970    //       X& X::operator=(const X&)
971    //
972    //   if
973    bool HasConstCopyAssignment = true;
974
975    //       -- each direct base class B of X has a copy assignment operator
976    //          whose parameter is of type const B&, const volatile B& or B,
977    //          and
978    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
979         HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
980      const CXXRecordDecl *BaseClassDecl
981        = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
982      HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
983    }
984
985    //       -- for all the nonstatic data members of X that are of a class
986    //          type M (or array thereof), each such class type has a copy
987    //          assignment operator whose parameter is of type const M&,
988    //          const volatile M& or M.
989    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
990         HasConstCopyAssignment && Field != ClassDecl->field_end(); ++Field) {
991      QualType FieldType = (*Field)->getType();
992      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
993        FieldType = Array->getElementType();
994      if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
995        const CXXRecordDecl *FieldClassDecl
996          = cast<CXXRecordDecl>(FieldClassType->getDecl());
997        HasConstCopyAssignment
998          = FieldClassDecl->hasConstCopyAssignment(Context);
999      }
1000    }
1001
1002    //   Otherwise, the implicitly declared copy assignment operator will
1003    //   have the form
1004    //
1005    //       X& X::operator=(X&)
1006    QualType ArgType = ClassType;
1007    QualType RetType = Context.getLValueReferenceType(ArgType);
1008    if (HasConstCopyAssignment)
1009      ArgType = ArgType.withConst();
1010    ArgType = Context.getLValueReferenceType(ArgType);
1011
1012    //   An implicitly-declared copy assignment operator is an inline public
1013    //   member of its class.
1014    DeclarationName Name =
1015      Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1016    CXXMethodDecl *CopyAssignment =
1017      CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1018                            Context.getFunctionType(RetType, &ArgType, 1,
1019                                                    false, 0),
1020                            /*isStatic=*/false, /*isInline=*/true);
1021    CopyAssignment->setAccess(AS_public);
1022    CopyAssignment->setImplicit();
1023
1024    // Add the parameter to the operator.
1025    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1026                                                 ClassDecl->getLocation(),
1027                                                 /*IdentifierInfo=*/0,
1028                                                 ArgType, VarDecl::None, 0);
1029    CopyAssignment->setParams(Context, &FromParam, 1);
1030
1031    // Don't call addedAssignmentOperator. There is no way to distinguish an
1032    // implicit from an explicit assignment operator.
1033    ClassDecl->addDecl(CopyAssignment);
1034  }
1035
1036  if (!ClassDecl->hasUserDeclaredDestructor()) {
1037    // C++ [class.dtor]p2:
1038    //   If a class has no user-declared destructor, a destructor is
1039    //   declared implicitly. An implicitly-declared destructor is an
1040    //   inline public member of its class.
1041    DeclarationName Name
1042      = Context.DeclarationNames.getCXXDestructorName(ClassType);
1043    CXXDestructorDecl *Destructor
1044      = CXXDestructorDecl::Create(Context, ClassDecl,
1045                                  ClassDecl->getLocation(), Name,
1046                                  Context.getFunctionType(Context.VoidTy,
1047                                                          0, 0, false, 0),
1048                                  /*isInline=*/true,
1049                                  /*isImplicitlyDeclared=*/true);
1050    Destructor->setAccess(AS_public);
1051    Destructor->setImplicit();
1052    ClassDecl->addDecl(Destructor);
1053  }
1054}
1055
1056/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1057/// parsing a top-level (non-nested) C++ class, and we are now
1058/// parsing those parts of the given Method declaration that could
1059/// not be parsed earlier (C++ [class.mem]p2), such as default
1060/// arguments. This action should enter the scope of the given
1061/// Method declaration as if we had just parsed the qualified method
1062/// name. However, it should not bring the parameters into scope;
1063/// that will be performed by ActOnDelayedCXXMethodParameter.
1064void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) {
1065  CXXScopeSpec SS;
1066  SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext());
1067  ActOnCXXEnterDeclaratorScope(S, SS);
1068}
1069
1070/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1071/// C++ method declaration. We're (re-)introducing the given
1072/// function parameter into scope for use in parsing later parts of
1073/// the method declaration. For example, we could see an
1074/// ActOnParamDefaultArgument event for this parameter.
1075void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
1076  ParmVarDecl *Param = (ParmVarDecl*)ParamD;
1077
1078  // If this parameter has an unparsed default argument, clear it out
1079  // to make way for the parsed default argument.
1080  if (Param->hasUnparsedDefaultArg())
1081    Param->setDefaultArg(0);
1082
1083  S->AddDecl(Param);
1084  if (Param->getDeclName())
1085    IdResolver.AddDecl(Param);
1086}
1087
1088/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1089/// processing the delayed method declaration for Method. The method
1090/// declaration is now considered finished. There may be a separate
1091/// ActOnStartOfFunctionDef action later (not necessarily
1092/// immediately!) for this method, if it was also defined inside the
1093/// class body.
1094void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
1095  FunctionDecl *Method = (FunctionDecl*)MethodD;
1096  CXXScopeSpec SS;
1097  SS.setScopeRep(Method->getDeclContext());
1098  ActOnCXXExitDeclaratorScope(S, SS);
1099
1100  // Now that we have our default arguments, check the constructor
1101  // again. It could produce additional diagnostics or affect whether
1102  // the class has implicitly-declared destructors, among other
1103  // things.
1104  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
1105    if (CheckConstructor(Constructor))
1106      Constructor->setInvalidDecl();
1107  }
1108
1109  // Check the default arguments, which we may have added.
1110  if (!Method->isInvalidDecl())
1111    CheckCXXDefaultArguments(Method);
1112}
1113
1114/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
1115/// the well-formedness of the constructor declarator @p D with type @p
1116/// R. If there are any errors in the declarator, this routine will
1117/// emit diagnostics and return true. Otherwise, it will return
1118/// false. Either way, the type @p R will be updated to reflect a
1119/// well-formed type for the constructor.
1120bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
1121                                      FunctionDecl::StorageClass& SC) {
1122  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1123  bool isInvalid = false;
1124
1125  // C++ [class.ctor]p3:
1126  //   A constructor shall not be virtual (10.3) or static (9.4). A
1127  //   constructor can be invoked for a const, volatile or const
1128  //   volatile object. A constructor shall not be declared const,
1129  //   volatile, or const volatile (9.3.2).
1130  if (isVirtual) {
1131    Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1132      << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1133      << SourceRange(D.getIdentifierLoc());
1134    isInvalid = true;
1135  }
1136  if (SC == FunctionDecl::Static) {
1137    Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1138      << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1139      << SourceRange(D.getIdentifierLoc());
1140    isInvalid = true;
1141    SC = FunctionDecl::None;
1142  }
1143  if (D.getDeclSpec().hasTypeSpecifier()) {
1144    // Constructors don't have return types, but the parser will
1145    // happily parse something like:
1146    //
1147    //   class X {
1148    //     float X(float);
1149    //   };
1150    //
1151    // The return type will be eliminated later.
1152    Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
1153      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1154      << SourceRange(D.getIdentifierLoc());
1155  }
1156  if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
1157    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1158    if (FTI.TypeQuals & QualType::Const)
1159      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1160        << "const" << SourceRange(D.getIdentifierLoc());
1161    if (FTI.TypeQuals & QualType::Volatile)
1162      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1163        << "volatile" << SourceRange(D.getIdentifierLoc());
1164    if (FTI.TypeQuals & QualType::Restrict)
1165      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1166        << "restrict" << SourceRange(D.getIdentifierLoc());
1167  }
1168
1169  // Rebuild the function type "R" without any type qualifiers (in
1170  // case any of the errors above fired) and with "void" as the
1171  // return type, since constructors don't have return types. We
1172  // *always* have to do this, because GetTypeForDeclarator will
1173  // put in a result type of "int" when none was specified.
1174  const FunctionProtoType *Proto = R->getAsFunctionProtoType();
1175  R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1176                              Proto->getNumArgs(),
1177                              Proto->isVariadic(),
1178                              0);
1179
1180  return isInvalid;
1181}
1182
1183/// CheckConstructor - Checks a fully-formed constructor for
1184/// well-formedness, issuing any diagnostics required. Returns true if
1185/// the constructor declarator is invalid.
1186bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1187  if (Constructor->isInvalidDecl())
1188    return true;
1189
1190  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1191  bool Invalid = false;
1192
1193  // C++ [class.copy]p3:
1194  //   A declaration of a constructor for a class X is ill-formed if
1195  //   its first parameter is of type (optionally cv-qualified) X and
1196  //   either there are no other parameters or else all other
1197  //   parameters have default arguments.
1198  if ((Constructor->getNumParams() == 1) ||
1199      (Constructor->getNumParams() > 1 &&
1200       Constructor->getParamDecl(1)->getDefaultArg() != 0)) {
1201    QualType ParamType = Constructor->getParamDecl(0)->getType();
1202    QualType ClassTy = Context.getTagDeclType(ClassDecl);
1203    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1204      Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1205        << SourceRange(Constructor->getParamDecl(0)->getLocation());
1206      Invalid = true;
1207    }
1208  }
1209
1210  // Notify the class that we've added a constructor.
1211  ClassDecl->addedConstructor(Context, Constructor);
1212
1213  return Invalid;
1214}
1215
1216/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1217/// the well-formednes of the destructor declarator @p D with type @p
1218/// R. If there are any errors in the declarator, this routine will
1219/// emit diagnostics and return true. Otherwise, it will return
1220/// false. Either way, the type @p R will be updated to reflect a
1221/// well-formed type for the destructor.
1222bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1223                                     FunctionDecl::StorageClass& SC) {
1224  bool isInvalid = false;
1225
1226  // C++ [class.dtor]p1:
1227  //   [...] A typedef-name that names a class is a class-name
1228  //   (7.1.3); however, a typedef-name that names a class shall not
1229  //   be used as the identifier in the declarator for a destructor
1230  //   declaration.
1231  QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1232  if (DeclaratorType->getAsTypedefType()) {
1233    Diag(D.getIdentifierLoc(),  diag::err_destructor_typedef_name)
1234      << DeclaratorType;
1235    isInvalid = true;
1236  }
1237
1238  // C++ [class.dtor]p2:
1239  //   A destructor is used to destroy objects of its class type. A
1240  //   destructor takes no parameters, and no return type can be
1241  //   specified for it (not even void). The address of a destructor
1242  //   shall not be taken. A destructor shall not be static. A
1243  //   destructor can be invoked for a const, volatile or const
1244  //   volatile object. A destructor shall not be declared const,
1245  //   volatile or const volatile (9.3.2).
1246  if (SC == FunctionDecl::Static) {
1247    Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1248      << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1249      << SourceRange(D.getIdentifierLoc());
1250    isInvalid = true;
1251    SC = FunctionDecl::None;
1252  }
1253  if (D.getDeclSpec().hasTypeSpecifier()) {
1254    // Destructors don't have return types, but the parser will
1255    // happily parse something like:
1256    //
1257    //   class X {
1258    //     float ~X();
1259    //   };
1260    //
1261    // The return type will be eliminated later.
1262    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1263      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1264      << SourceRange(D.getIdentifierLoc());
1265  }
1266  if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
1267    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1268    if (FTI.TypeQuals & QualType::Const)
1269      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1270        << "const" << SourceRange(D.getIdentifierLoc());
1271    if (FTI.TypeQuals & QualType::Volatile)
1272      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1273        << "volatile" << SourceRange(D.getIdentifierLoc());
1274    if (FTI.TypeQuals & QualType::Restrict)
1275      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1276        << "restrict" << SourceRange(D.getIdentifierLoc());
1277  }
1278
1279  // Make sure we don't have any parameters.
1280  if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
1281    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1282
1283    // Delete the parameters.
1284    D.getTypeObject(0).Fun.freeArgs();
1285  }
1286
1287  // Make sure the destructor isn't variadic.
1288  if (R->getAsFunctionProtoType()->isVariadic())
1289    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1290
1291  // Rebuild the function type "R" without any type qualifiers or
1292  // parameters (in case any of the errors above fired) and with
1293  // "void" as the return type, since destructors don't have return
1294  // types. We *always* have to do this, because GetTypeForDeclarator
1295  // will put in a result type of "int" when none was specified.
1296  R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1297
1298  return isInvalid;
1299}
1300
1301/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1302/// well-formednes of the conversion function declarator @p D with
1303/// type @p R. If there are any errors in the declarator, this routine
1304/// will emit diagnostics and return true. Otherwise, it will return
1305/// false. Either way, the type @p R will be updated to reflect a
1306/// well-formed type for the conversion operator.
1307bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1308                                     FunctionDecl::StorageClass& SC) {
1309  bool isInvalid = false;
1310
1311  // C++ [class.conv.fct]p1:
1312  //   Neither parameter types nor return type can be specified. The
1313  //   type of a conversion function (8.3.5) is “function taking no
1314  //   parameter returning conversion-type-id.”
1315  if (SC == FunctionDecl::Static) {
1316    Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1317      << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1318      << SourceRange(D.getIdentifierLoc());
1319    isInvalid = true;
1320    SC = FunctionDecl::None;
1321  }
1322  if (D.getDeclSpec().hasTypeSpecifier()) {
1323    // Conversion functions don't have return types, but the parser will
1324    // happily parse something like:
1325    //
1326    //   class X {
1327    //     float operator bool();
1328    //   };
1329    //
1330    // The return type will be changed later anyway.
1331    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1332      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1333      << SourceRange(D.getIdentifierLoc());
1334  }
1335
1336  // Make sure we don't have any parameters.
1337  if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
1338    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1339
1340    // Delete the parameters.
1341    D.getTypeObject(0).Fun.freeArgs();
1342  }
1343
1344  // Make sure the conversion function isn't variadic.
1345  if (R->getAsFunctionProtoType()->isVariadic())
1346    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1347
1348  // C++ [class.conv.fct]p4:
1349  //   The conversion-type-id shall not represent a function type nor
1350  //   an array type.
1351  QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1352  if (ConvType->isArrayType()) {
1353    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1354    ConvType = Context.getPointerType(ConvType);
1355  } else if (ConvType->isFunctionType()) {
1356    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1357    ConvType = Context.getPointerType(ConvType);
1358  }
1359
1360  // Rebuild the function type "R" without any parameters (in case any
1361  // of the errors above fired) and with the conversion type as the
1362  // return type.
1363  R = Context.getFunctionType(ConvType, 0, 0, false,
1364                              R->getAsFunctionProtoType()->getTypeQuals());
1365
1366  // C++0x explicit conversion operators.
1367  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1368    Diag(D.getDeclSpec().getExplicitSpecLoc(),
1369         diag::warn_explicit_conversion_functions)
1370      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1371
1372  return isInvalid;
1373}
1374
1375/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1376/// the declaration of the given C++ conversion function. This routine
1377/// is responsible for recording the conversion function in the C++
1378/// class, if possible.
1379Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1380  assert(Conversion && "Expected to receive a conversion function declaration");
1381
1382  // Set the lexical context of this conversion function
1383  Conversion->setLexicalDeclContext(CurContext);
1384
1385  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
1386
1387  // Make sure we aren't redeclaring the conversion function.
1388  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
1389
1390  // C++ [class.conv.fct]p1:
1391  //   [...] A conversion function is never used to convert a
1392  //   (possibly cv-qualified) object to the (possibly cv-qualified)
1393  //   same object type (or a reference to it), to a (possibly
1394  //   cv-qualified) base class of that type (or a reference to it),
1395  //   or to (possibly cv-qualified) void.
1396  // FIXME: Suppress this warning if the conversion function ends up
1397  // being a virtual function that overrides a virtual function in a
1398  // base class.
1399  QualType ClassType
1400    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1401  if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1402    ConvType = ConvTypeRef->getPointeeType();
1403  if (ConvType->isRecordType()) {
1404    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1405    if (ConvType == ClassType)
1406      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
1407        << ClassType;
1408    else if (IsDerivedFrom(ClassType, ConvType))
1409      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
1410        <<  ClassType << ConvType;
1411  } else if (ConvType->isVoidType()) {
1412    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
1413      << ClassType << ConvType;
1414  }
1415
1416  if (Conversion->getPreviousDeclaration()) {
1417    OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1418    for (OverloadedFunctionDecl::function_iterator
1419           Conv = Conversions->function_begin(),
1420           ConvEnd = Conversions->function_end();
1421         Conv != ConvEnd; ++Conv) {
1422      if (*Conv == Conversion->getPreviousDeclaration()) {
1423        *Conv = Conversion;
1424        return (DeclTy *)Conversion;
1425      }
1426    }
1427    assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1428  } else
1429    ClassDecl->addConversionFunction(Context, Conversion);
1430
1431  return (DeclTy *)Conversion;
1432}
1433
1434//===----------------------------------------------------------------------===//
1435// Namespace Handling
1436//===----------------------------------------------------------------------===//
1437
1438/// ActOnStartNamespaceDef - This is called at the start of a namespace
1439/// definition.
1440Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1441                                           SourceLocation IdentLoc,
1442                                           IdentifierInfo *II,
1443                                           SourceLocation LBrace) {
1444  NamespaceDecl *Namespc =
1445      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1446  Namespc->setLBracLoc(LBrace);
1447
1448  Scope *DeclRegionScope = NamespcScope->getParent();
1449
1450  if (II) {
1451    // C++ [namespace.def]p2:
1452    // The identifier in an original-namespace-definition shall not have been
1453    // previously defined in the declarative region in which the
1454    // original-namespace-definition appears. The identifier in an
1455    // original-namespace-definition is the name of the namespace. Subsequently
1456    // in that declarative region, it is treated as an original-namespace-name.
1457
1458    NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1459                                     true);
1460
1461    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1462      // This is an extended namespace definition.
1463      // Attach this namespace decl to the chain of extended namespace
1464      // definitions.
1465      OrigNS->setNextNamespace(Namespc);
1466      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
1467
1468      // Remove the previous declaration from the scope.
1469      if (DeclRegionScope->isDeclScope(OrigNS)) {
1470        IdResolver.RemoveDecl(OrigNS);
1471        DeclRegionScope->RemoveDecl(OrigNS);
1472      }
1473    } else if (PrevDecl) {
1474      // This is an invalid name redefinition.
1475      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1476       << Namespc->getDeclName();
1477      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1478      Namespc->setInvalidDecl();
1479      // Continue on to push Namespc as current DeclContext and return it.
1480    }
1481
1482    PushOnScopeChains(Namespc, DeclRegionScope);
1483  } else {
1484    // FIXME: Handle anonymous namespaces
1485  }
1486
1487  // Although we could have an invalid decl (i.e. the namespace name is a
1488  // redefinition), push it as current DeclContext and try to continue parsing.
1489  // FIXME: We should be able to push Namespc here, so that the
1490  // each DeclContext for the namespace has the declarations
1491  // that showed up in that particular namespace definition.
1492  PushDeclContext(NamespcScope, Namespc);
1493  return Namespc;
1494}
1495
1496/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1497/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1498void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1499  Decl *Dcl = static_cast<Decl *>(D);
1500  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1501  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1502  Namespc->setRBracLoc(RBrace);
1503  PopDeclContext();
1504}
1505
1506Sema::DeclTy *Sema::ActOnUsingDirective(Scope *S,
1507                                        SourceLocation UsingLoc,
1508                                        SourceLocation NamespcLoc,
1509                                        const CXXScopeSpec &SS,
1510                                        SourceLocation IdentLoc,
1511                                        IdentifierInfo *NamespcName,
1512                                        AttributeList *AttrList) {
1513  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1514  assert(NamespcName && "Invalid NamespcName.");
1515  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
1516  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
1517
1518  UsingDirectiveDecl *UDir = 0;
1519
1520  // Lookup namespace name.
1521  LookupResult R = LookupParsedName(S, &SS, NamespcName,
1522                                    LookupNamespaceName, false);
1523  if (R.isAmbiguous()) {
1524    DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
1525    return 0;
1526  }
1527  if (NamedDecl *NS = R) {
1528    assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
1529    // C++ [namespace.udir]p1:
1530    //   A using-directive specifies that the names in the nominated
1531    //   namespace can be used in the scope in which the
1532    //   using-directive appears after the using-directive. During
1533    //   unqualified name lookup (3.4.1), the names appear as if they
1534    //   were declared in the nearest enclosing namespace which
1535    //   contains both the using-directive and the nominated
1536    //   namespace. [Note: in this context, “contains” means “contains
1537    //   directly or indirectly”. ]
1538
1539    // Find enclosing context containing both using-directive and
1540    // nominated namespace.
1541    DeclContext *CommonAncestor = cast<DeclContext>(NS);
1542    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1543      CommonAncestor = CommonAncestor->getParent();
1544
1545    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc,
1546                                      NamespcLoc, IdentLoc,
1547                                      cast<NamespaceDecl>(NS),
1548                                      CommonAncestor);
1549    PushUsingDirective(S, UDir);
1550  } else {
1551    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
1552  }
1553
1554  // FIXME: We ignore attributes for now.
1555  delete AttrList;
1556  return UDir;
1557}
1558
1559void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1560  // If scope has associated entity, then using directive is at namespace
1561  // or translation unit scope. We add UsingDirectiveDecls, into
1562  // it's lookup structure.
1563  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
1564    Ctx->addDecl(UDir);
1565  else
1566    // Otherwise it is block-sope. using-directives will affect lookup
1567    // only to the end of scope.
1568    S->PushUsingDirective(UDir);
1569}
1570
1571/// AddCXXDirectInitializerToDecl - This action is called immediately after
1572/// ActOnDeclarator, when a C++ direct initializer is present.
1573/// e.g: "int x(1);"
1574void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1575                                         MultiExprArg Exprs,
1576                                         SourceLocation *CommaLocs,
1577                                         SourceLocation RParenLoc) {
1578  unsigned NumExprs = Exprs.size();
1579  assert(NumExprs != 0 && Exprs.get() && "missing expressions");
1580  Decl *RealDecl = static_cast<Decl *>(Dcl);
1581
1582  // If there is no declaration, there was an error parsing it.  Just ignore
1583  // the initializer.
1584  if (RealDecl == 0) {
1585    return;
1586  }
1587
1588  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1589  if (!VDecl) {
1590    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1591    RealDecl->setInvalidDecl();
1592    return;
1593  }
1594
1595  // We will treat direct-initialization as a copy-initialization:
1596  //    int x(1);  -as-> int x = 1;
1597  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1598  //
1599  // Clients that want to distinguish between the two forms, can check for
1600  // direct initializer using VarDecl::hasCXXDirectInitializer().
1601  // A major benefit is that clients that don't particularly care about which
1602  // exactly form was it (like the CodeGen) can handle both cases without
1603  // special case code.
1604
1605  // C++ 8.5p11:
1606  // The form of initialization (using parentheses or '=') is generally
1607  // insignificant, but does matter when the entity being initialized has a
1608  // class type.
1609  QualType DeclInitType = VDecl->getType();
1610  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1611    DeclInitType = Array->getElementType();
1612
1613  if (VDecl->getType()->isRecordType()) {
1614    CXXConstructorDecl *Constructor
1615      = PerformInitializationByConstructor(DeclInitType,
1616                                           (Expr **)Exprs.get(), NumExprs,
1617                                           VDecl->getLocation(),
1618                                           SourceRange(VDecl->getLocation(),
1619                                                       RParenLoc),
1620                                           VDecl->getDeclName(),
1621                                           IK_Direct);
1622    if (!Constructor)
1623      RealDecl->setInvalidDecl();
1624    else
1625      Exprs.release();
1626
1627    // Let clients know that initialization was done with a direct
1628    // initializer.
1629    VDecl->setCXXDirectInitializer(true);
1630
1631    // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1632    // the initializer.
1633    return;
1634  }
1635
1636  if (NumExprs > 1) {
1637    Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1638      << SourceRange(VDecl->getLocation(), RParenLoc);
1639    RealDecl->setInvalidDecl();
1640    return;
1641  }
1642
1643  // Let clients know that initialization was done with a direct initializer.
1644  VDecl->setCXXDirectInitializer(true);
1645
1646  assert(NumExprs == 1 && "Expected 1 expression");
1647  // Set the init expression, handles conversions.
1648  AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
1649                       /*DirectInit=*/true);
1650}
1651
1652/// PerformInitializationByConstructor - Perform initialization by
1653/// constructor (C++ [dcl.init]p14), which may occur as part of
1654/// direct-initialization or copy-initialization. We are initializing
1655/// an object of type @p ClassType with the given arguments @p
1656/// Args. @p Loc is the location in the source code where the
1657/// initializer occurs (e.g., a declaration, member initializer,
1658/// functional cast, etc.) while @p Range covers the whole
1659/// initialization. @p InitEntity is the entity being initialized,
1660/// which may by the name of a declaration or a type. @p Kind is the
1661/// kind of initialization we're performing, which affects whether
1662/// explicit constructors will be considered. When successful, returns
1663/// the constructor that will be used to perform the initialization;
1664/// when the initialization fails, emits a diagnostic and returns
1665/// null.
1666CXXConstructorDecl *
1667Sema::PerformInitializationByConstructor(QualType ClassType,
1668                                         Expr **Args, unsigned NumArgs,
1669                                         SourceLocation Loc, SourceRange Range,
1670                                         DeclarationName InitEntity,
1671                                         InitializationKind Kind) {
1672  const RecordType *ClassRec = ClassType->getAsRecordType();
1673  assert(ClassRec && "Can only initialize a class type here");
1674
1675  // C++ [dcl.init]p14:
1676  //
1677  //   If the initialization is direct-initialization, or if it is
1678  //   copy-initialization where the cv-unqualified version of the
1679  //   source type is the same class as, or a derived class of, the
1680  //   class of the destination, constructors are considered. The
1681  //   applicable constructors are enumerated (13.3.1.3), and the
1682  //   best one is chosen through overload resolution (13.3). The
1683  //   constructor so selected is called to initialize the object,
1684  //   with the initializer expression(s) as its argument(s). If no
1685  //   constructor applies, or the overload resolution is ambiguous,
1686  //   the initialization is ill-formed.
1687  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1688  OverloadCandidateSet CandidateSet;
1689
1690  // Add constructors to the overload set.
1691  DeclarationName ConstructorName
1692    = Context.DeclarationNames.getCXXConstructorName(
1693                       Context.getCanonicalType(ClassType.getUnqualifiedType()));
1694  DeclContext::lookup_const_iterator Con, ConEnd;
1695  for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
1696       Con != ConEnd; ++Con) {
1697    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1698    if ((Kind == IK_Direct) ||
1699        (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1700        (Kind == IK_Default && Constructor->isDefaultConstructor()))
1701      AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1702  }
1703
1704  // FIXME: When we decide not to synthesize the implicitly-declared
1705  // constructors, we'll need to make them appear here.
1706
1707  OverloadCandidateSet::iterator Best;
1708  switch (BestViableFunction(CandidateSet, Best)) {
1709  case OR_Success:
1710    // We found a constructor. Return it.
1711    return cast<CXXConstructorDecl>(Best->Function);
1712
1713  case OR_No_Viable_Function:
1714    if (InitEntity)
1715      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1716        << InitEntity << Range;
1717    else
1718      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1719        << ClassType << Range;
1720    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1721    return 0;
1722
1723  case OR_Ambiguous:
1724    if (InitEntity)
1725      Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
1726    else
1727      Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
1728    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1729    return 0;
1730
1731  case OR_Deleted:
1732    if (InitEntity)
1733      Diag(Loc, diag::err_ovl_deleted_init)
1734        << Best->Function->isDeleted()
1735        << InitEntity << Range;
1736    else
1737      Diag(Loc, diag::err_ovl_deleted_init)
1738        << Best->Function->isDeleted()
1739        << InitEntity << Range;
1740    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1741    return 0;
1742  }
1743
1744  return 0;
1745}
1746
1747/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1748/// determine whether they are reference-related,
1749/// reference-compatible, reference-compatible with added
1750/// qualification, or incompatible, for use in C++ initialization by
1751/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1752/// type, and the first type (T1) is the pointee type of the reference
1753/// type being initialized.
1754Sema::ReferenceCompareResult
1755Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1756                                   bool& DerivedToBase) {
1757  assert(!T1->isReferenceType() &&
1758    "T1 must be the pointee type of the reference type");
1759  assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1760
1761  T1 = Context.getCanonicalType(T1);
1762  T2 = Context.getCanonicalType(T2);
1763  QualType UnqualT1 = T1.getUnqualifiedType();
1764  QualType UnqualT2 = T2.getUnqualifiedType();
1765
1766  // C++ [dcl.init.ref]p4:
1767  //   Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1768  //   reference-related to “cv2 T2” if T1 is the same type as T2, or
1769  //   T1 is a base class of T2.
1770  if (UnqualT1 == UnqualT2)
1771    DerivedToBase = false;
1772  else if (IsDerivedFrom(UnqualT2, UnqualT1))
1773    DerivedToBase = true;
1774  else
1775    return Ref_Incompatible;
1776
1777  // At this point, we know that T1 and T2 are reference-related (at
1778  // least).
1779
1780  // C++ [dcl.init.ref]p4:
1781  //   "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1782  //   reference-related to T2 and cv1 is the same cv-qualification
1783  //   as, or greater cv-qualification than, cv2. For purposes of
1784  //   overload resolution, cases for which cv1 is greater
1785  //   cv-qualification than cv2 are identified as
1786  //   reference-compatible with added qualification (see 13.3.3.2).
1787  if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1788    return Ref_Compatible;
1789  else if (T1.isMoreQualifiedThan(T2))
1790    return Ref_Compatible_With_Added_Qualification;
1791  else
1792    return Ref_Related;
1793}
1794
1795/// CheckReferenceInit - Check the initialization of a reference
1796/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1797/// the initializer (either a simple initializer or an initializer
1798/// list), and DeclType is the type of the declaration. When ICS is
1799/// non-null, this routine will compute the implicit conversion
1800/// sequence according to C++ [over.ics.ref] and will not produce any
1801/// diagnostics; when ICS is null, it will emit diagnostics when any
1802/// errors are found. Either way, a return value of true indicates
1803/// that there was a failure, a return value of false indicates that
1804/// the reference initialization succeeded.
1805///
1806/// When @p SuppressUserConversions, user-defined conversions are
1807/// suppressed.
1808/// When @p AllowExplicit, we also permit explicit user-defined
1809/// conversion functions.
1810bool
1811Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
1812                         ImplicitConversionSequence *ICS,
1813                         bool SuppressUserConversions,
1814                         bool AllowExplicit) {
1815  assert(DeclType->isReferenceType() && "Reference init needs a reference");
1816
1817  QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1818  QualType T2 = Init->getType();
1819
1820  // If the initializer is the address of an overloaded function, try
1821  // to resolve the overloaded function. If all goes well, T2 is the
1822  // type of the resulting function.
1823  if (Context.getCanonicalType(T2) == Context.OverloadTy) {
1824    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1825                                                          ICS != 0);
1826    if (Fn) {
1827      // Since we're performing this reference-initialization for
1828      // real, update the initializer with the resulting function.
1829      if (!ICS) {
1830        if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
1831          return true;
1832
1833        FixOverloadedFunctionReference(Init, Fn);
1834      }
1835
1836      T2 = Fn->getType();
1837    }
1838  }
1839
1840  // Compute some basic properties of the types and the initializer.
1841  bool isRValRef = DeclType->isRValueReferenceType();
1842  bool DerivedToBase = false;
1843  Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
1844  ReferenceCompareResult RefRelationship
1845    = CompareReferenceRelationship(T1, T2, DerivedToBase);
1846
1847  // Most paths end in a failed conversion.
1848  if (ICS)
1849    ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
1850
1851  // C++ [dcl.init.ref]p5:
1852  //   A reference to type “cv1 T1” is initialized by an expression
1853  //   of type “cv2 T2” as follows:
1854
1855  //     -- If the initializer expression
1856
1857  bool BindsDirectly = false;
1858  //       -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1859  //          reference-compatible with “cv2 T2,” or
1860  //
1861  // Note that the bit-field check is skipped if we are just computing
1862  // the implicit conversion sequence (C++ [over.best.ics]p2).
1863  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1864      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1865    BindsDirectly = true;
1866
1867    // Rvalue references cannot bind to lvalues (N2812).
1868    // FIXME: This part of rvalue references is still in flux. Revisit later.
1869    if (isRValRef) {
1870      if (!ICS)
1871        Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
1872          << Init->getSourceRange();
1873      return true;
1874    }
1875
1876    if (ICS) {
1877      // C++ [over.ics.ref]p1:
1878      //   When a parameter of reference type binds directly (8.5.3)
1879      //   to an argument expression, the implicit conversion sequence
1880      //   is the identity conversion, unless the argument expression
1881      //   has a type that is a derived class of the parameter type,
1882      //   in which case the implicit conversion sequence is a
1883      //   derived-to-base Conversion (13.3.3.1).
1884      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1885      ICS->Standard.First = ICK_Identity;
1886      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1887      ICS->Standard.Third = ICK_Identity;
1888      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1889      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
1890      ICS->Standard.ReferenceBinding = true;
1891      ICS->Standard.DirectBinding = true;
1892
1893      // Nothing more to do: the inaccessibility/ambiguity check for
1894      // derived-to-base conversions is suppressed when we're
1895      // computing the implicit conversion sequence (C++
1896      // [over.best.ics]p2).
1897      return false;
1898    } else {
1899      // Perform the conversion.
1900      // FIXME: Binding to a subobject of the lvalue is going to require
1901      // more AST annotation than this.
1902      ImpCastExprToType(Init, T1, /*isLvalue=*/true);
1903    }
1904  }
1905
1906  //       -- has a class type (i.e., T2 is a class type) and can be
1907  //          implicitly converted to an lvalue of type “cv3 T3,”
1908  //          where “cv1 T1” is reference-compatible with “cv3 T3”
1909  //          92) (this conversion is selected by enumerating the
1910  //          applicable conversion functions (13.3.1.6) and choosing
1911  //          the best one through overload resolution (13.3)),
1912  // FIXME: Without standard language for N2812, the rvalue reference treatment
1913  // here is pretty much a guess.
1914  if (!isRValRef && !SuppressUserConversions && T2->isRecordType()) {
1915    // FIXME: Look for conversions in base classes!
1916    CXXRecordDecl *T2RecordDecl
1917      = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
1918
1919    OverloadCandidateSet CandidateSet;
1920    OverloadedFunctionDecl *Conversions
1921      = T2RecordDecl->getConversionFunctions();
1922    for (OverloadedFunctionDecl::function_iterator Func
1923           = Conversions->function_begin();
1924         Func != Conversions->function_end(); ++Func) {
1925      CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1926
1927      // If the conversion function doesn't return a reference type,
1928      // it can't be considered for this conversion.
1929      // FIXME: This will change when we support rvalue references.
1930      if (Conv->getConversionType()->isLValueReferenceType() &&
1931          (AllowExplicit || !Conv->isExplicit()))
1932        AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1933    }
1934
1935    OverloadCandidateSet::iterator Best;
1936    switch (BestViableFunction(CandidateSet, Best)) {
1937    case OR_Success:
1938      // This is a direct binding.
1939      BindsDirectly = true;
1940
1941      if (ICS) {
1942        // C++ [over.ics.ref]p1:
1943        //
1944        //   [...] If the parameter binds directly to the result of
1945        //   applying a conversion function to the argument
1946        //   expression, the implicit conversion sequence is a
1947        //   user-defined conversion sequence (13.3.3.1.2), with the
1948        //   second standard conversion sequence either an identity
1949        //   conversion or, if the conversion function returns an
1950        //   entity of a type that is a derived class of the parameter
1951        //   type, a derived-to-base Conversion.
1952        ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1953        ICS->UserDefined.Before = Best->Conversions[0].Standard;
1954        ICS->UserDefined.After = Best->FinalConversion;
1955        ICS->UserDefined.ConversionFunction = Best->Function;
1956        assert(ICS->UserDefined.After.ReferenceBinding &&
1957               ICS->UserDefined.After.DirectBinding &&
1958               "Expected a direct reference binding!");
1959        return false;
1960      } else {
1961        // Perform the conversion.
1962        // FIXME: Binding to a subobject of the lvalue is going to require
1963        // more AST annotation than this.
1964        ImpCastExprToType(Init, T1, /*isLvalue=*/true);
1965      }
1966      break;
1967
1968    case OR_Ambiguous:
1969      assert(false && "Ambiguous reference binding conversions not implemented.");
1970      return true;
1971
1972    case OR_No_Viable_Function:
1973    case OR_Deleted:
1974      // There was no suitable conversion, or we found a deleted
1975      // conversion; continue with other checks.
1976      break;
1977    }
1978  }
1979
1980  if (BindsDirectly) {
1981    // C++ [dcl.init.ref]p4:
1982    //   [...] In all cases where the reference-related or
1983    //   reference-compatible relationship of two types is used to
1984    //   establish the validity of a reference binding, and T1 is a
1985    //   base class of T2, a program that necessitates such a binding
1986    //   is ill-formed if T1 is an inaccessible (clause 11) or
1987    //   ambiguous (10.2) base class of T2.
1988    //
1989    // Note that we only check this condition when we're allowed to
1990    // complain about errors, because we should not be checking for
1991    // ambiguity (or inaccessibility) unless the reference binding
1992    // actually happens.
1993    if (DerivedToBase)
1994      return CheckDerivedToBaseConversion(T2, T1,
1995                                          Init->getSourceRange().getBegin(),
1996                                          Init->getSourceRange());
1997    else
1998      return false;
1999  }
2000
2001  //     -- Otherwise, the reference shall be to a non-volatile const
2002  //        type (i.e., cv1 shall be const), or shall be an rvalue reference.
2003  if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
2004    if (!ICS)
2005      Diag(Init->getSourceRange().getBegin(),
2006           diag::err_not_reference_to_const_init)
2007        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2008        << T2 << Init->getSourceRange();
2009    return true;
2010  }
2011
2012  //       -- If the initializer expression is an rvalue, with T2 a
2013  //          class type, and “cv1 T1” is reference-compatible with
2014  //          “cv2 T2,” the reference is bound in one of the
2015  //          following ways (the choice is implementation-defined):
2016  //
2017  //          -- The reference is bound to the object represented by
2018  //             the rvalue (see 3.10) or to a sub-object within that
2019  //             object.
2020  //
2021  //          -- A temporary of type “cv1 T2” [sic] is created, and
2022  //             a constructor is called to copy the entire rvalue
2023  //             object into the temporary. The reference is bound to
2024  //             the temporary or to a sub-object within the
2025  //             temporary.
2026  //
2027  //          The constructor that would be used to make the copy
2028  //          shall be callable whether or not the copy is actually
2029  //          done.
2030  //
2031  // Note that C++0x [dcl.ref.init]p5 takes away this implementation
2032  // freedom, so we will always take the first option and never build
2033  // a temporary in this case. FIXME: We will, however, have to check
2034  // for the presence of a copy constructor in C++98/03 mode.
2035  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2036      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
2037    if (ICS) {
2038      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2039      ICS->Standard.First = ICK_Identity;
2040      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2041      ICS->Standard.Third = ICK_Identity;
2042      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2043      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
2044      ICS->Standard.ReferenceBinding = true;
2045      ICS->Standard.DirectBinding = false;
2046    } else {
2047      // FIXME: Binding to a subobject of the rvalue is going to require
2048      // more AST annotation than this.
2049      ImpCastExprToType(Init, T1, /*isLvalue=*/true);
2050    }
2051    return false;
2052  }
2053
2054  //       -- Otherwise, a temporary of type “cv1 T1” is created and
2055  //          initialized from the initializer expression using the
2056  //          rules for a non-reference copy initialization (8.5). The
2057  //          reference is then bound to the temporary. If T1 is
2058  //          reference-related to T2, cv1 must be the same
2059  //          cv-qualification as, or greater cv-qualification than,
2060  //          cv2; otherwise, the program is ill-formed.
2061  if (RefRelationship == Ref_Related) {
2062    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2063    // we would be reference-compatible or reference-compatible with
2064    // added qualification. But that wasn't the case, so the reference
2065    // initialization fails.
2066    if (!ICS)
2067      Diag(Init->getSourceRange().getBegin(),
2068           diag::err_reference_init_drops_quals)
2069        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2070        << T2 << Init->getSourceRange();
2071    return true;
2072  }
2073
2074  // If at least one of the types is a class type, the types are not
2075  // related, and we aren't allowed any user conversions, the
2076  // reference binding fails. This case is important for breaking
2077  // recursion, since TryImplicitConversion below will attempt to
2078  // create a temporary through the use of a copy constructor.
2079  if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
2080      (T1->isRecordType() || T2->isRecordType())) {
2081    if (!ICS)
2082      Diag(Init->getSourceRange().getBegin(),
2083           diag::err_typecheck_convert_incompatible)
2084        << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
2085    return true;
2086  }
2087
2088  // Actually try to convert the initializer to T1.
2089  if (ICS) {
2090    /// C++ [over.ics.ref]p2:
2091    ///
2092    ///   When a parameter of reference type is not bound directly to
2093    ///   an argument expression, the conversion sequence is the one
2094    ///   required to convert the argument expression to the
2095    ///   underlying type of the reference according to
2096    ///   13.3.3.1. Conceptually, this conversion sequence corresponds
2097    ///   to copy-initializing a temporary of the underlying type with
2098    ///   the argument expression. Any difference in top-level
2099    ///   cv-qualification is subsumed by the initialization itself
2100    ///   and does not constitute a conversion.
2101    *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
2102    return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
2103  } else {
2104    return PerformImplicitConversion(Init, T1, "initializing");
2105  }
2106}
2107
2108/// CheckOverloadedOperatorDeclaration - Check whether the declaration
2109/// of this overloaded operator is well-formed. If so, returns false;
2110/// otherwise, emits appropriate diagnostics and returns true.
2111bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
2112  assert(FnDecl && FnDecl->isOverloadedOperator() &&
2113         "Expected an overloaded operator declaration");
2114
2115  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
2116
2117  // C++ [over.oper]p5:
2118  //   The allocation and deallocation functions, operator new,
2119  //   operator new[], operator delete and operator delete[], are
2120  //   described completely in 3.7.3. The attributes and restrictions
2121  //   found in the rest of this subclause do not apply to them unless
2122  //   explicitly stated in 3.7.3.
2123  // FIXME: Write a separate routine for checking this. For now, just
2124  // allow it.
2125  if (Op == OO_New || Op == OO_Array_New ||
2126      Op == OO_Delete || Op == OO_Array_Delete)
2127    return false;
2128
2129  // C++ [over.oper]p6:
2130  //   An operator function shall either be a non-static member
2131  //   function or be a non-member function and have at least one
2132  //   parameter whose type is a class, a reference to a class, an
2133  //   enumeration, or a reference to an enumeration.
2134  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
2135    if (MethodDecl->isStatic())
2136      return Diag(FnDecl->getLocation(),
2137                  diag::err_operator_overload_static) << FnDecl->getDeclName();
2138  } else {
2139    bool ClassOrEnumParam = false;
2140    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2141                                   ParamEnd = FnDecl->param_end();
2142         Param != ParamEnd; ++Param) {
2143      QualType ParamType = (*Param)->getType().getNonReferenceType();
2144      if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
2145        ClassOrEnumParam = true;
2146        break;
2147      }
2148    }
2149
2150    if (!ClassOrEnumParam)
2151      return Diag(FnDecl->getLocation(),
2152                  diag::err_operator_overload_needs_class_or_enum)
2153        << FnDecl->getDeclName();
2154  }
2155
2156  // C++ [over.oper]p8:
2157  //   An operator function cannot have default arguments (8.3.6),
2158  //   except where explicitly stated below.
2159  //
2160  // Only the function-call operator allows default arguments
2161  // (C++ [over.call]p1).
2162  if (Op != OO_Call) {
2163    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2164         Param != FnDecl->param_end(); ++Param) {
2165      if ((*Param)->hasUnparsedDefaultArg())
2166        return Diag((*Param)->getLocation(),
2167                    diag::err_operator_overload_default_arg)
2168          << FnDecl->getDeclName();
2169      else if (Expr *DefArg = (*Param)->getDefaultArg())
2170        return Diag((*Param)->getLocation(),
2171                    diag::err_operator_overload_default_arg)
2172          << FnDecl->getDeclName() << DefArg->getSourceRange();
2173    }
2174  }
2175
2176  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2177    { false, false, false }
2178#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2179    , { Unary, Binary, MemberOnly }
2180#include "clang/Basic/OperatorKinds.def"
2181  };
2182
2183  bool CanBeUnaryOperator = OperatorUses[Op][0];
2184  bool CanBeBinaryOperator = OperatorUses[Op][1];
2185  bool MustBeMemberOperator = OperatorUses[Op][2];
2186
2187  // C++ [over.oper]p8:
2188  //   [...] Operator functions cannot have more or fewer parameters
2189  //   than the number required for the corresponding operator, as
2190  //   described in the rest of this subclause.
2191  unsigned NumParams = FnDecl->getNumParams()
2192                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
2193  if (Op != OO_Call &&
2194      ((NumParams == 1 && !CanBeUnaryOperator) ||
2195       (NumParams == 2 && !CanBeBinaryOperator) ||
2196       (NumParams < 1) || (NumParams > 2))) {
2197    // We have the wrong number of parameters.
2198    unsigned ErrorKind;
2199    if (CanBeUnaryOperator && CanBeBinaryOperator) {
2200      ErrorKind = 2;  // 2 -> unary or binary.
2201    } else if (CanBeUnaryOperator) {
2202      ErrorKind = 0;  // 0 -> unary
2203    } else {
2204      assert(CanBeBinaryOperator &&
2205             "All non-call overloaded operators are unary or binary!");
2206      ErrorKind = 1;  // 1 -> binary
2207    }
2208
2209    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
2210      << FnDecl->getDeclName() << NumParams << ErrorKind;
2211  }
2212
2213  // Overloaded operators other than operator() cannot be variadic.
2214  if (Op != OO_Call &&
2215      FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
2216    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
2217      << FnDecl->getDeclName();
2218  }
2219
2220  // Some operators must be non-static member functions.
2221  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2222    return Diag(FnDecl->getLocation(),
2223                diag::err_operator_overload_must_be_member)
2224      << FnDecl->getDeclName();
2225  }
2226
2227  // C++ [over.inc]p1:
2228  //   The user-defined function called operator++ implements the
2229  //   prefix and postfix ++ operator. If this function is a member
2230  //   function with no parameters, or a non-member function with one
2231  //   parameter of class or enumeration type, it defines the prefix
2232  //   increment operator ++ for objects of that type. If the function
2233  //   is a member function with one parameter (which shall be of type
2234  //   int) or a non-member function with two parameters (the second
2235  //   of which shall be of type int), it defines the postfix
2236  //   increment operator ++ for objects of that type.
2237  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2238    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2239    bool ParamIsInt = false;
2240    if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2241      ParamIsInt = BT->getKind() == BuiltinType::Int;
2242
2243    if (!ParamIsInt)
2244      return Diag(LastParam->getLocation(),
2245                  diag::err_operator_overload_post_incdec_must_be_int)
2246        << LastParam->getType() << (Op == OO_MinusMinus);
2247  }
2248
2249  // Notify the class if it got an assignment operator.
2250  if (Op == OO_Equal) {
2251    // Would have returned earlier otherwise.
2252    assert(isa<CXXMethodDecl>(FnDecl) &&
2253      "Overloaded = not member, but not filtered.");
2254    CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2255    Method->getParent()->addedAssignmentOperator(Context, Method);
2256  }
2257
2258  return false;
2259}
2260
2261/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2262/// linkage specification, including the language and (if present)
2263/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2264/// the location of the language string literal, which is provided
2265/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2266/// the '{' brace. Otherwise, this linkage specification does not
2267/// have any braces.
2268Sema::DeclTy *Sema::ActOnStartLinkageSpecification(Scope *S,
2269                                                   SourceLocation ExternLoc,
2270                                                   SourceLocation LangLoc,
2271                                                   const char *Lang,
2272                                                   unsigned StrSize,
2273                                                   SourceLocation LBraceLoc) {
2274  LinkageSpecDecl::LanguageIDs Language;
2275  if (strncmp(Lang, "\"C\"", StrSize) == 0)
2276    Language = LinkageSpecDecl::lang_c;
2277  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2278    Language = LinkageSpecDecl::lang_cxx;
2279  else {
2280    Diag(LangLoc, diag::err_bad_language);
2281    return 0;
2282  }
2283
2284  // FIXME: Add all the various semantics of linkage specifications
2285
2286  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2287                                               LangLoc, Language,
2288                                               LBraceLoc.isValid());
2289  CurContext->addDecl(D);
2290  PushDeclContext(S, D);
2291  return D;
2292}
2293
2294/// ActOnFinishLinkageSpecification - Completely the definition of
2295/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2296/// valid, it's the position of the closing '}' brace in a linkage
2297/// specification that uses braces.
2298Sema::DeclTy *Sema::ActOnFinishLinkageSpecification(Scope *S,
2299                                                    DeclTy *LinkageSpec,
2300                                                    SourceLocation RBraceLoc) {
2301  if (LinkageSpec)
2302    PopDeclContext();
2303  return LinkageSpec;
2304}
2305
2306/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2307/// handler.
2308Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D)
2309{
2310  QualType ExDeclType = GetTypeForDeclarator(D, S);
2311  SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin();
2312
2313  bool Invalid = false;
2314
2315  // Arrays and functions decay.
2316  if (ExDeclType->isArrayType())
2317    ExDeclType = Context.getArrayDecayedType(ExDeclType);
2318  else if (ExDeclType->isFunctionType())
2319    ExDeclType = Context.getPointerType(ExDeclType);
2320
2321  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2322  // The exception-declaration shall not denote a pointer or reference to an
2323  // incomplete type, other than [cv] void*.
2324  QualType BaseType = ExDeclType;
2325  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
2326  unsigned DK = diag::err_catch_incomplete;
2327  if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2328    BaseType = Ptr->getPointeeType();
2329    Mode = 1;
2330    DK = diag::err_catch_incomplete_ptr;
2331  } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2332    BaseType = Ref->getPointeeType();
2333    Mode = 2;
2334    DK = diag::err_catch_incomplete_ref;
2335  }
2336  if ((Mode == 0 || !BaseType->isVoidType()) &&
2337      RequireCompleteType(Begin, BaseType, DK))
2338    Invalid = true;
2339
2340  // FIXME: C++0x [except.handle] names the handler as cv T or cv T&, i.e.
2341  // rvalue references aren't there. Oversight or intentional?
2342  // FIXME: Need to test for ability to copy-construct and destroy the
2343  // exception variable.
2344  // FIXME: Need to check for abstract classes.
2345
2346  IdentifierInfo *II = D.getIdentifier();
2347  if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
2348    // The scope should be freshly made just for us. There is just no way
2349    // it contains any previous declaration.
2350    assert(!S->isDeclScope(PrevDecl));
2351    if (PrevDecl->isTemplateParameter()) {
2352      // Maybe we will complain about the shadowed template parameter.
2353      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2354
2355    }
2356  }
2357
2358  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
2359                                    II, ExDeclType, VarDecl::None, Begin);
2360  if (D.getInvalidType() || Invalid)
2361    ExDecl->setInvalidDecl();
2362
2363  if (D.getCXXScopeSpec().isSet()) {
2364    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2365      << D.getCXXScopeSpec().getRange();
2366    ExDecl->setInvalidDecl();
2367  }
2368
2369  // Add the exception declaration into this scope.
2370  S->AddDecl(ExDecl);
2371  if (II)
2372    IdResolver.AddDecl(ExDecl);
2373
2374  ProcessDeclAttributes(ExDecl, D);
2375  return ExDecl;
2376}
2377
2378Sema::DeclTy *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
2379                                                 ExprArg assertexpr,
2380                                                 ExprArg assertmessageexpr) {
2381  Expr *AssertExpr = (Expr *)assertexpr.get();
2382  StringLiteral *AssertMessage =
2383    cast<StringLiteral>((Expr *)assertmessageexpr.get());
2384
2385  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
2386    llvm::APSInt Value(32);
2387    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
2388      Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
2389        AssertExpr->getSourceRange();
2390      return 0;
2391    }
2392
2393    if (Value == 0) {
2394      std::string str(AssertMessage->getStrData(),
2395                      AssertMessage->getByteLength());
2396      Diag(AssertLoc, diag::err_static_assert_failed)
2397        << str << AssertExpr->getSourceRange();
2398    }
2399  }
2400
2401  assertexpr.release();
2402  assertmessageexpr.release();
2403  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
2404                                        AssertExpr, AssertMessage);
2405
2406  CurContext->addDecl(Decl);
2407  return Decl;
2408}
2409