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