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