SemaDeclCXX.cpp revision 2b2b736550746280d96b8c49a0462c7b7b6c1408
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/DeclVisitor.h"
19#include "clang/AST/TypeOrdering.h"
20#include "clang/AST/StmtVisitor.h"
21#include "clang/Lex/Preprocessor.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(DeclPtrTy param, SourceLocation EqualLoc,
109                                ExprArg defarg) {
110  if (!param || !defarg.get())
111    return;
112
113  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
114  UnparsedDefaultArgLocs.erase(Param);
115
116  ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
117  QualType ParamType = Param->getType();
118
119  // Default arguments are only permitted in C++
120  if (!getLangOptions().CPlusPlus) {
121    Diag(EqualLoc, diag::err_param_default_argument)
122      << DefaultArg->getSourceRange();
123    Param->setInvalidDecl();
124    return;
125  }
126
127  // C++ [dcl.fct.default]p5
128  //   A default argument expression is implicitly converted (clause
129  //   4) to the parameter type. The default argument expression has
130  //   the same semantic constraints as the initializer expression in
131  //   a declaration of a variable of the parameter type, using the
132  //   copy-initialization semantics (8.5).
133  Expr *DefaultArgPtr = DefaultArg.get();
134  bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
135                                                 EqualLoc,
136                                                 Param->getDeclName(),
137                                                 /*DirectInit=*/false);
138  if (DefaultArgPtr != DefaultArg.get()) {
139    DefaultArg.take();
140    DefaultArg.reset(DefaultArgPtr);
141  }
142  if (DefaultInitFailed) {
143    return;
144  }
145
146  // Check that the default argument is well-formed
147  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
148  if (DefaultArgChecker.Visit(DefaultArg.get())) {
149    Param->setInvalidDecl();
150    return;
151  }
152
153  DefaultArgPtr = MaybeCreateCXXExprWithTemporaries(DefaultArg.take(),
154                                                    /*DestroyTemps=*/false);
155
156  // Okay: add the default argument to the parameter
157  Param->setDefaultArg(DefaultArgPtr);
158}
159
160/// ActOnParamUnparsedDefaultArgument - We've seen a default
161/// argument for a function parameter, but we can't parse it yet
162/// because we're inside a class definition. Note that this default
163/// argument will be parsed later.
164void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
165                                             SourceLocation EqualLoc,
166                                             SourceLocation ArgLoc) {
167  if (!param)
168    return;
169
170  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
171  if (Param)
172    Param->setUnparsedDefaultArg();
173
174  UnparsedDefaultArgLocs[Param] = ArgLoc;
175}
176
177/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
178/// the default argument for the parameter param failed.
179void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
180  if (!param)
181    return;
182
183  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
184
185  Param->setInvalidDecl();
186
187  UnparsedDefaultArgLocs.erase(Param);
188}
189
190/// CheckExtraCXXDefaultArguments - Check for any extra default
191/// arguments in the declarator, which is not a function declaration
192/// or definition and therefore is not permitted to have default
193/// arguments. This routine should be invoked for every declarator
194/// that is not a function declaration or definition.
195void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
196  // C++ [dcl.fct.default]p3
197  //   A default argument expression shall be specified only in the
198  //   parameter-declaration-clause of a function declaration or in a
199  //   template-parameter (14.1). It shall not be specified for a
200  //   parameter pack. If it is specified in a
201  //   parameter-declaration-clause, it shall not occur within a
202  //   declarator or abstract-declarator of a parameter-declaration.
203  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
204    DeclaratorChunk &chunk = D.getTypeObject(i);
205    if (chunk.Kind == DeclaratorChunk::Function) {
206      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
207        ParmVarDecl *Param =
208          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
209        if (Param->hasUnparsedDefaultArg()) {
210          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
211          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
212            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
213          delete Toks;
214          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
215        } else if (Param->getDefaultArg()) {
216          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
217            << Param->getDefaultArg()->getSourceRange();
218          Param->setDefaultArg(0);
219        }
220      }
221    }
222  }
223}
224
225// MergeCXXFunctionDecl - Merge two declarations of the same C++
226// function, once we already know that they have the same
227// type. Subroutine of MergeFunctionDecl. Returns true if there was an
228// error, false otherwise.
229bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
230  bool Invalid = false;
231
232  // C++ [dcl.fct.default]p4:
233  //
234  //   For non-template functions, default arguments can be added in
235  //   later declarations of a function in the same
236  //   scope. Declarations in different scopes have completely
237  //   distinct sets of default arguments. That is, declarations in
238  //   inner scopes do not acquire default arguments from
239  //   declarations in outer scopes, and vice versa. In a given
240  //   function declaration, all parameters subsequent to a
241  //   parameter with a default argument shall have default
242  //   arguments supplied in this or previous declarations. A
243  //   default argument shall not be redefined by a later
244  //   declaration (not even to the same value).
245  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
246    ParmVarDecl *OldParam = Old->getParamDecl(p);
247    ParmVarDecl *NewParam = New->getParamDecl(p);
248
249    if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
250      Diag(NewParam->getLocation(),
251           diag::err_param_default_argument_redefinition)
252        << NewParam->getDefaultArg()->getSourceRange();
253      Diag(OldParam->getLocation(), diag::note_previous_definition);
254      Invalid = true;
255    } else if (OldParam->getDefaultArg()) {
256      // Merge the old default argument into the new parameter
257      NewParam->setDefaultArg(OldParam->getDefaultArg());
258    }
259  }
260
261  return Invalid;
262}
263
264/// CheckCXXDefaultArguments - Verify that the default arguments for a
265/// function declaration are well-formed according to C++
266/// [dcl.fct.default].
267void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
268  unsigned NumParams = FD->getNumParams();
269  unsigned p;
270
271  // Find first parameter with a default argument
272  for (p = 0; p < NumParams; ++p) {
273    ParmVarDecl *Param = FD->getParamDecl(p);
274    if (Param->getDefaultArg())
275      break;
276  }
277
278  // C++ [dcl.fct.default]p4:
279  //   In a given function declaration, all parameters
280  //   subsequent to a parameter with a default argument shall
281  //   have default arguments supplied in this or previous
282  //   declarations. A default argument shall not be redefined
283  //   by a later declaration (not even to the same value).
284  unsigned LastMissingDefaultArg = 0;
285  for(; p < NumParams; ++p) {
286    ParmVarDecl *Param = FD->getParamDecl(p);
287    if (!Param->getDefaultArg()) {
288      if (Param->isInvalidDecl())
289        /* We already complained about this parameter. */;
290      else if (Param->getIdentifier())
291        Diag(Param->getLocation(),
292             diag::err_param_default_argument_missing_name)
293          << Param->getIdentifier();
294      else
295        Diag(Param->getLocation(),
296             diag::err_param_default_argument_missing);
297
298      LastMissingDefaultArg = p;
299    }
300  }
301
302  if (LastMissingDefaultArg > 0) {
303    // Some default arguments were missing. Clear out all of the
304    // default arguments up to (and including) the last missing
305    // default argument, so that we leave the function parameters
306    // in a semantically valid state.
307    for (p = 0; p <= LastMissingDefaultArg; ++p) {
308      ParmVarDecl *Param = FD->getParamDecl(p);
309      if (Param->hasDefaultArg()) {
310        if (!Param->hasUnparsedDefaultArg())
311          Param->getDefaultArg()->Destroy(Context);
312        Param->setDefaultArg(0);
313      }
314    }
315  }
316}
317
318/// isCurrentClassName - Determine whether the identifier II is the
319/// name of the class type currently being defined. In the case of
320/// nested classes, this will only return true if II is the name of
321/// the innermost class.
322bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
323                              const CXXScopeSpec *SS) {
324  CXXRecordDecl *CurDecl;
325  if (SS && SS->isSet() && !SS->isInvalid()) {
326    DeclContext *DC = computeDeclContext(*SS);
327    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
328  } else
329    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
330
331  if (CurDecl)
332    return &II == CurDecl->getIdentifier();
333  else
334    return false;
335}
336
337/// \brief Check the validity of a C++ base class specifier.
338///
339/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
340/// and returns NULL otherwise.
341CXXBaseSpecifier *
342Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
343                         SourceRange SpecifierRange,
344                         bool Virtual, AccessSpecifier Access,
345                         QualType BaseType,
346                         SourceLocation BaseLoc) {
347  // C++ [class.union]p1:
348  //   A union shall not have base classes.
349  if (Class->isUnion()) {
350    Diag(Class->getLocation(), diag::err_base_clause_on_union)
351      << SpecifierRange;
352    return 0;
353  }
354
355  if (BaseType->isDependentType())
356    return new CXXBaseSpecifier(SpecifierRange, Virtual,
357                                Class->getTagKind() == RecordDecl::TK_class,
358                                Access, BaseType);
359
360  // Base specifiers must be record types.
361  if (!BaseType->isRecordType()) {
362    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
363    return 0;
364  }
365
366  // C++ [class.union]p1:
367  //   A union shall not be used as a base class.
368  if (BaseType->isUnionType()) {
369    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
370    return 0;
371  }
372
373  // C++ [class.derived]p2:
374  //   The class-name in a base-specifier shall not be an incompletely
375  //   defined class.
376  if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
377                          SpecifierRange))
378    return 0;
379
380  // If the base class is polymorphic, the new one is, too.
381  RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
382  assert(BaseDecl && "Record type has no declaration");
383  BaseDecl = BaseDecl->getDefinition(Context);
384  assert(BaseDecl && "Base type is not incomplete, but has no definition");
385  if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
386    Class->setPolymorphic(true);
387
388  // C++ [dcl.init.aggr]p1:
389  //   An aggregate is [...] a class with [...] no base classes [...].
390  Class->setAggregate(false);
391  Class->setPOD(false);
392
393  if (Virtual) {
394    // C++ [class.ctor]p5:
395    //   A constructor is trivial if its class has no virtual base classes.
396    Class->setHasTrivialConstructor(false);
397  } else {
398    // C++ [class.ctor]p5:
399    //   A constructor is trivial if all the direct base classes of its
400    //   class have trivial constructors.
401    Class->setHasTrivialConstructor(cast<CXXRecordDecl>(BaseDecl)->
402                                    hasTrivialConstructor());
403  }
404
405  // C++ [class.ctor]p3:
406  //   A destructor is trivial if all the direct base classes of its class
407  //   have trivial destructors.
408  Class->setHasTrivialDestructor(cast<CXXRecordDecl>(BaseDecl)->
409                                 hasTrivialDestructor());
410
411  // Create the base specifier.
412  // FIXME: Allocate via ASTContext?
413  return new CXXBaseSpecifier(SpecifierRange, Virtual,
414                              Class->getTagKind() == RecordDecl::TK_class,
415                              Access, BaseType);
416}
417
418/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
419/// one entry in the base class list of a class specifier, for
420/// example:
421///    class foo : public bar, virtual private baz {
422/// 'public bar' and 'virtual private baz' are each base-specifiers.
423Sema::BaseResult
424Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
425                         bool Virtual, AccessSpecifier Access,
426                         TypeTy *basetype, SourceLocation BaseLoc) {
427  if (!classdecl)
428    return true;
429
430  AdjustDeclIfTemplate(classdecl);
431  CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
432  QualType BaseType = QualType::getFromOpaquePtr(basetype);
433  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
434                                                      Virtual, Access,
435                                                      BaseType, BaseLoc))
436    return BaseSpec;
437
438  return true;
439}
440
441/// \brief Performs the actual work of attaching the given base class
442/// specifiers to a C++ class.
443bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
444                                unsigned NumBases) {
445 if (NumBases == 0)
446    return false;
447
448  // Used to keep track of which base types we have already seen, so
449  // that we can properly diagnose redundant direct base types. Note
450  // that the key is always the unqualified canonical type of the base
451  // class.
452  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
453
454  // Copy non-redundant base specifiers into permanent storage.
455  unsigned NumGoodBases = 0;
456  bool Invalid = false;
457  for (unsigned idx = 0; idx < NumBases; ++idx) {
458    QualType NewBaseType
459      = Context.getCanonicalType(Bases[idx]->getType());
460    NewBaseType = NewBaseType.getUnqualifiedType();
461
462    if (KnownBaseTypes[NewBaseType]) {
463      // C++ [class.mi]p3:
464      //   A class shall not be specified as a direct base class of a
465      //   derived class more than once.
466      Diag(Bases[idx]->getSourceRange().getBegin(),
467           diag::err_duplicate_base_class)
468        << KnownBaseTypes[NewBaseType]->getType()
469        << Bases[idx]->getSourceRange();
470
471      // Delete the duplicate base class specifier; we're going to
472      // overwrite its pointer later.
473      delete Bases[idx];
474
475      Invalid = true;
476    } else {
477      // Okay, add this new base class.
478      KnownBaseTypes[NewBaseType] = Bases[idx];
479      Bases[NumGoodBases++] = Bases[idx];
480    }
481  }
482
483  // Attach the remaining base class specifiers to the derived class.
484  Class->setBases(Bases, NumGoodBases);
485
486  // Delete the remaining (good) base class specifiers, since their
487  // data has been copied into the CXXRecordDecl.
488  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
489    delete Bases[idx];
490
491  return Invalid;
492}
493
494/// ActOnBaseSpecifiers - Attach the given base specifiers to the
495/// class, after checking whether there are any duplicate base
496/// classes.
497void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
498                               unsigned NumBases) {
499  if (!ClassDecl || !Bases || !NumBases)
500    return;
501
502  AdjustDeclIfTemplate(ClassDecl);
503  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
504                       (CXXBaseSpecifier**)(Bases), NumBases);
505}
506
507//===----------------------------------------------------------------------===//
508// C++ class member Handling
509//===----------------------------------------------------------------------===//
510
511/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
512/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
513/// bitfield width if there is one and 'InitExpr' specifies the initializer if
514/// any.
515Sema::DeclPtrTy
516Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
517                               ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
518  const DeclSpec &DS = D.getDeclSpec();
519  DeclarationName Name = GetNameForDeclarator(D);
520  Expr *BitWidth = static_cast<Expr*>(BW);
521  Expr *Init = static_cast<Expr*>(InitExpr);
522  SourceLocation Loc = D.getIdentifierLoc();
523
524  bool isFunc = D.isFunctionDeclarator();
525
526  // C++ 9.2p6: A member shall not be declared to have automatic storage
527  // duration (auto, register) or with the extern storage-class-specifier.
528  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
529  // data members and cannot be applied to names declared const or static,
530  // and cannot be applied to reference members.
531  switch (DS.getStorageClassSpec()) {
532    case DeclSpec::SCS_unspecified:
533    case DeclSpec::SCS_typedef:
534    case DeclSpec::SCS_static:
535      // FALL THROUGH.
536      break;
537    case DeclSpec::SCS_mutable:
538      if (isFunc) {
539        if (DS.getStorageClassSpecLoc().isValid())
540          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
541        else
542          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
543
544        // FIXME: It would be nicer if the keyword was ignored only for this
545        // declarator. Otherwise we could get follow-up errors.
546        D.getMutableDeclSpec().ClearStorageClassSpecs();
547      } else {
548        QualType T = GetTypeForDeclarator(D, S);
549        diag::kind err = static_cast<diag::kind>(0);
550        if (T->isReferenceType())
551          err = diag::err_mutable_reference;
552        else if (T.isConstQualified())
553          err = diag::err_mutable_const;
554        if (err != 0) {
555          if (DS.getStorageClassSpecLoc().isValid())
556            Diag(DS.getStorageClassSpecLoc(), err);
557          else
558            Diag(DS.getThreadSpecLoc(), err);
559          // FIXME: It would be nicer if the keyword was ignored only for this
560          // declarator. Otherwise we could get follow-up errors.
561          D.getMutableDeclSpec().ClearStorageClassSpecs();
562        }
563      }
564      break;
565    default:
566      if (DS.getStorageClassSpecLoc().isValid())
567        Diag(DS.getStorageClassSpecLoc(),
568             diag::err_storageclass_invalid_for_member);
569      else
570        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
571      D.getMutableDeclSpec().ClearStorageClassSpecs();
572  }
573
574  if (!isFunc &&
575      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
576      D.getNumTypeObjects() == 0) {
577    // Check also for this case:
578    //
579    // typedef int f();
580    // f a;
581    //
582    QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep());
583    isFunc = TDType->isFunctionType();
584  }
585
586  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
587                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
588                      !isFunc);
589
590  Decl *Member;
591  if (isInstField) {
592    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
593                         AS);
594    assert(Member && "HandleField never returns null");
595  } else {
596    Member = ActOnDeclarator(S, D).getAs<Decl>();
597    if (!Member) {
598      if (BitWidth) DeleteExpr(BitWidth);
599      return DeclPtrTy();
600    }
601
602    // Non-instance-fields can't have a bitfield.
603    if (BitWidth) {
604      if (Member->isInvalidDecl()) {
605        // don't emit another diagnostic.
606      } else if (isa<VarDecl>(Member)) {
607        // C++ 9.6p3: A bit-field shall not be a static member.
608        // "static member 'A' cannot be a bit-field"
609        Diag(Loc, diag::err_static_not_bitfield)
610          << Name << BitWidth->getSourceRange();
611      } else if (isa<TypedefDecl>(Member)) {
612        // "typedef member 'x' cannot be a bit-field"
613        Diag(Loc, diag::err_typedef_not_bitfield)
614          << Name << BitWidth->getSourceRange();
615      } else {
616        // A function typedef ("typedef int f(); f a;").
617        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
618        Diag(Loc, diag::err_not_integral_type_bitfield)
619          << Name << cast<ValueDecl>(Member)->getType()
620          << BitWidth->getSourceRange();
621      }
622
623      DeleteExpr(BitWidth);
624      BitWidth = 0;
625      Member->setInvalidDecl();
626    }
627
628    Member->setAccess(AS);
629  }
630
631  assert((Name || isInstField) && "No identifier for non-field ?");
632
633  if (Init)
634    AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
635  if (Deleted) // FIXME: Source location is not very good.
636    SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
637
638  if (isInstField) {
639    FieldCollector->Add(cast<FieldDecl>(Member));
640    return DeclPtrTy();
641  }
642  return DeclPtrTy::make(Member);
643}
644
645/// ActOnMemInitializer - Handle a C++ member initializer.
646Sema::MemInitResult
647Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
648                          Scope *S,
649                          const CXXScopeSpec &SS,
650                          IdentifierInfo *MemberOrBase,
651                          TypeTy *TemplateTypeTy,
652                          SourceLocation IdLoc,
653                          SourceLocation LParenLoc,
654                          ExprTy **Args, unsigned NumArgs,
655                          SourceLocation *CommaLocs,
656                          SourceLocation RParenLoc) {
657  if (!ConstructorD)
658    return true;
659
660  CXXConstructorDecl *Constructor
661    = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
662  if (!Constructor) {
663    // The user wrote a constructor initializer on a function that is
664    // not a C++ constructor. Ignore the error for now, because we may
665    // have more member initializers coming; we'll diagnose it just
666    // once in ActOnMemInitializers.
667    return true;
668  }
669
670  CXXRecordDecl *ClassDecl = Constructor->getParent();
671
672  // C++ [class.base.init]p2:
673  //   Names in a mem-initializer-id are looked up in the scope of the
674  //   constructor’s class and, if not found in that scope, are looked
675  //   up in the scope containing the constructor’s
676  //   definition. [Note: if the constructor’s class contains a member
677  //   with the same name as a direct or virtual base class of the
678  //   class, a mem-initializer-id naming the member or base class and
679  //   composed of a single identifier refers to the class member. A
680  //   mem-initializer-id for the hidden base class may be specified
681  //   using a qualified name. ]
682  if (!SS.getScopeRep() && !TemplateTypeTy) {
683    // Look for a member, first.
684    FieldDecl *Member = 0;
685    DeclContext::lookup_result Result
686      = ClassDecl->lookup(MemberOrBase);
687    if (Result.first != Result.second)
688      Member = dyn_cast<FieldDecl>(*Result.first);
689
690    // FIXME: Handle members of an anonymous union.
691
692    if (Member) {
693      // FIXME: Perform direct initialization of the member.
694      return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs,
695                                            IdLoc);
696    }
697  }
698  // It didn't name a member, so see if it names a class.
699  TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
700                     : getTypeName(*MemberOrBase, IdLoc, S, &SS);
701  if (!BaseTy)
702    return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
703      << MemberOrBase << SourceRange(IdLoc, RParenLoc);
704
705  QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
706  if (!BaseType->isRecordType() && !BaseType->isDependentType())
707    return Diag(IdLoc, diag::err_base_init_does_not_name_class)
708      << BaseType << SourceRange(IdLoc, RParenLoc);
709
710  // C++ [class.base.init]p2:
711  //   [...] Unless the mem-initializer-id names a nonstatic data
712  //   member of the constructor’s class or a direct or virtual base
713  //   of that class, the mem-initializer is ill-formed. A
714  //   mem-initializer-list can initialize a base class using any
715  //   name that denotes that base class type.
716
717  // First, check for a direct base class.
718  const CXXBaseSpecifier *DirectBaseSpec = 0;
719  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
720       Base != ClassDecl->bases_end(); ++Base) {
721    if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
722        Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
723      // We found a direct base of this type. That's what we're
724      // initializing.
725      DirectBaseSpec = &*Base;
726      break;
727    }
728  }
729
730  // Check for a virtual base class.
731  // FIXME: We might be able to short-circuit this if we know in advance that
732  // there are no virtual bases.
733  const CXXBaseSpecifier *VirtualBaseSpec = 0;
734  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
735    // We haven't found a base yet; search the class hierarchy for a
736    // virtual base class.
737    BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
738                    /*DetectVirtual=*/false);
739    if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
740      for (BasePaths::paths_iterator Path = Paths.begin();
741           Path != Paths.end(); ++Path) {
742        if (Path->back().Base->isVirtual()) {
743          VirtualBaseSpec = Path->back().Base;
744          break;
745        }
746      }
747    }
748  }
749
750  // C++ [base.class.init]p2:
751  //   If a mem-initializer-id is ambiguous because it designates both
752  //   a direct non-virtual base class and an inherited virtual base
753  //   class, the mem-initializer is ill-formed.
754  if (DirectBaseSpec && VirtualBaseSpec)
755    return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
756      << MemberOrBase << SourceRange(IdLoc, RParenLoc);
757  // C++ [base.class.init]p2:
758  // Unless the mem-initializer-id names a nonstatic data membeer of the
759  // constructor's class ot a direst or virtual base of that class, the
760  // mem-initializer is ill-formed.
761  if (!DirectBaseSpec && !VirtualBaseSpec)
762    return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
763    << BaseType << ClassDecl->getNameAsCString()
764    << SourceRange(IdLoc, RParenLoc);
765
766
767  return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs,
768                                        IdLoc);
769}
770
771void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
772                                SourceLocation ColonLoc,
773                                MemInitTy **MemInits, unsigned NumMemInits) {
774  if (!ConstructorDecl)
775    return;
776
777  CXXConstructorDecl *Constructor
778    = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
779
780  if (!Constructor) {
781    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
782    return;
783  }
784  llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
785
786  for (unsigned i = 0; i < NumMemInits; i++) {
787    CXXBaseOrMemberInitializer *Member =
788      static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
789    void *KeyToMember = Member->getBaseOrMember();
790    // For fields injected into the class via declaration of an anonymous union,
791    // use its anonymous union class declaration as the unique key.
792    if (FieldDecl *Field = Member->getMember())
793      if (Field->getDeclContext()->isRecord() &&
794          cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
795        KeyToMember = static_cast<void *>(Field->getDeclContext());
796    CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
797    if (!PrevMember) {
798      PrevMember = Member;
799      continue;
800    }
801    if (FieldDecl *Field = Member->getMember())
802      Diag(Member->getSourceLocation(),
803           diag::error_multiple_mem_initialization)
804      << Field->getNameAsString();
805    else {
806      Type *BaseClass = Member->getBaseClass();
807      assert(BaseClass && "ActOnMemInitializers - neither field or base");
808      Diag(Member->getSourceLocation(),
809           diag::error_multiple_base_initialization)
810        << BaseClass->getDesugaredType(true);
811    }
812    Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
813      << 0;
814  }
815}
816
817namespace {
818  /// PureVirtualMethodCollector - traverses a class and its superclasses
819  /// and determines if it has any pure virtual methods.
820  class VISIBILITY_HIDDEN PureVirtualMethodCollector {
821    ASTContext &Context;
822
823  public:
824    typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
825
826  private:
827    MethodList Methods;
828
829    void Collect(const CXXRecordDecl* RD, MethodList& Methods);
830
831  public:
832    PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
833      : Context(Ctx) {
834
835      MethodList List;
836      Collect(RD, List);
837
838      // Copy the temporary list to methods, and make sure to ignore any
839      // null entries.
840      for (size_t i = 0, e = List.size(); i != e; ++i) {
841        if (List[i])
842          Methods.push_back(List[i]);
843      }
844    }
845
846    bool empty() const { return Methods.empty(); }
847
848    MethodList::const_iterator methods_begin() { return Methods.begin(); }
849    MethodList::const_iterator methods_end() { return Methods.end(); }
850  };
851
852  void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
853                                           MethodList& Methods) {
854    // First, collect the pure virtual methods for the base classes.
855    for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
856         BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
857      if (const RecordType *RT = Base->getType()->getAsRecordType()) {
858        const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
859        if (BaseDecl && BaseDecl->isAbstract())
860          Collect(BaseDecl, Methods);
861      }
862    }
863
864    // Next, zero out any pure virtual methods that this class overrides.
865    typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
866
867    MethodSetTy OverriddenMethods;
868    size_t MethodsSize = Methods.size();
869
870    for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
871         i != e; ++i) {
872      // Traverse the record, looking for methods.
873      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
874        // If the method is pre virtual, add it to the methods vector.
875        if (MD->isPure()) {
876          Methods.push_back(MD);
877          continue;
878        }
879
880        // Otherwise, record all the overridden methods in our set.
881        for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
882             E = MD->end_overridden_methods(); I != E; ++I) {
883          // Keep track of the overridden methods.
884          OverriddenMethods.insert(*I);
885        }
886      }
887    }
888
889    // Now go through the methods and zero out all the ones we know are
890    // overridden.
891    for (size_t i = 0, e = MethodsSize; i != e; ++i) {
892      if (OverriddenMethods.count(Methods[i]))
893        Methods[i] = 0;
894    }
895
896  }
897}
898
899bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
900                                  unsigned DiagID, AbstractDiagSelID SelID,
901                                  const CXXRecordDecl *CurrentRD) {
902
903  if (!getLangOptions().CPlusPlus)
904    return false;
905
906  if (const ArrayType *AT = Context.getAsArrayType(T))
907    return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
908                                  CurrentRD);
909
910  if (const PointerType *PT = T->getAsPointerType()) {
911    // Find the innermost pointer type.
912    while (const PointerType *T = PT->getPointeeType()->getAsPointerType())
913      PT = T;
914
915    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
916      return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
917                                    CurrentRD);
918  }
919
920  const RecordType *RT = T->getAsRecordType();
921  if (!RT)
922    return false;
923
924  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
925  if (!RD)
926    return false;
927
928  if (CurrentRD && CurrentRD != RD)
929    return false;
930
931  if (!RD->isAbstract())
932    return false;
933
934  Diag(Loc, DiagID) << RD->getDeclName() << SelID;
935
936  // Check if we've already emitted the list of pure virtual functions for this
937  // class.
938  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
939    return true;
940
941  PureVirtualMethodCollector Collector(Context, RD);
942
943  for (PureVirtualMethodCollector::MethodList::const_iterator I =
944       Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
945    const CXXMethodDecl *MD = *I;
946
947    Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
948      MD->getDeclName();
949  }
950
951  if (!PureVirtualClassDiagSet)
952    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
953  PureVirtualClassDiagSet->insert(RD);
954
955  return true;
956}
957
958namespace {
959  class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
960    : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
961    Sema &SemaRef;
962    CXXRecordDecl *AbstractClass;
963
964    bool VisitDeclContext(const DeclContext *DC) {
965      bool Invalid = false;
966
967      for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
968           E = DC->decls_end(); I != E; ++I)
969        Invalid |= Visit(*I);
970
971      return Invalid;
972    }
973
974  public:
975    AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
976      : SemaRef(SemaRef), AbstractClass(ac) {
977        Visit(SemaRef.Context.getTranslationUnitDecl());
978    }
979
980    bool VisitFunctionDecl(const FunctionDecl *FD) {
981      if (FD->isThisDeclarationADefinition()) {
982        // No need to do the check if we're in a definition, because it requires
983        // that the return/param types are complete.
984        // because that requires
985        return VisitDeclContext(FD);
986      }
987
988      // Check the return type.
989      QualType RTy = FD->getType()->getAsFunctionType()->getResultType();
990      bool Invalid =
991        SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
992                                       diag::err_abstract_type_in_decl,
993                                       Sema::AbstractReturnType,
994                                       AbstractClass);
995
996      for (FunctionDecl::param_const_iterator I = FD->param_begin(),
997           E = FD->param_end(); I != E; ++I) {
998        const ParmVarDecl *VD = *I;
999        Invalid |=
1000          SemaRef.RequireNonAbstractType(VD->getLocation(),
1001                                         VD->getOriginalType(),
1002                                         diag::err_abstract_type_in_decl,
1003                                         Sema::AbstractParamType,
1004                                         AbstractClass);
1005      }
1006
1007      return Invalid;
1008    }
1009
1010    bool VisitDecl(const Decl* D) {
1011      if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1012        return VisitDeclContext(DC);
1013
1014      return false;
1015    }
1016  };
1017}
1018
1019void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
1020                                             DeclPtrTy TagDecl,
1021                                             SourceLocation LBrac,
1022                                             SourceLocation RBrac) {
1023  if (!TagDecl)
1024    return;
1025
1026  AdjustDeclIfTemplate(TagDecl);
1027  ActOnFields(S, RLoc, TagDecl,
1028              (DeclPtrTy*)FieldCollector->getCurFields(),
1029              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
1030
1031  CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
1032  if (!RD->isAbstract()) {
1033    // Collect all the pure virtual methods and see if this is an abstract
1034    // class after all.
1035    PureVirtualMethodCollector Collector(Context, RD);
1036    if (!Collector.empty())
1037      RD->setAbstract(true);
1038  }
1039
1040  if (RD->isAbstract())
1041    AbstractClassUsageDiagnoser(*this, RD);
1042
1043  if (RD->hasTrivialConstructor() || RD->hasTrivialDestructor()) {
1044    for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1045         i != e; ++i) {
1046      // All the nonstatic data members must have trivial constructors.
1047      QualType FTy = i->getType();
1048      while (const ArrayType *AT = Context.getAsArrayType(FTy))
1049        FTy = AT->getElementType();
1050
1051      if (const RecordType *RT = FTy->getAsRecordType()) {
1052        CXXRecordDecl *FieldRD = cast<CXXRecordDecl>(RT->getDecl());
1053
1054        if (!FieldRD->hasTrivialConstructor())
1055          RD->setHasTrivialConstructor(false);
1056        if (!FieldRD->hasTrivialDestructor())
1057          RD->setHasTrivialDestructor(false);
1058
1059        // If RD has neither a trivial constructor nor a trivial destructor
1060        // we don't need to continue checking.
1061        if (!RD->hasTrivialConstructor() && !RD->hasTrivialDestructor())
1062          break;
1063      }
1064    }
1065  }
1066
1067  if (!RD->isDependentType())
1068    AddImplicitlyDeclaredMembersToClass(RD);
1069}
1070
1071/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1072/// special functions, such as the default constructor, copy
1073/// constructor, or destructor, to the given C++ class (C++
1074/// [special]p1).  This routine can only be executed just before the
1075/// definition of the class is complete.
1076void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
1077  QualType ClassType = Context.getTypeDeclType(ClassDecl);
1078  ClassType = Context.getCanonicalType(ClassType);
1079
1080  // FIXME: Implicit declarations have exception specifications, which are
1081  // the union of the specifications of the implicitly called functions.
1082
1083  if (!ClassDecl->hasUserDeclaredConstructor()) {
1084    // C++ [class.ctor]p5:
1085    //   A default constructor for a class X is a constructor of class X
1086    //   that can be called without an argument. If there is no
1087    //   user-declared constructor for class X, a default constructor is
1088    //   implicitly declared. An implicitly-declared default constructor
1089    //   is an inline public member of its class.
1090    DeclarationName Name
1091      = Context.DeclarationNames.getCXXConstructorName(ClassType);
1092    CXXConstructorDecl *DefaultCon =
1093      CXXConstructorDecl::Create(Context, ClassDecl,
1094                                 ClassDecl->getLocation(), Name,
1095                                 Context.getFunctionType(Context.VoidTy,
1096                                                         0, 0, false, 0),
1097                                 /*isExplicit=*/false,
1098                                 /*isInline=*/true,
1099                                 /*isImplicitlyDeclared=*/true);
1100    DefaultCon->setAccess(AS_public);
1101    DefaultCon->setImplicit();
1102    ClassDecl->addDecl(DefaultCon);
1103  }
1104
1105  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1106    // C++ [class.copy]p4:
1107    //   If the class definition does not explicitly declare a copy
1108    //   constructor, one is declared implicitly.
1109
1110    // C++ [class.copy]p5:
1111    //   The implicitly-declared copy constructor for a class X will
1112    //   have the form
1113    //
1114    //       X::X(const X&)
1115    //
1116    //   if
1117    bool HasConstCopyConstructor = true;
1118
1119    //     -- each direct or virtual base class B of X has a copy
1120    //        constructor whose first parameter is of type const B& or
1121    //        const volatile B&, and
1122    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1123         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1124      const CXXRecordDecl *BaseClassDecl
1125        = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
1126      HasConstCopyConstructor
1127        = BaseClassDecl->hasConstCopyConstructor(Context);
1128    }
1129
1130    //     -- for all the nonstatic data members of X that are of a
1131    //        class type M (or array thereof), each such class type
1132    //        has a copy constructor whose first parameter is of type
1133    //        const M& or const volatile M&.
1134    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1135         HasConstCopyConstructor && Field != ClassDecl->field_end();
1136         ++Field) {
1137      QualType FieldType = (*Field)->getType();
1138      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1139        FieldType = Array->getElementType();
1140      if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
1141        const CXXRecordDecl *FieldClassDecl
1142          = cast<CXXRecordDecl>(FieldClassType->getDecl());
1143        HasConstCopyConstructor
1144          = FieldClassDecl->hasConstCopyConstructor(Context);
1145      }
1146    }
1147
1148    //   Otherwise, the implicitly declared copy constructor will have
1149    //   the form
1150    //
1151    //       X::X(X&)
1152    QualType ArgType = ClassType;
1153    if (HasConstCopyConstructor)
1154      ArgType = ArgType.withConst();
1155    ArgType = Context.getLValueReferenceType(ArgType);
1156
1157    //   An implicitly-declared copy constructor is an inline public
1158    //   member of its class.
1159    DeclarationName Name
1160      = Context.DeclarationNames.getCXXConstructorName(ClassType);
1161    CXXConstructorDecl *CopyConstructor
1162      = CXXConstructorDecl::Create(Context, ClassDecl,
1163                                   ClassDecl->getLocation(), Name,
1164                                   Context.getFunctionType(Context.VoidTy,
1165                                                           &ArgType, 1,
1166                                                           false, 0),
1167                                   /*isExplicit=*/false,
1168                                   /*isInline=*/true,
1169                                   /*isImplicitlyDeclared=*/true);
1170    CopyConstructor->setAccess(AS_public);
1171    CopyConstructor->setImplicit();
1172
1173    // Add the parameter to the constructor.
1174    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1175                                                 ClassDecl->getLocation(),
1176                                                 /*IdentifierInfo=*/0,
1177                                                 ArgType, VarDecl::None, 0);
1178    CopyConstructor->setParams(Context, &FromParam, 1);
1179    ClassDecl->addDecl(CopyConstructor);
1180  }
1181
1182  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1183    // Note: The following rules are largely analoguous to the copy
1184    // constructor rules. Note that virtual bases are not taken into account
1185    // for determining the argument type of the operator. Note also that
1186    // operators taking an object instead of a reference are allowed.
1187    //
1188    // C++ [class.copy]p10:
1189    //   If the class definition does not explicitly declare a copy
1190    //   assignment operator, one is declared implicitly.
1191    //   The implicitly-defined copy assignment operator for a class X
1192    //   will have the form
1193    //
1194    //       X& X::operator=(const X&)
1195    //
1196    //   if
1197    bool HasConstCopyAssignment = true;
1198
1199    //       -- each direct base class B of X has a copy assignment operator
1200    //          whose parameter is of type const B&, const volatile B& or B,
1201    //          and
1202    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1203         HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1204      const CXXRecordDecl *BaseClassDecl
1205        = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
1206      HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
1207    }
1208
1209    //       -- for all the nonstatic data members of X that are of a class
1210    //          type M (or array thereof), each such class type has a copy
1211    //          assignment operator whose parameter is of type const M&,
1212    //          const volatile M& or M.
1213    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1214         HasConstCopyAssignment && Field != ClassDecl->field_end();
1215         ++Field) {
1216      QualType FieldType = (*Field)->getType();
1217      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1218        FieldType = Array->getElementType();
1219      if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
1220        const CXXRecordDecl *FieldClassDecl
1221          = cast<CXXRecordDecl>(FieldClassType->getDecl());
1222        HasConstCopyAssignment
1223          = FieldClassDecl->hasConstCopyAssignment(Context);
1224      }
1225    }
1226
1227    //   Otherwise, the implicitly declared copy assignment operator will
1228    //   have the form
1229    //
1230    //       X& X::operator=(X&)
1231    QualType ArgType = ClassType;
1232    QualType RetType = Context.getLValueReferenceType(ArgType);
1233    if (HasConstCopyAssignment)
1234      ArgType = ArgType.withConst();
1235    ArgType = Context.getLValueReferenceType(ArgType);
1236
1237    //   An implicitly-declared copy assignment operator is an inline public
1238    //   member of its class.
1239    DeclarationName Name =
1240      Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1241    CXXMethodDecl *CopyAssignment =
1242      CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1243                            Context.getFunctionType(RetType, &ArgType, 1,
1244                                                    false, 0),
1245                            /*isStatic=*/false, /*isInline=*/true);
1246    CopyAssignment->setAccess(AS_public);
1247    CopyAssignment->setImplicit();
1248
1249    // Add the parameter to the operator.
1250    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1251                                                 ClassDecl->getLocation(),
1252                                                 /*IdentifierInfo=*/0,
1253                                                 ArgType, VarDecl::None, 0);
1254    CopyAssignment->setParams(Context, &FromParam, 1);
1255
1256    // Don't call addedAssignmentOperator. There is no way to distinguish an
1257    // implicit from an explicit assignment operator.
1258    ClassDecl->addDecl(CopyAssignment);
1259  }
1260
1261  if (!ClassDecl->hasUserDeclaredDestructor()) {
1262    // C++ [class.dtor]p2:
1263    //   If a class has no user-declared destructor, a destructor is
1264    //   declared implicitly. An implicitly-declared destructor is an
1265    //   inline public member of its class.
1266    DeclarationName Name
1267      = Context.DeclarationNames.getCXXDestructorName(ClassType);
1268    CXXDestructorDecl *Destructor
1269      = CXXDestructorDecl::Create(Context, ClassDecl,
1270                                  ClassDecl->getLocation(), Name,
1271                                  Context.getFunctionType(Context.VoidTy,
1272                                                          0, 0, false, 0),
1273                                  /*isInline=*/true,
1274                                  /*isImplicitlyDeclared=*/true);
1275    Destructor->setAccess(AS_public);
1276    Destructor->setImplicit();
1277    ClassDecl->addDecl(Destructor);
1278  }
1279}
1280
1281void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
1282  TemplateDecl *Template = TemplateD.getAs<TemplateDecl>();
1283  if (!Template)
1284    return;
1285
1286  TemplateParameterList *Params = Template->getTemplateParameters();
1287  for (TemplateParameterList::iterator Param = Params->begin(),
1288                                    ParamEnd = Params->end();
1289       Param != ParamEnd; ++Param) {
1290    NamedDecl *Named = cast<NamedDecl>(*Param);
1291    if (Named->getDeclName()) {
1292      S->AddDecl(DeclPtrTy::make(Named));
1293      IdResolver.AddDecl(Named);
1294    }
1295  }
1296}
1297
1298/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1299/// parsing a top-level (non-nested) C++ class, and we are now
1300/// parsing those parts of the given Method declaration that could
1301/// not be parsed earlier (C++ [class.mem]p2), such as default
1302/// arguments. This action should enter the scope of the given
1303/// Method declaration as if we had just parsed the qualified method
1304/// name. However, it should not bring the parameters into scope;
1305/// that will be performed by ActOnDelayedCXXMethodParameter.
1306void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
1307  if (!MethodD)
1308    return;
1309
1310  CXXScopeSpec SS;
1311  FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
1312  QualType ClassTy
1313    = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1314  SS.setScopeRep(
1315    NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
1316  ActOnCXXEnterDeclaratorScope(S, SS);
1317}
1318
1319/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1320/// C++ method declaration. We're (re-)introducing the given
1321/// function parameter into scope for use in parsing later parts of
1322/// the method declaration. For example, we could see an
1323/// ActOnParamDefaultArgument event for this parameter.
1324void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
1325  if (!ParamD)
1326    return;
1327
1328  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
1329
1330  // If this parameter has an unparsed default argument, clear it out
1331  // to make way for the parsed default argument.
1332  if (Param->hasUnparsedDefaultArg())
1333    Param->setDefaultArg(0);
1334
1335  S->AddDecl(DeclPtrTy::make(Param));
1336  if (Param->getDeclName())
1337    IdResolver.AddDecl(Param);
1338}
1339
1340/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1341/// processing the delayed method declaration for Method. The method
1342/// declaration is now considered finished. There may be a separate
1343/// ActOnStartOfFunctionDef action later (not necessarily
1344/// immediately!) for this method, if it was also defined inside the
1345/// class body.
1346void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
1347  if (!MethodD)
1348    return;
1349
1350  FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
1351  CXXScopeSpec SS;
1352  QualType ClassTy
1353    = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1354  SS.setScopeRep(
1355    NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
1356  ActOnCXXExitDeclaratorScope(S, SS);
1357
1358  // Now that we have our default arguments, check the constructor
1359  // again. It could produce additional diagnostics or affect whether
1360  // the class has implicitly-declared destructors, among other
1361  // things.
1362  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
1363    CheckConstructor(Constructor);
1364
1365  // Check the default arguments, which we may have added.
1366  if (!Method->isInvalidDecl())
1367    CheckCXXDefaultArguments(Method);
1368}
1369
1370/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
1371/// the well-formedness of the constructor declarator @p D with type @p
1372/// R. If there are any errors in the declarator, this routine will
1373/// emit diagnostics and set the invalid bit to true.  In any case, the type
1374/// will be updated to reflect a well-formed type for the constructor and
1375/// returned.
1376QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
1377                                          FunctionDecl::StorageClass &SC) {
1378  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1379
1380  // C++ [class.ctor]p3:
1381  //   A constructor shall not be virtual (10.3) or static (9.4). A
1382  //   constructor can be invoked for a const, volatile or const
1383  //   volatile object. A constructor shall not be declared const,
1384  //   volatile, or const volatile (9.3.2).
1385  if (isVirtual) {
1386    if (!D.isInvalidType())
1387      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1388        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1389        << SourceRange(D.getIdentifierLoc());
1390    D.setInvalidType();
1391  }
1392  if (SC == FunctionDecl::Static) {
1393    if (!D.isInvalidType())
1394      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1395        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1396        << SourceRange(D.getIdentifierLoc());
1397    D.setInvalidType();
1398    SC = FunctionDecl::None;
1399  }
1400
1401  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1402  if (FTI.TypeQuals != 0) {
1403    if (FTI.TypeQuals & QualType::Const)
1404      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1405        << "const" << SourceRange(D.getIdentifierLoc());
1406    if (FTI.TypeQuals & QualType::Volatile)
1407      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1408        << "volatile" << SourceRange(D.getIdentifierLoc());
1409    if (FTI.TypeQuals & QualType::Restrict)
1410      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1411        << "restrict" << SourceRange(D.getIdentifierLoc());
1412  }
1413
1414  // Rebuild the function type "R" without any type qualifiers (in
1415  // case any of the errors above fired) and with "void" as the
1416  // return type, since constructors don't have return types. We
1417  // *always* have to do this, because GetTypeForDeclarator will
1418  // put in a result type of "int" when none was specified.
1419  const FunctionProtoType *Proto = R->getAsFunctionProtoType();
1420  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1421                                 Proto->getNumArgs(),
1422                                 Proto->isVariadic(), 0);
1423}
1424
1425/// CheckConstructor - Checks a fully-formed constructor for
1426/// well-formedness, issuing any diagnostics required. Returns true if
1427/// the constructor declarator is invalid.
1428void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1429  CXXRecordDecl *ClassDecl
1430    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
1431  if (!ClassDecl)
1432    return Constructor->setInvalidDecl();
1433
1434  // C++ [class.copy]p3:
1435  //   A declaration of a constructor for a class X is ill-formed if
1436  //   its first parameter is of type (optionally cv-qualified) X and
1437  //   either there are no other parameters or else all other
1438  //   parameters have default arguments.
1439  if (!Constructor->isInvalidDecl() &&
1440      ((Constructor->getNumParams() == 1) ||
1441       (Constructor->getNumParams() > 1 &&
1442        Constructor->getParamDecl(1)->hasDefaultArg()))) {
1443    QualType ParamType = Constructor->getParamDecl(0)->getType();
1444    QualType ClassTy = Context.getTagDeclType(ClassDecl);
1445    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1446      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
1447      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
1448        << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
1449      Constructor->setInvalidDecl();
1450    }
1451  }
1452
1453  // Notify the class that we've added a constructor.
1454  ClassDecl->addedConstructor(Context, Constructor);
1455}
1456
1457static inline bool
1458FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
1459  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1460          FTI.ArgInfo[0].Param &&
1461          FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
1462}
1463
1464/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1465/// the well-formednes of the destructor declarator @p D with type @p
1466/// R. If there are any errors in the declarator, this routine will
1467/// emit diagnostics and set the declarator to invalid.  Even if this happens,
1468/// will be updated to reflect a well-formed type for the destructor and
1469/// returned.
1470QualType Sema::CheckDestructorDeclarator(Declarator &D,
1471                                         FunctionDecl::StorageClass& SC) {
1472  // C++ [class.dtor]p1:
1473  //   [...] A typedef-name that names a class is a class-name
1474  //   (7.1.3); however, a typedef-name that names a class shall not
1475  //   be used as the identifier in the declarator for a destructor
1476  //   declaration.
1477  QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1478  if (isa<TypedefType>(DeclaratorType)) {
1479    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
1480      << DeclaratorType;
1481    D.setInvalidType();
1482  }
1483
1484  // C++ [class.dtor]p2:
1485  //   A destructor is used to destroy objects of its class type. A
1486  //   destructor takes no parameters, and no return type can be
1487  //   specified for it (not even void). The address of a destructor
1488  //   shall not be taken. A destructor shall not be static. A
1489  //   destructor can be invoked for a const, volatile or const
1490  //   volatile object. A destructor shall not be declared const,
1491  //   volatile or const volatile (9.3.2).
1492  if (SC == FunctionDecl::Static) {
1493    if (!D.isInvalidType())
1494      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1495        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1496        << SourceRange(D.getIdentifierLoc());
1497    SC = FunctionDecl::None;
1498    D.setInvalidType();
1499  }
1500  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
1501    // Destructors don't have return types, but the parser will
1502    // happily parse something like:
1503    //
1504    //   class X {
1505    //     float ~X();
1506    //   };
1507    //
1508    // The return type will be eliminated later.
1509    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1510      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1511      << SourceRange(D.getIdentifierLoc());
1512  }
1513
1514  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1515  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
1516    if (FTI.TypeQuals & QualType::Const)
1517      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1518        << "const" << SourceRange(D.getIdentifierLoc());
1519    if (FTI.TypeQuals & QualType::Volatile)
1520      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1521        << "volatile" << SourceRange(D.getIdentifierLoc());
1522    if (FTI.TypeQuals & QualType::Restrict)
1523      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1524        << "restrict" << SourceRange(D.getIdentifierLoc());
1525    D.setInvalidType();
1526  }
1527
1528  // Make sure we don't have any parameters.
1529  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
1530    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1531
1532    // Delete the parameters.
1533    FTI.freeArgs();
1534    D.setInvalidType();
1535  }
1536
1537  // Make sure the destructor isn't variadic.
1538  if (FTI.isVariadic) {
1539    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1540    D.setInvalidType();
1541  }
1542
1543  // Rebuild the function type "R" without any type qualifiers or
1544  // parameters (in case any of the errors above fired) and with
1545  // "void" as the return type, since destructors don't have return
1546  // types. We *always* have to do this, because GetTypeForDeclarator
1547  // will put in a result type of "int" when none was specified.
1548  return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1549}
1550
1551/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1552/// well-formednes of the conversion function declarator @p D with
1553/// type @p R. If there are any errors in the declarator, this routine
1554/// will emit diagnostics and return true. Otherwise, it will return
1555/// false. Either way, the type @p R will be updated to reflect a
1556/// well-formed type for the conversion operator.
1557void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1558                                     FunctionDecl::StorageClass& SC) {
1559  // C++ [class.conv.fct]p1:
1560  //   Neither parameter types nor return type can be specified. The
1561  //   type of a conversion function (8.3.5) is “function taking no
1562  //   parameter returning conversion-type-id.”
1563  if (SC == FunctionDecl::Static) {
1564    if (!D.isInvalidType())
1565      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1566        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1567        << SourceRange(D.getIdentifierLoc());
1568    D.setInvalidType();
1569    SC = FunctionDecl::None;
1570  }
1571  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
1572    // Conversion functions don't have return types, but the parser will
1573    // happily parse something like:
1574    //
1575    //   class X {
1576    //     float operator bool();
1577    //   };
1578    //
1579    // The return type will be changed later anyway.
1580    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1581      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1582      << SourceRange(D.getIdentifierLoc());
1583  }
1584
1585  // Make sure we don't have any parameters.
1586  if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
1587    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1588
1589    // Delete the parameters.
1590    D.getTypeObject(0).Fun.freeArgs();
1591    D.setInvalidType();
1592  }
1593
1594  // Make sure the conversion function isn't variadic.
1595  if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) {
1596    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1597    D.setInvalidType();
1598  }
1599
1600  // C++ [class.conv.fct]p4:
1601  //   The conversion-type-id shall not represent a function type nor
1602  //   an array type.
1603  QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1604  if (ConvType->isArrayType()) {
1605    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1606    ConvType = Context.getPointerType(ConvType);
1607    D.setInvalidType();
1608  } else if (ConvType->isFunctionType()) {
1609    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1610    ConvType = Context.getPointerType(ConvType);
1611    D.setInvalidType();
1612  }
1613
1614  // Rebuild the function type "R" without any parameters (in case any
1615  // of the errors above fired) and with the conversion type as the
1616  // return type.
1617  R = Context.getFunctionType(ConvType, 0, 0, false,
1618                              R->getAsFunctionProtoType()->getTypeQuals());
1619
1620  // C++0x explicit conversion operators.
1621  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1622    Diag(D.getDeclSpec().getExplicitSpecLoc(),
1623         diag::warn_explicit_conversion_functions)
1624      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1625}
1626
1627/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1628/// the declaration of the given C++ conversion function. This routine
1629/// is responsible for recording the conversion function in the C++
1630/// class, if possible.
1631Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1632  assert(Conversion && "Expected to receive a conversion function declaration");
1633
1634  // Set the lexical context of this conversion function
1635  Conversion->setLexicalDeclContext(CurContext);
1636
1637  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
1638
1639  // Make sure we aren't redeclaring the conversion function.
1640  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
1641
1642  // C++ [class.conv.fct]p1:
1643  //   [...] A conversion function is never used to convert a
1644  //   (possibly cv-qualified) object to the (possibly cv-qualified)
1645  //   same object type (or a reference to it), to a (possibly
1646  //   cv-qualified) base class of that type (or a reference to it),
1647  //   or to (possibly cv-qualified) void.
1648  // FIXME: Suppress this warning if the conversion function ends up being a
1649  // virtual function that overrides a virtual function in a base class.
1650  QualType ClassType
1651    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1652  if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1653    ConvType = ConvTypeRef->getPointeeType();
1654  if (ConvType->isRecordType()) {
1655    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1656    if (ConvType == ClassType)
1657      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
1658        << ClassType;
1659    else if (IsDerivedFrom(ClassType, ConvType))
1660      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
1661        <<  ClassType << ConvType;
1662  } else if (ConvType->isVoidType()) {
1663    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
1664      << ClassType << ConvType;
1665  }
1666
1667  if (Conversion->getPreviousDeclaration()) {
1668    OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1669    for (OverloadedFunctionDecl::function_iterator
1670           Conv = Conversions->function_begin(),
1671           ConvEnd = Conversions->function_end();
1672         Conv != ConvEnd; ++Conv) {
1673      if (*Conv
1674            == cast_or_null<NamedDecl>(Conversion->getPreviousDeclaration())) {
1675        *Conv = Conversion;
1676        return DeclPtrTy::make(Conversion);
1677      }
1678    }
1679    assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1680  } else
1681    ClassDecl->addConversionFunction(Context, Conversion);
1682
1683  return DeclPtrTy::make(Conversion);
1684}
1685
1686//===----------------------------------------------------------------------===//
1687// Namespace Handling
1688//===----------------------------------------------------------------------===//
1689
1690/// ActOnStartNamespaceDef - This is called at the start of a namespace
1691/// definition.
1692Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1693                                             SourceLocation IdentLoc,
1694                                             IdentifierInfo *II,
1695                                             SourceLocation LBrace) {
1696  NamespaceDecl *Namespc =
1697      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1698  Namespc->setLBracLoc(LBrace);
1699
1700  Scope *DeclRegionScope = NamespcScope->getParent();
1701
1702  if (II) {
1703    // C++ [namespace.def]p2:
1704    // The identifier in an original-namespace-definition shall not have been
1705    // previously defined in the declarative region in which the
1706    // original-namespace-definition appears. The identifier in an
1707    // original-namespace-definition is the name of the namespace. Subsequently
1708    // in that declarative region, it is treated as an original-namespace-name.
1709
1710    NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1711                                     true);
1712
1713    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1714      // This is an extended namespace definition.
1715      // Attach this namespace decl to the chain of extended namespace
1716      // definitions.
1717      OrigNS->setNextNamespace(Namespc);
1718      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
1719
1720      // Remove the previous declaration from the scope.
1721      if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
1722        IdResolver.RemoveDecl(OrigNS);
1723        DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
1724      }
1725    } else if (PrevDecl) {
1726      // This is an invalid name redefinition.
1727      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1728       << Namespc->getDeclName();
1729      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1730      Namespc->setInvalidDecl();
1731      // Continue on to push Namespc as current DeclContext and return it.
1732    }
1733
1734    PushOnScopeChains(Namespc, DeclRegionScope);
1735  } else {
1736    // FIXME: Handle anonymous namespaces
1737  }
1738
1739  // Although we could have an invalid decl (i.e. the namespace name is a
1740  // redefinition), push it as current DeclContext and try to continue parsing.
1741  // FIXME: We should be able to push Namespc here, so that the each DeclContext
1742  // for the namespace has the declarations that showed up in that particular
1743  // namespace definition.
1744  PushDeclContext(NamespcScope, Namespc);
1745  return DeclPtrTy::make(Namespc);
1746}
1747
1748/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1749/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1750void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
1751  Decl *Dcl = D.getAs<Decl>();
1752  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1753  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1754  Namespc->setRBracLoc(RBrace);
1755  PopDeclContext();
1756}
1757
1758Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
1759                                          SourceLocation UsingLoc,
1760                                          SourceLocation NamespcLoc,
1761                                          const CXXScopeSpec &SS,
1762                                          SourceLocation IdentLoc,
1763                                          IdentifierInfo *NamespcName,
1764                                          AttributeList *AttrList) {
1765  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1766  assert(NamespcName && "Invalid NamespcName.");
1767  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
1768  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
1769
1770  UsingDirectiveDecl *UDir = 0;
1771
1772  // Lookup namespace name.
1773  LookupResult R = LookupParsedName(S, &SS, NamespcName,
1774                                    LookupNamespaceName, false);
1775  if (R.isAmbiguous()) {
1776    DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
1777    return DeclPtrTy();
1778  }
1779  if (NamedDecl *NS = R) {
1780    assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
1781    // C++ [namespace.udir]p1:
1782    //   A using-directive specifies that the names in the nominated
1783    //   namespace can be used in the scope in which the
1784    //   using-directive appears after the using-directive. During
1785    //   unqualified name lookup (3.4.1), the names appear as if they
1786    //   were declared in the nearest enclosing namespace which
1787    //   contains both the using-directive and the nominated
1788    //   namespace. [Note: in this context, “contains” means “contains
1789    //   directly or indirectly”. ]
1790
1791    // Find enclosing context containing both using-directive and
1792    // nominated namespace.
1793    DeclContext *CommonAncestor = cast<DeclContext>(NS);
1794    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1795      CommonAncestor = CommonAncestor->getParent();
1796
1797    UDir = UsingDirectiveDecl::Create(Context,
1798                                      CurContext, UsingLoc,
1799                                      NamespcLoc,
1800                                      SS.getRange(),
1801                                      (NestedNameSpecifier *)SS.getScopeRep(),
1802                                      IdentLoc,
1803                                      cast<NamespaceDecl>(NS),
1804                                      CommonAncestor);
1805    PushUsingDirective(S, UDir);
1806  } else {
1807    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
1808  }
1809
1810  // FIXME: We ignore attributes for now.
1811  delete AttrList;
1812  return DeclPtrTy::make(UDir);
1813}
1814
1815void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1816  // If scope has associated entity, then using directive is at namespace
1817  // or translation unit scope. We add UsingDirectiveDecls, into
1818  // it's lookup structure.
1819  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
1820    Ctx->addDecl(UDir);
1821  else
1822    // Otherwise it is block-sope. using-directives will affect lookup
1823    // only to the end of scope.
1824    S->PushUsingDirective(DeclPtrTy::make(UDir));
1825}
1826
1827
1828Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
1829                                          SourceLocation UsingLoc,
1830                                          const CXXScopeSpec &SS,
1831                                          SourceLocation IdentLoc,
1832                                          IdentifierInfo *TargetName,
1833                                          OverloadedOperatorKind Op,
1834                                          AttributeList *AttrList,
1835                                          bool IsTypeName) {
1836  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1837  assert((TargetName || Op) && "Invalid TargetName.");
1838  assert(IdentLoc.isValid() && "Invalid TargetName location.");
1839  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
1840
1841  UsingDecl *UsingAlias = 0;
1842
1843  DeclarationName Name;
1844  if (TargetName)
1845    Name = TargetName;
1846  else
1847    Name = Context.DeclarationNames.getCXXOperatorName(Op);
1848
1849  // Lookup target name.
1850  LookupResult R = LookupParsedName(S, &SS, Name, LookupOrdinaryName, false);
1851
1852  if (NamedDecl *NS = R) {
1853    if (IsTypeName && !isa<TypeDecl>(NS)) {
1854      Diag(IdentLoc, diag::err_using_typename_non_type);
1855    }
1856    UsingAlias = UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
1857        NS->getLocation(), UsingLoc, NS,
1858        static_cast<NestedNameSpecifier *>(SS.getScopeRep()),
1859        IsTypeName);
1860    PushOnScopeChains(UsingAlias, S);
1861  } else {
1862    Diag(IdentLoc, diag::err_using_requires_qualname) << SS.getRange();
1863  }
1864
1865  // FIXME: We ignore attributes for now.
1866  delete AttrList;
1867  return DeclPtrTy::make(UsingAlias);
1868}
1869
1870/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
1871/// is a namespace alias, returns the namespace it points to.
1872static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
1873  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
1874    return AD->getNamespace();
1875  return dyn_cast_or_null<NamespaceDecl>(D);
1876}
1877
1878Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
1879                                             SourceLocation NamespaceLoc,
1880                                             SourceLocation AliasLoc,
1881                                             IdentifierInfo *Alias,
1882                                             const CXXScopeSpec &SS,
1883                                             SourceLocation IdentLoc,
1884                                             IdentifierInfo *Ident) {
1885
1886  // Lookup the namespace name.
1887  LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
1888
1889  // Check if we have a previous declaration with the same name.
1890  if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
1891    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
1892      // We already have an alias with the same name that points to the same
1893      // namespace, so don't create a new one.
1894      if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
1895        return DeclPtrTy();
1896    }
1897
1898    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
1899      diag::err_redefinition_different_kind;
1900    Diag(AliasLoc, DiagID) << Alias;
1901    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1902    return DeclPtrTy();
1903  }
1904
1905  if (R.isAmbiguous()) {
1906    DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
1907    return DeclPtrTy();
1908  }
1909
1910  if (!R) {
1911    Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
1912    return DeclPtrTy();
1913  }
1914
1915  NamespaceAliasDecl *AliasDecl =
1916    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
1917                               Alias, SS.getRange(),
1918                               (NestedNameSpecifier *)SS.getScopeRep(),
1919                               IdentLoc, R);
1920
1921  CurContext->addDecl(AliasDecl);
1922  return DeclPtrTy::make(AliasDecl);
1923}
1924
1925void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
1926                                            CXXConstructorDecl *Constructor) {
1927  assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
1928          !Constructor->isUsed()) &&
1929    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
1930
1931  CXXRecordDecl *ClassDecl
1932    = cast<CXXRecordDecl>(Constructor->getDeclContext());
1933  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
1934  // Before the implicitly-declared default constructor for a class is
1935  // implicitly defined, all the implicitly-declared default constructors
1936  // for its base class and its non-static data members shall have been
1937  // implicitly defined.
1938  bool err = false;
1939  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1940       E = ClassDecl->bases_end(); Base != E; ++Base) {
1941    CXXRecordDecl *BaseClassDecl
1942      = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
1943    if (!BaseClassDecl->hasTrivialConstructor()) {
1944      if (CXXConstructorDecl *BaseCtor =
1945            BaseClassDecl->getDefaultConstructor(Context))
1946        MarkDeclarationReferenced(CurrentLocation, BaseCtor);
1947      else {
1948        Diag(CurrentLocation, diag::err_defining_default_ctor)
1949          << Context.getTagDeclType(ClassDecl) << 1
1950          << Context.getTagDeclType(BaseClassDecl);
1951        Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
1952              << Context.getTagDeclType(BaseClassDecl);
1953        err = true;
1954      }
1955    }
1956  }
1957  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1958       E = ClassDecl->field_end(); Field != E; ++Field) {
1959    QualType FieldType = Context.getCanonicalType((*Field)->getType());
1960    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1961      FieldType = Array->getElementType();
1962    if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
1963      CXXRecordDecl *FieldClassDecl
1964        = cast<CXXRecordDecl>(FieldClassType->getDecl());
1965      if (!FieldClassDecl->hasTrivialConstructor()) {
1966        if (CXXConstructorDecl *FieldCtor =
1967            FieldClassDecl->getDefaultConstructor(Context))
1968          MarkDeclarationReferenced(CurrentLocation, FieldCtor);
1969        else {
1970          Diag(CurrentLocation, diag::err_defining_default_ctor)
1971          << Context.getTagDeclType(ClassDecl) << 0 <<
1972              Context.getTagDeclType(FieldClassDecl);
1973          Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
1974          << Context.getTagDeclType(FieldClassDecl);
1975          err = true;
1976        }
1977      }
1978    }
1979    else if (FieldType->isReferenceType()) {
1980      Diag(CurrentLocation, diag::err_unintialized_member)
1981        << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getNameAsCString();
1982      Diag((*Field)->getLocation(), diag::note_declared_at);
1983      err = true;
1984    }
1985    else if (FieldType.isConstQualified()) {
1986      Diag(CurrentLocation, diag::err_unintialized_member)
1987        << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getNameAsCString();
1988       Diag((*Field)->getLocation(), diag::note_declared_at);
1989      err = true;
1990    }
1991  }
1992  if (!err)
1993    Constructor->setUsed();
1994  else
1995    Constructor->setInvalidDecl();
1996}
1997
1998void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
1999                                            CXXDestructorDecl *Destructor) {
2000  assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2001         "DefineImplicitDestructor - call it for implicit default dtor");
2002
2003  CXXRecordDecl *ClassDecl
2004  = cast<CXXRecordDecl>(Destructor->getDeclContext());
2005  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2006  // C++ [class.dtor] p5
2007  // Before the implicitly-declared default destructor for a class is
2008  // implicitly defined, all the implicitly-declared default destructors
2009  // for its base class and its non-static data members shall have been
2010  // implicitly defined.
2011  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2012       E = ClassDecl->bases_end(); Base != E; ++Base) {
2013    CXXRecordDecl *BaseClassDecl
2014      = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
2015    if (!BaseClassDecl->hasTrivialDestructor()) {
2016      if (CXXDestructorDecl *BaseDtor =
2017          const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2018        MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2019      else
2020        assert(false &&
2021               "DefineImplicitDestructor - missing dtor in a base class");
2022    }
2023  }
2024
2025  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2026       E = ClassDecl->field_end(); Field != E; ++Field) {
2027    QualType FieldType = Context.getCanonicalType((*Field)->getType());
2028    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2029      FieldType = Array->getElementType();
2030    if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
2031      CXXRecordDecl *FieldClassDecl
2032        = cast<CXXRecordDecl>(FieldClassType->getDecl());
2033      if (!FieldClassDecl->hasTrivialDestructor()) {
2034        if (CXXDestructorDecl *FieldDtor =
2035            const_cast<CXXDestructorDecl*>(
2036                                        FieldClassDecl->getDestructor(Context)))
2037          MarkDeclarationReferenced(CurrentLocation, FieldDtor);
2038        else
2039          assert(false &&
2040          "DefineImplicitDestructor - missing dtor in class of a data member");
2041      }
2042    }
2043  }
2044  Destructor->setUsed();
2045}
2046
2047void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
2048                                          CXXMethodDecl *MethodDecl) {
2049  assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
2050          MethodDecl->getOverloadedOperator() == OO_Equal &&
2051          !MethodDecl->isUsed()) &&
2052         "DefineImplicitOverloadedAssign - call it for implicit assignment op");
2053
2054  CXXRecordDecl *ClassDecl
2055    = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
2056
2057  // C++[class.copy] p12
2058  // Before the implicitly-declared copy assignment operator for a class is
2059  // implicitly defined, all implicitly-declared copy assignment operators
2060  // for its direct base classes and its nonstatic data members shall have
2061  // been implicitly defined.
2062  bool err = false;
2063  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2064       E = ClassDecl->bases_end(); Base != E; ++Base) {
2065    CXXRecordDecl *BaseClassDecl
2066      = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
2067    if (CXXMethodDecl *BaseAssignOpMethod =
2068          getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
2069      MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
2070  }
2071  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2072       E = ClassDecl->field_end(); Field != E; ++Field) {
2073    QualType FieldType = Context.getCanonicalType((*Field)->getType());
2074    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2075      FieldType = Array->getElementType();
2076    if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
2077      CXXRecordDecl *FieldClassDecl
2078        = cast<CXXRecordDecl>(FieldClassType->getDecl());
2079      if (CXXMethodDecl *FieldAssignOpMethod =
2080          getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
2081        MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
2082    }
2083    else if (FieldType->isReferenceType()) {
2084      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
2085      << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getNameAsCString();
2086      Diag((*Field)->getLocation(), diag::note_declared_at);
2087      Diag(CurrentLocation, diag::note_first_required_here);
2088      err = true;
2089    }
2090    else if (FieldType.isConstQualified()) {
2091      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
2092      << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getNameAsCString();
2093      Diag((*Field)->getLocation(), diag::note_declared_at);
2094      Diag(CurrentLocation, diag::note_first_required_here);
2095      err = true;
2096    }
2097  }
2098  if (!err)
2099    MethodDecl->setUsed();
2100}
2101
2102CXXMethodDecl *
2103Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
2104                              CXXRecordDecl *ClassDecl) {
2105  QualType LHSType = Context.getTypeDeclType(ClassDecl);
2106  QualType RHSType(LHSType);
2107  // If class's assignment operator argument is const/volatile qualified,
2108  // look for operator = (const/volatile B&). Otherwise, look for
2109  // operator = (B&).
2110  if (ParmDecl->getType().isConstQualified())
2111    RHSType.addConst();
2112  if (ParmDecl->getType().isVolatileQualified())
2113    RHSType.addVolatile();
2114  ExprOwningPtr<Expr> LHS(this,  new (Context) DeclRefExpr(ParmDecl,
2115                                                          LHSType,
2116                                                          SourceLocation()));
2117  ExprOwningPtr<Expr> RHS(this,  new (Context) DeclRefExpr(ParmDecl,
2118                                                          RHSType,
2119                                                          SourceLocation()));
2120  Expr *Args[2] = { &*LHS, &*RHS };
2121  OverloadCandidateSet CandidateSet;
2122  AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
2123                              CandidateSet);
2124  OverloadCandidateSet::iterator Best;
2125  if (BestViableFunction(CandidateSet,
2126                         ClassDecl->getLocation(), Best) == OR_Success)
2127    return cast<CXXMethodDecl>(Best->Function);
2128  assert(false &&
2129         "getAssignOperatorMethod - copy assignment operator method not found");
2130  return 0;
2131}
2132
2133void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2134                                   CXXConstructorDecl *CopyConstructor,
2135                                   unsigned TypeQuals) {
2136  assert((CopyConstructor->isImplicit() &&
2137          CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
2138          !CopyConstructor->isUsed()) &&
2139         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
2140
2141  CXXRecordDecl *ClassDecl
2142    = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
2143  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
2144  // C++ [class.copy] p209
2145  // Before the implicitly-declared copy constructor for a class is
2146  // implicitly defined, all the implicitly-declared copy constructors
2147  // for its base class and its non-static data members shall have been
2148  // implicitly defined.
2149  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2150       Base != ClassDecl->bases_end(); ++Base) {
2151    CXXRecordDecl *BaseClassDecl
2152      = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
2153    if (CXXConstructorDecl *BaseCopyCtor =
2154        BaseClassDecl->getCopyConstructor(Context, TypeQuals))
2155      MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
2156  }
2157  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2158                                  FieldEnd = ClassDecl->field_end();
2159       Field != FieldEnd; ++Field) {
2160    QualType FieldType = Context.getCanonicalType((*Field)->getType());
2161    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2162      FieldType = Array->getElementType();
2163    if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
2164      CXXRecordDecl *FieldClassDecl
2165        = cast<CXXRecordDecl>(FieldClassType->getDecl());
2166      if (CXXConstructorDecl *FieldCopyCtor =
2167          FieldClassDecl->getCopyConstructor(Context, TypeQuals))
2168        MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
2169    }
2170  }
2171  CopyConstructor->setUsed();
2172}
2173
2174void Sema::InitializeVarWithConstructor(VarDecl *VD,
2175                                        CXXConstructorDecl *Constructor,
2176                                        QualType DeclInitType,
2177                                        Expr **Exprs, unsigned NumExprs) {
2178  Expr *Temp = CXXConstructExpr::Create(Context, DeclInitType, Constructor,
2179                                        false, Exprs, NumExprs);
2180  MarkDeclarationReferenced(VD->getLocation(), Constructor);
2181  VD->setInit(Context, Temp);
2182}
2183
2184void Sema::MarkDestructorReferenced(SourceLocation Loc, QualType DeclInitType)
2185{
2186  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
2187                                  DeclInitType->getAsRecordType()->getDecl());
2188  if (!ClassDecl->hasTrivialDestructor())
2189    if (CXXDestructorDecl *Destructor =
2190        const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
2191      MarkDeclarationReferenced(Loc, Destructor);
2192}
2193
2194/// AddCXXDirectInitializerToDecl - This action is called immediately after
2195/// ActOnDeclarator, when a C++ direct initializer is present.
2196/// e.g: "int x(1);"
2197void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
2198                                         SourceLocation LParenLoc,
2199                                         MultiExprArg Exprs,
2200                                         SourceLocation *CommaLocs,
2201                                         SourceLocation RParenLoc) {
2202  unsigned NumExprs = Exprs.size();
2203  assert(NumExprs != 0 && Exprs.get() && "missing expressions");
2204  Decl *RealDecl = Dcl.getAs<Decl>();
2205
2206  // If there is no declaration, there was an error parsing it.  Just ignore
2207  // the initializer.
2208  if (RealDecl == 0)
2209    return;
2210
2211  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2212  if (!VDecl) {
2213    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
2214    RealDecl->setInvalidDecl();
2215    return;
2216  }
2217
2218  // FIXME: Need to handle dependent types and expressions here.
2219
2220  // We will treat direct-initialization as a copy-initialization:
2221  //    int x(1);  -as-> int x = 1;
2222  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
2223  //
2224  // Clients that want to distinguish between the two forms, can check for
2225  // direct initializer using VarDecl::hasCXXDirectInitializer().
2226  // A major benefit is that clients that don't particularly care about which
2227  // exactly form was it (like the CodeGen) can handle both cases without
2228  // special case code.
2229
2230  // C++ 8.5p11:
2231  // The form of initialization (using parentheses or '=') is generally
2232  // insignificant, but does matter when the entity being initialized has a
2233  // class type.
2234  QualType DeclInitType = VDecl->getType();
2235  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
2236    DeclInitType = Array->getElementType();
2237
2238  // FIXME: This isn't the right place to complete the type.
2239  if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
2240                          diag::err_typecheck_decl_incomplete_type)) {
2241    VDecl->setInvalidDecl();
2242    return;
2243  }
2244
2245  if (VDecl->getType()->isRecordType()) {
2246    CXXConstructorDecl *Constructor
2247      = PerformInitializationByConstructor(DeclInitType,
2248                                           (Expr **)Exprs.get(), NumExprs,
2249                                           VDecl->getLocation(),
2250                                           SourceRange(VDecl->getLocation(),
2251                                                       RParenLoc),
2252                                           VDecl->getDeclName(),
2253                                           IK_Direct);
2254    if (!Constructor)
2255      RealDecl->setInvalidDecl();
2256    else {
2257      VDecl->setCXXDirectInitializer(true);
2258      InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
2259                                   (Expr**)Exprs.release(), NumExprs);
2260      // FIXME. Must do all that is needed to destroy the object
2261      // on scope exit. For now, just mark the destructor as used.
2262      MarkDestructorReferenced(VDecl->getLocation(), DeclInitType);
2263    }
2264    return;
2265  }
2266
2267  if (NumExprs > 1) {
2268    Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
2269      << SourceRange(VDecl->getLocation(), RParenLoc);
2270    RealDecl->setInvalidDecl();
2271    return;
2272  }
2273
2274  // Let clients know that initialization was done with a direct initializer.
2275  VDecl->setCXXDirectInitializer(true);
2276
2277  assert(NumExprs == 1 && "Expected 1 expression");
2278  // Set the init expression, handles conversions.
2279  AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
2280                       /*DirectInit=*/true);
2281}
2282
2283/// PerformInitializationByConstructor - Perform initialization by
2284/// constructor (C++ [dcl.init]p14), which may occur as part of
2285/// direct-initialization or copy-initialization. We are initializing
2286/// an object of type @p ClassType with the given arguments @p
2287/// Args. @p Loc is the location in the source code where the
2288/// initializer occurs (e.g., a declaration, member initializer,
2289/// functional cast, etc.) while @p Range covers the whole
2290/// initialization. @p InitEntity is the entity being initialized,
2291/// which may by the name of a declaration or a type. @p Kind is the
2292/// kind of initialization we're performing, which affects whether
2293/// explicit constructors will be considered. When successful, returns
2294/// the constructor that will be used to perform the initialization;
2295/// when the initialization fails, emits a diagnostic and returns
2296/// null.
2297CXXConstructorDecl *
2298Sema::PerformInitializationByConstructor(QualType ClassType,
2299                                         Expr **Args, unsigned NumArgs,
2300                                         SourceLocation Loc, SourceRange Range,
2301                                         DeclarationName InitEntity,
2302                                         InitializationKind Kind) {
2303  const RecordType *ClassRec = ClassType->getAsRecordType();
2304  assert(ClassRec && "Can only initialize a class type here");
2305
2306  // C++ [dcl.init]p14:
2307  //
2308  //   If the initialization is direct-initialization, or if it is
2309  //   copy-initialization where the cv-unqualified version of the
2310  //   source type is the same class as, or a derived class of, the
2311  //   class of the destination, constructors are considered. The
2312  //   applicable constructors are enumerated (13.3.1.3), and the
2313  //   best one is chosen through overload resolution (13.3). The
2314  //   constructor so selected is called to initialize the object,
2315  //   with the initializer expression(s) as its argument(s). If no
2316  //   constructor applies, or the overload resolution is ambiguous,
2317  //   the initialization is ill-formed.
2318  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
2319  OverloadCandidateSet CandidateSet;
2320
2321  // Add constructors to the overload set.
2322  DeclarationName ConstructorName
2323    = Context.DeclarationNames.getCXXConstructorName(
2324                       Context.getCanonicalType(ClassType.getUnqualifiedType()));
2325  DeclContext::lookup_const_iterator Con, ConEnd;
2326  for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
2327       Con != ConEnd; ++Con) {
2328    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2329    if ((Kind == IK_Direct) ||
2330        (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
2331        (Kind == IK_Default && Constructor->isDefaultConstructor()))
2332      AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2333  }
2334
2335  // FIXME: When we decide not to synthesize the implicitly-declared
2336  // constructors, we'll need to make them appear here.
2337
2338  OverloadCandidateSet::iterator Best;
2339  switch (BestViableFunction(CandidateSet, Loc, Best)) {
2340  case OR_Success:
2341    // We found a constructor. Return it.
2342    return cast<CXXConstructorDecl>(Best->Function);
2343
2344  case OR_No_Viable_Function:
2345    if (InitEntity)
2346      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
2347        << InitEntity << Range;
2348    else
2349      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
2350        << ClassType << Range;
2351    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
2352    return 0;
2353
2354  case OR_Ambiguous:
2355    if (InitEntity)
2356      Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
2357    else
2358      Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
2359    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2360    return 0;
2361
2362  case OR_Deleted:
2363    if (InitEntity)
2364      Diag(Loc, diag::err_ovl_deleted_init)
2365        << Best->Function->isDeleted()
2366        << InitEntity << Range;
2367    else
2368      Diag(Loc, diag::err_ovl_deleted_init)
2369        << Best->Function->isDeleted()
2370        << InitEntity << Range;
2371    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2372    return 0;
2373  }
2374
2375  return 0;
2376}
2377
2378/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2379/// determine whether they are reference-related,
2380/// reference-compatible, reference-compatible with added
2381/// qualification, or incompatible, for use in C++ initialization by
2382/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2383/// type, and the first type (T1) is the pointee type of the reference
2384/// type being initialized.
2385Sema::ReferenceCompareResult
2386Sema::CompareReferenceRelationship(QualType T1, QualType T2,
2387                                   bool& DerivedToBase) {
2388  assert(!T1->isReferenceType() &&
2389    "T1 must be the pointee type of the reference type");
2390  assert(!T2->isReferenceType() && "T2 cannot be a reference type");
2391
2392  T1 = Context.getCanonicalType(T1);
2393  T2 = Context.getCanonicalType(T2);
2394  QualType UnqualT1 = T1.getUnqualifiedType();
2395  QualType UnqualT2 = T2.getUnqualifiedType();
2396
2397  // C++ [dcl.init.ref]p4:
2398  //   Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
2399  //   reference-related to “cv2 T2” if T1 is the same type as T2, or
2400  //   T1 is a base class of T2.
2401  if (UnqualT1 == UnqualT2)
2402    DerivedToBase = false;
2403  else if (IsDerivedFrom(UnqualT2, UnqualT1))
2404    DerivedToBase = true;
2405  else
2406    return Ref_Incompatible;
2407
2408  // At this point, we know that T1 and T2 are reference-related (at
2409  // least).
2410
2411  // C++ [dcl.init.ref]p4:
2412  //   "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
2413  //   reference-related to T2 and cv1 is the same cv-qualification
2414  //   as, or greater cv-qualification than, cv2. For purposes of
2415  //   overload resolution, cases for which cv1 is greater
2416  //   cv-qualification than cv2 are identified as
2417  //   reference-compatible with added qualification (see 13.3.3.2).
2418  if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2419    return Ref_Compatible;
2420  else if (T1.isMoreQualifiedThan(T2))
2421    return Ref_Compatible_With_Added_Qualification;
2422  else
2423    return Ref_Related;
2424}
2425
2426/// CheckReferenceInit - Check the initialization of a reference
2427/// variable with the given initializer (C++ [dcl.init.ref]). Init is
2428/// the initializer (either a simple initializer or an initializer
2429/// list), and DeclType is the type of the declaration. When ICS is
2430/// non-null, this routine will compute the implicit conversion
2431/// sequence according to C++ [over.ics.ref] and will not produce any
2432/// diagnostics; when ICS is null, it will emit diagnostics when any
2433/// errors are found. Either way, a return value of true indicates
2434/// that there was a failure, a return value of false indicates that
2435/// the reference initialization succeeded.
2436///
2437/// When @p SuppressUserConversions, user-defined conversions are
2438/// suppressed.
2439/// When @p AllowExplicit, we also permit explicit user-defined
2440/// conversion functions.
2441/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
2442bool
2443Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
2444                         ImplicitConversionSequence *ICS,
2445                         bool SuppressUserConversions,
2446                         bool AllowExplicit, bool ForceRValue) {
2447  assert(DeclType->isReferenceType() && "Reference init needs a reference");
2448
2449  QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
2450  QualType T2 = Init->getType();
2451
2452  // If the initializer is the address of an overloaded function, try
2453  // to resolve the overloaded function. If all goes well, T2 is the
2454  // type of the resulting function.
2455  if (Context.getCanonicalType(T2) == Context.OverloadTy) {
2456    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
2457                                                          ICS != 0);
2458    if (Fn) {
2459      // Since we're performing this reference-initialization for
2460      // real, update the initializer with the resulting function.
2461      if (!ICS) {
2462        if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
2463          return true;
2464
2465        FixOverloadedFunctionReference(Init, Fn);
2466      }
2467
2468      T2 = Fn->getType();
2469    }
2470  }
2471
2472  // Compute some basic properties of the types and the initializer.
2473  bool isRValRef = DeclType->isRValueReferenceType();
2474  bool DerivedToBase = false;
2475  Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2476                                                  Init->isLvalue(Context);
2477  ReferenceCompareResult RefRelationship
2478    = CompareReferenceRelationship(T1, T2, DerivedToBase);
2479
2480  // Most paths end in a failed conversion.
2481  if (ICS)
2482    ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
2483
2484  // C++ [dcl.init.ref]p5:
2485  //   A reference to type “cv1 T1” is initialized by an expression
2486  //   of type “cv2 T2” as follows:
2487
2488  //     -- If the initializer expression
2489
2490  // Rvalue references cannot bind to lvalues (N2812).
2491  // There is absolutely no situation where they can. In particular, note that
2492  // this is ill-formed, even if B has a user-defined conversion to A&&:
2493  //   B b;
2494  //   A&& r = b;
2495  if (isRValRef && InitLvalue == Expr::LV_Valid) {
2496    if (!ICS)
2497      Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
2498        << Init->getSourceRange();
2499    return true;
2500  }
2501
2502  bool BindsDirectly = false;
2503  //       -- is an lvalue (but is not a bit-field), and “cv1 T1” is
2504  //          reference-compatible with “cv2 T2,” or
2505  //
2506  // Note that the bit-field check is skipped if we are just computing
2507  // the implicit conversion sequence (C++ [over.best.ics]p2).
2508  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
2509      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
2510    BindsDirectly = true;
2511
2512    if (ICS) {
2513      // C++ [over.ics.ref]p1:
2514      //   When a parameter of reference type binds directly (8.5.3)
2515      //   to an argument expression, the implicit conversion sequence
2516      //   is the identity conversion, unless the argument expression
2517      //   has a type that is a derived class of the parameter type,
2518      //   in which case the implicit conversion sequence is a
2519      //   derived-to-base Conversion (13.3.3.1).
2520      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2521      ICS->Standard.First = ICK_Identity;
2522      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2523      ICS->Standard.Third = ICK_Identity;
2524      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2525      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
2526      ICS->Standard.ReferenceBinding = true;
2527      ICS->Standard.DirectBinding = true;
2528      ICS->Standard.RRefBinding = false;
2529      ICS->Standard.CopyConstructor = 0;
2530
2531      // Nothing more to do: the inaccessibility/ambiguity check for
2532      // derived-to-base conversions is suppressed when we're
2533      // computing the implicit conversion sequence (C++
2534      // [over.best.ics]p2).
2535      return false;
2536    } else {
2537      // Perform the conversion.
2538      // FIXME: Binding to a subobject of the lvalue is going to require more
2539      // AST annotation than this.
2540      ImpCastExprToType(Init, T1, /*isLvalue=*/true);
2541    }
2542  }
2543
2544  //       -- has a class type (i.e., T2 is a class type) and can be
2545  //          implicitly converted to an lvalue of type “cv3 T3,”
2546  //          where “cv1 T1” is reference-compatible with “cv3 T3”
2547  //          92) (this conversion is selected by enumerating the
2548  //          applicable conversion functions (13.3.1.6) and choosing
2549  //          the best one through overload resolution (13.3)),
2550  if (!isRValRef && !SuppressUserConversions && T2->isRecordType()) {
2551    // FIXME: Look for conversions in base classes!
2552    CXXRecordDecl *T2RecordDecl
2553      = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
2554
2555    OverloadCandidateSet CandidateSet;
2556    OverloadedFunctionDecl *Conversions
2557      = T2RecordDecl->getConversionFunctions();
2558    for (OverloadedFunctionDecl::function_iterator Func
2559           = Conversions->function_begin();
2560         Func != Conversions->function_end(); ++Func) {
2561      CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2562
2563      // If the conversion function doesn't return a reference type,
2564      // it can't be considered for this conversion.
2565      if (Conv->getConversionType()->isLValueReferenceType() &&
2566          (AllowExplicit || !Conv->isExplicit()))
2567        AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
2568    }
2569
2570    OverloadCandidateSet::iterator Best;
2571    switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) {
2572    case OR_Success:
2573      // This is a direct binding.
2574      BindsDirectly = true;
2575
2576      if (ICS) {
2577        // C++ [over.ics.ref]p1:
2578        //
2579        //   [...] If the parameter binds directly to the result of
2580        //   applying a conversion function to the argument
2581        //   expression, the implicit conversion sequence is a
2582        //   user-defined conversion sequence (13.3.3.1.2), with the
2583        //   second standard conversion sequence either an identity
2584        //   conversion or, if the conversion function returns an
2585        //   entity of a type that is a derived class of the parameter
2586        //   type, a derived-to-base Conversion.
2587        ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
2588        ICS->UserDefined.Before = Best->Conversions[0].Standard;
2589        ICS->UserDefined.After = Best->FinalConversion;
2590        ICS->UserDefined.ConversionFunction = Best->Function;
2591        assert(ICS->UserDefined.After.ReferenceBinding &&
2592               ICS->UserDefined.After.DirectBinding &&
2593               "Expected a direct reference binding!");
2594        return false;
2595      } else {
2596        // Perform the conversion.
2597        // FIXME: Binding to a subobject of the lvalue is going to require more
2598        // AST annotation than this.
2599        ImpCastExprToType(Init, T1, /*isLvalue=*/true);
2600      }
2601      break;
2602
2603    case OR_Ambiguous:
2604      assert(false && "Ambiguous reference binding conversions not implemented.");
2605      return true;
2606
2607    case OR_No_Viable_Function:
2608    case OR_Deleted:
2609      // There was no suitable conversion, or we found a deleted
2610      // conversion; continue with other checks.
2611      break;
2612    }
2613  }
2614
2615  if (BindsDirectly) {
2616    // C++ [dcl.init.ref]p4:
2617    //   [...] In all cases where the reference-related or
2618    //   reference-compatible relationship of two types is used to
2619    //   establish the validity of a reference binding, and T1 is a
2620    //   base class of T2, a program that necessitates such a binding
2621    //   is ill-formed if T1 is an inaccessible (clause 11) or
2622    //   ambiguous (10.2) base class of T2.
2623    //
2624    // Note that we only check this condition when we're allowed to
2625    // complain about errors, because we should not be checking for
2626    // ambiguity (or inaccessibility) unless the reference binding
2627    // actually happens.
2628    if (DerivedToBase)
2629      return CheckDerivedToBaseConversion(T2, T1,
2630                                          Init->getSourceRange().getBegin(),
2631                                          Init->getSourceRange());
2632    else
2633      return false;
2634  }
2635
2636  //     -- Otherwise, the reference shall be to a non-volatile const
2637  //        type (i.e., cv1 shall be const), or the reference shall be an
2638  //        rvalue reference and the initializer expression shall be an rvalue.
2639  if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
2640    if (!ICS)
2641      Diag(Init->getSourceRange().getBegin(),
2642           diag::err_not_reference_to_const_init)
2643        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2644        << T2 << Init->getSourceRange();
2645    return true;
2646  }
2647
2648  //       -- If the initializer expression is an rvalue, with T2 a
2649  //          class type, and “cv1 T1” is reference-compatible with
2650  //          “cv2 T2,” the reference is bound in one of the
2651  //          following ways (the choice is implementation-defined):
2652  //
2653  //          -- The reference is bound to the object represented by
2654  //             the rvalue (see 3.10) or to a sub-object within that
2655  //             object.
2656  //
2657  //          -- A temporary of type “cv1 T2” [sic] is created, and
2658  //             a constructor is called to copy the entire rvalue
2659  //             object into the temporary. The reference is bound to
2660  //             the temporary or to a sub-object within the
2661  //             temporary.
2662  //
2663  //          The constructor that would be used to make the copy
2664  //          shall be callable whether or not the copy is actually
2665  //          done.
2666  //
2667  // Note that C++0x [dcl.init.ref]p5 takes away this implementation
2668  // freedom, so we will always take the first option and never build
2669  // a temporary in this case. FIXME: We will, however, have to check
2670  // for the presence of a copy constructor in C++98/03 mode.
2671  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2672      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
2673    if (ICS) {
2674      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2675      ICS->Standard.First = ICK_Identity;
2676      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2677      ICS->Standard.Third = ICK_Identity;
2678      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2679      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
2680      ICS->Standard.ReferenceBinding = true;
2681      ICS->Standard.DirectBinding = false;
2682      ICS->Standard.RRefBinding = isRValRef;
2683      ICS->Standard.CopyConstructor = 0;
2684    } else {
2685      // FIXME: Binding to a subobject of the rvalue is going to require more
2686      // AST annotation than this.
2687      ImpCastExprToType(Init, T1, /*isLvalue=*/false);
2688    }
2689    return false;
2690  }
2691
2692  //       -- Otherwise, a temporary of type “cv1 T1” is created and
2693  //          initialized from the initializer expression using the
2694  //          rules for a non-reference copy initialization (8.5). The
2695  //          reference is then bound to the temporary. If T1 is
2696  //          reference-related to T2, cv1 must be the same
2697  //          cv-qualification as, or greater cv-qualification than,
2698  //          cv2; otherwise, the program is ill-formed.
2699  if (RefRelationship == Ref_Related) {
2700    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2701    // we would be reference-compatible or reference-compatible with
2702    // added qualification. But that wasn't the case, so the reference
2703    // initialization fails.
2704    if (!ICS)
2705      Diag(Init->getSourceRange().getBegin(),
2706           diag::err_reference_init_drops_quals)
2707        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2708        << T2 << Init->getSourceRange();
2709    return true;
2710  }
2711
2712  // If at least one of the types is a class type, the types are not
2713  // related, and we aren't allowed any user conversions, the
2714  // reference binding fails. This case is important for breaking
2715  // recursion, since TryImplicitConversion below will attempt to
2716  // create a temporary through the use of a copy constructor.
2717  if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
2718      (T1->isRecordType() || T2->isRecordType())) {
2719    if (!ICS)
2720      Diag(Init->getSourceRange().getBegin(),
2721           diag::err_typecheck_convert_incompatible)
2722        << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
2723    return true;
2724  }
2725
2726  // Actually try to convert the initializer to T1.
2727  if (ICS) {
2728    // C++ [over.ics.ref]p2:
2729    //
2730    //   When a parameter of reference type is not bound directly to
2731    //   an argument expression, the conversion sequence is the one
2732    //   required to convert the argument expression to the
2733    //   underlying type of the reference according to
2734    //   13.3.3.1. Conceptually, this conversion sequence corresponds
2735    //   to copy-initializing a temporary of the underlying type with
2736    //   the argument expression. Any difference in top-level
2737    //   cv-qualification is subsumed by the initialization itself
2738    //   and does not constitute a conversion.
2739    *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
2740    // Of course, that's still a reference binding.
2741    if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
2742      ICS->Standard.ReferenceBinding = true;
2743      ICS->Standard.RRefBinding = isRValRef;
2744    } else if(ICS->ConversionKind ==
2745              ImplicitConversionSequence::UserDefinedConversion) {
2746      ICS->UserDefined.After.ReferenceBinding = true;
2747      ICS->UserDefined.After.RRefBinding = isRValRef;
2748    }
2749    return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
2750  } else {
2751    return PerformImplicitConversion(Init, T1, "initializing");
2752  }
2753}
2754
2755/// CheckOverloadedOperatorDeclaration - Check whether the declaration
2756/// of this overloaded operator is well-formed. If so, returns false;
2757/// otherwise, emits appropriate diagnostics and returns true.
2758bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
2759  assert(FnDecl && FnDecl->isOverloadedOperator() &&
2760         "Expected an overloaded operator declaration");
2761
2762  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
2763
2764  // C++ [over.oper]p5:
2765  //   The allocation and deallocation functions, operator new,
2766  //   operator new[], operator delete and operator delete[], are
2767  //   described completely in 3.7.3. The attributes and restrictions
2768  //   found in the rest of this subclause do not apply to them unless
2769  //   explicitly stated in 3.7.3.
2770  // FIXME: Write a separate routine for checking this. For now, just allow it.
2771  if (Op == OO_New || Op == OO_Array_New ||
2772      Op == OO_Delete || Op == OO_Array_Delete)
2773    return false;
2774
2775  // C++ [over.oper]p6:
2776  //   An operator function shall either be a non-static member
2777  //   function or be a non-member function and have at least one
2778  //   parameter whose type is a class, a reference to a class, an
2779  //   enumeration, or a reference to an enumeration.
2780  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
2781    if (MethodDecl->isStatic())
2782      return Diag(FnDecl->getLocation(),
2783                  diag::err_operator_overload_static) << FnDecl->getDeclName();
2784  } else {
2785    bool ClassOrEnumParam = false;
2786    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2787                                   ParamEnd = FnDecl->param_end();
2788         Param != ParamEnd; ++Param) {
2789      QualType ParamType = (*Param)->getType().getNonReferenceType();
2790      if (ParamType->isDependentType() || ParamType->isRecordType() ||
2791          ParamType->isEnumeralType()) {
2792        ClassOrEnumParam = true;
2793        break;
2794      }
2795    }
2796
2797    if (!ClassOrEnumParam)
2798      return Diag(FnDecl->getLocation(),
2799                  diag::err_operator_overload_needs_class_or_enum)
2800        << FnDecl->getDeclName();
2801  }
2802
2803  // C++ [over.oper]p8:
2804  //   An operator function cannot have default arguments (8.3.6),
2805  //   except where explicitly stated below.
2806  //
2807  // Only the function-call operator allows default arguments
2808  // (C++ [over.call]p1).
2809  if (Op != OO_Call) {
2810    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2811         Param != FnDecl->param_end(); ++Param) {
2812      if ((*Param)->hasUnparsedDefaultArg())
2813        return Diag((*Param)->getLocation(),
2814                    diag::err_operator_overload_default_arg)
2815          << FnDecl->getDeclName();
2816      else if (Expr *DefArg = (*Param)->getDefaultArg())
2817        return Diag((*Param)->getLocation(),
2818                    diag::err_operator_overload_default_arg)
2819          << FnDecl->getDeclName() << DefArg->getSourceRange();
2820    }
2821  }
2822
2823  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2824    { false, false, false }
2825#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2826    , { Unary, Binary, MemberOnly }
2827#include "clang/Basic/OperatorKinds.def"
2828  };
2829
2830  bool CanBeUnaryOperator = OperatorUses[Op][0];
2831  bool CanBeBinaryOperator = OperatorUses[Op][1];
2832  bool MustBeMemberOperator = OperatorUses[Op][2];
2833
2834  // C++ [over.oper]p8:
2835  //   [...] Operator functions cannot have more or fewer parameters
2836  //   than the number required for the corresponding operator, as
2837  //   described in the rest of this subclause.
2838  unsigned NumParams = FnDecl->getNumParams()
2839                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
2840  if (Op != OO_Call &&
2841      ((NumParams == 1 && !CanBeUnaryOperator) ||
2842       (NumParams == 2 && !CanBeBinaryOperator) ||
2843       (NumParams < 1) || (NumParams > 2))) {
2844    // We have the wrong number of parameters.
2845    unsigned ErrorKind;
2846    if (CanBeUnaryOperator && CanBeBinaryOperator) {
2847      ErrorKind = 2;  // 2 -> unary or binary.
2848    } else if (CanBeUnaryOperator) {
2849      ErrorKind = 0;  // 0 -> unary
2850    } else {
2851      assert(CanBeBinaryOperator &&
2852             "All non-call overloaded operators are unary or binary!");
2853      ErrorKind = 1;  // 1 -> binary
2854    }
2855
2856    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
2857      << FnDecl->getDeclName() << NumParams << ErrorKind;
2858  }
2859
2860  // Overloaded operators other than operator() cannot be variadic.
2861  if (Op != OO_Call &&
2862      FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
2863    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
2864      << FnDecl->getDeclName();
2865  }
2866
2867  // Some operators must be non-static member functions.
2868  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2869    return Diag(FnDecl->getLocation(),
2870                diag::err_operator_overload_must_be_member)
2871      << FnDecl->getDeclName();
2872  }
2873
2874  // C++ [over.inc]p1:
2875  //   The user-defined function called operator++ implements the
2876  //   prefix and postfix ++ operator. If this function is a member
2877  //   function with no parameters, or a non-member function with one
2878  //   parameter of class or enumeration type, it defines the prefix
2879  //   increment operator ++ for objects of that type. If the function
2880  //   is a member function with one parameter (which shall be of type
2881  //   int) or a non-member function with two parameters (the second
2882  //   of which shall be of type int), it defines the postfix
2883  //   increment operator ++ for objects of that type.
2884  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2885    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2886    bool ParamIsInt = false;
2887    if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2888      ParamIsInt = BT->getKind() == BuiltinType::Int;
2889
2890    if (!ParamIsInt)
2891      return Diag(LastParam->getLocation(),
2892                  diag::err_operator_overload_post_incdec_must_be_int)
2893        << LastParam->getType() << (Op == OO_MinusMinus);
2894  }
2895
2896  // Notify the class if it got an assignment operator.
2897  if (Op == OO_Equal) {
2898    // Would have returned earlier otherwise.
2899    assert(isa<CXXMethodDecl>(FnDecl) &&
2900      "Overloaded = not member, but not filtered.");
2901    CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2902    Method->getParent()->addedAssignmentOperator(Context, Method);
2903  }
2904
2905  return false;
2906}
2907
2908/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2909/// linkage specification, including the language and (if present)
2910/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2911/// the location of the language string literal, which is provided
2912/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2913/// the '{' brace. Otherwise, this linkage specification does not
2914/// have any braces.
2915Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
2916                                                     SourceLocation ExternLoc,
2917                                                     SourceLocation LangLoc,
2918                                                     const char *Lang,
2919                                                     unsigned StrSize,
2920                                                     SourceLocation LBraceLoc) {
2921  LinkageSpecDecl::LanguageIDs Language;
2922  if (strncmp(Lang, "\"C\"", StrSize) == 0)
2923    Language = LinkageSpecDecl::lang_c;
2924  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2925    Language = LinkageSpecDecl::lang_cxx;
2926  else {
2927    Diag(LangLoc, diag::err_bad_language);
2928    return DeclPtrTy();
2929  }
2930
2931  // FIXME: Add all the various semantics of linkage specifications
2932
2933  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2934                                               LangLoc, Language,
2935                                               LBraceLoc.isValid());
2936  CurContext->addDecl(D);
2937  PushDeclContext(S, D);
2938  return DeclPtrTy::make(D);
2939}
2940
2941/// ActOnFinishLinkageSpecification - Completely the definition of
2942/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2943/// valid, it's the position of the closing '}' brace in a linkage
2944/// specification that uses braces.
2945Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
2946                                                      DeclPtrTy LinkageSpec,
2947                                                      SourceLocation RBraceLoc) {
2948  if (LinkageSpec)
2949    PopDeclContext();
2950  return LinkageSpec;
2951}
2952
2953/// \brief Perform semantic analysis for the variable declaration that
2954/// occurs within a C++ catch clause, returning the newly-created
2955/// variable.
2956VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
2957                                         IdentifierInfo *Name,
2958                                         SourceLocation Loc,
2959                                         SourceRange Range) {
2960  bool Invalid = false;
2961
2962  // Arrays and functions decay.
2963  if (ExDeclType->isArrayType())
2964    ExDeclType = Context.getArrayDecayedType(ExDeclType);
2965  else if (ExDeclType->isFunctionType())
2966    ExDeclType = Context.getPointerType(ExDeclType);
2967
2968  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2969  // The exception-declaration shall not denote a pointer or reference to an
2970  // incomplete type, other than [cv] void*.
2971  // N2844 forbids rvalue references.
2972  if(!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
2973    Diag(Loc, diag::err_catch_rvalue_ref) << Range;
2974    Invalid = true;
2975  }
2976
2977  QualType BaseType = ExDeclType;
2978  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
2979  unsigned DK = diag::err_catch_incomplete;
2980  if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2981    BaseType = Ptr->getPointeeType();
2982    Mode = 1;
2983    DK = diag::err_catch_incomplete_ptr;
2984  } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2985    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
2986    BaseType = Ref->getPointeeType();
2987    Mode = 2;
2988    DK = diag::err_catch_incomplete_ref;
2989  }
2990  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
2991      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
2992    Invalid = true;
2993
2994  if (!Invalid && !ExDeclType->isDependentType() &&
2995      RequireNonAbstractType(Loc, ExDeclType,
2996                             diag::err_abstract_type_in_decl,
2997                             AbstractVariableType))
2998    Invalid = true;
2999
3000  // FIXME: Need to test for ability to copy-construct and destroy the
3001  // exception variable.
3002
3003  // FIXME: Need to check for abstract classes.
3004
3005  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
3006                                    Name, ExDeclType, VarDecl::None,
3007                                    Range.getBegin());
3008
3009  if (Invalid)
3010    ExDecl->setInvalidDecl();
3011
3012  return ExDecl;
3013}
3014
3015/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
3016/// handler.
3017Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
3018  QualType ExDeclType = GetTypeForDeclarator(D, S);
3019
3020  bool Invalid = D.isInvalidType();
3021  IdentifierInfo *II = D.getIdentifier();
3022  if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
3023    // The scope should be freshly made just for us. There is just no way
3024    // it contains any previous declaration.
3025    assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
3026    if (PrevDecl->isTemplateParameter()) {
3027      // Maybe we will complain about the shadowed template parameter.
3028      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
3029    }
3030  }
3031
3032  if (D.getCXXScopeSpec().isSet() && !Invalid) {
3033    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
3034      << D.getCXXScopeSpec().getRange();
3035    Invalid = true;
3036  }
3037
3038  VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType,
3039                                              D.getIdentifier(),
3040                                              D.getIdentifierLoc(),
3041                                            D.getDeclSpec().getSourceRange());
3042
3043  if (Invalid)
3044    ExDecl->setInvalidDecl();
3045
3046  // Add the exception declaration into this scope.
3047  if (II)
3048    PushOnScopeChains(ExDecl, S);
3049  else
3050    CurContext->addDecl(ExDecl);
3051
3052  ProcessDeclAttributes(S, ExDecl, D);
3053  return DeclPtrTy::make(ExDecl);
3054}
3055
3056Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
3057                                                   ExprArg assertexpr,
3058                                                   ExprArg assertmessageexpr) {
3059  Expr *AssertExpr = (Expr *)assertexpr.get();
3060  StringLiteral *AssertMessage =
3061    cast<StringLiteral>((Expr *)assertmessageexpr.get());
3062
3063  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
3064    llvm::APSInt Value(32);
3065    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
3066      Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
3067        AssertExpr->getSourceRange();
3068      return DeclPtrTy();
3069    }
3070
3071    if (Value == 0) {
3072      std::string str(AssertMessage->getStrData(),
3073                      AssertMessage->getByteLength());
3074      Diag(AssertLoc, diag::err_static_assert_failed)
3075        << str << AssertExpr->getSourceRange();
3076    }
3077  }
3078
3079  assertexpr.release();
3080  assertmessageexpr.release();
3081  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
3082                                        AssertExpr, AssertMessage);
3083
3084  CurContext->addDecl(Decl);
3085  return DeclPtrTy::make(Decl);
3086}
3087
3088bool Sema::ActOnFriendDecl(Scope *S, SourceLocation FriendLoc, DeclPtrTy Dcl) {
3089  if (!(S->getFlags() & Scope::ClassScope)) {
3090    Diag(FriendLoc, diag::err_friend_decl_outside_class);
3091    return true;
3092  }
3093
3094  return false;
3095}
3096
3097void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
3098  Decl *Dcl = dcl.getAs<Decl>();
3099  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
3100  if (!Fn) {
3101    Diag(DelLoc, diag::err_deleted_non_function);
3102    return;
3103  }
3104  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
3105    Diag(DelLoc, diag::err_deleted_decl_not_first);
3106    Diag(Prev->getLocation(), diag::note_previous_declaration);
3107    // If the declaration wasn't the first, we delete the function anyway for
3108    // recovery.
3109  }
3110  Fn->setDeleted();
3111}
3112
3113static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
3114  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
3115       ++CI) {
3116    Stmt *SubStmt = *CI;
3117    if (!SubStmt)
3118      continue;
3119    if (isa<ReturnStmt>(SubStmt))
3120      Self.Diag(SubStmt->getSourceRange().getBegin(),
3121           diag::err_return_in_constructor_handler);
3122    if (!isa<Expr>(SubStmt))
3123      SearchForReturnInStmt(Self, SubStmt);
3124  }
3125}
3126
3127void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
3128  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
3129    CXXCatchStmt *Handler = TryBlock->getHandler(I);
3130    SearchForReturnInStmt(*this, Handler);
3131  }
3132}
3133
3134bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
3135                                             const CXXMethodDecl *Old) {
3136  QualType NewTy = New->getType()->getAsFunctionType()->getResultType();
3137  QualType OldTy = Old->getType()->getAsFunctionType()->getResultType();
3138
3139  QualType CNewTy = Context.getCanonicalType(NewTy);
3140  QualType COldTy = Context.getCanonicalType(OldTy);
3141
3142  if (CNewTy == COldTy &&
3143      CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
3144    return false;
3145
3146  // Check if the return types are covariant
3147  QualType NewClassTy, OldClassTy;
3148
3149  /// Both types must be pointers or references to classes.
3150  if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
3151    if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
3152      NewClassTy = NewPT->getPointeeType();
3153      OldClassTy = OldPT->getPointeeType();
3154    }
3155  } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
3156    if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
3157      NewClassTy = NewRT->getPointeeType();
3158      OldClassTy = OldRT->getPointeeType();
3159    }
3160  }
3161
3162  // The return types aren't either both pointers or references to a class type.
3163  if (NewClassTy.isNull()) {
3164    Diag(New->getLocation(),
3165         diag::err_different_return_type_for_overriding_virtual_function)
3166      << New->getDeclName() << NewTy << OldTy;
3167    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3168
3169    return true;
3170  }
3171
3172  if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
3173    // Check if the new class derives from the old class.
3174    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
3175      Diag(New->getLocation(),
3176           diag::err_covariant_return_not_derived)
3177      << New->getDeclName() << NewTy << OldTy;
3178      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3179      return true;
3180    }
3181
3182    // Check if we the conversion from derived to base is valid.
3183    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
3184                      diag::err_covariant_return_inaccessible_base,
3185                      diag::err_covariant_return_ambiguous_derived_to_base_conv,
3186                      // FIXME: Should this point to the return type?
3187                      New->getLocation(), SourceRange(), New->getDeclName())) {
3188      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3189      return true;
3190    }
3191  }
3192
3193  // The qualifiers of the return types must be the same.
3194  if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
3195    Diag(New->getLocation(),
3196         diag::err_covariant_return_type_different_qualifications)
3197    << New->getDeclName() << NewTy << OldTy;
3198    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3199    return true;
3200  };
3201
3202
3203  // The new class type must have the same or less qualifiers as the old type.
3204  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
3205    Diag(New->getLocation(),
3206         diag::err_covariant_return_type_class_type_more_qualified)
3207    << New->getDeclName() << NewTy << OldTy;
3208    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3209    return true;
3210  };
3211
3212  return false;
3213}
3214
3215/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
3216/// initializer for the declaration 'Dcl'.
3217/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
3218/// static data member of class X, names should be looked up in the scope of
3219/// class X.
3220void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
3221  Decl *D = Dcl.getAs<Decl>();
3222  // If there is no declaration, there was an error parsing it.
3223  if (D == 0)
3224    return;
3225
3226  // Check whether it is a declaration with a nested name specifier like
3227  // int foo::bar;
3228  if (!D->isOutOfLine())
3229    return;
3230
3231  // C++ [basic.lookup.unqual]p13
3232  //
3233  // A name used in the definition of a static data member of class X
3234  // (after the qualified-id of the static member) is looked up as if the name
3235  // was used in a member function of X.
3236
3237  // Change current context into the context of the initializing declaration.
3238  EnterDeclaratorContext(S, D->getDeclContext());
3239}
3240
3241/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
3242/// initializer for the declaration 'Dcl'.
3243void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
3244  Decl *D = Dcl.getAs<Decl>();
3245  // If there is no declaration, there was an error parsing it.
3246  if (D == 0)
3247    return;
3248
3249  // Check whether it is a declaration with a nested name specifier like
3250  // int foo::bar;
3251  if (!D->isOutOfLine())
3252    return;
3253
3254  assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
3255  ExitDeclaratorContext(S);
3256}
3257