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