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