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