SemaDeclCXX.cpp revision 225d6ca735de81dfb9bdc95645e30c6ba9514f43
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          << BaseClass->getDesugaredType(true);
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              << BaseClass->getDesugaredType(true);
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          << BaseClass->getDesugaredType(true);
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    // FIXME: Handle anonymous namespaces
2401  }
2402
2403  // Although we could have an invalid decl (i.e. the namespace name is a
2404  // redefinition), push it as current DeclContext and try to continue parsing.
2405  // FIXME: We should be able to push Namespc here, so that the each DeclContext
2406  // for the namespace has the declarations that showed up in that particular
2407  // namespace definition.
2408  PushDeclContext(NamespcScope, Namespc);
2409  return DeclPtrTy::make(Namespc);
2410}
2411
2412/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2413/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
2414void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2415  Decl *Dcl = D.getAs<Decl>();
2416  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2417  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2418  Namespc->setRBracLoc(RBrace);
2419  PopDeclContext();
2420}
2421
2422Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2423                                          SourceLocation UsingLoc,
2424                                          SourceLocation NamespcLoc,
2425                                          const CXXScopeSpec &SS,
2426                                          SourceLocation IdentLoc,
2427                                          IdentifierInfo *NamespcName,
2428                                          AttributeList *AttrList) {
2429  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2430  assert(NamespcName && "Invalid NamespcName.");
2431  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
2432  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
2433
2434  UsingDirectiveDecl *UDir = 0;
2435
2436  // Lookup namespace name.
2437  LookupResult R = LookupParsedName(S, &SS, NamespcName,
2438                                    LookupNamespaceName, false);
2439  if (R.isAmbiguous()) {
2440    DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
2441    return DeclPtrTy();
2442  }
2443  if (NamedDecl *NS = R) {
2444    assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
2445    // C++ [namespace.udir]p1:
2446    //   A using-directive specifies that the names in the nominated
2447    //   namespace can be used in the scope in which the
2448    //   using-directive appears after the using-directive. During
2449    //   unqualified name lookup (3.4.1), the names appear as if they
2450    //   were declared in the nearest enclosing namespace which
2451    //   contains both the using-directive and the nominated
2452    //   namespace. [Note: in this context, "contains" means "contains
2453    //   directly or indirectly". ]
2454
2455    // Find enclosing context containing both using-directive and
2456    // nominated namespace.
2457    DeclContext *CommonAncestor = cast<DeclContext>(NS);
2458    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2459      CommonAncestor = CommonAncestor->getParent();
2460
2461    UDir = UsingDirectiveDecl::Create(Context,
2462                                      CurContext, UsingLoc,
2463                                      NamespcLoc,
2464                                      SS.getRange(),
2465                                      (NestedNameSpecifier *)SS.getScopeRep(),
2466                                      IdentLoc,
2467                                      cast<NamespaceDecl>(NS),
2468                                      CommonAncestor);
2469    PushUsingDirective(S, UDir);
2470  } else {
2471    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
2472  }
2473
2474  // FIXME: We ignore attributes for now.
2475  delete AttrList;
2476  return DeclPtrTy::make(UDir);
2477}
2478
2479void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2480  // If scope has associated entity, then using directive is at namespace
2481  // or translation unit scope. We add UsingDirectiveDecls, into
2482  // it's lookup structure.
2483  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
2484    Ctx->addDecl(UDir);
2485  else
2486    // Otherwise it is block-sope. using-directives will affect lookup
2487    // only to the end of scope.
2488    S->PushUsingDirective(DeclPtrTy::make(UDir));
2489}
2490
2491
2492Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
2493                                            AccessSpecifier AS,
2494                                            SourceLocation UsingLoc,
2495                                            const CXXScopeSpec &SS,
2496                                            SourceLocation IdentLoc,
2497                                            IdentifierInfo *TargetName,
2498                                            OverloadedOperatorKind Op,
2499                                            AttributeList *AttrList,
2500                                            bool IsTypeName) {
2501  assert((TargetName || Op) && "Invalid TargetName.");
2502  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
2503
2504  DeclarationName Name;
2505  if (TargetName)
2506    Name = TargetName;
2507  else
2508    Name = Context.DeclarationNames.getCXXOperatorName(Op);
2509
2510  NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS, IdentLoc,
2511                                        Name, AttrList, IsTypeName);
2512  if (UD) {
2513    PushOnScopeChains(UD, S);
2514    UD->setAccess(AS);
2515  }
2516
2517  return DeclPtrTy::make(UD);
2518}
2519
2520NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2521                                       const CXXScopeSpec &SS,
2522                                       SourceLocation IdentLoc,
2523                                       DeclarationName Name,
2524                                       AttributeList *AttrList,
2525                                       bool IsTypeName) {
2526  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2527  assert(IdentLoc.isValid() && "Invalid TargetName location.");
2528
2529  // FIXME: We ignore attributes for now.
2530  delete AttrList;
2531
2532  if (SS.isEmpty()) {
2533    Diag(IdentLoc, diag::err_using_requires_qualname);
2534    return 0;
2535  }
2536
2537  NestedNameSpecifier *NNS =
2538    static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2539
2540  if (isUnknownSpecialization(SS)) {
2541    return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2542                                       SS.getRange(), NNS,
2543                                       IdentLoc, Name, IsTypeName);
2544  }
2545
2546  DeclContext *LookupContext = 0;
2547
2548  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2549    // C++0x N2914 [namespace.udecl]p3:
2550    // A using-declaration used as a member-declaration shall refer to a member
2551    // of a base class of the class being defined, shall refer to a member of an
2552    // anonymous union that is a member of a base class of the class being
2553    // defined, or shall refer to an enumerator for an enumeration type that is
2554    // a member of a base class of the class being defined.
2555    const Type *Ty = NNS->getAsType();
2556    if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) {
2557      Diag(SS.getRange().getBegin(),
2558           diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2559        << NNS << RD->getDeclName();
2560      return 0;
2561    }
2562
2563    QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0));
2564    LookupContext = BaseTy->getAs<RecordType>()->getDecl();
2565  } else {
2566    // C++0x N2914 [namespace.udecl]p8:
2567    // A using-declaration for a class member shall be a member-declaration.
2568    if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
2569      Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
2570        << SS.getRange();
2571      return 0;
2572    }
2573
2574    // C++0x N2914 [namespace.udecl]p9:
2575    // In a using-declaration, a prefix :: refers to the global namespace.
2576    if (NNS->getKind() == NestedNameSpecifier::Global)
2577      LookupContext = Context.getTranslationUnitDecl();
2578    else
2579      LookupContext = NNS->getAsNamespace();
2580  }
2581
2582
2583  // Lookup target name.
2584  LookupResult R = LookupQualifiedName(LookupContext,
2585                                       Name, LookupOrdinaryName);
2586
2587  if (!R) {
2588    DiagnoseMissingMember(IdentLoc, Name, NNS, SS.getRange());
2589    return 0;
2590  }
2591
2592  NamedDecl *ND = R.getAsDecl();
2593
2594  if (IsTypeName && !isa<TypeDecl>(ND)) {
2595    Diag(IdentLoc, diag::err_using_typename_non_type);
2596    return 0;
2597  }
2598
2599  // C++0x N2914 [namespace.udecl]p6:
2600  // A using-declaration shall not name a namespace.
2601  if (isa<NamespaceDecl>(ND)) {
2602    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2603      << SS.getRange();
2604    return 0;
2605  }
2606
2607  return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2608                           ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
2609}
2610
2611/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2612/// is a namespace alias, returns the namespace it points to.
2613static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2614  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2615    return AD->getNamespace();
2616  return dyn_cast_or_null<NamespaceDecl>(D);
2617}
2618
2619Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
2620                                             SourceLocation NamespaceLoc,
2621                                             SourceLocation AliasLoc,
2622                                             IdentifierInfo *Alias,
2623                                             const CXXScopeSpec &SS,
2624                                             SourceLocation IdentLoc,
2625                                             IdentifierInfo *Ident) {
2626
2627  // Lookup the namespace name.
2628  LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
2629
2630  // Check if we have a previous declaration with the same name.
2631  if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
2632    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
2633      // We already have an alias with the same name that points to the same
2634      // namespace, so don't create a new one.
2635      if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
2636        return DeclPtrTy();
2637    }
2638
2639    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2640      diag::err_redefinition_different_kind;
2641    Diag(AliasLoc, DiagID) << Alias;
2642    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2643    return DeclPtrTy();
2644  }
2645
2646  if (R.isAmbiguous()) {
2647    DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
2648    return DeclPtrTy();
2649  }
2650
2651  if (!R) {
2652    Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
2653    return DeclPtrTy();
2654  }
2655
2656  NamespaceAliasDecl *AliasDecl =
2657    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2658                               Alias, SS.getRange(),
2659                               (NestedNameSpecifier *)SS.getScopeRep(),
2660                               IdentLoc, R);
2661
2662  CurContext->addDecl(AliasDecl);
2663  return DeclPtrTy::make(AliasDecl);
2664}
2665
2666void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2667                                            CXXConstructorDecl *Constructor) {
2668  assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2669          !Constructor->isUsed()) &&
2670    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
2671
2672  CXXRecordDecl *ClassDecl
2673    = cast<CXXRecordDecl>(Constructor->getDeclContext());
2674  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
2675  // Before the implicitly-declared default constructor for a class is
2676  // implicitly defined, all the implicitly-declared default constructors
2677  // for its base class and its non-static data members shall have been
2678  // implicitly defined.
2679  bool err = false;
2680  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2681       E = ClassDecl->bases_end(); Base != E; ++Base) {
2682    CXXRecordDecl *BaseClassDecl
2683      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2684    if (!BaseClassDecl->hasTrivialConstructor()) {
2685      if (CXXConstructorDecl *BaseCtor =
2686            BaseClassDecl->getDefaultConstructor(Context))
2687        MarkDeclarationReferenced(CurrentLocation, BaseCtor);
2688      else {
2689        Diag(CurrentLocation, diag::err_defining_default_ctor)
2690          << Context.getTagDeclType(ClassDecl) << 1
2691          << Context.getTagDeclType(BaseClassDecl);
2692        Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
2693              << Context.getTagDeclType(BaseClassDecl);
2694        err = true;
2695      }
2696    }
2697  }
2698  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2699       E = ClassDecl->field_end(); Field != E; ++Field) {
2700    QualType FieldType = Context.getCanonicalType((*Field)->getType());
2701    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2702      FieldType = Array->getElementType();
2703    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2704      CXXRecordDecl *FieldClassDecl
2705        = cast<CXXRecordDecl>(FieldClassType->getDecl());
2706      if (!FieldClassDecl->hasTrivialConstructor()) {
2707        if (CXXConstructorDecl *FieldCtor =
2708            FieldClassDecl->getDefaultConstructor(Context))
2709          MarkDeclarationReferenced(CurrentLocation, FieldCtor);
2710        else {
2711          Diag(CurrentLocation, diag::err_defining_default_ctor)
2712          << Context.getTagDeclType(ClassDecl) << 0 <<
2713              Context.getTagDeclType(FieldClassDecl);
2714          Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
2715          << Context.getTagDeclType(FieldClassDecl);
2716          err = true;
2717        }
2718      }
2719    } else if (FieldType->isReferenceType()) {
2720      Diag(CurrentLocation, diag::err_unintialized_member)
2721        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
2722      Diag((*Field)->getLocation(), diag::note_declared_at);
2723      err = true;
2724    } else if (FieldType.isConstQualified()) {
2725      Diag(CurrentLocation, diag::err_unintialized_member)
2726        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
2727       Diag((*Field)->getLocation(), diag::note_declared_at);
2728      err = true;
2729    }
2730  }
2731  if (!err)
2732    Constructor->setUsed();
2733  else
2734    Constructor->setInvalidDecl();
2735}
2736
2737void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
2738                                    CXXDestructorDecl *Destructor) {
2739  assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2740         "DefineImplicitDestructor - call it for implicit default dtor");
2741
2742  CXXRecordDecl *ClassDecl
2743  = cast<CXXRecordDecl>(Destructor->getDeclContext());
2744  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2745  // C++ [class.dtor] p5
2746  // Before the implicitly-declared default destructor for a class is
2747  // implicitly defined, all the implicitly-declared default destructors
2748  // for its base class and its non-static data members shall have been
2749  // implicitly defined.
2750  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2751       E = ClassDecl->bases_end(); Base != E; ++Base) {
2752    CXXRecordDecl *BaseClassDecl
2753      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2754    if (!BaseClassDecl->hasTrivialDestructor()) {
2755      if (CXXDestructorDecl *BaseDtor =
2756          const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2757        MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2758      else
2759        assert(false &&
2760               "DefineImplicitDestructor - missing dtor in a base class");
2761    }
2762  }
2763
2764  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2765       E = ClassDecl->field_end(); Field != E; ++Field) {
2766    QualType FieldType = Context.getCanonicalType((*Field)->getType());
2767    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2768      FieldType = Array->getElementType();
2769    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2770      CXXRecordDecl *FieldClassDecl
2771        = cast<CXXRecordDecl>(FieldClassType->getDecl());
2772      if (!FieldClassDecl->hasTrivialDestructor()) {
2773        if (CXXDestructorDecl *FieldDtor =
2774            const_cast<CXXDestructorDecl*>(
2775                                        FieldClassDecl->getDestructor(Context)))
2776          MarkDeclarationReferenced(CurrentLocation, FieldDtor);
2777        else
2778          assert(false &&
2779          "DefineImplicitDestructor - missing dtor in class of a data member");
2780      }
2781    }
2782  }
2783  Destructor->setUsed();
2784}
2785
2786void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
2787                                          CXXMethodDecl *MethodDecl) {
2788  assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
2789          MethodDecl->getOverloadedOperator() == OO_Equal &&
2790          !MethodDecl->isUsed()) &&
2791         "DefineImplicitOverloadedAssign - call it for implicit assignment op");
2792
2793  CXXRecordDecl *ClassDecl
2794    = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
2795
2796  // C++[class.copy] p12
2797  // Before the implicitly-declared copy assignment operator for a class is
2798  // implicitly defined, all implicitly-declared copy assignment operators
2799  // for its direct base classes and its nonstatic data members shall have
2800  // been implicitly defined.
2801  bool err = false;
2802  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2803       E = ClassDecl->bases_end(); Base != E; ++Base) {
2804    CXXRecordDecl *BaseClassDecl
2805      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2806    if (CXXMethodDecl *BaseAssignOpMethod =
2807          getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
2808      MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
2809  }
2810  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2811       E = ClassDecl->field_end(); Field != E; ++Field) {
2812    QualType FieldType = Context.getCanonicalType((*Field)->getType());
2813    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2814      FieldType = Array->getElementType();
2815    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2816      CXXRecordDecl *FieldClassDecl
2817        = cast<CXXRecordDecl>(FieldClassType->getDecl());
2818      if (CXXMethodDecl *FieldAssignOpMethod =
2819          getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
2820        MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
2821    } else if (FieldType->isReferenceType()) {
2822      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
2823      << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
2824      Diag(Field->getLocation(), diag::note_declared_at);
2825      Diag(CurrentLocation, diag::note_first_required_here);
2826      err = true;
2827    } else if (FieldType.isConstQualified()) {
2828      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
2829      << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
2830      Diag(Field->getLocation(), diag::note_declared_at);
2831      Diag(CurrentLocation, diag::note_first_required_here);
2832      err = true;
2833    }
2834  }
2835  if (!err)
2836    MethodDecl->setUsed();
2837}
2838
2839CXXMethodDecl *
2840Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
2841                              CXXRecordDecl *ClassDecl) {
2842  QualType LHSType = Context.getTypeDeclType(ClassDecl);
2843  QualType RHSType(LHSType);
2844  // If class's assignment operator argument is const/volatile qualified,
2845  // look for operator = (const/volatile B&). Otherwise, look for
2846  // operator = (B&).
2847  RHSType = Context.getCVRQualifiedType(RHSType,
2848                                     ParmDecl->getType().getCVRQualifiers());
2849  ExprOwningPtr<Expr> LHS(this,  new (Context) DeclRefExpr(ParmDecl,
2850                                                          LHSType,
2851                                                          SourceLocation()));
2852  ExprOwningPtr<Expr> RHS(this,  new (Context) DeclRefExpr(ParmDecl,
2853                                                          RHSType,
2854                                                          SourceLocation()));
2855  Expr *Args[2] = { &*LHS, &*RHS };
2856  OverloadCandidateSet CandidateSet;
2857  AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
2858                              CandidateSet);
2859  OverloadCandidateSet::iterator Best;
2860  if (BestViableFunction(CandidateSet,
2861                         ClassDecl->getLocation(), Best) == OR_Success)
2862    return cast<CXXMethodDecl>(Best->Function);
2863  assert(false &&
2864         "getAssignOperatorMethod - copy assignment operator method not found");
2865  return 0;
2866}
2867
2868void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2869                                   CXXConstructorDecl *CopyConstructor,
2870                                   unsigned TypeQuals) {
2871  assert((CopyConstructor->isImplicit() &&
2872          CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
2873          !CopyConstructor->isUsed()) &&
2874         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
2875
2876  CXXRecordDecl *ClassDecl
2877    = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
2878  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
2879  // C++ [class.copy] p209
2880  // Before the implicitly-declared copy constructor for a class is
2881  // implicitly defined, all the implicitly-declared copy constructors
2882  // for its base class and its non-static data members shall have been
2883  // implicitly defined.
2884  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2885       Base != ClassDecl->bases_end(); ++Base) {
2886    CXXRecordDecl *BaseClassDecl
2887      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2888    if (CXXConstructorDecl *BaseCopyCtor =
2889        BaseClassDecl->getCopyConstructor(Context, TypeQuals))
2890      MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
2891  }
2892  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2893                                  FieldEnd = ClassDecl->field_end();
2894       Field != FieldEnd; ++Field) {
2895    QualType FieldType = Context.getCanonicalType((*Field)->getType());
2896    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2897      FieldType = Array->getElementType();
2898    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2899      CXXRecordDecl *FieldClassDecl
2900        = cast<CXXRecordDecl>(FieldClassType->getDecl());
2901      if (CXXConstructorDecl *FieldCopyCtor =
2902          FieldClassDecl->getCopyConstructor(Context, TypeQuals))
2903        MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
2904    }
2905  }
2906  CopyConstructor->setUsed();
2907}
2908
2909Sema::OwningExprResult
2910Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2911                            CXXConstructorDecl *Constructor,
2912                            MultiExprArg ExprArgs) {
2913  bool Elidable = false;
2914
2915  // C++ [class.copy]p15:
2916  //   Whenever a temporary class object is copied using a copy constructor, and
2917  //   this object and the copy have the same cv-unqualified type, an
2918  //   implementation is permitted to treat the original and the copy as two
2919  //   different ways of referring to the same object and not perform a copy at
2920  //   all, even if the class copy constructor or destructor have side effects.
2921
2922  // FIXME: Is this enough?
2923  if (Constructor->isCopyConstructor(Context)) {
2924    Expr *E = ((Expr **)ExprArgs.get())[0];
2925    while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2926      E = BE->getSubExpr();
2927    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2928      if (ICE->getCastKind() == CastExpr::CK_NoOp)
2929        E = ICE->getSubExpr();
2930
2931    if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
2932      Elidable = true;
2933  }
2934
2935  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
2936                               Elidable, move(ExprArgs));
2937}
2938
2939/// BuildCXXConstructExpr - Creates a complete call to a constructor,
2940/// including handling of its default argument expressions.
2941Sema::OwningExprResult
2942Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
2943                            CXXConstructorDecl *Constructor, bool Elidable,
2944                            MultiExprArg ExprArgs) {
2945  unsigned NumExprs = ExprArgs.size();
2946  Expr **Exprs = (Expr **)ExprArgs.release();
2947
2948  return Owned(CXXConstructExpr::Create(Context, DeclInitType, Constructor,
2949                                        Elidable, Exprs, NumExprs));
2950}
2951
2952Sema::OwningExprResult
2953Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
2954                                  QualType Ty,
2955                                  SourceLocation TyBeginLoc,
2956                                  MultiExprArg Args,
2957                                  SourceLocation RParenLoc) {
2958  unsigned NumExprs = Args.size();
2959  Expr **Exprs = (Expr **)Args.release();
2960
2961  return Owned(new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty,
2962                                                    TyBeginLoc, Exprs,
2963                                                    NumExprs, RParenLoc));
2964}
2965
2966
2967bool Sema::InitializeVarWithConstructor(VarDecl *VD,
2968                                        CXXConstructorDecl *Constructor,
2969                                        QualType DeclInitType,
2970                                        MultiExprArg Exprs) {
2971  OwningExprResult TempResult =
2972    BuildCXXConstructExpr(VD->getLocation(), DeclInitType, Constructor,
2973                          move(Exprs));
2974  if (TempResult.isInvalid())
2975    return true;
2976
2977  Expr *Temp = TempResult.takeAs<Expr>();
2978  MarkDeclarationReferenced(VD->getLocation(), Constructor);
2979  Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
2980  VD->setInit(Context, Temp);
2981
2982  return false;
2983}
2984
2985void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) {
2986  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
2987                                  DeclInitType->getAs<RecordType>()->getDecl());
2988  if (!ClassDecl->hasTrivialDestructor())
2989    if (CXXDestructorDecl *Destructor =
2990        const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
2991      MarkDeclarationReferenced(VD->getLocation(), Destructor);
2992}
2993
2994/// AddCXXDirectInitializerToDecl - This action is called immediately after
2995/// ActOnDeclarator, when a C++ direct initializer is present.
2996/// e.g: "int x(1);"
2997void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
2998                                         SourceLocation LParenLoc,
2999                                         MultiExprArg Exprs,
3000                                         SourceLocation *CommaLocs,
3001                                         SourceLocation RParenLoc) {
3002  unsigned NumExprs = Exprs.size();
3003  assert(NumExprs != 0 && Exprs.get() && "missing expressions");
3004  Decl *RealDecl = Dcl.getAs<Decl>();
3005
3006  // If there is no declaration, there was an error parsing it.  Just ignore
3007  // the initializer.
3008  if (RealDecl == 0)
3009    return;
3010
3011  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3012  if (!VDecl) {
3013    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3014    RealDecl->setInvalidDecl();
3015    return;
3016  }
3017
3018  // We will represent direct-initialization similarly to copy-initialization:
3019  //    int x(1);  -as-> int x = 1;
3020  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
3021  //
3022  // Clients that want to distinguish between the two forms, can check for
3023  // direct initializer using VarDecl::hasCXXDirectInitializer().
3024  // A major benefit is that clients that don't particularly care about which
3025  // exactly form was it (like the CodeGen) can handle both cases without
3026  // special case code.
3027
3028  // If either the declaration has a dependent type or if any of the expressions
3029  // is type-dependent, we represent the initialization via a ParenListExpr for
3030  // later use during template instantiation.
3031  if (VDecl->getType()->isDependentType() ||
3032      Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
3033    // Let clients know that initialization was done with a direct initializer.
3034    VDecl->setCXXDirectInitializer(true);
3035
3036    // Store the initialization expressions as a ParenListExpr.
3037    unsigned NumExprs = Exprs.size();
3038    VDecl->setInit(Context,
3039                   new (Context) ParenListExpr(Context, LParenLoc,
3040                                               (Expr **)Exprs.release(),
3041                                               NumExprs, RParenLoc));
3042    return;
3043  }
3044
3045
3046  // C++ 8.5p11:
3047  // The form of initialization (using parentheses or '=') is generally
3048  // insignificant, but does matter when the entity being initialized has a
3049  // class type.
3050  QualType DeclInitType = VDecl->getType();
3051  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
3052    DeclInitType = Array->getElementType();
3053
3054  // FIXME: This isn't the right place to complete the type.
3055  if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
3056                          diag::err_typecheck_decl_incomplete_type)) {
3057    VDecl->setInvalidDecl();
3058    return;
3059  }
3060
3061  if (VDecl->getType()->isRecordType()) {
3062    ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
3063
3064    CXXConstructorDecl *Constructor
3065      = PerformInitializationByConstructor(DeclInitType,
3066                                           move(Exprs),
3067                                           VDecl->getLocation(),
3068                                           SourceRange(VDecl->getLocation(),
3069                                                       RParenLoc),
3070                                           VDecl->getDeclName(),
3071                                           IK_Direct,
3072                                           ConstructorArgs);
3073    if (!Constructor)
3074      RealDecl->setInvalidDecl();
3075    else {
3076      VDecl->setCXXDirectInitializer(true);
3077      if (InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
3078                                       move_arg(ConstructorArgs)))
3079        RealDecl->setInvalidDecl();
3080      FinalizeVarWithDestructor(VDecl, DeclInitType);
3081    }
3082    return;
3083  }
3084
3085  if (NumExprs > 1) {
3086    Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
3087      << SourceRange(VDecl->getLocation(), RParenLoc);
3088    RealDecl->setInvalidDecl();
3089    return;
3090  }
3091
3092  // Let clients know that initialization was done with a direct initializer.
3093  VDecl->setCXXDirectInitializer(true);
3094
3095  assert(NumExprs == 1 && "Expected 1 expression");
3096  // Set the init expression, handles conversions.
3097  AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
3098                       /*DirectInit=*/true);
3099}
3100
3101/// \brief Perform initialization by constructor (C++ [dcl.init]p14), which
3102/// may occur as part of direct-initialization or copy-initialization.
3103///
3104/// \param ClassType the type of the object being initialized, which must have
3105/// class type.
3106///
3107/// \param ArgsPtr the arguments provided to initialize the object
3108///
3109/// \param Loc the source location where the initialization occurs
3110///
3111/// \param Range the source range that covers the entire initialization
3112///
3113/// \param InitEntity the name of the entity being initialized, if known
3114///
3115/// \param Kind the type of initialization being performed
3116///
3117/// \param ConvertedArgs a vector that will be filled in with the
3118/// appropriately-converted arguments to the constructor (if initialization
3119/// succeeded).
3120///
3121/// \returns the constructor used to initialize the object, if successful.
3122/// Otherwise, emits a diagnostic and returns NULL.
3123CXXConstructorDecl *
3124Sema::PerformInitializationByConstructor(QualType ClassType,
3125                                         MultiExprArg ArgsPtr,
3126                                         SourceLocation Loc, SourceRange Range,
3127                                         DeclarationName InitEntity,
3128                                         InitializationKind Kind,
3129                      ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3130  const RecordType *ClassRec = ClassType->getAs<RecordType>();
3131  assert(ClassRec && "Can only initialize a class type here");
3132  Expr **Args = (Expr **)ArgsPtr.get();
3133  unsigned NumArgs = ArgsPtr.size();
3134
3135  // C++ [dcl.init]p14:
3136  //   If the initialization is direct-initialization, or if it is
3137  //   copy-initialization where the cv-unqualified version of the
3138  //   source type is the same class as, or a derived class of, the
3139  //   class of the destination, constructors are considered. The
3140  //   applicable constructors are enumerated (13.3.1.3), and the
3141  //   best one is chosen through overload resolution (13.3). The
3142  //   constructor so selected is called to initialize the object,
3143  //   with the initializer expression(s) as its argument(s). If no
3144  //   constructor applies, or the overload resolution is ambiguous,
3145  //   the initialization is ill-formed.
3146  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
3147  OverloadCandidateSet CandidateSet;
3148
3149  // Add constructors to the overload set.
3150  DeclarationName ConstructorName
3151    = Context.DeclarationNames.getCXXConstructorName(
3152                       Context.getCanonicalType(ClassType.getUnqualifiedType()));
3153  DeclContext::lookup_const_iterator Con, ConEnd;
3154  for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
3155       Con != ConEnd; ++Con) {
3156    // Find the constructor (which may be a template).
3157    CXXConstructorDecl *Constructor = 0;
3158    FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
3159    if (ConstructorTmpl)
3160      Constructor
3161        = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3162    else
3163      Constructor = cast<CXXConstructorDecl>(*Con);
3164
3165    if ((Kind == IK_Direct) ||
3166        (Kind == IK_Copy &&
3167         Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
3168        (Kind == IK_Default && Constructor->isDefaultConstructor())) {
3169      if (ConstructorTmpl)
3170        AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
3171                                     Args, NumArgs, CandidateSet);
3172      else
3173        AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
3174    }
3175  }
3176
3177  // FIXME: When we decide not to synthesize the implicitly-declared
3178  // constructors, we'll need to make them appear here.
3179
3180  OverloadCandidateSet::iterator Best;
3181  switch (BestViableFunction(CandidateSet, Loc, Best)) {
3182  case OR_Success:
3183    // We found a constructor. Break out so that we can convert the arguments
3184    // appropriately.
3185    break;
3186
3187  case OR_No_Viable_Function:
3188    if (InitEntity)
3189      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
3190        << InitEntity << Range;
3191    else
3192      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
3193        << ClassType << Range;
3194    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3195    return 0;
3196
3197  case OR_Ambiguous:
3198    if (InitEntity)
3199      Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
3200    else
3201      Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
3202    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3203    return 0;
3204
3205  case OR_Deleted:
3206    if (InitEntity)
3207      Diag(Loc, diag::err_ovl_deleted_init)
3208        << Best->Function->isDeleted()
3209        << InitEntity << Range;
3210    else
3211      Diag(Loc, diag::err_ovl_deleted_init)
3212        << Best->Function->isDeleted()
3213        << InitEntity << Range;
3214    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3215    return 0;
3216  }
3217
3218  // Convert the arguments, fill in default arguments, etc.
3219  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3220  if (CompleteConstructorCall(Constructor, move(ArgsPtr), Loc, ConvertedArgs))
3221    return 0;
3222
3223  return Constructor;
3224}
3225
3226/// \brief Given a constructor and the set of arguments provided for the
3227/// constructor, convert the arguments and add any required default arguments
3228/// to form a proper call to this constructor.
3229///
3230/// \returns true if an error occurred, false otherwise.
3231bool
3232Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
3233                              MultiExprArg ArgsPtr,
3234                              SourceLocation Loc,
3235                     ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
3236  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
3237  unsigned NumArgs = ArgsPtr.size();
3238  Expr **Args = (Expr **)ArgsPtr.get();
3239
3240  const FunctionProtoType *Proto
3241    = Constructor->getType()->getAs<FunctionProtoType>();
3242  assert(Proto && "Constructor without a prototype?");
3243  unsigned NumArgsInProto = Proto->getNumArgs();
3244  unsigned NumArgsToCheck = NumArgs;
3245
3246  // If too few arguments are available, we'll fill in the rest with defaults.
3247  if (NumArgs < NumArgsInProto) {
3248    NumArgsToCheck = NumArgsInProto;
3249    ConvertedArgs.reserve(NumArgsInProto);
3250  } else {
3251    ConvertedArgs.reserve(NumArgs);
3252    if (NumArgs > NumArgsInProto)
3253      NumArgsToCheck = NumArgsInProto;
3254  }
3255
3256  // Convert arguments
3257  for (unsigned i = 0; i != NumArgsToCheck; i++) {
3258    QualType ProtoArgType = Proto->getArgType(i);
3259
3260    Expr *Arg;
3261    if (i < NumArgs) {
3262      Arg = Args[i];
3263
3264      // Pass the argument.
3265      if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3266        return true;
3267
3268      Args[i] = 0;
3269    } else {
3270      ParmVarDecl *Param = Constructor->getParamDecl(i);
3271
3272      OwningExprResult DefArg = BuildCXXDefaultArgExpr(Loc, Constructor, Param);
3273      if (DefArg.isInvalid())
3274        return true;
3275
3276      Arg = DefArg.takeAs<Expr>();
3277    }
3278
3279    ConvertedArgs.push_back(Arg);
3280  }
3281
3282  // If this is a variadic call, handle args passed through "...".
3283  if (Proto->isVariadic()) {
3284    // Promote the arguments (C99 6.5.2.2p7).
3285    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3286      Expr *Arg = Args[i];
3287      if (DefaultVariadicArgumentPromotion(Arg, VariadicConstructor))
3288        return true;
3289
3290      ConvertedArgs.push_back(Arg);
3291      Args[i] = 0;
3292    }
3293  }
3294
3295  return false;
3296}
3297
3298/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3299/// determine whether they are reference-related,
3300/// reference-compatible, reference-compatible with added
3301/// qualification, or incompatible, for use in C++ initialization by
3302/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3303/// type, and the first type (T1) is the pointee type of the reference
3304/// type being initialized.
3305Sema::ReferenceCompareResult
3306Sema::CompareReferenceRelationship(QualType T1, QualType T2,
3307                                   bool& DerivedToBase) {
3308  assert(!T1->isReferenceType() &&
3309    "T1 must be the pointee type of the reference type");
3310  assert(!T2->isReferenceType() && "T2 cannot be a reference type");
3311
3312  T1 = Context.getCanonicalType(T1);
3313  T2 = Context.getCanonicalType(T2);
3314  QualType UnqualT1 = T1.getUnqualifiedType();
3315  QualType UnqualT2 = T2.getUnqualifiedType();
3316
3317  // C++ [dcl.init.ref]p4:
3318  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3319  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3320  //   T1 is a base class of T2.
3321  if (UnqualT1 == UnqualT2)
3322    DerivedToBase = false;
3323  else if (IsDerivedFrom(UnqualT2, UnqualT1))
3324    DerivedToBase = true;
3325  else
3326    return Ref_Incompatible;
3327
3328  // At this point, we know that T1 and T2 are reference-related (at
3329  // least).
3330
3331  // C++ [dcl.init.ref]p4:
3332  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3333  //   reference-related to T2 and cv1 is the same cv-qualification
3334  //   as, or greater cv-qualification than, cv2. For purposes of
3335  //   overload resolution, cases for which cv1 is greater
3336  //   cv-qualification than cv2 are identified as
3337  //   reference-compatible with added qualification (see 13.3.3.2).
3338  if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3339    return Ref_Compatible;
3340  else if (T1.isMoreQualifiedThan(T2))
3341    return Ref_Compatible_With_Added_Qualification;
3342  else
3343    return Ref_Related;
3344}
3345
3346/// CheckReferenceInit - Check the initialization of a reference
3347/// variable with the given initializer (C++ [dcl.init.ref]). Init is
3348/// the initializer (either a simple initializer or an initializer
3349/// list), and DeclType is the type of the declaration. When ICS is
3350/// non-null, this routine will compute the implicit conversion
3351/// sequence according to C++ [over.ics.ref] and will not produce any
3352/// diagnostics; when ICS is null, it will emit diagnostics when any
3353/// errors are found. Either way, a return value of true indicates
3354/// that there was a failure, a return value of false indicates that
3355/// the reference initialization succeeded.
3356///
3357/// When @p SuppressUserConversions, user-defined conversions are
3358/// suppressed.
3359/// When @p AllowExplicit, we also permit explicit user-defined
3360/// conversion functions.
3361/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
3362bool
3363Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
3364                         SourceLocation DeclLoc,
3365                         bool SuppressUserConversions,
3366                         bool AllowExplicit, bool ForceRValue,
3367                         ImplicitConversionSequence *ICS) {
3368  assert(DeclType->isReferenceType() && "Reference init needs a reference");
3369
3370  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3371  QualType T2 = Init->getType();
3372
3373  // If the initializer is the address of an overloaded function, try
3374  // to resolve the overloaded function. If all goes well, T2 is the
3375  // type of the resulting function.
3376  if (Context.getCanonicalType(T2) == Context.OverloadTy) {
3377    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
3378                                                          ICS != 0);
3379    if (Fn) {
3380      // Since we're performing this reference-initialization for
3381      // real, update the initializer with the resulting function.
3382      if (!ICS) {
3383        if (DiagnoseUseOfDecl(Fn, DeclLoc))
3384          return true;
3385
3386        FixOverloadedFunctionReference(Init, Fn);
3387      }
3388
3389      T2 = Fn->getType();
3390    }
3391  }
3392
3393  // Compute some basic properties of the types and the initializer.
3394  bool isRValRef = DeclType->isRValueReferenceType();
3395  bool DerivedToBase = false;
3396  Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
3397                                                  Init->isLvalue(Context);
3398  ReferenceCompareResult RefRelationship
3399    = CompareReferenceRelationship(T1, T2, DerivedToBase);
3400
3401  // Most paths end in a failed conversion.
3402  if (ICS)
3403    ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
3404
3405  // C++ [dcl.init.ref]p5:
3406  //   A reference to type "cv1 T1" is initialized by an expression
3407  //   of type "cv2 T2" as follows:
3408
3409  //     -- If the initializer expression
3410
3411  // Rvalue references cannot bind to lvalues (N2812).
3412  // There is absolutely no situation where they can. In particular, note that
3413  // this is ill-formed, even if B has a user-defined conversion to A&&:
3414  //   B b;
3415  //   A&& r = b;
3416  if (isRValRef && InitLvalue == Expr::LV_Valid) {
3417    if (!ICS)
3418      Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
3419        << Init->getSourceRange();
3420    return true;
3421  }
3422
3423  bool BindsDirectly = false;
3424  //       -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3425  //          reference-compatible with "cv2 T2," or
3426  //
3427  // Note that the bit-field check is skipped if we are just computing
3428  // the implicit conversion sequence (C++ [over.best.ics]p2).
3429  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
3430      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3431    BindsDirectly = true;
3432
3433    if (ICS) {
3434      // C++ [over.ics.ref]p1:
3435      //   When a parameter of reference type binds directly (8.5.3)
3436      //   to an argument expression, the implicit conversion sequence
3437      //   is the identity conversion, unless the argument expression
3438      //   has a type that is a derived class of the parameter type,
3439      //   in which case the implicit conversion sequence is a
3440      //   derived-to-base Conversion (13.3.3.1).
3441      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3442      ICS->Standard.First = ICK_Identity;
3443      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3444      ICS->Standard.Third = ICK_Identity;
3445      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3446      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
3447      ICS->Standard.ReferenceBinding = true;
3448      ICS->Standard.DirectBinding = true;
3449      ICS->Standard.RRefBinding = false;
3450      ICS->Standard.CopyConstructor = 0;
3451
3452      // Nothing more to do: the inaccessibility/ambiguity check for
3453      // derived-to-base conversions is suppressed when we're
3454      // computing the implicit conversion sequence (C++
3455      // [over.best.ics]p2).
3456      return false;
3457    } else {
3458      // Perform the conversion.
3459      CastExpr::CastKind CK = CastExpr::CK_NoOp;
3460      if (DerivedToBase)
3461        CK = CastExpr::CK_DerivedToBase;
3462      ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
3463    }
3464  }
3465
3466  //       -- has a class type (i.e., T2 is a class type) and can be
3467  //          implicitly converted to an lvalue of type "cv3 T3,"
3468  //          where "cv1 T1" is reference-compatible with "cv3 T3"
3469  //          92) (this conversion is selected by enumerating the
3470  //          applicable conversion functions (13.3.1.6) and choosing
3471  //          the best one through overload resolution (13.3)),
3472  if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
3473      !RequireCompleteType(SourceLocation(), T2, 0)) {
3474    CXXRecordDecl *T2RecordDecl
3475      = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3476
3477    OverloadCandidateSet CandidateSet;
3478    OverloadedFunctionDecl *Conversions
3479      = T2RecordDecl->getVisibleConversionFunctions();
3480    for (OverloadedFunctionDecl::function_iterator Func
3481           = Conversions->function_begin();
3482         Func != Conversions->function_end(); ++Func) {
3483      FunctionTemplateDecl *ConvTemplate
3484        = dyn_cast<FunctionTemplateDecl>(*Func);
3485      CXXConversionDecl *Conv;
3486      if (ConvTemplate)
3487        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3488      else
3489        Conv = cast<CXXConversionDecl>(*Func);
3490
3491      // If the conversion function doesn't return a reference type,
3492      // it can't be considered for this conversion.
3493      if (Conv->getConversionType()->isLValueReferenceType() &&
3494          (AllowExplicit || !Conv->isExplicit())) {
3495        if (ConvTemplate)
3496          AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
3497                                         CandidateSet);
3498        else
3499          AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3500      }
3501    }
3502
3503    OverloadCandidateSet::iterator Best;
3504    switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
3505    case OR_Success:
3506      // This is a direct binding.
3507      BindsDirectly = true;
3508
3509      if (ICS) {
3510        // C++ [over.ics.ref]p1:
3511        //
3512        //   [...] If the parameter binds directly to the result of
3513        //   applying a conversion function to the argument
3514        //   expression, the implicit conversion sequence is a
3515        //   user-defined conversion sequence (13.3.3.1.2), with the
3516        //   second standard conversion sequence either an identity
3517        //   conversion or, if the conversion function returns an
3518        //   entity of a type that is a derived class of the parameter
3519        //   type, a derived-to-base Conversion.
3520        ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3521        ICS->UserDefined.Before = Best->Conversions[0].Standard;
3522        ICS->UserDefined.After = Best->FinalConversion;
3523        ICS->UserDefined.ConversionFunction = Best->Function;
3524        assert(ICS->UserDefined.After.ReferenceBinding &&
3525               ICS->UserDefined.After.DirectBinding &&
3526               "Expected a direct reference binding!");
3527        return false;
3528      } else {
3529        OwningExprResult InitConversion =
3530          BuildCXXCastArgument(DeclLoc, QualType(),
3531                               CastExpr::CK_UserDefinedConversion,
3532                               cast<CXXMethodDecl>(Best->Function),
3533                               Owned(Init));
3534        Init = InitConversion.takeAs<Expr>();
3535
3536        ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
3537                          /*isLvalue=*/true);
3538      }
3539      break;
3540
3541    case OR_Ambiguous:
3542      assert(false && "Ambiguous reference binding conversions not implemented.");
3543      return true;
3544
3545    case OR_No_Viable_Function:
3546    case OR_Deleted:
3547      // There was no suitable conversion, or we found a deleted
3548      // conversion; continue with other checks.
3549      break;
3550    }
3551  }
3552
3553  if (BindsDirectly) {
3554    // C++ [dcl.init.ref]p4:
3555    //   [...] In all cases where the reference-related or
3556    //   reference-compatible relationship of two types is used to
3557    //   establish the validity of a reference binding, and T1 is a
3558    //   base class of T2, a program that necessitates such a binding
3559    //   is ill-formed if T1 is an inaccessible (clause 11) or
3560    //   ambiguous (10.2) base class of T2.
3561    //
3562    // Note that we only check this condition when we're allowed to
3563    // complain about errors, because we should not be checking for
3564    // ambiguity (or inaccessibility) unless the reference binding
3565    // actually happens.
3566    if (DerivedToBase)
3567      return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
3568                                          Init->getSourceRange());
3569    else
3570      return false;
3571  }
3572
3573  //     -- Otherwise, the reference shall be to a non-volatile const
3574  //        type (i.e., cv1 shall be const), or the reference shall be an
3575  //        rvalue reference and the initializer expression shall be an rvalue.
3576  if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
3577    if (!ICS)
3578      Diag(DeclLoc, diag::err_not_reference_to_const_init)
3579        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3580        << T2 << Init->getSourceRange();
3581    return true;
3582  }
3583
3584  //       -- If the initializer expression is an rvalue, with T2 a
3585  //          class type, and "cv1 T1" is reference-compatible with
3586  //          "cv2 T2," the reference is bound in one of the
3587  //          following ways (the choice is implementation-defined):
3588  //
3589  //          -- The reference is bound to the object represented by
3590  //             the rvalue (see 3.10) or to a sub-object within that
3591  //             object.
3592  //
3593  //          -- A temporary of type "cv1 T2" [sic] is created, and
3594  //             a constructor is called to copy the entire rvalue
3595  //             object into the temporary. The reference is bound to
3596  //             the temporary or to a sub-object within the
3597  //             temporary.
3598  //
3599  //          The constructor that would be used to make the copy
3600  //          shall be callable whether or not the copy is actually
3601  //          done.
3602  //
3603  // Note that C++0x [dcl.init.ref]p5 takes away this implementation
3604  // freedom, so we will always take the first option and never build
3605  // a temporary in this case. FIXME: We will, however, have to check
3606  // for the presence of a copy constructor in C++98/03 mode.
3607  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
3608      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3609    if (ICS) {
3610      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3611      ICS->Standard.First = ICK_Identity;
3612      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3613      ICS->Standard.Third = ICK_Identity;
3614      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3615      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
3616      ICS->Standard.ReferenceBinding = true;
3617      ICS->Standard.DirectBinding = false;
3618      ICS->Standard.RRefBinding = isRValRef;
3619      ICS->Standard.CopyConstructor = 0;
3620    } else {
3621      CastExpr::CastKind CK = CastExpr::CK_NoOp;
3622      if (DerivedToBase)
3623        CK = CastExpr::CK_DerivedToBase;
3624      ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
3625    }
3626    return false;
3627  }
3628
3629  //       -- Otherwise, a temporary of type "cv1 T1" is created and
3630  //          initialized from the initializer expression using the
3631  //          rules for a non-reference copy initialization (8.5). The
3632  //          reference is then bound to the temporary. If T1 is
3633  //          reference-related to T2, cv1 must be the same
3634  //          cv-qualification as, or greater cv-qualification than,
3635  //          cv2; otherwise, the program is ill-formed.
3636  if (RefRelationship == Ref_Related) {
3637    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3638    // we would be reference-compatible or reference-compatible with
3639    // added qualification. But that wasn't the case, so the reference
3640    // initialization fails.
3641    if (!ICS)
3642      Diag(DeclLoc, diag::err_reference_init_drops_quals)
3643        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3644        << T2 << Init->getSourceRange();
3645    return true;
3646  }
3647
3648  // If at least one of the types is a class type, the types are not
3649  // related, and we aren't allowed any user conversions, the
3650  // reference binding fails. This case is important for breaking
3651  // recursion, since TryImplicitConversion below will attempt to
3652  // create a temporary through the use of a copy constructor.
3653  if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3654      (T1->isRecordType() || T2->isRecordType())) {
3655    if (!ICS)
3656      Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
3657        << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3658    return true;
3659  }
3660
3661  // Actually try to convert the initializer to T1.
3662  if (ICS) {
3663    // C++ [over.ics.ref]p2:
3664    //
3665    //   When a parameter of reference type is not bound directly to
3666    //   an argument expression, the conversion sequence is the one
3667    //   required to convert the argument expression to the
3668    //   underlying type of the reference according to
3669    //   13.3.3.1. Conceptually, this conversion sequence corresponds
3670    //   to copy-initializing a temporary of the underlying type with
3671    //   the argument expression. Any difference in top-level
3672    //   cv-qualification is subsumed by the initialization itself
3673    //   and does not constitute a conversion.
3674    *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
3675                                 /*AllowExplicit=*/false,
3676                                 /*ForceRValue=*/false,
3677                                 /*InOverloadResolution=*/false);
3678
3679    // Of course, that's still a reference binding.
3680    if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3681      ICS->Standard.ReferenceBinding = true;
3682      ICS->Standard.RRefBinding = isRValRef;
3683    } else if (ICS->ConversionKind ==
3684              ImplicitConversionSequence::UserDefinedConversion) {
3685      ICS->UserDefined.After.ReferenceBinding = true;
3686      ICS->UserDefined.After.RRefBinding = isRValRef;
3687    }
3688    return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3689  } else {
3690    ImplicitConversionSequence Conversions;
3691    bool badConversion = PerformImplicitConversion(Init, T1, "initializing",
3692                                                   false, false,
3693                                                   Conversions);
3694    if (badConversion) {
3695      if ((Conversions.ConversionKind  ==
3696            ImplicitConversionSequence::BadConversion)
3697          && !Conversions.ConversionFunctionSet.empty()) {
3698        Diag(DeclLoc,
3699             diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
3700        for (int j = Conversions.ConversionFunctionSet.size()-1;
3701             j >= 0; j--) {
3702          FunctionDecl *Func = Conversions.ConversionFunctionSet[j];
3703          Diag(Func->getLocation(), diag::err_ovl_candidate);
3704        }
3705      }
3706      else
3707        Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
3708          << Init->getSourceRange();
3709    }
3710    return badConversion;
3711  }
3712}
3713
3714/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3715/// of this overloaded operator is well-formed. If so, returns false;
3716/// otherwise, emits appropriate diagnostics and returns true.
3717bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
3718  assert(FnDecl && FnDecl->isOverloadedOperator() &&
3719         "Expected an overloaded operator declaration");
3720
3721  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
3722
3723  // C++ [over.oper]p5:
3724  //   The allocation and deallocation functions, operator new,
3725  //   operator new[], operator delete and operator delete[], are
3726  //   described completely in 3.7.3. The attributes and restrictions
3727  //   found in the rest of this subclause do not apply to them unless
3728  //   explicitly stated in 3.7.3.
3729  // FIXME: Write a separate routine for checking this. For now, just allow it.
3730  if (Op == OO_New || Op == OO_Array_New ||
3731      Op == OO_Delete || Op == OO_Array_Delete)
3732    return false;
3733
3734  // C++ [over.oper]p6:
3735  //   An operator function shall either be a non-static member
3736  //   function or be a non-member function and have at least one
3737  //   parameter whose type is a class, a reference to a class, an
3738  //   enumeration, or a reference to an enumeration.
3739  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
3740    if (MethodDecl->isStatic())
3741      return Diag(FnDecl->getLocation(),
3742                  diag::err_operator_overload_static) << FnDecl->getDeclName();
3743  } else {
3744    bool ClassOrEnumParam = false;
3745    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
3746                                   ParamEnd = FnDecl->param_end();
3747         Param != ParamEnd; ++Param) {
3748      QualType ParamType = (*Param)->getType().getNonReferenceType();
3749      if (ParamType->isDependentType() || ParamType->isRecordType() ||
3750          ParamType->isEnumeralType()) {
3751        ClassOrEnumParam = true;
3752        break;
3753      }
3754    }
3755
3756    if (!ClassOrEnumParam)
3757      return Diag(FnDecl->getLocation(),
3758                  diag::err_operator_overload_needs_class_or_enum)
3759        << FnDecl->getDeclName();
3760  }
3761
3762  // C++ [over.oper]p8:
3763  //   An operator function cannot have default arguments (8.3.6),
3764  //   except where explicitly stated below.
3765  //
3766  // Only the function-call operator allows default arguments
3767  // (C++ [over.call]p1).
3768  if (Op != OO_Call) {
3769    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
3770         Param != FnDecl->param_end(); ++Param) {
3771      if ((*Param)->hasUnparsedDefaultArg())
3772        return Diag((*Param)->getLocation(),
3773                    diag::err_operator_overload_default_arg)
3774          << FnDecl->getDeclName();
3775      else if (Expr *DefArg = (*Param)->getDefaultArg())
3776        return Diag((*Param)->getLocation(),
3777                    diag::err_operator_overload_default_arg)
3778          << FnDecl->getDeclName() << DefArg->getSourceRange();
3779    }
3780  }
3781
3782  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
3783    { false, false, false }
3784#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3785    , { Unary, Binary, MemberOnly }
3786#include "clang/Basic/OperatorKinds.def"
3787  };
3788
3789  bool CanBeUnaryOperator = OperatorUses[Op][0];
3790  bool CanBeBinaryOperator = OperatorUses[Op][1];
3791  bool MustBeMemberOperator = OperatorUses[Op][2];
3792
3793  // C++ [over.oper]p8:
3794  //   [...] Operator functions cannot have more or fewer parameters
3795  //   than the number required for the corresponding operator, as
3796  //   described in the rest of this subclause.
3797  unsigned NumParams = FnDecl->getNumParams()
3798                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
3799  if (Op != OO_Call &&
3800      ((NumParams == 1 && !CanBeUnaryOperator) ||
3801       (NumParams == 2 && !CanBeBinaryOperator) ||
3802       (NumParams < 1) || (NumParams > 2))) {
3803    // We have the wrong number of parameters.
3804    unsigned ErrorKind;
3805    if (CanBeUnaryOperator && CanBeBinaryOperator) {
3806      ErrorKind = 2;  // 2 -> unary or binary.
3807    } else if (CanBeUnaryOperator) {
3808      ErrorKind = 0;  // 0 -> unary
3809    } else {
3810      assert(CanBeBinaryOperator &&
3811             "All non-call overloaded operators are unary or binary!");
3812      ErrorKind = 1;  // 1 -> binary
3813    }
3814
3815    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
3816      << FnDecl->getDeclName() << NumParams << ErrorKind;
3817  }
3818
3819  // Overloaded operators other than operator() cannot be variadic.
3820  if (Op != OO_Call &&
3821      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
3822    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
3823      << FnDecl->getDeclName();
3824  }
3825
3826  // Some operators must be non-static member functions.
3827  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
3828    return Diag(FnDecl->getLocation(),
3829                diag::err_operator_overload_must_be_member)
3830      << FnDecl->getDeclName();
3831  }
3832
3833  // C++ [over.inc]p1:
3834  //   The user-defined function called operator++ implements the
3835  //   prefix and postfix ++ operator. If this function is a member
3836  //   function with no parameters, or a non-member function with one
3837  //   parameter of class or enumeration type, it defines the prefix
3838  //   increment operator ++ for objects of that type. If the function
3839  //   is a member function with one parameter (which shall be of type
3840  //   int) or a non-member function with two parameters (the second
3841  //   of which shall be of type int), it defines the postfix
3842  //   increment operator ++ for objects of that type.
3843  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
3844    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
3845    bool ParamIsInt = false;
3846    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
3847      ParamIsInt = BT->getKind() == BuiltinType::Int;
3848
3849    if (!ParamIsInt)
3850      return Diag(LastParam->getLocation(),
3851                  diag::err_operator_overload_post_incdec_must_be_int)
3852        << LastParam->getType() << (Op == OO_MinusMinus);
3853  }
3854
3855  // Notify the class if it got an assignment operator.
3856  if (Op == OO_Equal) {
3857    // Would have returned earlier otherwise.
3858    assert(isa<CXXMethodDecl>(FnDecl) &&
3859      "Overloaded = not member, but not filtered.");
3860    CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
3861    Method->setCopyAssignment(true);
3862    Method->getParent()->addedAssignmentOperator(Context, Method);
3863  }
3864
3865  return false;
3866}
3867
3868/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
3869/// linkage specification, including the language and (if present)
3870/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
3871/// the location of the language string literal, which is provided
3872/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
3873/// the '{' brace. Otherwise, this linkage specification does not
3874/// have any braces.
3875Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
3876                                                     SourceLocation ExternLoc,
3877                                                     SourceLocation LangLoc,
3878                                                     const char *Lang,
3879                                                     unsigned StrSize,
3880                                                     SourceLocation LBraceLoc) {
3881  LinkageSpecDecl::LanguageIDs Language;
3882  if (strncmp(Lang, "\"C\"", StrSize) == 0)
3883    Language = LinkageSpecDecl::lang_c;
3884  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3885    Language = LinkageSpecDecl::lang_cxx;
3886  else {
3887    Diag(LangLoc, diag::err_bad_language);
3888    return DeclPtrTy();
3889  }
3890
3891  // FIXME: Add all the various semantics of linkage specifications
3892
3893  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
3894                                               LangLoc, Language,
3895                                               LBraceLoc.isValid());
3896  CurContext->addDecl(D);
3897  PushDeclContext(S, D);
3898  return DeclPtrTy::make(D);
3899}
3900
3901/// ActOnFinishLinkageSpecification - Completely the definition of
3902/// the C++ linkage specification LinkageSpec. If RBraceLoc is
3903/// valid, it's the position of the closing '}' brace in a linkage
3904/// specification that uses braces.
3905Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
3906                                                      DeclPtrTy LinkageSpec,
3907                                                      SourceLocation RBraceLoc) {
3908  if (LinkageSpec)
3909    PopDeclContext();
3910  return LinkageSpec;
3911}
3912
3913/// \brief Perform semantic analysis for the variable declaration that
3914/// occurs within a C++ catch clause, returning the newly-created
3915/// variable.
3916VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
3917                                         DeclaratorInfo *DInfo,
3918                                         IdentifierInfo *Name,
3919                                         SourceLocation Loc,
3920                                         SourceRange Range) {
3921  bool Invalid = false;
3922
3923  // Arrays and functions decay.
3924  if (ExDeclType->isArrayType())
3925    ExDeclType = Context.getArrayDecayedType(ExDeclType);
3926  else if (ExDeclType->isFunctionType())
3927    ExDeclType = Context.getPointerType(ExDeclType);
3928
3929  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
3930  // The exception-declaration shall not denote a pointer or reference to an
3931  // incomplete type, other than [cv] void*.
3932  // N2844 forbids rvalue references.
3933  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
3934    Diag(Loc, diag::err_catch_rvalue_ref) << Range;
3935    Invalid = true;
3936  }
3937
3938  QualType BaseType = ExDeclType;
3939  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
3940  unsigned DK = diag::err_catch_incomplete;
3941  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
3942    BaseType = Ptr->getPointeeType();
3943    Mode = 1;
3944    DK = diag::err_catch_incomplete_ptr;
3945  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
3946    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
3947    BaseType = Ref->getPointeeType();
3948    Mode = 2;
3949    DK = diag::err_catch_incomplete_ref;
3950  }
3951  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
3952      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
3953    Invalid = true;
3954
3955  if (!Invalid && !ExDeclType->isDependentType() &&
3956      RequireNonAbstractType(Loc, ExDeclType,
3957                             diag::err_abstract_type_in_decl,
3958                             AbstractVariableType))
3959    Invalid = true;
3960
3961  // FIXME: Need to test for ability to copy-construct and destroy the
3962  // exception variable.
3963
3964  // FIXME: Need to check for abstract classes.
3965
3966  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
3967                                    Name, ExDeclType, DInfo, VarDecl::None);
3968
3969  if (Invalid)
3970    ExDecl->setInvalidDecl();
3971
3972  return ExDecl;
3973}
3974
3975/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
3976/// handler.
3977Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
3978  DeclaratorInfo *DInfo = 0;
3979  QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
3980
3981  bool Invalid = D.isInvalidType();
3982  IdentifierInfo *II = D.getIdentifier();
3983  if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
3984    // The scope should be freshly made just for us. There is just no way
3985    // it contains any previous declaration.
3986    assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
3987    if (PrevDecl->isTemplateParameter()) {
3988      // Maybe we will complain about the shadowed template parameter.
3989      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
3990    }
3991  }
3992
3993  if (D.getCXXScopeSpec().isSet() && !Invalid) {
3994    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
3995      << D.getCXXScopeSpec().getRange();
3996    Invalid = true;
3997  }
3998
3999  VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
4000                                              D.getIdentifier(),
4001                                              D.getIdentifierLoc(),
4002                                            D.getDeclSpec().getSourceRange());
4003
4004  if (Invalid)
4005    ExDecl->setInvalidDecl();
4006
4007  // Add the exception declaration into this scope.
4008  if (II)
4009    PushOnScopeChains(ExDecl, S);
4010  else
4011    CurContext->addDecl(ExDecl);
4012
4013  ProcessDeclAttributes(S, ExDecl, D);
4014  return DeclPtrTy::make(ExDecl);
4015}
4016
4017Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
4018                                                   ExprArg assertexpr,
4019                                                   ExprArg assertmessageexpr) {
4020  Expr *AssertExpr = (Expr *)assertexpr.get();
4021  StringLiteral *AssertMessage =
4022    cast<StringLiteral>((Expr *)assertmessageexpr.get());
4023
4024  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
4025    llvm::APSInt Value(32);
4026    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
4027      Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
4028        AssertExpr->getSourceRange();
4029      return DeclPtrTy();
4030    }
4031
4032    if (Value == 0) {
4033      std::string str(AssertMessage->getStrData(),
4034                      AssertMessage->getByteLength());
4035      Diag(AssertLoc, diag::err_static_assert_failed)
4036        << str << AssertExpr->getSourceRange();
4037    }
4038  }
4039
4040  assertexpr.release();
4041  assertmessageexpr.release();
4042  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
4043                                        AssertExpr, AssertMessage);
4044
4045  CurContext->addDecl(Decl);
4046  return DeclPtrTy::make(Decl);
4047}
4048
4049/// Handle a friend type declaration.  This works in tandem with
4050/// ActOnTag.
4051///
4052/// Notes on friend class templates:
4053///
4054/// We generally treat friend class declarations as if they were
4055/// declaring a class.  So, for example, the elaborated type specifier
4056/// in a friend declaration is required to obey the restrictions of a
4057/// class-head (i.e. no typedefs in the scope chain), template
4058/// parameters are required to match up with simple template-ids, &c.
4059/// However, unlike when declaring a template specialization, it's
4060/// okay to refer to a template specialization without an empty
4061/// template parameter declaration, e.g.
4062///   friend class A<T>::B<unsigned>;
4063/// We permit this as a special case; if there are any template
4064/// parameters present at all, require proper matching, i.e.
4065///   template <> template <class T> friend class A<int>::B;
4066Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S,
4067                                          const DeclSpec &DS,
4068                                          MultiTemplateParamsArg TempParams) {
4069  SourceLocation Loc = DS.getSourceRange().getBegin();
4070
4071  assert(DS.isFriendSpecified());
4072  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4073
4074  // Try to convert the decl specifier to a type.  This works for
4075  // friend templates because ActOnTag never produces a ClassTemplateDecl
4076  // for a TUK_Friend.
4077  bool invalid = false;
4078  QualType SourceTy;
4079  QualType T = ConvertDeclSpecToType(DS, Loc, invalid, SourceTy);
4080  if (invalid) return DeclPtrTy();
4081
4082  // This is definitely an error in C++98.  It's probably meant to
4083  // be forbidden in C++0x, too, but the specification is just
4084  // poorly written.
4085  //
4086  // The problem is with declarations like the following:
4087  //   template <T> friend A<T>::foo;
4088  // where deciding whether a class C is a friend or not now hinges
4089  // on whether there exists an instantiation of A that causes
4090  // 'foo' to equal C.  There are restrictions on class-heads
4091  // (which we declare (by fiat) elaborated friend declarations to
4092  // be) that makes this tractable.
4093  //
4094  // FIXME: handle "template <> friend class A<T>;", which
4095  // is possibly well-formed?  Who even knows?
4096  if (TempParams.size() && !isa<ElaboratedType>(T)) {
4097    Diag(Loc, diag::err_tagless_friend_type_template)
4098      << DS.getSourceRange();
4099    return DeclPtrTy();
4100  }
4101
4102  // C++ [class.friend]p2:
4103  //   An elaborated-type-specifier shall be used in a friend declaration
4104  //   for a class.*
4105  //   * The class-key of the elaborated-type-specifier is required.
4106  // This is one of the rare places in Clang where it's legitimate to
4107  // ask about the "spelling" of the type.
4108  if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
4109    // If we evaluated the type to a record type, suggest putting
4110    // a tag in front.
4111    if (const RecordType *RT = T->getAs<RecordType>()) {
4112      RecordDecl *RD = RT->getDecl();
4113
4114      std::string InsertionText = std::string(" ") + RD->getKindName();
4115
4116      Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type)
4117        << (RD->isUnion())
4118        << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
4119                                                 InsertionText);
4120      return DeclPtrTy();
4121    }else {
4122      Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
4123          << DS.getSourceRange();
4124      return DeclPtrTy();
4125    }
4126  }
4127
4128  bool IsDefinition = false;
4129
4130  // We want to do a few things differently if the type was declared with
4131  // a tag:  specifically, we want to use the associated RecordDecl as
4132  // the object of our friend declaration, and we want to disallow
4133  // class definitions.
4134  switch (DS.getTypeSpecType()) {
4135  default: break;
4136  case DeclSpec::TST_class:
4137  case DeclSpec::TST_struct:
4138  case DeclSpec::TST_union:
4139    CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep());
4140    if (RD)
4141      IsDefinition |= RD->isDefinition();
4142    break;
4143  }
4144
4145  // C++98 [class.friend]p1: A friend of a class is a function
4146  //   or class that is not a member of the class . . .
4147  // But that's a silly restriction which nobody implements for
4148  // inner classes, and C++0x removes it anyway, so we only report
4149  // this (as a warning) if we're being pedantic.
4150  if (!getLangOptions().CPlusPlus0x)
4151    if (const RecordType *RT = T->getAs<RecordType>())
4152      if (RT->getDecl()->getDeclContext() == CurContext)
4153        Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
4154
4155  Decl *D;
4156  if (TempParams.size())
4157    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
4158                                   TempParams.size(),
4159                                 (TemplateParameterList**) TempParams.release(),
4160                                   T.getTypePtr(),
4161                                   DS.getFriendSpecLoc());
4162  else
4163    D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
4164                           DS.getFriendSpecLoc());
4165  D->setAccess(AS_public);
4166  CurContext->addDecl(D);
4167
4168  return DeclPtrTy::make(D);
4169}
4170
4171Sema::DeclPtrTy
4172Sema::ActOnFriendFunctionDecl(Scope *S,
4173                              Declarator &D,
4174                              bool IsDefinition,
4175                              MultiTemplateParamsArg TemplateParams) {
4176  // FIXME: do something with template parameters
4177
4178  const DeclSpec &DS = D.getDeclSpec();
4179
4180  assert(DS.isFriendSpecified());
4181  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
4182
4183  SourceLocation Loc = D.getIdentifierLoc();
4184  DeclaratorInfo *DInfo = 0;
4185  QualType T = GetTypeForDeclarator(D, S, &DInfo);
4186
4187  // C++ [class.friend]p1
4188  //   A friend of a class is a function or class....
4189  // Note that this sees through typedefs, which is intended.
4190  // It *doesn't* see through dependent types, which is correct
4191  // according to [temp.arg.type]p3:
4192  //   If a declaration acquires a function type through a
4193  //   type dependent on a template-parameter and this causes
4194  //   a declaration that does not use the syntactic form of a
4195  //   function declarator to have a function type, the program
4196  //   is ill-formed.
4197  if (!T->isFunctionType()) {
4198    Diag(Loc, diag::err_unexpected_friend);
4199
4200    // It might be worthwhile to try to recover by creating an
4201    // appropriate declaration.
4202    return DeclPtrTy();
4203  }
4204
4205  // C++ [namespace.memdef]p3
4206  //  - If a friend declaration in a non-local class first declares a
4207  //    class or function, the friend class or function is a member
4208  //    of the innermost enclosing namespace.
4209  //  - The name of the friend is not found by simple name lookup
4210  //    until a matching declaration is provided in that namespace
4211  //    scope (either before or after the class declaration granting
4212  //    friendship).
4213  //  - If a friend function is called, its name may be found by the
4214  //    name lookup that considers functions from namespaces and
4215  //    classes associated with the types of the function arguments.
4216  //  - When looking for a prior declaration of a class or a function
4217  //    declared as a friend, scopes outside the innermost enclosing
4218  //    namespace scope are not considered.
4219
4220  CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
4221  DeclarationName Name = GetNameForDeclarator(D);
4222  assert(Name);
4223
4224  // The context we found the declaration in, or in which we should
4225  // create the declaration.
4226  DeclContext *DC;
4227
4228  // FIXME: handle local classes
4229
4230  // Recover from invalid scope qualifiers as if they just weren't there.
4231  NamedDecl *PrevDecl = 0;
4232  if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
4233    DC = computeDeclContext(ScopeQual);
4234
4235    // FIXME: handle dependent contexts
4236    if (!DC) return DeclPtrTy();
4237
4238    PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName, true);
4239
4240    // If searching in that context implicitly found a declaration in
4241    // a different context, treat it like it wasn't found at all.
4242    // TODO: better diagnostics for this case.  Suggesting the right
4243    // qualified scope would be nice...
4244    if (!PrevDecl || !PrevDecl->getDeclContext()->Equals(DC)) {
4245      D.setInvalidType();
4246      Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
4247      return DeclPtrTy();
4248    }
4249
4250    // C++ [class.friend]p1: A friend of a class is a function or
4251    //   class that is not a member of the class . . .
4252    if (DC->Equals(CurContext))
4253      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4254
4255  // Otherwise walk out to the nearest namespace scope looking for matches.
4256  } else {
4257    // TODO: handle local class contexts.
4258
4259    DC = CurContext;
4260    while (true) {
4261      // Skip class contexts.  If someone can cite chapter and verse
4262      // for this behavior, that would be nice --- it's what GCC and
4263      // EDG do, and it seems like a reasonable intent, but the spec
4264      // really only says that checks for unqualified existing
4265      // declarations should stop at the nearest enclosing namespace,
4266      // not that they should only consider the nearest enclosing
4267      // namespace.
4268      while (DC->isRecord())
4269        DC = DC->getParent();
4270
4271      PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName, true);
4272
4273      // TODO: decide what we think about using declarations.
4274      if (PrevDecl)
4275        break;
4276
4277      if (DC->isFileContext()) break;
4278      DC = DC->getParent();
4279    }
4280
4281    // C++ [class.friend]p1: A friend of a class is a function or
4282    //   class that is not a member of the class . . .
4283    // C++0x changes this for both friend types and functions.
4284    // Most C++ 98 compilers do seem to give an error here, so
4285    // we do, too.
4286    if (PrevDecl && DC->Equals(CurContext) && !getLangOptions().CPlusPlus0x)
4287      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
4288  }
4289
4290  if (DC->isFileContext()) {
4291    // This implies that it has to be an operator or function.
4292    if (D.getKind() == Declarator::DK_Constructor ||
4293        D.getKind() == Declarator::DK_Destructor ||
4294        D.getKind() == Declarator::DK_Conversion) {
4295      Diag(Loc, diag::err_introducing_special_friend) <<
4296        (D.getKind() == Declarator::DK_Constructor ? 0 :
4297         D.getKind() == Declarator::DK_Destructor ? 1 : 2);
4298      return DeclPtrTy();
4299    }
4300  }
4301
4302  bool Redeclaration = false;
4303  NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, PrevDecl,
4304                                          MultiTemplateParamsArg(*this),
4305                                          IsDefinition,
4306                                          Redeclaration);
4307  if (!ND) return DeclPtrTy();
4308
4309  assert(ND->getDeclContext() == DC);
4310  assert(ND->getLexicalDeclContext() == CurContext);
4311
4312  // Add the function declaration to the appropriate lookup tables,
4313  // adjusting the redeclarations list as necessary.  We don't
4314  // want to do this yet if the friending class is dependent.
4315  //
4316  // Also update the scope-based lookup if the target context's
4317  // lookup context is in lexical scope.
4318  if (!CurContext->isDependentContext()) {
4319    DC = DC->getLookupContext();
4320    DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
4321    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4322      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
4323  }
4324
4325  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
4326                                       D.getIdentifierLoc(), ND,
4327                                       DS.getFriendSpecLoc());
4328  FrD->setAccess(AS_public);
4329  CurContext->addDecl(FrD);
4330
4331  return DeclPtrTy::make(ND);
4332}
4333
4334void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
4335  AdjustDeclIfTemplate(dcl);
4336
4337  Decl *Dcl = dcl.getAs<Decl>();
4338  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
4339  if (!Fn) {
4340    Diag(DelLoc, diag::err_deleted_non_function);
4341    return;
4342  }
4343  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
4344    Diag(DelLoc, diag::err_deleted_decl_not_first);
4345    Diag(Prev->getLocation(), diag::note_previous_declaration);
4346    // If the declaration wasn't the first, we delete the function anyway for
4347    // recovery.
4348  }
4349  Fn->setDeleted();
4350}
4351
4352static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
4353  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
4354       ++CI) {
4355    Stmt *SubStmt = *CI;
4356    if (!SubStmt)
4357      continue;
4358    if (isa<ReturnStmt>(SubStmt))
4359      Self.Diag(SubStmt->getSourceRange().getBegin(),
4360           diag::err_return_in_constructor_handler);
4361    if (!isa<Expr>(SubStmt))
4362      SearchForReturnInStmt(Self, SubStmt);
4363  }
4364}
4365
4366void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
4367  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
4368    CXXCatchStmt *Handler = TryBlock->getHandler(I);
4369    SearchForReturnInStmt(*this, Handler);
4370  }
4371}
4372
4373bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
4374                                             const CXXMethodDecl *Old) {
4375  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
4376  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
4377
4378  QualType CNewTy = Context.getCanonicalType(NewTy);
4379  QualType COldTy = Context.getCanonicalType(OldTy);
4380
4381  if (CNewTy == COldTy &&
4382      CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
4383    return false;
4384
4385  // Check if the return types are covariant
4386  QualType NewClassTy, OldClassTy;
4387
4388  /// Both types must be pointers or references to classes.
4389  if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
4390    if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
4391      NewClassTy = NewPT->getPointeeType();
4392      OldClassTy = OldPT->getPointeeType();
4393    }
4394  } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
4395    if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
4396      NewClassTy = NewRT->getPointeeType();
4397      OldClassTy = OldRT->getPointeeType();
4398    }
4399  }
4400
4401  // The return types aren't either both pointers or references to a class type.
4402  if (NewClassTy.isNull()) {
4403    Diag(New->getLocation(),
4404         diag::err_different_return_type_for_overriding_virtual_function)
4405      << New->getDeclName() << NewTy << OldTy;
4406    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4407
4408    return true;
4409  }
4410
4411  if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
4412    // Check if the new class derives from the old class.
4413    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
4414      Diag(New->getLocation(),
4415           diag::err_covariant_return_not_derived)
4416      << New->getDeclName() << NewTy << OldTy;
4417      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4418      return true;
4419    }
4420
4421    // Check if we the conversion from derived to base is valid.
4422    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
4423                      diag::err_covariant_return_inaccessible_base,
4424                      diag::err_covariant_return_ambiguous_derived_to_base_conv,
4425                      // FIXME: Should this point to the return type?
4426                      New->getLocation(), SourceRange(), New->getDeclName())) {
4427      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4428      return true;
4429    }
4430  }
4431
4432  // The qualifiers of the return types must be the same.
4433  if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
4434    Diag(New->getLocation(),
4435         diag::err_covariant_return_type_different_qualifications)
4436    << New->getDeclName() << NewTy << OldTy;
4437    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4438    return true;
4439  };
4440
4441
4442  // The new class type must have the same or less qualifiers as the old type.
4443  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
4444    Diag(New->getLocation(),
4445         diag::err_covariant_return_type_class_type_more_qualified)
4446    << New->getDeclName() << NewTy << OldTy;
4447    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
4448    return true;
4449  };
4450
4451  return false;
4452}
4453
4454bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
4455                                                const CXXMethodDecl *Old) {
4456  return CheckExceptionSpecSubset(diag::err_override_exception_spec,
4457                                  diag::note_overridden_virtual_function,
4458                                  Old->getType()->getAs<FunctionProtoType>(),
4459                                  Old->getLocation(),
4460                                  New->getType()->getAs<FunctionProtoType>(),
4461                                  New->getLocation());
4462}
4463
4464/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
4465/// initializer for the declaration 'Dcl'.
4466/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
4467/// static data member of class X, names should be looked up in the scope of
4468/// class X.
4469void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
4470  AdjustDeclIfTemplate(Dcl);
4471
4472  Decl *D = Dcl.getAs<Decl>();
4473  // If there is no declaration, there was an error parsing it.
4474  if (D == 0)
4475    return;
4476
4477  // Check whether it is a declaration with a nested name specifier like
4478  // int foo::bar;
4479  if (!D->isOutOfLine())
4480    return;
4481
4482  // C++ [basic.lookup.unqual]p13
4483  //
4484  // A name used in the definition of a static data member of class X
4485  // (after the qualified-id of the static member) is looked up as if the name
4486  // was used in a member function of X.
4487
4488  // Change current context into the context of the initializing declaration.
4489  EnterDeclaratorContext(S, D->getDeclContext());
4490}
4491
4492/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
4493/// initializer for the declaration 'Dcl'.
4494void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
4495  AdjustDeclIfTemplate(Dcl);
4496
4497  Decl *D = Dcl.getAs<Decl>();
4498  // If there is no declaration, there was an error parsing it.
4499  if (D == 0)
4500    return;
4501
4502  // Check whether it is a declaration with a nested name specifier like
4503  // int foo::bar;
4504  if (!D->isOutOfLine())
4505    return;
4506
4507  assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
4508  ExitDeclaratorContext(S);
4509}
4510