SemaDeclCXX.cpp revision 204962
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 "SemaInit.h"
16#include "Lookup.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/RecordLayout.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/DeclVisitor.h"
22#include "clang/AST/TypeLoc.h"
23#include "clang/AST/TypeOrdering.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Template.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Lex/Preprocessor.h"
29#include "llvm/ADT/STLExtras.h"
30#include <map>
31#include <set>
32
33using namespace clang;
34
35//===----------------------------------------------------------------------===//
36// CheckDefaultArgumentVisitor
37//===----------------------------------------------------------------------===//
38
39namespace {
40  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
41  /// the default argument of a parameter to determine whether it
42  /// contains any ill-formed subexpressions. For example, this will
43  /// diagnose the use of local variables or parameters within the
44  /// default argument expression.
45  class CheckDefaultArgumentVisitor
46    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
47    Expr *DefaultArg;
48    Sema *S;
49
50  public:
51    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
52      : DefaultArg(defarg), S(s) {}
53
54    bool VisitExpr(Expr *Node);
55    bool VisitDeclRefExpr(DeclRefExpr *DRE);
56    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
57  };
58
59  /// VisitExpr - Visit all of the children of this expression.
60  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
61    bool IsInvalid = false;
62    for (Stmt::child_iterator I = Node->child_begin(),
63         E = Node->child_end(); I != E; ++I)
64      IsInvalid |= Visit(*I);
65    return IsInvalid;
66  }
67
68  /// VisitDeclRefExpr - Visit a reference to a declaration, to
69  /// determine whether this declaration can be used in the default
70  /// argument expression.
71  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
72    NamedDecl *Decl = DRE->getDecl();
73    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
74      // C++ [dcl.fct.default]p9
75      //   Default arguments are evaluated each time the function is
76      //   called. The order of evaluation of function arguments is
77      //   unspecified. Consequently, parameters of a function shall not
78      //   be used in default argument expressions, even if they are not
79      //   evaluated. Parameters of a function declared before a default
80      //   argument expression are in scope and can hide namespace and
81      //   class member names.
82      return S->Diag(DRE->getSourceRange().getBegin(),
83                     diag::err_param_default_argument_references_param)
84         << Param->getDeclName() << DefaultArg->getSourceRange();
85    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
86      // C++ [dcl.fct.default]p7
87      //   Local variables shall not be used in default argument
88      //   expressions.
89      if (VDecl->isBlockVarDecl())
90        return S->Diag(DRE->getSourceRange().getBegin(),
91                       diag::err_param_default_argument_references_local)
92          << VDecl->getDeclName() << DefaultArg->getSourceRange();
93    }
94
95    return false;
96  }
97
98  /// VisitCXXThisExpr - Visit a C++ "this" expression.
99  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
100    // C++ [dcl.fct.default]p8:
101    //   The keyword this shall not be used in a default argument of a
102    //   member function.
103    return S->Diag(ThisE->getSourceRange().getBegin(),
104                   diag::err_param_default_argument_references_this)
105               << ThisE->getSourceRange();
106  }
107}
108
109bool
110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
111                              SourceLocation EqualLoc) {
112  if (RequireCompleteType(Param->getLocation(), Param->getType(),
113                          diag::err_typecheck_decl_incomplete_type)) {
114    Param->setInvalidDecl();
115    return true;
116  }
117
118  Expr *Arg = (Expr *)DefaultArg.get();
119
120  // C++ [dcl.fct.default]p5
121  //   A default argument expression is implicitly converted (clause
122  //   4) to the parameter type. The default argument expression has
123  //   the same semantic constraints as the initializer expression in
124  //   a declaration of a variable of the parameter type, using the
125  //   copy-initialization semantics (8.5).
126  InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
127  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
128                                                           EqualLoc);
129  InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
130  OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
131                                          MultiExprArg(*this, (void**)&Arg, 1));
132  if (Result.isInvalid())
133    return true;
134  Arg = Result.takeAs<Expr>();
135
136  Arg = MaybeCreateCXXExprWithTemporaries(Arg);
137
138  // Okay: add the default argument to the parameter
139  Param->setDefaultArg(Arg);
140
141  DefaultArg.release();
142
143  return false;
144}
145
146/// ActOnParamDefaultArgument - Check whether the default argument
147/// provided for a function parameter is well-formed. If so, attach it
148/// to the parameter declaration.
149void
150Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
151                                ExprArg defarg) {
152  if (!param || !defarg.get())
153    return;
154
155  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
156  UnparsedDefaultArgLocs.erase(Param);
157
158  ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
159
160  // Default arguments are only permitted in C++
161  if (!getLangOptions().CPlusPlus) {
162    Diag(EqualLoc, diag::err_param_default_argument)
163      << DefaultArg->getSourceRange();
164    Param->setInvalidDecl();
165    return;
166  }
167
168  // Check that the default argument is well-formed
169  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
170  if (DefaultArgChecker.Visit(DefaultArg.get())) {
171    Param->setInvalidDecl();
172    return;
173  }
174
175  SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
176}
177
178/// ActOnParamUnparsedDefaultArgument - We've seen a default
179/// argument for a function parameter, but we can't parse it yet
180/// because we're inside a class definition. Note that this default
181/// argument will be parsed later.
182void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
183                                             SourceLocation EqualLoc,
184                                             SourceLocation ArgLoc) {
185  if (!param)
186    return;
187
188  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
189  if (Param)
190    Param->setUnparsedDefaultArg();
191
192  UnparsedDefaultArgLocs[Param] = ArgLoc;
193}
194
195/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
196/// the default argument for the parameter param failed.
197void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
198  if (!param)
199    return;
200
201  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
202
203  Param->setInvalidDecl();
204
205  UnparsedDefaultArgLocs.erase(Param);
206}
207
208/// CheckExtraCXXDefaultArguments - Check for any extra default
209/// arguments in the declarator, which is not a function declaration
210/// or definition and therefore is not permitted to have default
211/// arguments. This routine should be invoked for every declarator
212/// that is not a function declaration or definition.
213void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
214  // C++ [dcl.fct.default]p3
215  //   A default argument expression shall be specified only in the
216  //   parameter-declaration-clause of a function declaration or in a
217  //   template-parameter (14.1). It shall not be specified for a
218  //   parameter pack. If it is specified in a
219  //   parameter-declaration-clause, it shall not occur within a
220  //   declarator or abstract-declarator of a parameter-declaration.
221  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
222    DeclaratorChunk &chunk = D.getTypeObject(i);
223    if (chunk.Kind == DeclaratorChunk::Function) {
224      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
225        ParmVarDecl *Param =
226          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
227        if (Param->hasUnparsedDefaultArg()) {
228          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
229          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
231          delete Toks;
232          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
233        } else if (Param->getDefaultArg()) {
234          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
235            << Param->getDefaultArg()->getSourceRange();
236          Param->setDefaultArg(0);
237        }
238      }
239    }
240  }
241}
242
243// MergeCXXFunctionDecl - Merge two declarations of the same C++
244// function, once we already know that they have the same
245// type. Subroutine of MergeFunctionDecl. Returns true if there was an
246// error, false otherwise.
247bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
248  bool Invalid = false;
249
250  // C++ [dcl.fct.default]p4:
251  //   For non-template functions, default arguments can be added in
252  //   later declarations of a function in the same
253  //   scope. Declarations in different scopes have completely
254  //   distinct sets of default arguments. That is, declarations in
255  //   inner scopes do not acquire default arguments from
256  //   declarations in outer scopes, and vice versa. In a given
257  //   function declaration, all parameters subsequent to a
258  //   parameter with a default argument shall have default
259  //   arguments supplied in this or previous declarations. A
260  //   default argument shall not be redefined by a later
261  //   declaration (not even to the same value).
262  //
263  // C++ [dcl.fct.default]p6:
264  //   Except for member functions of class templates, the default arguments
265  //   in a member function definition that appears outside of the class
266  //   definition are added to the set of default arguments provided by the
267  //   member function declaration in the class definition.
268  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
269    ParmVarDecl *OldParam = Old->getParamDecl(p);
270    ParmVarDecl *NewParam = New->getParamDecl(p);
271
272    if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
273      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
274      // hint here. Alternatively, we could walk the type-source information
275      // for NewParam to find the last source location in the type... but it
276      // isn't worth the effort right now. This is the kind of test case that
277      // is hard to get right:
278
279      //   int f(int);
280      //   void g(int (*fp)(int) = f);
281      //   void g(int (*fp)(int) = &f);
282      Diag(NewParam->getLocation(),
283           diag::err_param_default_argument_redefinition)
284        << NewParam->getDefaultArgRange();
285
286      // Look for the function declaration where the default argument was
287      // actually written, which may be a declaration prior to Old.
288      for (FunctionDecl *Older = Old->getPreviousDeclaration();
289           Older; Older = Older->getPreviousDeclaration()) {
290        if (!Older->getParamDecl(p)->hasDefaultArg())
291          break;
292
293        OldParam = Older->getParamDecl(p);
294      }
295
296      Diag(OldParam->getLocation(), diag::note_previous_definition)
297        << OldParam->getDefaultArgRange();
298      Invalid = true;
299    } else if (OldParam->hasDefaultArg()) {
300      // Merge the old default argument into the new parameter
301      if (OldParam->hasUninstantiatedDefaultArg())
302        NewParam->setUninstantiatedDefaultArg(
303                                      OldParam->getUninstantiatedDefaultArg());
304      else
305        NewParam->setDefaultArg(OldParam->getDefaultArg());
306    } else if (NewParam->hasDefaultArg()) {
307      if (New->getDescribedFunctionTemplate()) {
308        // Paragraph 4, quoted above, only applies to non-template functions.
309        Diag(NewParam->getLocation(),
310             diag::err_param_default_argument_template_redecl)
311          << NewParam->getDefaultArgRange();
312        Diag(Old->getLocation(), diag::note_template_prev_declaration)
313          << false;
314      } else if (New->getTemplateSpecializationKind()
315                   != TSK_ImplicitInstantiation &&
316                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
317        // C++ [temp.expr.spec]p21:
318        //   Default function arguments shall not be specified in a declaration
319        //   or a definition for one of the following explicit specializations:
320        //     - the explicit specialization of a function template;
321        //     - the explicit specialization of a member function template;
322        //     - the explicit specialization of a member function of a class
323        //       template where the class template specialization to which the
324        //       member function specialization belongs is implicitly
325        //       instantiated.
326        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
327          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
328          << New->getDeclName()
329          << NewParam->getDefaultArgRange();
330      } else if (New->getDeclContext()->isDependentContext()) {
331        // C++ [dcl.fct.default]p6 (DR217):
332        //   Default arguments for a member function of a class template shall
333        //   be specified on the initial declaration of the member function
334        //   within the class template.
335        //
336        // Reading the tea leaves a bit in DR217 and its reference to DR205
337        // leads me to the conclusion that one cannot add default function
338        // arguments for an out-of-line definition of a member function of a
339        // dependent type.
340        int WhichKind = 2;
341        if (CXXRecordDecl *Record
342              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
343          if (Record->getDescribedClassTemplate())
344            WhichKind = 0;
345          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
346            WhichKind = 1;
347          else
348            WhichKind = 2;
349        }
350
351        Diag(NewParam->getLocation(),
352             diag::err_param_default_argument_member_template_redecl)
353          << WhichKind
354          << NewParam->getDefaultArgRange();
355      }
356    }
357  }
358
359  if (CheckEquivalentExceptionSpec(Old, New))
360    Invalid = true;
361
362  return Invalid;
363}
364
365/// CheckCXXDefaultArguments - Verify that the default arguments for a
366/// function declaration are well-formed according to C++
367/// [dcl.fct.default].
368void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
369  unsigned NumParams = FD->getNumParams();
370  unsigned p;
371
372  // Find first parameter with a default argument
373  for (p = 0; p < NumParams; ++p) {
374    ParmVarDecl *Param = FD->getParamDecl(p);
375    if (Param->hasDefaultArg())
376      break;
377  }
378
379  // C++ [dcl.fct.default]p4:
380  //   In a given function declaration, all parameters
381  //   subsequent to a parameter with a default argument shall
382  //   have default arguments supplied in this or previous
383  //   declarations. A default argument shall not be redefined
384  //   by a later declaration (not even to the same value).
385  unsigned LastMissingDefaultArg = 0;
386  for (; p < NumParams; ++p) {
387    ParmVarDecl *Param = FD->getParamDecl(p);
388    if (!Param->hasDefaultArg()) {
389      if (Param->isInvalidDecl())
390        /* We already complained about this parameter. */;
391      else if (Param->getIdentifier())
392        Diag(Param->getLocation(),
393             diag::err_param_default_argument_missing_name)
394          << Param->getIdentifier();
395      else
396        Diag(Param->getLocation(),
397             diag::err_param_default_argument_missing);
398
399      LastMissingDefaultArg = p;
400    }
401  }
402
403  if (LastMissingDefaultArg > 0) {
404    // Some default arguments were missing. Clear out all of the
405    // default arguments up to (and including) the last missing
406    // default argument, so that we leave the function parameters
407    // in a semantically valid state.
408    for (p = 0; p <= LastMissingDefaultArg; ++p) {
409      ParmVarDecl *Param = FD->getParamDecl(p);
410      if (Param->hasDefaultArg()) {
411        if (!Param->hasUnparsedDefaultArg())
412          Param->getDefaultArg()->Destroy(Context);
413        Param->setDefaultArg(0);
414      }
415    }
416  }
417}
418
419/// isCurrentClassName - Determine whether the identifier II is the
420/// name of the class type currently being defined. In the case of
421/// nested classes, this will only return true if II is the name of
422/// the innermost class.
423bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
424                              const CXXScopeSpec *SS) {
425  assert(getLangOptions().CPlusPlus && "No class names in C!");
426
427  CXXRecordDecl *CurDecl;
428  if (SS && SS->isSet() && !SS->isInvalid()) {
429    DeclContext *DC = computeDeclContext(*SS, true);
430    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
431  } else
432    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
433
434  if (CurDecl && CurDecl->getIdentifier())
435    return &II == CurDecl->getIdentifier();
436  else
437    return false;
438}
439
440/// \brief Check the validity of a C++ base class specifier.
441///
442/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
443/// and returns NULL otherwise.
444CXXBaseSpecifier *
445Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
446                         SourceRange SpecifierRange,
447                         bool Virtual, AccessSpecifier Access,
448                         QualType BaseType,
449                         SourceLocation BaseLoc) {
450  // C++ [class.union]p1:
451  //   A union shall not have base classes.
452  if (Class->isUnion()) {
453    Diag(Class->getLocation(), diag::err_base_clause_on_union)
454      << SpecifierRange;
455    return 0;
456  }
457
458  if (BaseType->isDependentType())
459    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
460                                Class->getTagKind() == RecordDecl::TK_class,
461                                Access, BaseType);
462
463  // Base specifiers must be record types.
464  if (!BaseType->isRecordType()) {
465    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
466    return 0;
467  }
468
469  // C++ [class.union]p1:
470  //   A union shall not be used as a base class.
471  if (BaseType->isUnionType()) {
472    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
473    return 0;
474  }
475
476  // C++ [class.derived]p2:
477  //   The class-name in a base-specifier shall not be an incompletely
478  //   defined class.
479  if (RequireCompleteType(BaseLoc, BaseType,
480                          PDiag(diag::err_incomplete_base_class)
481                            << SpecifierRange))
482    return 0;
483
484  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
485  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
486  assert(BaseDecl && "Record type has no declaration");
487  BaseDecl = BaseDecl->getDefinition();
488  assert(BaseDecl && "Base type is not incomplete, but has no definition");
489  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
490  assert(CXXBaseDecl && "Base type is not a C++ type");
491
492  // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
493  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
494    Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
495    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
496      << BaseType;
497    return 0;
498  }
499
500  SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
501
502  // Create the base specifier.
503  // FIXME: Allocate via ASTContext?
504  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
505                              Class->getTagKind() == RecordDecl::TK_class,
506                              Access, BaseType);
507}
508
509void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
510                                          const CXXRecordDecl *BaseClass,
511                                          bool BaseIsVirtual) {
512  // A class with a non-empty base class is not empty.
513  // FIXME: Standard ref?
514  if (!BaseClass->isEmpty())
515    Class->setEmpty(false);
516
517  // C++ [class.virtual]p1:
518  //   A class that [...] inherits a virtual function is called a polymorphic
519  //   class.
520  if (BaseClass->isPolymorphic())
521    Class->setPolymorphic(true);
522
523  // C++ [dcl.init.aggr]p1:
524  //   An aggregate is [...] a class with [...] no base classes [...].
525  Class->setAggregate(false);
526
527  // C++ [class]p4:
528  //   A POD-struct is an aggregate class...
529  Class->setPOD(false);
530
531  if (BaseIsVirtual) {
532    // C++ [class.ctor]p5:
533    //   A constructor is trivial if its class has no virtual base classes.
534    Class->setHasTrivialConstructor(false);
535
536    // C++ [class.copy]p6:
537    //   A copy constructor is trivial if its class has no virtual base classes.
538    Class->setHasTrivialCopyConstructor(false);
539
540    // C++ [class.copy]p11:
541    //   A copy assignment operator is trivial if its class has no virtual
542    //   base classes.
543    Class->setHasTrivialCopyAssignment(false);
544
545    // C++0x [meta.unary.prop] is_empty:
546    //    T is a class type, but not a union type, with ... no virtual base
547    //    classes
548    Class->setEmpty(false);
549  } else {
550    // C++ [class.ctor]p5:
551    //   A constructor is trivial if all the direct base classes of its
552    //   class have trivial constructors.
553    if (!BaseClass->hasTrivialConstructor())
554      Class->setHasTrivialConstructor(false);
555
556    // C++ [class.copy]p6:
557    //   A copy constructor is trivial if all the direct base classes of its
558    //   class have trivial copy constructors.
559    if (!BaseClass->hasTrivialCopyConstructor())
560      Class->setHasTrivialCopyConstructor(false);
561
562    // C++ [class.copy]p11:
563    //   A copy assignment operator is trivial if all the direct base classes
564    //   of its class have trivial copy assignment operators.
565    if (!BaseClass->hasTrivialCopyAssignment())
566      Class->setHasTrivialCopyAssignment(false);
567  }
568
569  // C++ [class.ctor]p3:
570  //   A destructor is trivial if all the direct base classes of its class
571  //   have trivial destructors.
572  if (!BaseClass->hasTrivialDestructor())
573    Class->setHasTrivialDestructor(false);
574}
575
576/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
577/// one entry in the base class list of a class specifier, for
578/// example:
579///    class foo : public bar, virtual private baz {
580/// 'public bar' and 'virtual private baz' are each base-specifiers.
581Sema::BaseResult
582Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
583                         bool Virtual, AccessSpecifier Access,
584                         TypeTy *basetype, SourceLocation BaseLoc) {
585  if (!classdecl)
586    return true;
587
588  AdjustDeclIfTemplate(classdecl);
589  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
590  if (!Class)
591    return true;
592
593  QualType BaseType = GetTypeFromParser(basetype);
594  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
595                                                      Virtual, Access,
596                                                      BaseType, BaseLoc))
597    return BaseSpec;
598
599  return true;
600}
601
602/// \brief Performs the actual work of attaching the given base class
603/// specifiers to a C++ class.
604bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
605                                unsigned NumBases) {
606 if (NumBases == 0)
607    return false;
608
609  // Used to keep track of which base types we have already seen, so
610  // that we can properly diagnose redundant direct base types. Note
611  // that the key is always the unqualified canonical type of the base
612  // class.
613  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
614
615  // Copy non-redundant base specifiers into permanent storage.
616  unsigned NumGoodBases = 0;
617  bool Invalid = false;
618  for (unsigned idx = 0; idx < NumBases; ++idx) {
619    QualType NewBaseType
620      = Context.getCanonicalType(Bases[idx]->getType());
621    NewBaseType = NewBaseType.getLocalUnqualifiedType();
622
623    if (KnownBaseTypes[NewBaseType]) {
624      // C++ [class.mi]p3:
625      //   A class shall not be specified as a direct base class of a
626      //   derived class more than once.
627      Diag(Bases[idx]->getSourceRange().getBegin(),
628           diag::err_duplicate_base_class)
629        << KnownBaseTypes[NewBaseType]->getType()
630        << Bases[idx]->getSourceRange();
631
632      // Delete the duplicate base class specifier; we're going to
633      // overwrite its pointer later.
634      Context.Deallocate(Bases[idx]);
635
636      Invalid = true;
637    } else {
638      // Okay, add this new base class.
639      KnownBaseTypes[NewBaseType] = Bases[idx];
640      Bases[NumGoodBases++] = Bases[idx];
641    }
642  }
643
644  // Attach the remaining base class specifiers to the derived class.
645  Class->setBases(Bases, NumGoodBases);
646
647  // Delete the remaining (good) base class specifiers, since their
648  // data has been copied into the CXXRecordDecl.
649  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
650    Context.Deallocate(Bases[idx]);
651
652  return Invalid;
653}
654
655/// ActOnBaseSpecifiers - Attach the given base specifiers to the
656/// class, after checking whether there are any duplicate base
657/// classes.
658void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
659                               unsigned NumBases) {
660  if (!ClassDecl || !Bases || !NumBases)
661    return;
662
663  AdjustDeclIfTemplate(ClassDecl);
664  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
665                       (CXXBaseSpecifier**)(Bases), NumBases);
666}
667
668static CXXRecordDecl *GetClassForType(QualType T) {
669  if (const RecordType *RT = T->getAs<RecordType>())
670    return cast<CXXRecordDecl>(RT->getDecl());
671  else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
672    return ICT->getDecl();
673  else
674    return 0;
675}
676
677/// \brief Determine whether the type \p Derived is a C++ class that is
678/// derived from the type \p Base.
679bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
680  if (!getLangOptions().CPlusPlus)
681    return false;
682
683  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
684  if (!DerivedRD)
685    return false;
686
687  CXXRecordDecl *BaseRD = GetClassForType(Base);
688  if (!BaseRD)
689    return false;
690
691  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
692  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
693}
694
695/// \brief Determine whether the type \p Derived is a C++ class that is
696/// derived from the type \p Base.
697bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
698  if (!getLangOptions().CPlusPlus)
699    return false;
700
701  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
702  if (!DerivedRD)
703    return false;
704
705  CXXRecordDecl *BaseRD = GetClassForType(Base);
706  if (!BaseRD)
707    return false;
708
709  return DerivedRD->isDerivedFrom(BaseRD, Paths);
710}
711
712/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
713/// conversion (where Derived and Base are class types) is
714/// well-formed, meaning that the conversion is unambiguous (and
715/// that all of the base classes are accessible). Returns true
716/// and emits a diagnostic if the code is ill-formed, returns false
717/// otherwise. Loc is the location where this routine should point to
718/// if there is an error, and Range is the source range to highlight
719/// if there is an error.
720bool
721Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
722                                   AccessDiagnosticsKind ADK,
723                                   unsigned AmbigiousBaseConvID,
724                                   SourceLocation Loc, SourceRange Range,
725                                   DeclarationName Name) {
726  // First, determine whether the path from Derived to Base is
727  // ambiguous. This is slightly more expensive than checking whether
728  // the Derived to Base conversion exists, because here we need to
729  // explore multiple paths to determine if there is an ambiguity.
730  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
731                     /*DetectVirtual=*/false);
732  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
733  assert(DerivationOkay &&
734         "Can only be used with a derived-to-base conversion");
735  (void)DerivationOkay;
736
737  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
738    if (ADK == ADK_quiet)
739      return false;
740
741    // Check that the base class can be accessed.
742    switch (CheckBaseClassAccess(Loc, /*IsBaseToDerived*/ false,
743                                 Base, Derived, Paths.front(),
744                                 /*force*/ false,
745                                 /*unprivileged*/ false,
746                                 ADK)) {
747    case AR_accessible: return false;
748    case AR_inaccessible: return true;
749    case AR_dependent: return false;
750    case AR_delayed: return false;
751    }
752  }
753
754  // We know that the derived-to-base conversion is ambiguous, and
755  // we're going to produce a diagnostic. Perform the derived-to-base
756  // search just one more time to compute all of the possible paths so
757  // that we can print them out. This is more expensive than any of
758  // the previous derived-to-base checks we've done, but at this point
759  // performance isn't as much of an issue.
760  Paths.clear();
761  Paths.setRecordingPaths(true);
762  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
763  assert(StillOkay && "Can only be used with a derived-to-base conversion");
764  (void)StillOkay;
765
766  // Build up a textual representation of the ambiguous paths, e.g.,
767  // D -> B -> A, that will be used to illustrate the ambiguous
768  // conversions in the diagnostic. We only print one of the paths
769  // to each base class subobject.
770  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
771
772  Diag(Loc, AmbigiousBaseConvID)
773  << Derived << Base << PathDisplayStr << Range << Name;
774  return true;
775}
776
777bool
778Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
779                                   SourceLocation Loc, SourceRange Range,
780                                   bool IgnoreAccess) {
781  return CheckDerivedToBaseConversion(Derived, Base,
782                                      IgnoreAccess ? ADK_quiet : ADK_normal,
783                                      diag::err_ambiguous_derived_to_base_conv,
784                                      Loc, Range, DeclarationName());
785}
786
787
788/// @brief Builds a string representing ambiguous paths from a
789/// specific derived class to different subobjects of the same base
790/// class.
791///
792/// This function builds a string that can be used in error messages
793/// to show the different paths that one can take through the
794/// inheritance hierarchy to go from the derived class to different
795/// subobjects of a base class. The result looks something like this:
796/// @code
797/// struct D -> struct B -> struct A
798/// struct D -> struct C -> struct A
799/// @endcode
800std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
801  std::string PathDisplayStr;
802  std::set<unsigned> DisplayedPaths;
803  for (CXXBasePaths::paths_iterator Path = Paths.begin();
804       Path != Paths.end(); ++Path) {
805    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
806      // We haven't displayed a path to this particular base
807      // class subobject yet.
808      PathDisplayStr += "\n    ";
809      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
810      for (CXXBasePath::const_iterator Element = Path->begin();
811           Element != Path->end(); ++Element)
812        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
813    }
814  }
815
816  return PathDisplayStr;
817}
818
819//===----------------------------------------------------------------------===//
820// C++ class member Handling
821//===----------------------------------------------------------------------===//
822
823/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
824/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
825/// bitfield width if there is one and 'InitExpr' specifies the initializer if
826/// any.
827Sema::DeclPtrTy
828Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
829                               MultiTemplateParamsArg TemplateParameterLists,
830                               ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
831                               bool Deleted) {
832  const DeclSpec &DS = D.getDeclSpec();
833  DeclarationName Name = GetNameForDeclarator(D);
834  Expr *BitWidth = static_cast<Expr*>(BW);
835  Expr *Init = static_cast<Expr*>(InitExpr);
836  SourceLocation Loc = D.getIdentifierLoc();
837
838  bool isFunc = D.isFunctionDeclarator();
839
840  assert(!DS.isFriendSpecified());
841
842  // C++ 9.2p6: A member shall not be declared to have automatic storage
843  // duration (auto, register) or with the extern storage-class-specifier.
844  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
845  // data members and cannot be applied to names declared const or static,
846  // and cannot be applied to reference members.
847  switch (DS.getStorageClassSpec()) {
848    case DeclSpec::SCS_unspecified:
849    case DeclSpec::SCS_typedef:
850    case DeclSpec::SCS_static:
851      // FALL THROUGH.
852      break;
853    case DeclSpec::SCS_mutable:
854      if (isFunc) {
855        if (DS.getStorageClassSpecLoc().isValid())
856          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
857        else
858          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
859
860        // FIXME: It would be nicer if the keyword was ignored only for this
861        // declarator. Otherwise we could get follow-up errors.
862        D.getMutableDeclSpec().ClearStorageClassSpecs();
863      } else {
864        QualType T = GetTypeForDeclarator(D, S);
865        diag::kind err = static_cast<diag::kind>(0);
866        if (T->isReferenceType())
867          err = diag::err_mutable_reference;
868        else if (T.isConstQualified())
869          err = diag::err_mutable_const;
870        if (err != 0) {
871          if (DS.getStorageClassSpecLoc().isValid())
872            Diag(DS.getStorageClassSpecLoc(), err);
873          else
874            Diag(DS.getThreadSpecLoc(), err);
875          // FIXME: It would be nicer if the keyword was ignored only for this
876          // declarator. Otherwise we could get follow-up errors.
877          D.getMutableDeclSpec().ClearStorageClassSpecs();
878        }
879      }
880      break;
881    default:
882      if (DS.getStorageClassSpecLoc().isValid())
883        Diag(DS.getStorageClassSpecLoc(),
884             diag::err_storageclass_invalid_for_member);
885      else
886        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
887      D.getMutableDeclSpec().ClearStorageClassSpecs();
888  }
889
890  if (!isFunc &&
891      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
892      D.getNumTypeObjects() == 0) {
893    // Check also for this case:
894    //
895    // typedef int f();
896    // f a;
897    //
898    QualType TDType = GetTypeFromParser(DS.getTypeRep());
899    isFunc = TDType->isFunctionType();
900  }
901
902  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
903                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
904                      !isFunc);
905
906  Decl *Member;
907  if (isInstField) {
908    // FIXME: Check for template parameters!
909    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
910                         AS);
911    assert(Member && "HandleField never returns null");
912  } else {
913    Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
914               .getAs<Decl>();
915    if (!Member) {
916      if (BitWidth) DeleteExpr(BitWidth);
917      return DeclPtrTy();
918    }
919
920    // Non-instance-fields can't have a bitfield.
921    if (BitWidth) {
922      if (Member->isInvalidDecl()) {
923        // don't emit another diagnostic.
924      } else if (isa<VarDecl>(Member)) {
925        // C++ 9.6p3: A bit-field shall not be a static member.
926        // "static member 'A' cannot be a bit-field"
927        Diag(Loc, diag::err_static_not_bitfield)
928          << Name << BitWidth->getSourceRange();
929      } else if (isa<TypedefDecl>(Member)) {
930        // "typedef member 'x' cannot be a bit-field"
931        Diag(Loc, diag::err_typedef_not_bitfield)
932          << Name << BitWidth->getSourceRange();
933      } else {
934        // A function typedef ("typedef int f(); f a;").
935        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
936        Diag(Loc, diag::err_not_integral_type_bitfield)
937          << Name << cast<ValueDecl>(Member)->getType()
938          << BitWidth->getSourceRange();
939      }
940
941      DeleteExpr(BitWidth);
942      BitWidth = 0;
943      Member->setInvalidDecl();
944    }
945
946    Member->setAccess(AS);
947
948    // If we have declared a member function template, set the access of the
949    // templated declaration as well.
950    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
951      FunTmpl->getTemplatedDecl()->setAccess(AS);
952  }
953
954  assert((Name || isInstField) && "No identifier for non-field ?");
955
956  if (Init)
957    AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
958  if (Deleted) // FIXME: Source location is not very good.
959    SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
960
961  if (isInstField) {
962    FieldCollector->Add(cast<FieldDecl>(Member));
963    return DeclPtrTy();
964  }
965  return DeclPtrTy::make(Member);
966}
967
968/// \brief Find the direct and/or virtual base specifiers that
969/// correspond to the given base type, for use in base initialization
970/// within a constructor.
971static bool FindBaseInitializer(Sema &SemaRef,
972                                CXXRecordDecl *ClassDecl,
973                                QualType BaseType,
974                                const CXXBaseSpecifier *&DirectBaseSpec,
975                                const CXXBaseSpecifier *&VirtualBaseSpec) {
976  // First, check for a direct base class.
977  DirectBaseSpec = 0;
978  for (CXXRecordDecl::base_class_const_iterator Base
979         = ClassDecl->bases_begin();
980       Base != ClassDecl->bases_end(); ++Base) {
981    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
982      // We found a direct base of this type. That's what we're
983      // initializing.
984      DirectBaseSpec = &*Base;
985      break;
986    }
987  }
988
989  // Check for a virtual base class.
990  // FIXME: We might be able to short-circuit this if we know in advance that
991  // there are no virtual bases.
992  VirtualBaseSpec = 0;
993  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
994    // We haven't found a base yet; search the class hierarchy for a
995    // virtual base class.
996    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
997                       /*DetectVirtual=*/false);
998    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
999                              BaseType, Paths)) {
1000      for (CXXBasePaths::paths_iterator Path = Paths.begin();
1001           Path != Paths.end(); ++Path) {
1002        if (Path->back().Base->isVirtual()) {
1003          VirtualBaseSpec = Path->back().Base;
1004          break;
1005        }
1006      }
1007    }
1008  }
1009
1010  return DirectBaseSpec || VirtualBaseSpec;
1011}
1012
1013/// ActOnMemInitializer - Handle a C++ member initializer.
1014Sema::MemInitResult
1015Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
1016                          Scope *S,
1017                          const CXXScopeSpec &SS,
1018                          IdentifierInfo *MemberOrBase,
1019                          TypeTy *TemplateTypeTy,
1020                          SourceLocation IdLoc,
1021                          SourceLocation LParenLoc,
1022                          ExprTy **Args, unsigned NumArgs,
1023                          SourceLocation *CommaLocs,
1024                          SourceLocation RParenLoc) {
1025  if (!ConstructorD)
1026    return true;
1027
1028  AdjustDeclIfTemplate(ConstructorD);
1029
1030  CXXConstructorDecl *Constructor
1031    = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
1032  if (!Constructor) {
1033    // The user wrote a constructor initializer on a function that is
1034    // not a C++ constructor. Ignore the error for now, because we may
1035    // have more member initializers coming; we'll diagnose it just
1036    // once in ActOnMemInitializers.
1037    return true;
1038  }
1039
1040  CXXRecordDecl *ClassDecl = Constructor->getParent();
1041
1042  // C++ [class.base.init]p2:
1043  //   Names in a mem-initializer-id are looked up in the scope of the
1044  //   constructor���s class and, if not found in that scope, are looked
1045  //   up in the scope containing the constructor���s
1046  //   definition. [Note: if the constructor���s class contains a member
1047  //   with the same name as a direct or virtual base class of the
1048  //   class, a mem-initializer-id naming the member or base class and
1049  //   composed of a single identifier refers to the class member. A
1050  //   mem-initializer-id for the hidden base class may be specified
1051  //   using a qualified name. ]
1052  if (!SS.getScopeRep() && !TemplateTypeTy) {
1053    // Look for a member, first.
1054    FieldDecl *Member = 0;
1055    DeclContext::lookup_result Result
1056      = ClassDecl->lookup(MemberOrBase);
1057    if (Result.first != Result.second)
1058      Member = dyn_cast<FieldDecl>(*Result.first);
1059
1060    // FIXME: Handle members of an anonymous union.
1061
1062    if (Member)
1063      return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1064                                    LParenLoc, RParenLoc);
1065  }
1066  // It didn't name a member, so see if it names a class.
1067  QualType BaseType;
1068  TypeSourceInfo *TInfo = 0;
1069
1070  if (TemplateTypeTy) {
1071    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1072  } else {
1073    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1074    LookupParsedName(R, S, &SS);
1075
1076    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1077    if (!TyD) {
1078      if (R.isAmbiguous()) return true;
1079
1080      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1081        bool NotUnknownSpecialization = false;
1082        DeclContext *DC = computeDeclContext(SS, false);
1083        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1084          NotUnknownSpecialization = !Record->hasAnyDependentBases();
1085
1086        if (!NotUnknownSpecialization) {
1087          // When the scope specifier can refer to a member of an unknown
1088          // specialization, we take it as a type name.
1089          BaseType = CheckTypenameType((NestedNameSpecifier *)SS.getScopeRep(),
1090                                       *MemberOrBase, SS.getRange());
1091          if (BaseType.isNull())
1092            return true;
1093
1094          R.clear();
1095        }
1096      }
1097
1098      // If no results were found, try to correct typos.
1099      if (R.empty() && BaseType.isNull() &&
1100          CorrectTypo(R, S, &SS, ClassDecl) && R.isSingleResult()) {
1101        if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1102          if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1103            // We have found a non-static data member with a similar
1104            // name to what was typed; complain and initialize that
1105            // member.
1106            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1107              << MemberOrBase << true << R.getLookupName()
1108              << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1109                                               R.getLookupName().getAsString());
1110            Diag(Member->getLocation(), diag::note_previous_decl)
1111              << Member->getDeclName();
1112
1113            return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1114                                          LParenLoc, RParenLoc);
1115          }
1116        } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1117          const CXXBaseSpecifier *DirectBaseSpec;
1118          const CXXBaseSpecifier *VirtualBaseSpec;
1119          if (FindBaseInitializer(*this, ClassDecl,
1120                                  Context.getTypeDeclType(Type),
1121                                  DirectBaseSpec, VirtualBaseSpec)) {
1122            // We have found a direct or virtual base class with a
1123            // similar name to what was typed; complain and initialize
1124            // that base class.
1125            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1126              << MemberOrBase << false << R.getLookupName()
1127              << CodeModificationHint::CreateReplacement(R.getNameLoc(),
1128                                               R.getLookupName().getAsString());
1129
1130            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1131                                                             : VirtualBaseSpec;
1132            Diag(BaseSpec->getSourceRange().getBegin(),
1133                 diag::note_base_class_specified_here)
1134              << BaseSpec->getType()
1135              << BaseSpec->getSourceRange();
1136
1137            TyD = Type;
1138          }
1139        }
1140      }
1141
1142      if (!TyD && BaseType.isNull()) {
1143        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1144          << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1145        return true;
1146      }
1147    }
1148
1149    if (BaseType.isNull()) {
1150      BaseType = Context.getTypeDeclType(TyD);
1151      if (SS.isSet()) {
1152        NestedNameSpecifier *Qualifier =
1153          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1154
1155        // FIXME: preserve source range information
1156        BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1157      }
1158    }
1159  }
1160
1161  if (!TInfo)
1162    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1163
1164  return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
1165                              LParenLoc, RParenLoc, ClassDecl);
1166}
1167
1168/// Checks an initializer expression for use of uninitialized fields, such as
1169/// containing the field that is being initialized. Returns true if there is an
1170/// uninitialized field was used an updates the SourceLocation parameter; false
1171/// otherwise.
1172static bool InitExprContainsUninitializedFields(const Stmt* S,
1173                                                const FieldDecl* LhsField,
1174                                                SourceLocation* L) {
1175  const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1176  if (ME) {
1177    const NamedDecl* RhsField = ME->getMemberDecl();
1178    if (RhsField == LhsField) {
1179      // Initializing a field with itself. Throw a warning.
1180      // But wait; there are exceptions!
1181      // Exception #1:  The field may not belong to this record.
1182      // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1183      const Expr* base = ME->getBase();
1184      if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1185        // Even though the field matches, it does not belong to this record.
1186        return false;
1187      }
1188      // None of the exceptions triggered; return true to indicate an
1189      // uninitialized field was used.
1190      *L = ME->getMemberLoc();
1191      return true;
1192    }
1193  }
1194  bool found = false;
1195  for (Stmt::const_child_iterator it = S->child_begin();
1196       it != S->child_end() && found == false;
1197       ++it) {
1198    if (isa<CallExpr>(S)) {
1199      // Do not descend into function calls or constructors, as the use
1200      // of an uninitialized field may be valid. One would have to inspect
1201      // the contents of the function/ctor to determine if it is safe or not.
1202      // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1203      // may be safe, depending on what the function/ctor does.
1204      continue;
1205    }
1206    found = InitExprContainsUninitializedFields(*it, LhsField, L);
1207  }
1208  return found;
1209}
1210
1211Sema::MemInitResult
1212Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1213                             unsigned NumArgs, SourceLocation IdLoc,
1214                             SourceLocation LParenLoc,
1215                             SourceLocation RParenLoc) {
1216  // Diagnose value-uses of fields to initialize themselves, e.g.
1217  //   foo(foo)
1218  // where foo is not also a parameter to the constructor.
1219  // TODO: implement -Wuninitialized and fold this into that framework.
1220  for (unsigned i = 0; i < NumArgs; ++i) {
1221    SourceLocation L;
1222    if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1223      // FIXME: Return true in the case when other fields are used before being
1224      // uninitialized. For example, let this field be the i'th field. When
1225      // initializing the i'th field, throw a warning if any of the >= i'th
1226      // fields are used, as they are not yet initialized.
1227      // Right now we are only handling the case where the i'th field uses
1228      // itself in its initializer.
1229      Diag(L, diag::warn_field_is_uninit);
1230    }
1231  }
1232
1233  bool HasDependentArg = false;
1234  for (unsigned i = 0; i < NumArgs; i++)
1235    HasDependentArg |= Args[i]->isTypeDependent();
1236
1237  QualType FieldType = Member->getType();
1238  if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1239    FieldType = Array->getElementType();
1240  ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1241  if (FieldType->isDependentType() || HasDependentArg) {
1242    // Can't check initialization for a member of dependent type or when
1243    // any of the arguments are type-dependent expressions.
1244    OwningExprResult Init
1245      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1246                                          RParenLoc));
1247
1248    // Erase any temporaries within this evaluation context; we're not
1249    // going to track them in the AST, since we'll be rebuilding the
1250    // ASTs during template instantiation.
1251    ExprTemporaries.erase(
1252              ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1253                          ExprTemporaries.end());
1254
1255    return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1256                                                    LParenLoc,
1257                                                    Init.takeAs<Expr>(),
1258                                                    RParenLoc);
1259
1260  }
1261
1262  if (Member->isInvalidDecl())
1263    return true;
1264
1265  // Initialize the member.
1266  InitializedEntity MemberEntity =
1267    InitializedEntity::InitializeMember(Member, 0);
1268  InitializationKind Kind =
1269    InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1270
1271  InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1272
1273  OwningExprResult MemberInit =
1274    InitSeq.Perform(*this, MemberEntity, Kind,
1275                    MultiExprArg(*this, (void**)Args, NumArgs), 0);
1276  if (MemberInit.isInvalid())
1277    return true;
1278
1279  // C++0x [class.base.init]p7:
1280  //   The initialization of each base and member constitutes a
1281  //   full-expression.
1282  MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1283  if (MemberInit.isInvalid())
1284    return true;
1285
1286  // If we are in a dependent context, template instantiation will
1287  // perform this type-checking again. Just save the arguments that we
1288  // received in a ParenListExpr.
1289  // FIXME: This isn't quite ideal, since our ASTs don't capture all
1290  // of the information that we have about the member
1291  // initializer. However, deconstructing the ASTs is a dicey process,
1292  // and this approach is far more likely to get the corner cases right.
1293  if (CurContext->isDependentContext()) {
1294    // Bump the reference count of all of the arguments.
1295    for (unsigned I = 0; I != NumArgs; ++I)
1296      Args[I]->Retain();
1297
1298    OwningExprResult Init
1299      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1300                                          RParenLoc));
1301    return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1302                                                    LParenLoc,
1303                                                    Init.takeAs<Expr>(),
1304                                                    RParenLoc);
1305  }
1306
1307  return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1308                                                  LParenLoc,
1309                                                  MemberInit.takeAs<Expr>(),
1310                                                  RParenLoc);
1311}
1312
1313Sema::MemInitResult
1314Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
1315                           Expr **Args, unsigned NumArgs,
1316                           SourceLocation LParenLoc, SourceLocation RParenLoc,
1317                           CXXRecordDecl *ClassDecl) {
1318  bool HasDependentArg = false;
1319  for (unsigned i = 0; i < NumArgs; i++)
1320    HasDependentArg |= Args[i]->isTypeDependent();
1321
1322  SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
1323  if (BaseType->isDependentType() || HasDependentArg) {
1324    // Can't check initialization for a base of dependent type or when
1325    // any of the arguments are type-dependent expressions.
1326    OwningExprResult BaseInit
1327      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1328                                          RParenLoc));
1329
1330    // Erase any temporaries within this evaluation context; we're not
1331    // going to track them in the AST, since we'll be rebuilding the
1332    // ASTs during template instantiation.
1333    ExprTemporaries.erase(
1334              ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1335                          ExprTemporaries.end());
1336
1337    return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1338                                                    LParenLoc,
1339                                                    BaseInit.takeAs<Expr>(),
1340                                                    RParenLoc);
1341  }
1342
1343  if (!BaseType->isRecordType())
1344    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1345             << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1346
1347  // C++ [class.base.init]p2:
1348  //   [...] Unless the mem-initializer-id names a nonstatic data
1349  //   member of the constructor���s class or a direct or virtual base
1350  //   of that class, the mem-initializer is ill-formed. A
1351  //   mem-initializer-list can initialize a base class using any
1352  //   name that denotes that base class type.
1353
1354  // Check for direct and virtual base classes.
1355  const CXXBaseSpecifier *DirectBaseSpec = 0;
1356  const CXXBaseSpecifier *VirtualBaseSpec = 0;
1357  FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1358                      VirtualBaseSpec);
1359
1360  // C++ [base.class.init]p2:
1361  //   If a mem-initializer-id is ambiguous because it designates both
1362  //   a direct non-virtual base class and an inherited virtual base
1363  //   class, the mem-initializer is ill-formed.
1364  if (DirectBaseSpec && VirtualBaseSpec)
1365    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1366      << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1367  // C++ [base.class.init]p2:
1368  // Unless the mem-initializer-id names a nonstatic data membeer of the
1369  // constructor's class ot a direst or virtual base of that class, the
1370  // mem-initializer is ill-formed.
1371  if (!DirectBaseSpec && !VirtualBaseSpec)
1372    return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1373      << BaseType << ClassDecl->getNameAsCString()
1374      << BaseTInfo->getTypeLoc().getSourceRange();
1375
1376  CXXBaseSpecifier *BaseSpec
1377    = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1378  if (!BaseSpec)
1379    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1380
1381  // Initialize the base.
1382  InitializedEntity BaseEntity =
1383    InitializedEntity::InitializeBase(Context, BaseSpec);
1384  InitializationKind Kind =
1385    InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1386
1387  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1388
1389  OwningExprResult BaseInit =
1390    InitSeq.Perform(*this, BaseEntity, Kind,
1391                    MultiExprArg(*this, (void**)Args, NumArgs), 0);
1392  if (BaseInit.isInvalid())
1393    return true;
1394
1395  // C++0x [class.base.init]p7:
1396  //   The initialization of each base and member constitutes a
1397  //   full-expression.
1398  BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1399  if (BaseInit.isInvalid())
1400    return true;
1401
1402  // If we are in a dependent context, template instantiation will
1403  // perform this type-checking again. Just save the arguments that we
1404  // received in a ParenListExpr.
1405  // FIXME: This isn't quite ideal, since our ASTs don't capture all
1406  // of the information that we have about the base
1407  // initializer. However, deconstructing the ASTs is a dicey process,
1408  // and this approach is far more likely to get the corner cases right.
1409  if (CurContext->isDependentContext()) {
1410    // Bump the reference count of all of the arguments.
1411    for (unsigned I = 0; I != NumArgs; ++I)
1412      Args[I]->Retain();
1413
1414    OwningExprResult Init
1415      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1416                                          RParenLoc));
1417    return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1418                                                    LParenLoc,
1419                                                    Init.takeAs<Expr>(),
1420                                                    RParenLoc);
1421  }
1422
1423  return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1424                                                  LParenLoc,
1425                                                  BaseInit.takeAs<Expr>(),
1426                                                  RParenLoc);
1427}
1428
1429bool
1430Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
1431                                  CXXBaseOrMemberInitializer **Initializers,
1432                                  unsigned NumInitializers,
1433                                  bool IsImplicitConstructor,
1434                                  bool AnyErrors) {
1435  // We need to build the initializer AST according to order of construction
1436  // and not what user specified in the Initializers list.
1437  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1438  llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1439  llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1440  bool HasDependentBaseInit = false;
1441  bool HadError = false;
1442
1443  for (unsigned i = 0; i < NumInitializers; i++) {
1444    CXXBaseOrMemberInitializer *Member = Initializers[i];
1445    if (Member->isBaseInitializer()) {
1446      if (Member->getBaseClass()->isDependentType())
1447        HasDependentBaseInit = true;
1448      AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1449    } else {
1450      AllBaseFields[Member->getMember()] = Member;
1451    }
1452  }
1453
1454  if (HasDependentBaseInit) {
1455    // FIXME. This does not preserve the ordering of the initializers.
1456    // Try (with -Wreorder)
1457    // template<class X> struct A {};
1458    // template<class X> struct B : A<X> {
1459    //   B() : x1(10), A<X>() {}
1460    //   int x1;
1461    // };
1462    // B<int> x;
1463    // On seeing one dependent type, we should essentially exit this routine
1464    // while preserving user-declared initializer list. When this routine is
1465    // called during instantiatiation process, this routine will rebuild the
1466    // ordered initializer list correctly.
1467
1468    // If we have a dependent base initialization, we can't determine the
1469    // association between initializers and bases; just dump the known
1470    // initializers into the list, and don't try to deal with other bases.
1471    for (unsigned i = 0; i < NumInitializers; i++) {
1472      CXXBaseOrMemberInitializer *Member = Initializers[i];
1473      if (Member->isBaseInitializer())
1474        AllToInit.push_back(Member);
1475    }
1476  } else {
1477    llvm::SmallVector<CXXBaseSpecifier *, 4> BasesToDefaultInit;
1478
1479    // Push virtual bases before others.
1480    for (CXXRecordDecl::base_class_iterator VBase =
1481         ClassDecl->vbases_begin(),
1482         E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1483      if (VBase->getType()->isDependentType())
1484        continue;
1485      if (CXXBaseOrMemberInitializer *Value
1486            = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1487        AllToInit.push_back(Value);
1488      } else if (!AnyErrors) {
1489        InitializedEntity InitEntity
1490          = InitializedEntity::InitializeBase(Context, VBase);
1491        InitializationKind InitKind
1492          = InitializationKind::CreateDefault(Constructor->getLocation());
1493        InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1494        OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1495                                                    MultiExprArg(*this, 0, 0));
1496        BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1497        if (BaseInit.isInvalid()) {
1498          HadError = true;
1499          continue;
1500        }
1501
1502        // Don't attach synthesized base initializers in a dependent
1503        // context; they'll be checked again at template instantiation
1504        // time.
1505        if (CurContext->isDependentContext())
1506          continue;
1507
1508        CXXBaseOrMemberInitializer *CXXBaseInit =
1509          new (Context) CXXBaseOrMemberInitializer(Context,
1510                             Context.getTrivialTypeSourceInfo(VBase->getType(),
1511                                                              SourceLocation()),
1512                                                   SourceLocation(),
1513                                                   BaseInit.takeAs<Expr>(),
1514                                                   SourceLocation());
1515        AllToInit.push_back(CXXBaseInit);
1516      }
1517    }
1518
1519    for (CXXRecordDecl::base_class_iterator Base =
1520         ClassDecl->bases_begin(),
1521         E = ClassDecl->bases_end(); Base != E; ++Base) {
1522      // Virtuals are in the virtual base list and already constructed.
1523      if (Base->isVirtual())
1524        continue;
1525      // Skip dependent types.
1526      if (Base->getType()->isDependentType())
1527        continue;
1528      if (CXXBaseOrMemberInitializer *Value
1529            = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1530        AllToInit.push_back(Value);
1531      }
1532      else if (!AnyErrors) {
1533        InitializedEntity InitEntity
1534          = InitializedEntity::InitializeBase(Context, Base);
1535        InitializationKind InitKind
1536          = InitializationKind::CreateDefault(Constructor->getLocation());
1537        InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1538        OwningExprResult BaseInit = InitSeq.Perform(*this, InitEntity, InitKind,
1539                                                    MultiExprArg(*this, 0, 0));
1540        BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1541        if (BaseInit.isInvalid()) {
1542          HadError = true;
1543          continue;
1544        }
1545
1546        // Don't attach synthesized base initializers in a dependent
1547        // context; they'll be regenerated at template instantiation
1548        // time.
1549        if (CurContext->isDependentContext())
1550          continue;
1551
1552        CXXBaseOrMemberInitializer *CXXBaseInit =
1553          new (Context) CXXBaseOrMemberInitializer(Context,
1554                             Context.getTrivialTypeSourceInfo(Base->getType(),
1555                                                              SourceLocation()),
1556                                                   SourceLocation(),
1557                                                   BaseInit.takeAs<Expr>(),
1558                                                   SourceLocation());
1559        AllToInit.push_back(CXXBaseInit);
1560      }
1561    }
1562  }
1563
1564  // non-static data members.
1565  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1566       E = ClassDecl->field_end(); Field != E; ++Field) {
1567    if ((*Field)->isAnonymousStructOrUnion()) {
1568      if (const RecordType *FieldClassType =
1569          Field->getType()->getAs<RecordType>()) {
1570        CXXRecordDecl *FieldClassDecl
1571          = cast<CXXRecordDecl>(FieldClassType->getDecl());
1572        for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1573            EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1574          if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1575            // 'Member' is the anonymous union field and 'AnonUnionMember' is
1576            // set to the anonymous union data member used in the initializer
1577            // list.
1578            Value->setMember(*Field);
1579            Value->setAnonUnionMember(*FA);
1580            AllToInit.push_back(Value);
1581            break;
1582          }
1583        }
1584      }
1585      continue;
1586    }
1587    if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1588      AllToInit.push_back(Value);
1589      continue;
1590    }
1591
1592    if ((*Field)->getType()->isDependentType() || AnyErrors)
1593      continue;
1594
1595    QualType FT = Context.getBaseElementType((*Field)->getType());
1596    if (FT->getAs<RecordType>()) {
1597      InitializedEntity InitEntity
1598        = InitializedEntity::InitializeMember(*Field);
1599      InitializationKind InitKind
1600        = InitializationKind::CreateDefault(Constructor->getLocation());
1601
1602      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
1603      OwningExprResult MemberInit = InitSeq.Perform(*this, InitEntity, InitKind,
1604                                                    MultiExprArg(*this, 0, 0));
1605      MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1606      if (MemberInit.isInvalid()) {
1607        HadError = true;
1608        continue;
1609      }
1610
1611      // Don't attach synthesized member initializers in a dependent
1612      // context; they'll be regenerated a template instantiation
1613      // time.
1614      if (CurContext->isDependentContext())
1615        continue;
1616
1617      CXXBaseOrMemberInitializer *Member =
1618        new (Context) CXXBaseOrMemberInitializer(Context,
1619                                                 *Field, SourceLocation(),
1620                                                 SourceLocation(),
1621                                                 MemberInit.takeAs<Expr>(),
1622                                                 SourceLocation());
1623
1624      AllToInit.push_back(Member);
1625    }
1626    else if (FT->isReferenceType()) {
1627      Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
1628        << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1629        << 0 << (*Field)->getDeclName();
1630      Diag((*Field)->getLocation(), diag::note_declared_at);
1631      HadError = true;
1632    }
1633    else if (FT.isConstQualified()) {
1634      Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor)
1635        << (int)IsImplicitConstructor << Context.getTagDeclType(ClassDecl)
1636        << 1 << (*Field)->getDeclName();
1637      Diag((*Field)->getLocation(), diag::note_declared_at);
1638      HadError = true;
1639    }
1640  }
1641
1642  NumInitializers = AllToInit.size();
1643  if (NumInitializers > 0) {
1644    Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1645    CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1646      new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1647
1648    Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1649    for (unsigned Idx = 0; Idx < NumInitializers; ++Idx) {
1650      CXXBaseOrMemberInitializer *Member = AllToInit[Idx];
1651      baseOrMemberInitializers[Idx] = Member;
1652      if (!Member->isBaseInitializer())
1653        continue;
1654      const Type *BaseType = Member->getBaseClass();
1655      const RecordType *RT = BaseType->getAs<RecordType>();
1656      if (!RT)
1657        continue;
1658      CXXRecordDecl *BaseClassDecl =
1659          cast<CXXRecordDecl>(RT->getDecl());
1660      if (BaseClassDecl->hasTrivialDestructor())
1661        continue;
1662      CXXDestructorDecl *DD = BaseClassDecl->getDestructor(Context);
1663      MarkDeclarationReferenced(Constructor->getLocation(), DD);
1664    }
1665  }
1666
1667  return HadError;
1668}
1669
1670static void *GetKeyForTopLevelField(FieldDecl *Field) {
1671  // For anonymous unions, use the class declaration as the key.
1672  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
1673    if (RT->getDecl()->isAnonymousStructOrUnion())
1674      return static_cast<void *>(RT->getDecl());
1675  }
1676  return static_cast<void *>(Field);
1677}
1678
1679static void *GetKeyForBase(QualType BaseType) {
1680  if (const RecordType *RT = BaseType->getAs<RecordType>())
1681    return (void *)RT;
1682
1683  assert(0 && "Unexpected base type!");
1684  return 0;
1685}
1686
1687static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
1688                             bool MemberMaybeAnon = false) {
1689  // For fields injected into the class via declaration of an anonymous union,
1690  // use its anonymous union class declaration as the unique key.
1691  if (Member->isMemberInitializer()) {
1692    FieldDecl *Field = Member->getMember();
1693
1694    // After SetBaseOrMemberInitializers call, Field is the anonymous union
1695    // data member of the class. Data member used in the initializer list is
1696    // in AnonUnionMember field.
1697    if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1698      Field = Member->getAnonUnionMember();
1699    if (Field->getDeclContext()->isRecord()) {
1700      RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
1701      if (RD->isAnonymousStructOrUnion())
1702        return static_cast<void *>(RD);
1703    }
1704    return static_cast<void *>(Field);
1705  }
1706
1707  return GetKeyForBase(QualType(Member->getBaseClass(), 0));
1708}
1709
1710/// ActOnMemInitializers - Handle the member initializers for a constructor.
1711void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
1712                                SourceLocation ColonLoc,
1713                                MemInitTy **MemInits, unsigned NumMemInits,
1714                                bool AnyErrors) {
1715  if (!ConstructorDecl)
1716    return;
1717
1718  AdjustDeclIfTemplate(ConstructorDecl);
1719
1720  CXXConstructorDecl *Constructor
1721    = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
1722
1723  if (!Constructor) {
1724    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
1725    return;
1726  }
1727
1728  if (!Constructor->isDependentContext()) {
1729    llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
1730    bool err = false;
1731    for (unsigned i = 0; i < NumMemInits; i++) {
1732      CXXBaseOrMemberInitializer *Member =
1733        static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1734      void *KeyToMember = GetKeyForMember(Member);
1735      CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
1736      if (!PrevMember) {
1737        PrevMember = Member;
1738        continue;
1739      }
1740      if (FieldDecl *Field = Member->getMember())
1741        Diag(Member->getSourceLocation(),
1742             diag::error_multiple_mem_initialization)
1743          << Field->getNameAsString()
1744          << Member->getSourceRange();
1745      else {
1746        Type *BaseClass = Member->getBaseClass();
1747        assert(BaseClass && "ActOnMemInitializers - neither field or base");
1748        Diag(Member->getSourceLocation(),
1749             diag::error_multiple_base_initialization)
1750          << QualType(BaseClass, 0)
1751          << Member->getSourceRange();
1752      }
1753      Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
1754        << 0;
1755      err = true;
1756    }
1757
1758    if (err)
1759      return;
1760  }
1761
1762  SetBaseOrMemberInitializers(Constructor,
1763                      reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
1764                      NumMemInits, false, AnyErrors);
1765
1766  if (Constructor->isDependentContext())
1767    return;
1768
1769  if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
1770      Diagnostic::Ignored &&
1771      Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
1772      Diagnostic::Ignored)
1773    return;
1774
1775  // Also issue warning if order of ctor-initializer list does not match order
1776  // of 1) base class declarations and 2) order of non-static data members.
1777  llvm::SmallVector<const void*, 32> AllBaseOrMembers;
1778
1779  CXXRecordDecl *ClassDecl
1780    = cast<CXXRecordDecl>(Constructor->getDeclContext());
1781  // Push virtual bases before others.
1782  for (CXXRecordDecl::base_class_iterator VBase =
1783       ClassDecl->vbases_begin(),
1784       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
1785    AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType()));
1786
1787  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1788       E = ClassDecl->bases_end(); Base != E; ++Base) {
1789    // Virtuals are alread in the virtual base list and are constructed
1790    // first.
1791    if (Base->isVirtual())
1792      continue;
1793    AllBaseOrMembers.push_back(GetKeyForBase(Base->getType()));
1794  }
1795
1796  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1797       E = ClassDecl->field_end(); Field != E; ++Field)
1798    AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
1799
1800  int Last = AllBaseOrMembers.size();
1801  int curIndex = 0;
1802  CXXBaseOrMemberInitializer *PrevMember = 0;
1803  for (unsigned i = 0; i < NumMemInits; i++) {
1804    CXXBaseOrMemberInitializer *Member =
1805      static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1806    void *MemberInCtorList = GetKeyForMember(Member, true);
1807
1808    for (; curIndex < Last; curIndex++)
1809      if (MemberInCtorList == AllBaseOrMembers[curIndex])
1810        break;
1811    if (curIndex == Last) {
1812      assert(PrevMember && "Member not in member list?!");
1813      // Initializer as specified in ctor-initializer list is out of order.
1814      // Issue a warning diagnostic.
1815      if (PrevMember->isBaseInitializer()) {
1816        // Diagnostics is for an initialized base class.
1817        Type *BaseClass = PrevMember->getBaseClass();
1818        Diag(PrevMember->getSourceLocation(),
1819             diag::warn_base_initialized)
1820          << QualType(BaseClass, 0);
1821      } else {
1822        FieldDecl *Field = PrevMember->getMember();
1823        Diag(PrevMember->getSourceLocation(),
1824             diag::warn_field_initialized)
1825          << Field->getNameAsString();
1826      }
1827      // Also the note!
1828      if (FieldDecl *Field = Member->getMember())
1829        Diag(Member->getSourceLocation(),
1830             diag::note_fieldorbase_initialized_here) << 0
1831          << Field->getNameAsString();
1832      else {
1833        Type *BaseClass = Member->getBaseClass();
1834        Diag(Member->getSourceLocation(),
1835             diag::note_fieldorbase_initialized_here) << 1
1836          << QualType(BaseClass, 0);
1837      }
1838      for (curIndex = 0; curIndex < Last; curIndex++)
1839        if (MemberInCtorList == AllBaseOrMembers[curIndex])
1840          break;
1841    }
1842    PrevMember = Member;
1843  }
1844}
1845
1846void
1847Sema::MarkBaseAndMemberDestructorsReferenced(CXXDestructorDecl *Destructor) {
1848  // Ignore dependent destructors.
1849  if (Destructor->isDependentContext())
1850    return;
1851
1852  CXXRecordDecl *ClassDecl = Destructor->getParent();
1853
1854  // Non-static data members.
1855  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1856       E = ClassDecl->field_end(); I != E; ++I) {
1857    FieldDecl *Field = *I;
1858
1859    QualType FieldType = Context.getBaseElementType(Field->getType());
1860
1861    const RecordType* RT = FieldType->getAs<RecordType>();
1862    if (!RT)
1863      continue;
1864
1865    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1866    if (FieldClassDecl->hasTrivialDestructor())
1867      continue;
1868
1869    const CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
1870    MarkDeclarationReferenced(Destructor->getLocation(),
1871                              const_cast<CXXDestructorDecl*>(Dtor));
1872  }
1873
1874  // Bases.
1875  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1876       E = ClassDecl->bases_end(); Base != E; ++Base) {
1877    // Ignore virtual bases.
1878    if (Base->isVirtual())
1879      continue;
1880
1881    // Ignore trivial destructors.
1882    CXXRecordDecl *BaseClassDecl
1883      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
1884    if (BaseClassDecl->hasTrivialDestructor())
1885      continue;
1886
1887    const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1888    MarkDeclarationReferenced(Destructor->getLocation(),
1889                              const_cast<CXXDestructorDecl*>(Dtor));
1890  }
1891
1892  // Virtual bases.
1893  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1894       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1895    // Ignore trivial destructors.
1896    CXXRecordDecl *BaseClassDecl
1897      = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl());
1898    if (BaseClassDecl->hasTrivialDestructor())
1899      continue;
1900
1901    const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
1902    MarkDeclarationReferenced(Destructor->getLocation(),
1903                              const_cast<CXXDestructorDecl*>(Dtor));
1904  }
1905}
1906
1907void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
1908  if (!CDtorDecl)
1909    return;
1910
1911  AdjustDeclIfTemplate(CDtorDecl);
1912
1913  if (CXXConstructorDecl *Constructor
1914      = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
1915    SetBaseOrMemberInitializers(Constructor, 0, 0, false, false);
1916}
1917
1918namespace {
1919  /// PureVirtualMethodCollector - traverses a class and its superclasses
1920  /// and determines if it has any pure virtual methods.
1921  class PureVirtualMethodCollector {
1922    ASTContext &Context;
1923
1924  public:
1925    typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
1926
1927  private:
1928    MethodList Methods;
1929
1930    void Collect(const CXXRecordDecl* RD, MethodList& Methods);
1931
1932  public:
1933    PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
1934      : Context(Ctx) {
1935
1936      MethodList List;
1937      Collect(RD, List);
1938
1939      // Copy the temporary list to methods, and make sure to ignore any
1940      // null entries.
1941      for (size_t i = 0, e = List.size(); i != e; ++i) {
1942        if (List[i])
1943          Methods.push_back(List[i]);
1944      }
1945    }
1946
1947    bool empty() const { return Methods.empty(); }
1948
1949    MethodList::const_iterator methods_begin() { return Methods.begin(); }
1950    MethodList::const_iterator methods_end() { return Methods.end(); }
1951  };
1952
1953  void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
1954                                           MethodList& Methods) {
1955    // First, collect the pure virtual methods for the base classes.
1956    for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1957         BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
1958      if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
1959        const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
1960        if (BaseDecl && BaseDecl->isAbstract())
1961          Collect(BaseDecl, Methods);
1962      }
1963    }
1964
1965    // Next, zero out any pure virtual methods that this class overrides.
1966    typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
1967
1968    MethodSetTy OverriddenMethods;
1969    size_t MethodsSize = Methods.size();
1970
1971    for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
1972         i != e; ++i) {
1973      // Traverse the record, looking for methods.
1974      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
1975        // If the method is pure virtual, add it to the methods vector.
1976        if (MD->isPure())
1977          Methods.push_back(MD);
1978
1979        // Record all the overridden methods in our set.
1980        for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1981             E = MD->end_overridden_methods(); I != E; ++I) {
1982          // Keep track of the overridden methods.
1983          OverriddenMethods.insert(*I);
1984        }
1985      }
1986    }
1987
1988    // Now go through the methods and zero out all the ones we know are
1989    // overridden.
1990    for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1991      if (OverriddenMethods.count(Methods[i]))
1992        Methods[i] = 0;
1993    }
1994
1995  }
1996}
1997
1998
1999bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2000                                  unsigned DiagID, AbstractDiagSelID SelID,
2001                                  const CXXRecordDecl *CurrentRD) {
2002  if (SelID == -1)
2003    return RequireNonAbstractType(Loc, T,
2004                                  PDiag(DiagID), CurrentRD);
2005  else
2006    return RequireNonAbstractType(Loc, T,
2007                                  PDiag(DiagID) << SelID, CurrentRD);
2008}
2009
2010bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2011                                  const PartialDiagnostic &PD,
2012                                  const CXXRecordDecl *CurrentRD) {
2013  if (!getLangOptions().CPlusPlus)
2014    return false;
2015
2016  if (const ArrayType *AT = Context.getAsArrayType(T))
2017    return RequireNonAbstractType(Loc, AT->getElementType(), PD,
2018                                  CurrentRD);
2019
2020  if (const PointerType *PT = T->getAs<PointerType>()) {
2021    // Find the innermost pointer type.
2022    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
2023      PT = T;
2024
2025    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
2026      return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
2027  }
2028
2029  const RecordType *RT = T->getAs<RecordType>();
2030  if (!RT)
2031    return false;
2032
2033  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2034
2035  if (CurrentRD && CurrentRD != RD)
2036    return false;
2037
2038  // FIXME: is this reasonable?  It matches current behavior, but....
2039  if (!RD->getDefinition())
2040    return false;
2041
2042  if (!RD->isAbstract())
2043    return false;
2044
2045  Diag(Loc, PD) << RD->getDeclName();
2046
2047  // Check if we've already emitted the list of pure virtual functions for this
2048  // class.
2049  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2050    return true;
2051
2052  PureVirtualMethodCollector Collector(Context, RD);
2053
2054  for (PureVirtualMethodCollector::MethodList::const_iterator I =
2055       Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
2056    const CXXMethodDecl *MD = *I;
2057
2058    Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
2059      MD->getDeclName();
2060  }
2061
2062  if (!PureVirtualClassDiagSet)
2063    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2064  PureVirtualClassDiagSet->insert(RD);
2065
2066  return true;
2067}
2068
2069namespace {
2070  class AbstractClassUsageDiagnoser
2071    : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2072    Sema &SemaRef;
2073    CXXRecordDecl *AbstractClass;
2074
2075    bool VisitDeclContext(const DeclContext *DC) {
2076      bool Invalid = false;
2077
2078      for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2079           E = DC->decls_end(); I != E; ++I)
2080        Invalid |= Visit(*I);
2081
2082      return Invalid;
2083    }
2084
2085  public:
2086    AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2087      : SemaRef(SemaRef), AbstractClass(ac) {
2088        Visit(SemaRef.Context.getTranslationUnitDecl());
2089    }
2090
2091    bool VisitFunctionDecl(const FunctionDecl *FD) {
2092      if (FD->isThisDeclarationADefinition()) {
2093        // No need to do the check if we're in a definition, because it requires
2094        // that the return/param types are complete.
2095        // because that requires
2096        return VisitDeclContext(FD);
2097      }
2098
2099      // Check the return type.
2100      QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
2101      bool Invalid =
2102        SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2103                                       diag::err_abstract_type_in_decl,
2104                                       Sema::AbstractReturnType,
2105                                       AbstractClass);
2106
2107      for (FunctionDecl::param_const_iterator I = FD->param_begin(),
2108           E = FD->param_end(); I != E; ++I) {
2109        const ParmVarDecl *VD = *I;
2110        Invalid |=
2111          SemaRef.RequireNonAbstractType(VD->getLocation(),
2112                                         VD->getOriginalType(),
2113                                         diag::err_abstract_type_in_decl,
2114                                         Sema::AbstractParamType,
2115                                         AbstractClass);
2116      }
2117
2118      return Invalid;
2119    }
2120
2121    bool VisitDecl(const Decl* D) {
2122      if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2123        return VisitDeclContext(DC);
2124
2125      return false;
2126    }
2127  };
2128}
2129
2130/// \brief Perform semantic checks on a class definition that has been
2131/// completing, introducing implicitly-declared members, checking for
2132/// abstract types, etc.
2133void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2134  if (!Record || Record->isInvalidDecl())
2135    return;
2136
2137  if (!Record->isDependentType())
2138    AddImplicitlyDeclaredMembersToClass(Record);
2139
2140  if (Record->isInvalidDecl())
2141    return;
2142
2143  // Set access bits correctly on the directly-declared conversions.
2144  UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2145  for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2146    Convs->setAccess(I, (*I)->getAccess());
2147
2148  if (!Record->isAbstract()) {
2149    // Collect all the pure virtual methods and see if this is an abstract
2150    // class after all.
2151    PureVirtualMethodCollector Collector(Context, Record);
2152    if (!Collector.empty())
2153      Record->setAbstract(true);
2154  }
2155
2156  if (Record->isAbstract())
2157    (void)AbstractClassUsageDiagnoser(*this, Record);
2158}
2159
2160void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
2161                                             DeclPtrTy TagDecl,
2162                                             SourceLocation LBrac,
2163                                             SourceLocation RBrac) {
2164  if (!TagDecl)
2165    return;
2166
2167  AdjustDeclIfTemplate(TagDecl);
2168
2169  ActOnFields(S, RLoc, TagDecl,
2170              (DeclPtrTy*)FieldCollector->getCurFields(),
2171              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
2172
2173  CheckCompletedCXXClass(
2174                      dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
2175}
2176
2177/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2178/// special functions, such as the default constructor, copy
2179/// constructor, or destructor, to the given C++ class (C++
2180/// [special]p1).  This routine can only be executed just before the
2181/// definition of the class is complete.
2182void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
2183  CanQualType ClassType
2184    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
2185
2186  // FIXME: Implicit declarations have exception specifications, which are
2187  // the union of the specifications of the implicitly called functions.
2188
2189  if (!ClassDecl->hasUserDeclaredConstructor()) {
2190    // C++ [class.ctor]p5:
2191    //   A default constructor for a class X is a constructor of class X
2192    //   that can be called without an argument. If there is no
2193    //   user-declared constructor for class X, a default constructor is
2194    //   implicitly declared. An implicitly-declared default constructor
2195    //   is an inline public member of its class.
2196    DeclarationName Name
2197      = Context.DeclarationNames.getCXXConstructorName(ClassType);
2198    CXXConstructorDecl *DefaultCon =
2199      CXXConstructorDecl::Create(Context, ClassDecl,
2200                                 ClassDecl->getLocation(), Name,
2201                                 Context.getFunctionType(Context.VoidTy,
2202                                                         0, 0, false, 0,
2203                                                         /*FIXME*/false, false,
2204                                                         0, 0, false,
2205                                                         CC_Default),
2206                                 /*TInfo=*/0,
2207                                 /*isExplicit=*/false,
2208                                 /*isInline=*/true,
2209                                 /*isImplicitlyDeclared=*/true);
2210    DefaultCon->setAccess(AS_public);
2211    DefaultCon->setImplicit();
2212    DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
2213    ClassDecl->addDecl(DefaultCon);
2214  }
2215
2216  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2217    // C++ [class.copy]p4:
2218    //   If the class definition does not explicitly declare a copy
2219    //   constructor, one is declared implicitly.
2220
2221    // C++ [class.copy]p5:
2222    //   The implicitly-declared copy constructor for a class X will
2223    //   have the form
2224    //
2225    //       X::X(const X&)
2226    //
2227    //   if
2228    bool HasConstCopyConstructor = true;
2229
2230    //     -- each direct or virtual base class B of X has a copy
2231    //        constructor whose first parameter is of type const B& or
2232    //        const volatile B&, and
2233    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2234         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2235      const CXXRecordDecl *BaseClassDecl
2236        = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2237      HasConstCopyConstructor
2238        = BaseClassDecl->hasConstCopyConstructor(Context);
2239    }
2240
2241    //     -- for all the nonstatic data members of X that are of a
2242    //        class type M (or array thereof), each such class type
2243    //        has a copy constructor whose first parameter is of type
2244    //        const M& or const volatile M&.
2245    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2246         HasConstCopyConstructor && Field != ClassDecl->field_end();
2247         ++Field) {
2248      QualType FieldType = (*Field)->getType();
2249      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2250        FieldType = Array->getElementType();
2251      if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2252        const CXXRecordDecl *FieldClassDecl
2253          = cast<CXXRecordDecl>(FieldClassType->getDecl());
2254        HasConstCopyConstructor
2255          = FieldClassDecl->hasConstCopyConstructor(Context);
2256      }
2257    }
2258
2259    //   Otherwise, the implicitly declared copy constructor will have
2260    //   the form
2261    //
2262    //       X::X(X&)
2263    QualType ArgType = ClassType;
2264    if (HasConstCopyConstructor)
2265      ArgType = ArgType.withConst();
2266    ArgType = Context.getLValueReferenceType(ArgType);
2267
2268    //   An implicitly-declared copy constructor is an inline public
2269    //   member of its class.
2270    DeclarationName Name
2271      = Context.DeclarationNames.getCXXConstructorName(ClassType);
2272    CXXConstructorDecl *CopyConstructor
2273      = CXXConstructorDecl::Create(Context, ClassDecl,
2274                                   ClassDecl->getLocation(), Name,
2275                                   Context.getFunctionType(Context.VoidTy,
2276                                                           &ArgType, 1,
2277                                                           false, 0,
2278                                                           /*FIXME:*/false,
2279                                                           false, 0, 0, false,
2280                                                           CC_Default),
2281                                   /*TInfo=*/0,
2282                                   /*isExplicit=*/false,
2283                                   /*isInline=*/true,
2284                                   /*isImplicitlyDeclared=*/true);
2285    CopyConstructor->setAccess(AS_public);
2286    CopyConstructor->setImplicit();
2287    CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
2288
2289    // Add the parameter to the constructor.
2290    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2291                                                 ClassDecl->getLocation(),
2292                                                 /*IdentifierInfo=*/0,
2293                                                 ArgType, /*TInfo=*/0,
2294                                                 VarDecl::None, 0);
2295    CopyConstructor->setParams(&FromParam, 1);
2296    ClassDecl->addDecl(CopyConstructor);
2297  }
2298
2299  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2300    // Note: The following rules are largely analoguous to the copy
2301    // constructor rules. Note that virtual bases are not taken into account
2302    // for determining the argument type of the operator. Note also that
2303    // operators taking an object instead of a reference are allowed.
2304    //
2305    // C++ [class.copy]p10:
2306    //   If the class definition does not explicitly declare a copy
2307    //   assignment operator, one is declared implicitly.
2308    //   The implicitly-defined copy assignment operator for a class X
2309    //   will have the form
2310    //
2311    //       X& X::operator=(const X&)
2312    //
2313    //   if
2314    bool HasConstCopyAssignment = true;
2315
2316    //       -- each direct base class B of X has a copy assignment operator
2317    //          whose parameter is of type const B&, const volatile B& or B,
2318    //          and
2319    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2320         HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
2321      assert(!Base->getType()->isDependentType() &&
2322            "Cannot generate implicit members for class with dependent bases.");
2323      const CXXRecordDecl *BaseClassDecl
2324        = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2325      const CXXMethodDecl *MD = 0;
2326      HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
2327                                                                     MD);
2328    }
2329
2330    //       -- for all the nonstatic data members of X that are of a class
2331    //          type M (or array thereof), each such class type has a copy
2332    //          assignment operator whose parameter is of type const M&,
2333    //          const volatile M& or M.
2334    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2335         HasConstCopyAssignment && Field != ClassDecl->field_end();
2336         ++Field) {
2337      QualType FieldType = (*Field)->getType();
2338      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2339        FieldType = Array->getElementType();
2340      if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2341        const CXXRecordDecl *FieldClassDecl
2342          = cast<CXXRecordDecl>(FieldClassType->getDecl());
2343        const CXXMethodDecl *MD = 0;
2344        HasConstCopyAssignment
2345          = FieldClassDecl->hasConstCopyAssignment(Context, MD);
2346      }
2347    }
2348
2349    //   Otherwise, the implicitly declared copy assignment operator will
2350    //   have the form
2351    //
2352    //       X& X::operator=(X&)
2353    QualType ArgType = ClassType;
2354    QualType RetType = Context.getLValueReferenceType(ArgType);
2355    if (HasConstCopyAssignment)
2356      ArgType = ArgType.withConst();
2357    ArgType = Context.getLValueReferenceType(ArgType);
2358
2359    //   An implicitly-declared copy assignment operator is an inline public
2360    //   member of its class.
2361    DeclarationName Name =
2362      Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2363    CXXMethodDecl *CopyAssignment =
2364      CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2365                            Context.getFunctionType(RetType, &ArgType, 1,
2366                                                    false, 0,
2367                                                    /*FIXME:*/false,
2368                                                    false, 0, 0, false,
2369                                                    CC_Default),
2370                            /*TInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
2371    CopyAssignment->setAccess(AS_public);
2372    CopyAssignment->setImplicit();
2373    CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
2374    CopyAssignment->setCopyAssignment(true);
2375
2376    // Add the parameter to the operator.
2377    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2378                                                 ClassDecl->getLocation(),
2379                                                 /*IdentifierInfo=*/0,
2380                                                 ArgType, /*TInfo=*/0,
2381                                                 VarDecl::None, 0);
2382    CopyAssignment->setParams(&FromParam, 1);
2383
2384    // Don't call addedAssignmentOperator. There is no way to distinguish an
2385    // implicit from an explicit assignment operator.
2386    ClassDecl->addDecl(CopyAssignment);
2387    AddOverriddenMethods(ClassDecl, CopyAssignment);
2388  }
2389
2390  if (!ClassDecl->hasUserDeclaredDestructor()) {
2391    // C++ [class.dtor]p2:
2392    //   If a class has no user-declared destructor, a destructor is
2393    //   declared implicitly. An implicitly-declared destructor is an
2394    //   inline public member of its class.
2395    DeclarationName Name
2396      = Context.DeclarationNames.getCXXDestructorName(ClassType);
2397    CXXDestructorDecl *Destructor
2398      = CXXDestructorDecl::Create(Context, ClassDecl,
2399                                  ClassDecl->getLocation(), Name,
2400                                  Context.getFunctionType(Context.VoidTy,
2401                                                          0, 0, false, 0,
2402                                                           /*FIXME:*/false,
2403                                                           false, 0, 0, false,
2404                                                           CC_Default),
2405                                  /*isInline=*/true,
2406                                  /*isImplicitlyDeclared=*/true);
2407    Destructor->setAccess(AS_public);
2408    Destructor->setImplicit();
2409    Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
2410    ClassDecl->addDecl(Destructor);
2411
2412    AddOverriddenMethods(ClassDecl, Destructor);
2413  }
2414}
2415
2416void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
2417  Decl *D = TemplateD.getAs<Decl>();
2418  if (!D)
2419    return;
2420
2421  TemplateParameterList *Params = 0;
2422  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2423    Params = Template->getTemplateParameters();
2424  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2425           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2426    Params = PartialSpec->getTemplateParameters();
2427  else
2428    return;
2429
2430  for (TemplateParameterList::iterator Param = Params->begin(),
2431                                    ParamEnd = Params->end();
2432       Param != ParamEnd; ++Param) {
2433    NamedDecl *Named = cast<NamedDecl>(*Param);
2434    if (Named->getDeclName()) {
2435      S->AddDecl(DeclPtrTy::make(Named));
2436      IdResolver.AddDecl(Named);
2437    }
2438  }
2439}
2440
2441void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2442  if (!RecordD) return;
2443  AdjustDeclIfTemplate(RecordD);
2444  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2445  PushDeclContext(S, Record);
2446}
2447
2448void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2449  if (!RecordD) return;
2450  PopDeclContext();
2451}
2452
2453/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2454/// parsing a top-level (non-nested) C++ class, and we are now
2455/// parsing those parts of the given Method declaration that could
2456/// not be parsed earlier (C++ [class.mem]p2), such as default
2457/// arguments. This action should enter the scope of the given
2458/// Method declaration as if we had just parsed the qualified method
2459/// name. However, it should not bring the parameters into scope;
2460/// that will be performed by ActOnDelayedCXXMethodParameter.
2461void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2462}
2463
2464/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2465/// C++ method declaration. We're (re-)introducing the given
2466/// function parameter into scope for use in parsing later parts of
2467/// the method declaration. For example, we could see an
2468/// ActOnParamDefaultArgument event for this parameter.
2469void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
2470  if (!ParamD)
2471    return;
2472
2473  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
2474
2475  // If this parameter has an unparsed default argument, clear it out
2476  // to make way for the parsed default argument.
2477  if (Param->hasUnparsedDefaultArg())
2478    Param->setDefaultArg(0);
2479
2480  S->AddDecl(DeclPtrTy::make(Param));
2481  if (Param->getDeclName())
2482    IdResolver.AddDecl(Param);
2483}
2484
2485/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2486/// processing the delayed method declaration for Method. The method
2487/// declaration is now considered finished. There may be a separate
2488/// ActOnStartOfFunctionDef action later (not necessarily
2489/// immediately!) for this method, if it was also defined inside the
2490/// class body.
2491void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2492  if (!MethodD)
2493    return;
2494
2495  AdjustDeclIfTemplate(MethodD);
2496
2497  FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
2498
2499  // Now that we have our default arguments, check the constructor
2500  // again. It could produce additional diagnostics or affect whether
2501  // the class has implicitly-declared destructors, among other
2502  // things.
2503  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2504    CheckConstructor(Constructor);
2505
2506  // Check the default arguments, which we may have added.
2507  if (!Method->isInvalidDecl())
2508    CheckCXXDefaultArguments(Method);
2509}
2510
2511/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
2512/// the well-formedness of the constructor declarator @p D with type @p
2513/// R. If there are any errors in the declarator, this routine will
2514/// emit diagnostics and set the invalid bit to true.  In any case, the type
2515/// will be updated to reflect a well-formed type for the constructor and
2516/// returned.
2517QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2518                                          FunctionDecl::StorageClass &SC) {
2519  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2520
2521  // C++ [class.ctor]p3:
2522  //   A constructor shall not be virtual (10.3) or static (9.4). A
2523  //   constructor can be invoked for a const, volatile or const
2524  //   volatile object. A constructor shall not be declared const,
2525  //   volatile, or const volatile (9.3.2).
2526  if (isVirtual) {
2527    if (!D.isInvalidType())
2528      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2529        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2530        << SourceRange(D.getIdentifierLoc());
2531    D.setInvalidType();
2532  }
2533  if (SC == FunctionDecl::Static) {
2534    if (!D.isInvalidType())
2535      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2536        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2537        << SourceRange(D.getIdentifierLoc());
2538    D.setInvalidType();
2539    SC = FunctionDecl::None;
2540  }
2541
2542  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2543  if (FTI.TypeQuals != 0) {
2544    if (FTI.TypeQuals & Qualifiers::Const)
2545      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2546        << "const" << SourceRange(D.getIdentifierLoc());
2547    if (FTI.TypeQuals & Qualifiers::Volatile)
2548      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2549        << "volatile" << SourceRange(D.getIdentifierLoc());
2550    if (FTI.TypeQuals & Qualifiers::Restrict)
2551      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2552        << "restrict" << SourceRange(D.getIdentifierLoc());
2553  }
2554
2555  // Rebuild the function type "R" without any type qualifiers (in
2556  // case any of the errors above fired) and with "void" as the
2557  // return type, since constructors don't have return types. We
2558  // *always* have to do this, because GetTypeForDeclarator will
2559  // put in a result type of "int" when none was specified.
2560  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
2561  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2562                                 Proto->getNumArgs(),
2563                                 Proto->isVariadic(), 0,
2564                                 Proto->hasExceptionSpec(),
2565                                 Proto->hasAnyExceptionSpec(),
2566                                 Proto->getNumExceptions(),
2567                                 Proto->exception_begin(),
2568                                 Proto->getNoReturnAttr(),
2569                                 Proto->getCallConv());
2570}
2571
2572/// CheckConstructor - Checks a fully-formed constructor for
2573/// well-formedness, issuing any diagnostics required. Returns true if
2574/// the constructor declarator is invalid.
2575void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
2576  CXXRecordDecl *ClassDecl
2577    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2578  if (!ClassDecl)
2579    return Constructor->setInvalidDecl();
2580
2581  // C++ [class.copy]p3:
2582  //   A declaration of a constructor for a class X is ill-formed if
2583  //   its first parameter is of type (optionally cv-qualified) X and
2584  //   either there are no other parameters or else all other
2585  //   parameters have default arguments.
2586  if (!Constructor->isInvalidDecl() &&
2587      ((Constructor->getNumParams() == 1) ||
2588       (Constructor->getNumParams() > 1 &&
2589        Constructor->getParamDecl(1)->hasDefaultArg())) &&
2590      Constructor->getTemplateSpecializationKind()
2591                                              != TSK_ImplicitInstantiation) {
2592    QualType ParamType = Constructor->getParamDecl(0)->getType();
2593    QualType ClassTy = Context.getTagDeclType(ClassDecl);
2594    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
2595      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2596      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
2597        << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
2598
2599      // FIXME: Rather that making the constructor invalid, we should endeavor
2600      // to fix the type.
2601      Constructor->setInvalidDecl();
2602    }
2603  }
2604
2605  // Notify the class that we've added a constructor.
2606  ClassDecl->addedConstructor(Context, Constructor);
2607}
2608
2609/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2610/// issuing any diagnostics required. Returns true on error.
2611bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
2612  CXXRecordDecl *RD = Destructor->getParent();
2613
2614  if (Destructor->isVirtual()) {
2615    SourceLocation Loc;
2616
2617    if (!Destructor->isImplicit())
2618      Loc = Destructor->getLocation();
2619    else
2620      Loc = RD->getLocation();
2621
2622    // If we have a virtual destructor, look up the deallocation function
2623    FunctionDecl *OperatorDelete = 0;
2624    DeclarationName Name =
2625    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2626    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2627      return true;
2628
2629    Destructor->setOperatorDelete(OperatorDelete);
2630  }
2631
2632  return false;
2633}
2634
2635static inline bool
2636FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2637  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2638          FTI.ArgInfo[0].Param &&
2639          FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2640}
2641
2642/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2643/// the well-formednes of the destructor declarator @p D with type @p
2644/// R. If there are any errors in the declarator, this routine will
2645/// emit diagnostics and set the declarator to invalid.  Even if this happens,
2646/// will be updated to reflect a well-formed type for the destructor and
2647/// returned.
2648QualType Sema::CheckDestructorDeclarator(Declarator &D,
2649                                         FunctionDecl::StorageClass& SC) {
2650  // C++ [class.dtor]p1:
2651  //   [...] A typedef-name that names a class is a class-name
2652  //   (7.1.3); however, a typedef-name that names a class shall not
2653  //   be used as the identifier in the declarator for a destructor
2654  //   declaration.
2655  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
2656  if (isa<TypedefType>(DeclaratorType)) {
2657    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
2658      << DeclaratorType;
2659    D.setInvalidType();
2660  }
2661
2662  // C++ [class.dtor]p2:
2663  //   A destructor is used to destroy objects of its class type. A
2664  //   destructor takes no parameters, and no return type can be
2665  //   specified for it (not even void). The address of a destructor
2666  //   shall not be taken. A destructor shall not be static. A
2667  //   destructor can be invoked for a const, volatile or const
2668  //   volatile object. A destructor shall not be declared const,
2669  //   volatile or const volatile (9.3.2).
2670  if (SC == FunctionDecl::Static) {
2671    if (!D.isInvalidType())
2672      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2673        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2674        << SourceRange(D.getIdentifierLoc());
2675    SC = FunctionDecl::None;
2676    D.setInvalidType();
2677  }
2678  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
2679    // Destructors don't have return types, but the parser will
2680    // happily parse something like:
2681    //
2682    //   class X {
2683    //     float ~X();
2684    //   };
2685    //
2686    // The return type will be eliminated later.
2687    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2688      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2689      << SourceRange(D.getIdentifierLoc());
2690  }
2691
2692  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2693  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
2694    if (FTI.TypeQuals & Qualifiers::Const)
2695      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2696        << "const" << SourceRange(D.getIdentifierLoc());
2697    if (FTI.TypeQuals & Qualifiers::Volatile)
2698      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2699        << "volatile" << SourceRange(D.getIdentifierLoc());
2700    if (FTI.TypeQuals & Qualifiers::Restrict)
2701      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2702        << "restrict" << SourceRange(D.getIdentifierLoc());
2703    D.setInvalidType();
2704  }
2705
2706  // Make sure we don't have any parameters.
2707  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
2708    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2709
2710    // Delete the parameters.
2711    FTI.freeArgs();
2712    D.setInvalidType();
2713  }
2714
2715  // Make sure the destructor isn't variadic.
2716  if (FTI.isVariadic) {
2717    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
2718    D.setInvalidType();
2719  }
2720
2721  // Rebuild the function type "R" without any type qualifiers or
2722  // parameters (in case any of the errors above fired) and with
2723  // "void" as the return type, since destructors don't have return
2724  // types. We *always* have to do this, because GetTypeForDeclarator
2725  // will put in a result type of "int" when none was specified.
2726  // FIXME: Exceptions!
2727  return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
2728                                 false, false, 0, 0, false, CC_Default);
2729}
2730
2731/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2732/// well-formednes of the conversion function declarator @p D with
2733/// type @p R. If there are any errors in the declarator, this routine
2734/// will emit diagnostics and return true. Otherwise, it will return
2735/// false. Either way, the type @p R will be updated to reflect a
2736/// well-formed type for the conversion operator.
2737void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
2738                                     FunctionDecl::StorageClass& SC) {
2739  // C++ [class.conv.fct]p1:
2740  //   Neither parameter types nor return type can be specified. The
2741  //   type of a conversion function (8.3.5) is "function taking no
2742  //   parameter returning conversion-type-id."
2743  if (SC == FunctionDecl::Static) {
2744    if (!D.isInvalidType())
2745      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2746        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2747        << SourceRange(D.getIdentifierLoc());
2748    D.setInvalidType();
2749    SC = FunctionDecl::None;
2750  }
2751  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
2752    // Conversion functions don't have return types, but the parser will
2753    // happily parse something like:
2754    //
2755    //   class X {
2756    //     float operator bool();
2757    //   };
2758    //
2759    // The return type will be changed later anyway.
2760    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
2761      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2762      << SourceRange(D.getIdentifierLoc());
2763  }
2764
2765  // Make sure we don't have any parameters.
2766  if (R->getAs<FunctionProtoType>()->getNumArgs() > 0) {
2767    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
2768
2769    // Delete the parameters.
2770    D.getTypeObject(0).Fun.freeArgs();
2771    D.setInvalidType();
2772  }
2773
2774  // Make sure the conversion function isn't variadic.
2775  if (R->getAs<FunctionProtoType>()->isVariadic() && !D.isInvalidType()) {
2776    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
2777    D.setInvalidType();
2778  }
2779
2780  // C++ [class.conv.fct]p4:
2781  //   The conversion-type-id shall not represent a function type nor
2782  //   an array type.
2783  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
2784  if (ConvType->isArrayType()) {
2785    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
2786    ConvType = Context.getPointerType(ConvType);
2787    D.setInvalidType();
2788  } else if (ConvType->isFunctionType()) {
2789    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
2790    ConvType = Context.getPointerType(ConvType);
2791    D.setInvalidType();
2792  }
2793
2794  // Rebuild the function type "R" without any parameters (in case any
2795  // of the errors above fired) and with the conversion type as the
2796  // return type.
2797  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
2798  R = Context.getFunctionType(ConvType, 0, 0, false,
2799                              Proto->getTypeQuals(),
2800                              Proto->hasExceptionSpec(),
2801                              Proto->hasAnyExceptionSpec(),
2802                              Proto->getNumExceptions(),
2803                              Proto->exception_begin(),
2804                              Proto->getNoReturnAttr(),
2805                              Proto->getCallConv());
2806
2807  // C++0x explicit conversion operators.
2808  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
2809    Diag(D.getDeclSpec().getExplicitSpecLoc(),
2810         diag::warn_explicit_conversion_functions)
2811      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
2812}
2813
2814/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
2815/// the declaration of the given C++ conversion function. This routine
2816/// is responsible for recording the conversion function in the C++
2817/// class, if possible.
2818Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
2819  assert(Conversion && "Expected to receive a conversion function declaration");
2820
2821  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
2822
2823  // Make sure we aren't redeclaring the conversion function.
2824  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
2825
2826  // C++ [class.conv.fct]p1:
2827  //   [...] A conversion function is never used to convert a
2828  //   (possibly cv-qualified) object to the (possibly cv-qualified)
2829  //   same object type (or a reference to it), to a (possibly
2830  //   cv-qualified) base class of that type (or a reference to it),
2831  //   or to (possibly cv-qualified) void.
2832  // FIXME: Suppress this warning if the conversion function ends up being a
2833  // virtual function that overrides a virtual function in a base class.
2834  QualType ClassType
2835    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
2836  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
2837    ConvType = ConvTypeRef->getPointeeType();
2838  if (ConvType->isRecordType()) {
2839    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
2840    if (ConvType == ClassType)
2841      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
2842        << ClassType;
2843    else if (IsDerivedFrom(ClassType, ConvType))
2844      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
2845        <<  ClassType << ConvType;
2846  } else if (ConvType->isVoidType()) {
2847    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
2848      << ClassType << ConvType;
2849  }
2850
2851  if (Conversion->getPrimaryTemplate()) {
2852    // ignore specializations
2853  } else if (Conversion->getPreviousDeclaration()) {
2854    if (FunctionTemplateDecl *ConversionTemplate
2855                                  = Conversion->getDescribedFunctionTemplate()) {
2856      if (ClassDecl->replaceConversion(
2857                                   ConversionTemplate->getPreviousDeclaration(),
2858                                       ConversionTemplate))
2859        return DeclPtrTy::make(ConversionTemplate);
2860    } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
2861                                            Conversion))
2862      return DeclPtrTy::make(Conversion);
2863    assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
2864  } else if (FunctionTemplateDecl *ConversionTemplate
2865               = Conversion->getDescribedFunctionTemplate())
2866    ClassDecl->addConversionFunction(ConversionTemplate);
2867  else
2868    ClassDecl->addConversionFunction(Conversion);
2869
2870  return DeclPtrTy::make(Conversion);
2871}
2872
2873//===----------------------------------------------------------------------===//
2874// Namespace Handling
2875//===----------------------------------------------------------------------===//
2876
2877/// ActOnStartNamespaceDef - This is called at the start of a namespace
2878/// definition.
2879Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
2880                                             SourceLocation IdentLoc,
2881                                             IdentifierInfo *II,
2882                                             SourceLocation LBrace,
2883                                             AttributeList *AttrList) {
2884  NamespaceDecl *Namespc =
2885      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
2886  Namespc->setLBracLoc(LBrace);
2887
2888  Scope *DeclRegionScope = NamespcScope->getParent();
2889
2890  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
2891
2892  if (II) {
2893    // C++ [namespace.def]p2:
2894    // The identifier in an original-namespace-definition shall not have been
2895    // previously defined in the declarative region in which the
2896    // original-namespace-definition appears. The identifier in an
2897    // original-namespace-definition is the name of the namespace. Subsequently
2898    // in that declarative region, it is treated as an original-namespace-name.
2899
2900    NamedDecl *PrevDecl
2901      = LookupSingleName(DeclRegionScope, II, LookupOrdinaryName,
2902                         ForRedeclaration);
2903
2904    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
2905      // This is an extended namespace definition.
2906      // Attach this namespace decl to the chain of extended namespace
2907      // definitions.
2908      OrigNS->setNextNamespace(Namespc);
2909      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
2910
2911      // Remove the previous declaration from the scope.
2912      if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
2913        IdResolver.RemoveDecl(OrigNS);
2914        DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
2915      }
2916    } else if (PrevDecl) {
2917      // This is an invalid name redefinition.
2918      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
2919       << Namespc->getDeclName();
2920      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2921      Namespc->setInvalidDecl();
2922      // Continue on to push Namespc as current DeclContext and return it.
2923    } else if (II->isStr("std") &&
2924               CurContext->getLookupContext()->isTranslationUnit()) {
2925      // This is the first "real" definition of the namespace "std", so update
2926      // our cache of the "std" namespace to point at this definition.
2927      if (StdNamespace) {
2928        // We had already defined a dummy namespace "std". Link this new
2929        // namespace definition to the dummy namespace "std".
2930        StdNamespace->setNextNamespace(Namespc);
2931        StdNamespace->setLocation(IdentLoc);
2932        Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
2933      }
2934
2935      // Make our StdNamespace cache point at the first real definition of the
2936      // "std" namespace.
2937      StdNamespace = Namespc;
2938    }
2939
2940    PushOnScopeChains(Namespc, DeclRegionScope);
2941  } else {
2942    // Anonymous namespaces.
2943    assert(Namespc->isAnonymousNamespace());
2944    CurContext->addDecl(Namespc);
2945
2946    // Link the anonymous namespace into its parent.
2947    NamespaceDecl *PrevDecl;
2948    DeclContext *Parent = CurContext->getLookupContext();
2949    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
2950      PrevDecl = TU->getAnonymousNamespace();
2951      TU->setAnonymousNamespace(Namespc);
2952    } else {
2953      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
2954      PrevDecl = ND->getAnonymousNamespace();
2955      ND->setAnonymousNamespace(Namespc);
2956    }
2957
2958    // Link the anonymous namespace with its previous declaration.
2959    if (PrevDecl) {
2960      assert(PrevDecl->isAnonymousNamespace());
2961      assert(!PrevDecl->getNextNamespace());
2962      Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
2963      PrevDecl->setNextNamespace(Namespc);
2964    }
2965
2966    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
2967    //   behaves as if it were replaced by
2968    //     namespace unique { /* empty body */ }
2969    //     using namespace unique;
2970    //     namespace unique { namespace-body }
2971    //   where all occurrences of 'unique' in a translation unit are
2972    //   replaced by the same identifier and this identifier differs
2973    //   from all other identifiers in the entire program.
2974
2975    // We just create the namespace with an empty name and then add an
2976    // implicit using declaration, just like the standard suggests.
2977    //
2978    // CodeGen enforces the "universally unique" aspect by giving all
2979    // declarations semantically contained within an anonymous
2980    // namespace internal linkage.
2981
2982    if (!PrevDecl) {
2983      UsingDirectiveDecl* UD
2984        = UsingDirectiveDecl::Create(Context, CurContext,
2985                                     /* 'using' */ LBrace,
2986                                     /* 'namespace' */ SourceLocation(),
2987                                     /* qualifier */ SourceRange(),
2988                                     /* NNS */ NULL,
2989                                     /* identifier */ SourceLocation(),
2990                                     Namespc,
2991                                     /* Ancestor */ CurContext);
2992      UD->setImplicit();
2993      CurContext->addDecl(UD);
2994    }
2995  }
2996
2997  // Although we could have an invalid decl (i.e. the namespace name is a
2998  // redefinition), push it as current DeclContext and try to continue parsing.
2999  // FIXME: We should be able to push Namespc here, so that the each DeclContext
3000  // for the namespace has the declarations that showed up in that particular
3001  // namespace definition.
3002  PushDeclContext(NamespcScope, Namespc);
3003  return DeclPtrTy::make(Namespc);
3004}
3005
3006/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3007/// is a namespace alias, returns the namespace it points to.
3008static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3009  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3010    return AD->getNamespace();
3011  return dyn_cast_or_null<NamespaceDecl>(D);
3012}
3013
3014/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3015/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
3016void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3017  Decl *Dcl = D.getAs<Decl>();
3018  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3019  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3020  Namespc->setRBracLoc(RBrace);
3021  PopDeclContext();
3022}
3023
3024Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3025                                          SourceLocation UsingLoc,
3026                                          SourceLocation NamespcLoc,
3027                                          const CXXScopeSpec &SS,
3028                                          SourceLocation IdentLoc,
3029                                          IdentifierInfo *NamespcName,
3030                                          AttributeList *AttrList) {
3031  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3032  assert(NamespcName && "Invalid NamespcName.");
3033  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
3034  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
3035
3036  UsingDirectiveDecl *UDir = 0;
3037
3038  // Lookup namespace name.
3039  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3040  LookupParsedName(R, S, &SS);
3041  if (R.isAmbiguous())
3042    return DeclPtrTy();
3043
3044  if (!R.empty()) {
3045    NamedDecl *Named = R.getFoundDecl();
3046    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3047        && "expected namespace decl");
3048    // C++ [namespace.udir]p1:
3049    //   A using-directive specifies that the names in the nominated
3050    //   namespace can be used in the scope in which the
3051    //   using-directive appears after the using-directive. During
3052    //   unqualified name lookup (3.4.1), the names appear as if they
3053    //   were declared in the nearest enclosing namespace which
3054    //   contains both the using-directive and the nominated
3055    //   namespace. [Note: in this context, "contains" means "contains
3056    //   directly or indirectly". ]
3057
3058    // Find enclosing context containing both using-directive and
3059    // nominated namespace.
3060    NamespaceDecl *NS = getNamespaceDecl(Named);
3061    DeclContext *CommonAncestor = cast<DeclContext>(NS);
3062    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3063      CommonAncestor = CommonAncestor->getParent();
3064
3065    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
3066                                      SS.getRange(),
3067                                      (NestedNameSpecifier *)SS.getScopeRep(),
3068                                      IdentLoc, Named, CommonAncestor);
3069    PushUsingDirective(S, UDir);
3070  } else {
3071    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
3072  }
3073
3074  // FIXME: We ignore attributes for now.
3075  delete AttrList;
3076  return DeclPtrTy::make(UDir);
3077}
3078
3079void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3080  // If scope has associated entity, then using directive is at namespace
3081  // or translation unit scope. We add UsingDirectiveDecls, into
3082  // it's lookup structure.
3083  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
3084    Ctx->addDecl(UDir);
3085  else
3086    // Otherwise it is block-sope. using-directives will affect lookup
3087    // only to the end of scope.
3088    S->PushUsingDirective(DeclPtrTy::make(UDir));
3089}
3090
3091
3092Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
3093                                            AccessSpecifier AS,
3094                                            bool HasUsingKeyword,
3095                                            SourceLocation UsingLoc,
3096                                            const CXXScopeSpec &SS,
3097                                            UnqualifiedId &Name,
3098                                            AttributeList *AttrList,
3099                                            bool IsTypeName,
3100                                            SourceLocation TypenameLoc) {
3101  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
3102
3103  switch (Name.getKind()) {
3104  case UnqualifiedId::IK_Identifier:
3105  case UnqualifiedId::IK_OperatorFunctionId:
3106  case UnqualifiedId::IK_LiteralOperatorId:
3107  case UnqualifiedId::IK_ConversionFunctionId:
3108    break;
3109
3110  case UnqualifiedId::IK_ConstructorName:
3111  case UnqualifiedId::IK_ConstructorTemplateId:
3112    // C++0x inherited constructors.
3113    if (getLangOptions().CPlusPlus0x) break;
3114
3115    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3116      << SS.getRange();
3117    return DeclPtrTy();
3118
3119  case UnqualifiedId::IK_DestructorName:
3120    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3121      << SS.getRange();
3122    return DeclPtrTy();
3123
3124  case UnqualifiedId::IK_TemplateId:
3125    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3126      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3127    return DeclPtrTy();
3128  }
3129
3130  DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
3131  if (!TargetName)
3132    return DeclPtrTy();
3133
3134  // Warn about using declarations.
3135  // TODO: store that the declaration was written without 'using' and
3136  // talk about access decls instead of using decls in the
3137  // diagnostics.
3138  if (!HasUsingKeyword) {
3139    UsingLoc = Name.getSourceRange().getBegin();
3140
3141    Diag(UsingLoc, diag::warn_access_decl_deprecated)
3142      << CodeModificationHint::CreateInsertion(SS.getRange().getBegin(),
3143                                               "using ");
3144  }
3145
3146  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
3147                                        Name.getSourceRange().getBegin(),
3148                                        TargetName, AttrList,
3149                                        /* IsInstantiation */ false,
3150                                        IsTypeName, TypenameLoc);
3151  if (UD)
3152    PushOnScopeChains(UD, S, /*AddToContext*/ false);
3153
3154  return DeclPtrTy::make(UD);
3155}
3156
3157/// Determines whether to create a using shadow decl for a particular
3158/// decl, given the set of decls existing prior to this using lookup.
3159bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3160                                const LookupResult &Previous) {
3161  // Diagnose finding a decl which is not from a base class of the
3162  // current class.  We do this now because there are cases where this
3163  // function will silently decide not to build a shadow decl, which
3164  // will pre-empt further diagnostics.
3165  //
3166  // We don't need to do this in C++0x because we do the check once on
3167  // the qualifier.
3168  //
3169  // FIXME: diagnose the following if we care enough:
3170  //   struct A { int foo; };
3171  //   struct B : A { using A::foo; };
3172  //   template <class T> struct C : A {};
3173  //   template <class T> struct D : C<T> { using B::foo; } // <---
3174  // This is invalid (during instantiation) in C++03 because B::foo
3175  // resolves to the using decl in B, which is not a base class of D<T>.
3176  // We can't diagnose it immediately because C<T> is an unknown
3177  // specialization.  The UsingShadowDecl in D<T> then points directly
3178  // to A::foo, which will look well-formed when we instantiate.
3179  // The right solution is to not collapse the shadow-decl chain.
3180  if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3181    DeclContext *OrigDC = Orig->getDeclContext();
3182
3183    // Handle enums and anonymous structs.
3184    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3185    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3186    while (OrigRec->isAnonymousStructOrUnion())
3187      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3188
3189    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3190      if (OrigDC == CurContext) {
3191        Diag(Using->getLocation(),
3192             diag::err_using_decl_nested_name_specifier_is_current_class)
3193          << Using->getNestedNameRange();
3194        Diag(Orig->getLocation(), diag::note_using_decl_target);
3195        return true;
3196      }
3197
3198      Diag(Using->getNestedNameRange().getBegin(),
3199           diag::err_using_decl_nested_name_specifier_is_not_base_class)
3200        << Using->getTargetNestedNameDecl()
3201        << cast<CXXRecordDecl>(CurContext)
3202        << Using->getNestedNameRange();
3203      Diag(Orig->getLocation(), diag::note_using_decl_target);
3204      return true;
3205    }
3206  }
3207
3208  if (Previous.empty()) return false;
3209
3210  NamedDecl *Target = Orig;
3211  if (isa<UsingShadowDecl>(Target))
3212    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3213
3214  // If the target happens to be one of the previous declarations, we
3215  // don't have a conflict.
3216  //
3217  // FIXME: but we might be increasing its access, in which case we
3218  // should redeclare it.
3219  NamedDecl *NonTag = 0, *Tag = 0;
3220  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3221         I != E; ++I) {
3222    NamedDecl *D = (*I)->getUnderlyingDecl();
3223    if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3224      return false;
3225
3226    (isa<TagDecl>(D) ? Tag : NonTag) = D;
3227  }
3228
3229  if (Target->isFunctionOrFunctionTemplate()) {
3230    FunctionDecl *FD;
3231    if (isa<FunctionTemplateDecl>(Target))
3232      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3233    else
3234      FD = cast<FunctionDecl>(Target);
3235
3236    NamedDecl *OldDecl = 0;
3237    switch (CheckOverload(FD, Previous, OldDecl)) {
3238    case Ovl_Overload:
3239      return false;
3240
3241    case Ovl_NonFunction:
3242      Diag(Using->getLocation(), diag::err_using_decl_conflict);
3243      break;
3244
3245    // We found a decl with the exact signature.
3246    case Ovl_Match:
3247      if (isa<UsingShadowDecl>(OldDecl)) {
3248        // Silently ignore the possible conflict.
3249        return false;
3250      }
3251
3252      // If we're in a record, we want to hide the target, so we
3253      // return true (without a diagnostic) to tell the caller not to
3254      // build a shadow decl.
3255      if (CurContext->isRecord())
3256        return true;
3257
3258      // If we're not in a record, this is an error.
3259      Diag(Using->getLocation(), diag::err_using_decl_conflict);
3260      break;
3261    }
3262
3263    Diag(Target->getLocation(), diag::note_using_decl_target);
3264    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3265    return true;
3266  }
3267
3268  // Target is not a function.
3269
3270  if (isa<TagDecl>(Target)) {
3271    // No conflict between a tag and a non-tag.
3272    if (!Tag) return false;
3273
3274    Diag(Using->getLocation(), diag::err_using_decl_conflict);
3275    Diag(Target->getLocation(), diag::note_using_decl_target);
3276    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3277    return true;
3278  }
3279
3280  // No conflict between a tag and a non-tag.
3281  if (!NonTag) return false;
3282
3283  Diag(Using->getLocation(), diag::err_using_decl_conflict);
3284  Diag(Target->getLocation(), diag::note_using_decl_target);
3285  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3286  return true;
3287}
3288
3289/// Builds a shadow declaration corresponding to a 'using' declaration.
3290UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
3291                                            UsingDecl *UD,
3292                                            NamedDecl *Orig) {
3293
3294  // If we resolved to another shadow declaration, just coalesce them.
3295  NamedDecl *Target = Orig;
3296  if (isa<UsingShadowDecl>(Target)) {
3297    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3298    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
3299  }
3300
3301  UsingShadowDecl *Shadow
3302    = UsingShadowDecl::Create(Context, CurContext,
3303                              UD->getLocation(), UD, Target);
3304  UD->addShadowDecl(Shadow);
3305
3306  if (S)
3307    PushOnScopeChains(Shadow, S);
3308  else
3309    CurContext->addDecl(Shadow);
3310  Shadow->setAccess(UD->getAccess());
3311
3312  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3313    Shadow->setInvalidDecl();
3314
3315  return Shadow;
3316}
3317
3318/// Hides a using shadow declaration.  This is required by the current
3319/// using-decl implementation when a resolvable using declaration in a
3320/// class is followed by a declaration which would hide or override
3321/// one or more of the using decl's targets; for example:
3322///
3323///   struct Base { void foo(int); };
3324///   struct Derived : Base {
3325///     using Base::foo;
3326///     void foo(int);
3327///   };
3328///
3329/// The governing language is C++03 [namespace.udecl]p12:
3330///
3331///   When a using-declaration brings names from a base class into a
3332///   derived class scope, member functions in the derived class
3333///   override and/or hide member functions with the same name and
3334///   parameter types in a base class (rather than conflicting).
3335///
3336/// There are two ways to implement this:
3337///   (1) optimistically create shadow decls when they're not hidden
3338///       by existing declarations, or
3339///   (2) don't create any shadow decls (or at least don't make them
3340///       visible) until we've fully parsed/instantiated the class.
3341/// The problem with (1) is that we might have to retroactively remove
3342/// a shadow decl, which requires several O(n) operations because the
3343/// decl structures are (very reasonably) not designed for removal.
3344/// (2) avoids this but is very fiddly and phase-dependent.
3345void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3346  // Remove it from the DeclContext...
3347  Shadow->getDeclContext()->removeDecl(Shadow);
3348
3349  // ...and the scope, if applicable...
3350  if (S) {
3351    S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3352    IdResolver.RemoveDecl(Shadow);
3353  }
3354
3355  // ...and the using decl.
3356  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3357
3358  // TODO: complain somehow if Shadow was used.  It shouldn't
3359  // be possible for this to happen, because
3360}
3361
3362/// Builds a using declaration.
3363///
3364/// \param IsInstantiation - Whether this call arises from an
3365///   instantiation of an unresolved using declaration.  We treat
3366///   the lookup differently for these declarations.
3367NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3368                                       SourceLocation UsingLoc,
3369                                       const CXXScopeSpec &SS,
3370                                       SourceLocation IdentLoc,
3371                                       DeclarationName Name,
3372                                       AttributeList *AttrList,
3373                                       bool IsInstantiation,
3374                                       bool IsTypeName,
3375                                       SourceLocation TypenameLoc) {
3376  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3377  assert(IdentLoc.isValid() && "Invalid TargetName location.");
3378
3379  // FIXME: We ignore attributes for now.
3380  delete AttrList;
3381
3382  if (SS.isEmpty()) {
3383    Diag(IdentLoc, diag::err_using_requires_qualname);
3384    return 0;
3385  }
3386
3387  // Do the redeclaration lookup in the current scope.
3388  LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3389                        ForRedeclaration);
3390  Previous.setHideTags(false);
3391  if (S) {
3392    LookupName(Previous, S);
3393
3394    // It is really dumb that we have to do this.
3395    LookupResult::Filter F = Previous.makeFilter();
3396    while (F.hasNext()) {
3397      NamedDecl *D = F.next();
3398      if (!isDeclInScope(D, CurContext, S))
3399        F.erase();
3400    }
3401    F.done();
3402  } else {
3403    assert(IsInstantiation && "no scope in non-instantiation");
3404    assert(CurContext->isRecord() && "scope not record in instantiation");
3405    LookupQualifiedName(Previous, CurContext);
3406  }
3407
3408  NestedNameSpecifier *NNS =
3409    static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3410
3411  // Check for invalid redeclarations.
3412  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3413    return 0;
3414
3415  // Check for bad qualifiers.
3416  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3417    return 0;
3418
3419  DeclContext *LookupContext = computeDeclContext(SS);
3420  NamedDecl *D;
3421  if (!LookupContext) {
3422    if (IsTypeName) {
3423      // FIXME: not all declaration name kinds are legal here
3424      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3425                                              UsingLoc, TypenameLoc,
3426                                              SS.getRange(), NNS,
3427                                              IdentLoc, Name);
3428    } else {
3429      D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3430                                           UsingLoc, SS.getRange(), NNS,
3431                                           IdentLoc, Name);
3432    }
3433  } else {
3434    D = UsingDecl::Create(Context, CurContext, IdentLoc,
3435                          SS.getRange(), UsingLoc, NNS, Name,
3436                          IsTypeName);
3437  }
3438  D->setAccess(AS);
3439  CurContext->addDecl(D);
3440
3441  if (!LookupContext) return D;
3442  UsingDecl *UD = cast<UsingDecl>(D);
3443
3444  if (RequireCompleteDeclContext(SS)) {
3445    UD->setInvalidDecl();
3446    return UD;
3447  }
3448
3449  // Look up the target name.
3450
3451  LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
3452
3453  // Unlike most lookups, we don't always want to hide tag
3454  // declarations: tag names are visible through the using declaration
3455  // even if hidden by ordinary names, *except* in a dependent context
3456  // where it's important for the sanity of two-phase lookup.
3457  if (!IsInstantiation)
3458    R.setHideTags(false);
3459
3460  LookupQualifiedName(R, LookupContext);
3461
3462  if (R.empty()) {
3463    Diag(IdentLoc, diag::err_no_member)
3464      << Name << LookupContext << SS.getRange();
3465    UD->setInvalidDecl();
3466    return UD;
3467  }
3468
3469  if (R.isAmbiguous()) {
3470    UD->setInvalidDecl();
3471    return UD;
3472  }
3473
3474  if (IsTypeName) {
3475    // If we asked for a typename and got a non-type decl, error out.
3476    if (!R.getAsSingle<TypeDecl>()) {
3477      Diag(IdentLoc, diag::err_using_typename_non_type);
3478      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3479        Diag((*I)->getUnderlyingDecl()->getLocation(),
3480             diag::note_using_decl_target);
3481      UD->setInvalidDecl();
3482      return UD;
3483    }
3484  } else {
3485    // If we asked for a non-typename and we got a type, error out,
3486    // but only if this is an instantiation of an unresolved using
3487    // decl.  Otherwise just silently find the type name.
3488    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
3489      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3490      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
3491      UD->setInvalidDecl();
3492      return UD;
3493    }
3494  }
3495
3496  // C++0x N2914 [namespace.udecl]p6:
3497  // A using-declaration shall not name a namespace.
3498  if (R.getAsSingle<NamespaceDecl>()) {
3499    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3500      << SS.getRange();
3501    UD->setInvalidDecl();
3502    return UD;
3503  }
3504
3505  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3506    if (!CheckUsingShadowDecl(UD, *I, Previous))
3507      BuildUsingShadowDecl(S, UD, *I);
3508  }
3509
3510  return UD;
3511}
3512
3513/// Checks that the given using declaration is not an invalid
3514/// redeclaration.  Note that this is checking only for the using decl
3515/// itself, not for any ill-formedness among the UsingShadowDecls.
3516bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3517                                       bool isTypeName,
3518                                       const CXXScopeSpec &SS,
3519                                       SourceLocation NameLoc,
3520                                       const LookupResult &Prev) {
3521  // C++03 [namespace.udecl]p8:
3522  // C++0x [namespace.udecl]p10:
3523  //   A using-declaration is a declaration and can therefore be used
3524  //   repeatedly where (and only where) multiple declarations are
3525  //   allowed.
3526  // That's only in file contexts.
3527  if (CurContext->getLookupContext()->isFileContext())
3528    return false;
3529
3530  NestedNameSpecifier *Qual
3531    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3532
3533  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3534    NamedDecl *D = *I;
3535
3536    bool DTypename;
3537    NestedNameSpecifier *DQual;
3538    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3539      DTypename = UD->isTypeName();
3540      DQual = UD->getTargetNestedNameDecl();
3541    } else if (UnresolvedUsingValueDecl *UD
3542                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3543      DTypename = false;
3544      DQual = UD->getTargetNestedNameSpecifier();
3545    } else if (UnresolvedUsingTypenameDecl *UD
3546                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3547      DTypename = true;
3548      DQual = UD->getTargetNestedNameSpecifier();
3549    } else continue;
3550
3551    // using decls differ if one says 'typename' and the other doesn't.
3552    // FIXME: non-dependent using decls?
3553    if (isTypeName != DTypename) continue;
3554
3555    // using decls differ if they name different scopes (but note that
3556    // template instantiation can cause this check to trigger when it
3557    // didn't before instantiation).
3558    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3559        Context.getCanonicalNestedNameSpecifier(DQual))
3560      continue;
3561
3562    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
3563    Diag(D->getLocation(), diag::note_using_decl) << 1;
3564    return true;
3565  }
3566
3567  return false;
3568}
3569
3570
3571/// Checks that the given nested-name qualifier used in a using decl
3572/// in the current context is appropriately related to the current
3573/// scope.  If an error is found, diagnoses it and returns true.
3574bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3575                                   const CXXScopeSpec &SS,
3576                                   SourceLocation NameLoc) {
3577  DeclContext *NamedContext = computeDeclContext(SS);
3578
3579  if (!CurContext->isRecord()) {
3580    // C++03 [namespace.udecl]p3:
3581    // C++0x [namespace.udecl]p8:
3582    //   A using-declaration for a class member shall be a member-declaration.
3583
3584    // If we weren't able to compute a valid scope, it must be a
3585    // dependent class scope.
3586    if (!NamedContext || NamedContext->isRecord()) {
3587      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3588        << SS.getRange();
3589      return true;
3590    }
3591
3592    // Otherwise, everything is known to be fine.
3593    return false;
3594  }
3595
3596  // The current scope is a record.
3597
3598  // If the named context is dependent, we can't decide much.
3599  if (!NamedContext) {
3600    // FIXME: in C++0x, we can diagnose if we can prove that the
3601    // nested-name-specifier does not refer to a base class, which is
3602    // still possible in some cases.
3603
3604    // Otherwise we have to conservatively report that things might be
3605    // okay.
3606    return false;
3607  }
3608
3609  if (!NamedContext->isRecord()) {
3610    // Ideally this would point at the last name in the specifier,
3611    // but we don't have that level of source info.
3612    Diag(SS.getRange().getBegin(),
3613         diag::err_using_decl_nested_name_specifier_is_not_class)
3614      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3615    return true;
3616  }
3617
3618  if (getLangOptions().CPlusPlus0x) {
3619    // C++0x [namespace.udecl]p3:
3620    //   In a using-declaration used as a member-declaration, the
3621    //   nested-name-specifier shall name a base class of the class
3622    //   being defined.
3623
3624    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3625                                 cast<CXXRecordDecl>(NamedContext))) {
3626      if (CurContext == NamedContext) {
3627        Diag(NameLoc,
3628             diag::err_using_decl_nested_name_specifier_is_current_class)
3629          << SS.getRange();
3630        return true;
3631      }
3632
3633      Diag(SS.getRange().getBegin(),
3634           diag::err_using_decl_nested_name_specifier_is_not_base_class)
3635        << (NestedNameSpecifier*) SS.getScopeRep()
3636        << cast<CXXRecordDecl>(CurContext)
3637        << SS.getRange();
3638      return true;
3639    }
3640
3641    return false;
3642  }
3643
3644  // C++03 [namespace.udecl]p4:
3645  //   A using-declaration used as a member-declaration shall refer
3646  //   to a member of a base class of the class being defined [etc.].
3647
3648  // Salient point: SS doesn't have to name a base class as long as
3649  // lookup only finds members from base classes.  Therefore we can
3650  // diagnose here only if we can prove that that can't happen,
3651  // i.e. if the class hierarchies provably don't intersect.
3652
3653  // TODO: it would be nice if "definitely valid" results were cached
3654  // in the UsingDecl and UsingShadowDecl so that these checks didn't
3655  // need to be repeated.
3656
3657  struct UserData {
3658    llvm::DenseSet<const CXXRecordDecl*> Bases;
3659
3660    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3661      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3662      Data->Bases.insert(Base);
3663      return true;
3664    }
3665
3666    bool hasDependentBases(const CXXRecordDecl *Class) {
3667      return !Class->forallBases(collect, this);
3668    }
3669
3670    /// Returns true if the base is dependent or is one of the
3671    /// accumulated base classes.
3672    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3673      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3674      return !Data->Bases.count(Base);
3675    }
3676
3677    bool mightShareBases(const CXXRecordDecl *Class) {
3678      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3679    }
3680  };
3681
3682  UserData Data;
3683
3684  // Returns false if we find a dependent base.
3685  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3686    return false;
3687
3688  // Returns false if the class has a dependent base or if it or one
3689  // of its bases is present in the base set of the current context.
3690  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3691    return false;
3692
3693  Diag(SS.getRange().getBegin(),
3694       diag::err_using_decl_nested_name_specifier_is_not_base_class)
3695    << (NestedNameSpecifier*) SS.getScopeRep()
3696    << cast<CXXRecordDecl>(CurContext)
3697    << SS.getRange();
3698
3699  return true;
3700}
3701
3702Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
3703                                             SourceLocation NamespaceLoc,
3704                                             SourceLocation AliasLoc,
3705                                             IdentifierInfo *Alias,
3706                                             const CXXScopeSpec &SS,
3707                                             SourceLocation IdentLoc,
3708                                             IdentifierInfo *Ident) {
3709
3710  // Lookup the namespace name.
3711  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
3712  LookupParsedName(R, S, &SS);
3713
3714  // Check if we have a previous declaration with the same name.
3715  if (NamedDecl *PrevDecl
3716        = LookupSingleName(S, Alias, LookupOrdinaryName, ForRedeclaration)) {
3717    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
3718      // We already have an alias with the same name that points to the same
3719      // namespace, so don't create a new one.
3720      if (!R.isAmbiguous() && !R.empty() &&
3721          AD->getNamespace() == getNamespaceDecl(R.getFoundDecl()))
3722        return DeclPtrTy();
3723    }
3724
3725    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
3726      diag::err_redefinition_different_kind;
3727    Diag(AliasLoc, DiagID) << Alias;
3728    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3729    return DeclPtrTy();
3730  }
3731
3732  if (R.isAmbiguous())
3733    return DeclPtrTy();
3734
3735  if (R.empty()) {
3736    Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
3737    return DeclPtrTy();
3738  }
3739
3740  NamespaceAliasDecl *AliasDecl =
3741    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
3742                               Alias, SS.getRange(),
3743                               (NestedNameSpecifier *)SS.getScopeRep(),
3744                               IdentLoc, R.getFoundDecl());
3745
3746  PushOnScopeChains(AliasDecl, S);
3747  return DeclPtrTy::make(AliasDecl);
3748}
3749
3750void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
3751                                            CXXConstructorDecl *Constructor) {
3752  assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
3753          !Constructor->isUsed()) &&
3754    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
3755
3756  CXXRecordDecl *ClassDecl
3757    = cast<CXXRecordDecl>(Constructor->getDeclContext());
3758  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
3759
3760  DeclContext *PreviousContext = CurContext;
3761  CurContext = Constructor;
3762  if (SetBaseOrMemberInitializers(Constructor, 0, 0, true, false)) {
3763    Diag(CurrentLocation, diag::note_member_synthesized_at)
3764      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
3765    Constructor->setInvalidDecl();
3766  } else {
3767    Constructor->setUsed();
3768  }
3769  CurContext = PreviousContext;
3770}
3771
3772void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
3773                                    CXXDestructorDecl *Destructor) {
3774  assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
3775         "DefineImplicitDestructor - call it for implicit default dtor");
3776  CXXRecordDecl *ClassDecl = Destructor->getParent();
3777  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
3778
3779  DeclContext *PreviousContext = CurContext;
3780  CurContext = Destructor;
3781
3782  // C++ [class.dtor] p5
3783  // Before the implicitly-declared default destructor for a class is
3784  // implicitly defined, all the implicitly-declared default destructors
3785  // for its base class and its non-static data members shall have been
3786  // implicitly defined.
3787  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3788       E = ClassDecl->bases_end(); Base != E; ++Base) {
3789    CXXRecordDecl *BaseClassDecl
3790      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3791    if (!BaseClassDecl->hasTrivialDestructor()) {
3792      if (CXXDestructorDecl *BaseDtor =
3793          const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
3794        MarkDeclarationReferenced(CurrentLocation, BaseDtor);
3795      else
3796        assert(false &&
3797               "DefineImplicitDestructor - missing dtor in a base class");
3798    }
3799  }
3800
3801  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3802       E = ClassDecl->field_end(); Field != E; ++Field) {
3803    QualType FieldType = Context.getCanonicalType((*Field)->getType());
3804    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3805      FieldType = Array->getElementType();
3806    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
3807      CXXRecordDecl *FieldClassDecl
3808        = cast<CXXRecordDecl>(FieldClassType->getDecl());
3809      if (!FieldClassDecl->hasTrivialDestructor()) {
3810        if (CXXDestructorDecl *FieldDtor =
3811            const_cast<CXXDestructorDecl*>(
3812                                        FieldClassDecl->getDestructor(Context)))
3813          MarkDeclarationReferenced(CurrentLocation, FieldDtor);
3814        else
3815          assert(false &&
3816          "DefineImplicitDestructor - missing dtor in class of a data member");
3817      }
3818    }
3819  }
3820
3821  // FIXME: If CheckDestructor fails, we should emit a note about where the
3822  // implicit destructor was needed.
3823  if (CheckDestructor(Destructor)) {
3824    Diag(CurrentLocation, diag::note_member_synthesized_at)
3825      << CXXDestructor << Context.getTagDeclType(ClassDecl);
3826
3827    Destructor->setInvalidDecl();
3828    CurContext = PreviousContext;
3829
3830    return;
3831  }
3832  CurContext = PreviousContext;
3833
3834  Destructor->setUsed();
3835}
3836
3837void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
3838                                          CXXMethodDecl *MethodDecl) {
3839  assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
3840          MethodDecl->getOverloadedOperator() == OO_Equal &&
3841          !MethodDecl->isUsed()) &&
3842         "DefineImplicitOverloadedAssign - call it for implicit assignment op");
3843
3844  CXXRecordDecl *ClassDecl
3845    = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
3846
3847  DeclContext *PreviousContext = CurContext;
3848  CurContext = MethodDecl;
3849
3850  // C++[class.copy] p12
3851  // Before the implicitly-declared copy assignment operator for a class is
3852  // implicitly defined, all implicitly-declared copy assignment operators
3853  // for its direct base classes and its nonstatic data members shall have
3854  // been implicitly defined.
3855  bool err = false;
3856  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3857       E = ClassDecl->bases_end(); Base != E; ++Base) {
3858    CXXRecordDecl *BaseClassDecl
3859      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3860    if (CXXMethodDecl *BaseAssignOpMethod =
3861          getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3862                                  BaseClassDecl))
3863      MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
3864  }
3865  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3866       E = ClassDecl->field_end(); Field != E; ++Field) {
3867    QualType FieldType = Context.getCanonicalType((*Field)->getType());
3868    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3869      FieldType = Array->getElementType();
3870    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
3871      CXXRecordDecl *FieldClassDecl
3872        = cast<CXXRecordDecl>(FieldClassType->getDecl());
3873      if (CXXMethodDecl *FieldAssignOpMethod =
3874          getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
3875                                  FieldClassDecl))
3876        MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
3877    } else if (FieldType->isReferenceType()) {
3878      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
3879      << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
3880      Diag(Field->getLocation(), diag::note_declared_at);
3881      Diag(CurrentLocation, diag::note_first_required_here);
3882      err = true;
3883    } else if (FieldType.isConstQualified()) {
3884      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
3885      << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
3886      Diag(Field->getLocation(), diag::note_declared_at);
3887      Diag(CurrentLocation, diag::note_first_required_here);
3888      err = true;
3889    }
3890  }
3891  if (!err)
3892    MethodDecl->setUsed();
3893
3894  CurContext = PreviousContext;
3895}
3896
3897CXXMethodDecl *
3898Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
3899                              ParmVarDecl *ParmDecl,
3900                              CXXRecordDecl *ClassDecl) {
3901  QualType LHSType = Context.getTypeDeclType(ClassDecl);
3902  QualType RHSType(LHSType);
3903  // If class's assignment operator argument is const/volatile qualified,
3904  // look for operator = (const/volatile B&). Otherwise, look for
3905  // operator = (B&).
3906  RHSType = Context.getCVRQualifiedType(RHSType,
3907                                     ParmDecl->getType().getCVRQualifiers());
3908  ExprOwningPtr<Expr> LHS(this,  new (Context) DeclRefExpr(ParmDecl,
3909                                                           LHSType,
3910                                                           SourceLocation()));
3911  ExprOwningPtr<Expr> RHS(this,  new (Context) DeclRefExpr(ParmDecl,
3912                                                           RHSType,
3913                                                           CurrentLocation));
3914  Expr *Args[2] = { &*LHS, &*RHS };
3915  OverloadCandidateSet CandidateSet(CurrentLocation);
3916  AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
3917                              CandidateSet);
3918  OverloadCandidateSet::iterator Best;
3919  if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
3920    return cast<CXXMethodDecl>(Best->Function);
3921  assert(false &&
3922         "getAssignOperatorMethod - copy assignment operator method not found");
3923  return 0;
3924}
3925
3926void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
3927                                   CXXConstructorDecl *CopyConstructor,
3928                                   unsigned TypeQuals) {
3929  assert((CopyConstructor->isImplicit() &&
3930          CopyConstructor->isCopyConstructor(TypeQuals) &&
3931          !CopyConstructor->isUsed()) &&
3932         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
3933
3934  CXXRecordDecl *ClassDecl
3935    = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
3936  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
3937
3938  DeclContext *PreviousContext = CurContext;
3939  CurContext = CopyConstructor;
3940
3941  // C++ [class.copy] p209
3942  // Before the implicitly-declared copy constructor for a class is
3943  // implicitly defined, all the implicitly-declared copy constructors
3944  // for its base class and its non-static data members shall have been
3945  // implicitly defined.
3946  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3947       Base != ClassDecl->bases_end(); ++Base) {
3948    CXXRecordDecl *BaseClassDecl
3949      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
3950    if (CXXConstructorDecl *BaseCopyCtor =
3951        BaseClassDecl->getCopyConstructor(Context, TypeQuals))
3952      MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
3953  }
3954  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3955                                  FieldEnd = ClassDecl->field_end();
3956       Field != FieldEnd; ++Field) {
3957    QualType FieldType = Context.getCanonicalType((*Field)->getType());
3958    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
3959      FieldType = Array->getElementType();
3960    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
3961      CXXRecordDecl *FieldClassDecl
3962        = cast<CXXRecordDecl>(FieldClassType->getDecl());
3963      if (CXXConstructorDecl *FieldCopyCtor =
3964          FieldClassDecl->getCopyConstructor(Context, TypeQuals))
3965        MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
3966    }
3967  }
3968  CopyConstructor->setUsed();
3969
3970  CurContext = PreviousContext;
3971}
3972
3973Sema::OwningExprResult
3974Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
3975                            CXXConstructorDecl *Constructor,
3976                            MultiExprArg ExprArgs,
3977                            bool RequiresZeroInit,
3978                            bool BaseInitialization) {
3979  bool Elidable = false;
3980
3981  // C++ [class.copy]p15:
3982  //   Whenever a temporary class object is copied using a copy constructor, and
3983  //   this object and the copy have the same cv-unqualified type, an
3984  //   implementation is permitted to treat the original and the copy as two
3985  //   different ways of referring to the same object and not perform a copy at
3986  //   all, even if the class copy constructor or destructor have side effects.
3987
3988  // FIXME: Is this enough?
3989  if (Constructor->isCopyConstructor()) {
3990    Expr *E = ((Expr **)ExprArgs.get())[0];
3991    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3992      if (ICE->getCastKind() == CastExpr::CK_NoOp)
3993        E = ICE->getSubExpr();
3994    if (CXXFunctionalCastExpr *FCE = dyn_cast<CXXFunctionalCastExpr>(E))
3995      E = FCE->getSubExpr();
3996    while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3997      E = BE->getSubExpr();
3998    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3999      if (ICE->getCastKind() == CastExpr::CK_NoOp)
4000        E = ICE->getSubExpr();
4001
4002    if (CallExpr *CE = dyn_cast<CallExpr>(E))
4003      Elidable = !CE->getCallReturnType()->isReferenceType();
4004    else if (isa<CXXTemporaryObjectExpr>(E))
4005      Elidable = true;
4006    else if (isa<CXXConstructExpr>(E))
4007      Elidable = true;
4008  }
4009
4010  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
4011                               Elidable, move(ExprArgs), RequiresZeroInit,
4012                               BaseInitialization);
4013}
4014
4015/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4016/// including handling of its default argument expressions.
4017Sema::OwningExprResult
4018Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4019                            CXXConstructorDecl *Constructor, bool Elidable,
4020                            MultiExprArg ExprArgs,
4021                            bool RequiresZeroInit,
4022                            bool BaseInitialization) {
4023  unsigned NumExprs = ExprArgs.size();
4024  Expr **Exprs = (Expr **)ExprArgs.release();
4025
4026  MarkDeclarationReferenced(ConstructLoc, Constructor);
4027  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
4028                                        Constructor, Elidable, Exprs, NumExprs,
4029                                        RequiresZeroInit, BaseInitialization));
4030}
4031
4032bool Sema::InitializeVarWithConstructor(VarDecl *VD,
4033                                        CXXConstructorDecl *Constructor,
4034                                        MultiExprArg Exprs) {
4035  OwningExprResult TempResult =
4036    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
4037                          move(Exprs));
4038  if (TempResult.isInvalid())
4039    return true;
4040
4041  Expr *Temp = TempResult.takeAs<Expr>();
4042  MarkDeclarationReferenced(VD->getLocation(), Constructor);
4043  Temp = MaybeCreateCXXExprWithTemporaries(Temp);
4044  VD->setInit(Temp);
4045
4046  return false;
4047}
4048
4049void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4050  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
4051  if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4052      !ClassDecl->hasTrivialDestructor()) {
4053    CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4054    MarkDeclarationReferenced(VD->getLocation(), Destructor);
4055    CheckDestructorAccess(VD->getLocation(), Record);
4056  }
4057}
4058
4059/// AddCXXDirectInitializerToDecl - This action is called immediately after
4060/// ActOnDeclarator, when a C++ direct initializer is present.
4061/// e.g: "int x(1);"
4062void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4063                                         SourceLocation LParenLoc,
4064                                         MultiExprArg Exprs,
4065                                         SourceLocation *CommaLocs,
4066                                         SourceLocation RParenLoc) {
4067  assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
4068  Decl *RealDecl = Dcl.getAs<Decl>();
4069
4070  // If there is no declaration, there was an error parsing it.  Just ignore
4071  // the initializer.
4072  if (RealDecl == 0)
4073    return;
4074
4075  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4076  if (!VDecl) {
4077    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4078    RealDecl->setInvalidDecl();
4079    return;
4080  }
4081
4082  // We will represent direct-initialization similarly to copy-initialization:
4083  //    int x(1);  -as-> int x = 1;
4084  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4085  //
4086  // Clients that want to distinguish between the two forms, can check for
4087  // direct initializer using VarDecl::hasCXXDirectInitializer().
4088  // A major benefit is that clients that don't particularly care about which
4089  // exactly form was it (like the CodeGen) can handle both cases without
4090  // special case code.
4091
4092  // C++ 8.5p11:
4093  // The form of initialization (using parentheses or '=') is generally
4094  // insignificant, but does matter when the entity being initialized has a
4095  // class type.
4096  QualType DeclInitType = VDecl->getType();
4097  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
4098    DeclInitType = Context.getBaseElementType(Array);
4099
4100  if (!VDecl->getType()->isDependentType() &&
4101      RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
4102                          diag::err_typecheck_decl_incomplete_type)) {
4103    VDecl->setInvalidDecl();
4104    return;
4105  }
4106
4107  // The variable can not have an abstract class type.
4108  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4109                             diag::err_abstract_type_in_decl,
4110                             AbstractVariableType))
4111    VDecl->setInvalidDecl();
4112
4113  const VarDecl *Def;
4114  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
4115    Diag(VDecl->getLocation(), diag::err_redefinition)
4116    << VDecl->getDeclName();
4117    Diag(Def->getLocation(), diag::note_previous_definition);
4118    VDecl->setInvalidDecl();
4119    return;
4120  }
4121
4122  // If either the declaration has a dependent type or if any of the
4123  // expressions is type-dependent, we represent the initialization
4124  // via a ParenListExpr for later use during template instantiation.
4125  if (VDecl->getType()->isDependentType() ||
4126      Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4127    // Let clients know that initialization was done with a direct initializer.
4128    VDecl->setCXXDirectInitializer(true);
4129
4130    // Store the initialization expressions as a ParenListExpr.
4131    unsigned NumExprs = Exprs.size();
4132    VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4133                                               (Expr **)Exprs.release(),
4134                                               NumExprs, RParenLoc));
4135    return;
4136  }
4137
4138  // Capture the variable that is being initialized and the style of
4139  // initialization.
4140  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4141
4142  // FIXME: Poor source location information.
4143  InitializationKind Kind
4144    = InitializationKind::CreateDirect(VDecl->getLocation(),
4145                                       LParenLoc, RParenLoc);
4146
4147  InitializationSequence InitSeq(*this, Entity, Kind,
4148                                 (Expr**)Exprs.get(), Exprs.size());
4149  OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4150  if (Result.isInvalid()) {
4151    VDecl->setInvalidDecl();
4152    return;
4153  }
4154
4155  Result = MaybeCreateCXXExprWithTemporaries(move(Result));
4156  VDecl->setInit(Result.takeAs<Expr>());
4157  VDecl->setCXXDirectInitializer(true);
4158
4159  if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4160    FinalizeVarWithDestructor(VDecl, Record);
4161}
4162
4163/// \brief Add the applicable constructor candidates for an initialization
4164/// by constructor.
4165static void AddConstructorInitializationCandidates(Sema &SemaRef,
4166                                                   QualType ClassType,
4167                                                   Expr **Args,
4168                                                   unsigned NumArgs,
4169                                                   InitializationKind Kind,
4170                                           OverloadCandidateSet &CandidateSet) {
4171  // C++ [dcl.init]p14:
4172  //   If the initialization is direct-initialization, or if it is
4173  //   copy-initialization where the cv-unqualified version of the
4174  //   source type is the same class as, or a derived class of, the
4175  //   class of the destination, constructors are considered. The
4176  //   applicable constructors are enumerated (13.3.1.3), and the
4177  //   best one is chosen through overload resolution (13.3). The
4178  //   constructor so selected is called to initialize the object,
4179  //   with the initializer expression(s) as its argument(s). If no
4180  //   constructor applies, or the overload resolution is ambiguous,
4181  //   the initialization is ill-formed.
4182  const RecordType *ClassRec = ClassType->getAs<RecordType>();
4183  assert(ClassRec && "Can only initialize a class type here");
4184
4185  // FIXME: When we decide not to synthesize the implicitly-declared
4186  // constructors, we'll need to make them appear here.
4187
4188  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
4189  DeclarationName ConstructorName
4190    = SemaRef.Context.DeclarationNames.getCXXConstructorName(
4191              SemaRef.Context.getCanonicalType(ClassType).getUnqualifiedType());
4192  DeclContext::lookup_const_iterator Con, ConEnd;
4193  for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
4194       Con != ConEnd; ++Con) {
4195    // Find the constructor (which may be a template).
4196    CXXConstructorDecl *Constructor = 0;
4197    FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
4198    if (ConstructorTmpl)
4199      Constructor
4200      = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
4201    else
4202      Constructor = cast<CXXConstructorDecl>(*Con);
4203
4204    if ((Kind.getKind() == InitializationKind::IK_Direct) ||
4205        (Kind.getKind() == InitializationKind::IK_Value) ||
4206        (Kind.getKind() == InitializationKind::IK_Copy &&
4207         Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
4208        ((Kind.getKind() == InitializationKind::IK_Default) &&
4209         Constructor->isDefaultConstructor())) {
4210      if (ConstructorTmpl)
4211        SemaRef.AddTemplateOverloadCandidate(ConstructorTmpl,
4212                                             ConstructorTmpl->getAccess(),
4213                                             /*ExplicitArgs*/ 0,
4214                                             Args, NumArgs, CandidateSet);
4215      else
4216        SemaRef.AddOverloadCandidate(Constructor, Constructor->getAccess(),
4217                                     Args, NumArgs, CandidateSet);
4218    }
4219  }
4220}
4221
4222/// \brief Attempt to perform initialization by constructor
4223/// (C++ [dcl.init]p14), which may occur as part of direct-initialization or
4224/// copy-initialization.
4225///
4226/// This routine determines whether initialization by constructor is possible,
4227/// but it does not emit any diagnostics in the case where the initialization
4228/// is ill-formed.
4229///
4230/// \param ClassType the type of the object being initialized, which must have
4231/// class type.
4232///
4233/// \param Args the arguments provided to initialize the object
4234///
4235/// \param NumArgs the number of arguments provided to initialize the object
4236///
4237/// \param Kind the type of initialization being performed
4238///
4239/// \returns the constructor used to initialize the object, if successful.
4240/// Otherwise, emits a diagnostic and returns NULL.
4241CXXConstructorDecl *
4242Sema::TryInitializationByConstructor(QualType ClassType,
4243                                     Expr **Args, unsigned NumArgs,
4244                                     SourceLocation Loc,
4245                                     InitializationKind Kind) {
4246  // Build the overload candidate set
4247  OverloadCandidateSet CandidateSet(Loc);
4248  AddConstructorInitializationCandidates(*this, ClassType, Args, NumArgs, Kind,
4249                                         CandidateSet);
4250
4251  // Determine whether we found a constructor we can use.
4252  OverloadCandidateSet::iterator Best;
4253  switch (BestViableFunction(CandidateSet, Loc, Best)) {
4254    case OR_Success:
4255    case OR_Deleted:
4256      // We found a constructor. Return it.
4257      return cast<CXXConstructorDecl>(Best->Function);
4258
4259    case OR_No_Viable_Function:
4260    case OR_Ambiguous:
4261      // Overload resolution failed. Return nothing.
4262      return 0;
4263  }
4264
4265  // Silence GCC warning
4266  return 0;
4267}
4268
4269/// \brief Given a constructor and the set of arguments provided for the
4270/// constructor, convert the arguments and add any required default arguments
4271/// to form a proper call to this constructor.
4272///
4273/// \returns true if an error occurred, false otherwise.
4274bool
4275Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4276                              MultiExprArg ArgsPtr,
4277                              SourceLocation Loc,
4278                     ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4279  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4280  unsigned NumArgs = ArgsPtr.size();
4281  Expr **Args = (Expr **)ArgsPtr.get();
4282
4283  const FunctionProtoType *Proto
4284    = Constructor->getType()->getAs<FunctionProtoType>();
4285  assert(Proto && "Constructor without a prototype?");
4286  unsigned NumArgsInProto = Proto->getNumArgs();
4287
4288  // If too few arguments are available, we'll fill in the rest with defaults.
4289  if (NumArgs < NumArgsInProto)
4290    ConvertedArgs.reserve(NumArgsInProto);
4291  else
4292    ConvertedArgs.reserve(NumArgs);
4293
4294  VariadicCallType CallType =
4295    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4296  llvm::SmallVector<Expr *, 8> AllArgs;
4297  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4298                                        Proto, 0, Args, NumArgs, AllArgs,
4299                                        CallType);
4300  for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4301    ConvertedArgs.push_back(AllArgs[i]);
4302  return Invalid;
4303}
4304
4305/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4306/// determine whether they are reference-related,
4307/// reference-compatible, reference-compatible with added
4308/// qualification, or incompatible, for use in C++ initialization by
4309/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4310/// type, and the first type (T1) is the pointee type of the reference
4311/// type being initialized.
4312Sema::ReferenceCompareResult
4313Sema::CompareReferenceRelationship(SourceLocation Loc,
4314                                   QualType OrigT1, QualType OrigT2,
4315                                   bool& DerivedToBase) {
4316  assert(!OrigT1->isReferenceType() &&
4317    "T1 must be the pointee type of the reference type");
4318  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4319
4320  QualType T1 = Context.getCanonicalType(OrigT1);
4321  QualType T2 = Context.getCanonicalType(OrigT2);
4322  Qualifiers T1Quals, T2Quals;
4323  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4324  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4325
4326  // C++ [dcl.init.ref]p4:
4327  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4328  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4329  //   T1 is a base class of T2.
4330  if (UnqualT1 == UnqualT2)
4331    DerivedToBase = false;
4332  else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
4333           !RequireCompleteType(Loc, OrigT2, PDiag()) &&
4334           IsDerivedFrom(UnqualT2, UnqualT1))
4335    DerivedToBase = true;
4336  else
4337    return Ref_Incompatible;
4338
4339  // At this point, we know that T1 and T2 are reference-related (at
4340  // least).
4341
4342  // If the type is an array type, promote the element qualifiers to the type
4343  // for comparison.
4344  if (isa<ArrayType>(T1) && T1Quals)
4345    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4346  if (isa<ArrayType>(T2) && T2Quals)
4347    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4348
4349  // C++ [dcl.init.ref]p4:
4350  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4351  //   reference-related to T2 and cv1 is the same cv-qualification
4352  //   as, or greater cv-qualification than, cv2. For purposes of
4353  //   overload resolution, cases for which cv1 is greater
4354  //   cv-qualification than cv2 are identified as
4355  //   reference-compatible with added qualification (see 13.3.3.2).
4356  if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
4357    return Ref_Compatible;
4358  else if (T1.isMoreQualifiedThan(T2))
4359    return Ref_Compatible_With_Added_Qualification;
4360  else
4361    return Ref_Related;
4362}
4363
4364/// CheckReferenceInit - Check the initialization of a reference
4365/// variable with the given initializer (C++ [dcl.init.ref]). Init is
4366/// the initializer (either a simple initializer or an initializer
4367/// list), and DeclType is the type of the declaration. When ICS is
4368/// non-null, this routine will compute the implicit conversion
4369/// sequence according to C++ [over.ics.ref] and will not produce any
4370/// diagnostics; when ICS is null, it will emit diagnostics when any
4371/// errors are found. Either way, a return value of true indicates
4372/// that there was a failure, a return value of false indicates that
4373/// the reference initialization succeeded.
4374///
4375/// When @p SuppressUserConversions, user-defined conversions are
4376/// suppressed.
4377/// When @p AllowExplicit, we also permit explicit user-defined
4378/// conversion functions.
4379/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
4380/// When @p IgnoreBaseAccess, we don't do access control on to-base conversion.
4381/// This is used when this is called from a C-style cast.
4382bool
4383Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
4384                         SourceLocation DeclLoc,
4385                         bool SuppressUserConversions,
4386                         bool AllowExplicit, bool ForceRValue,
4387                         ImplicitConversionSequence *ICS,
4388                         bool IgnoreBaseAccess) {
4389  assert(DeclType->isReferenceType() && "Reference init needs a reference");
4390
4391  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4392  QualType T2 = Init->getType();
4393
4394  // If the initializer is the address of an overloaded function, try
4395  // to resolve the overloaded function. If all goes well, T2 is the
4396  // type of the resulting function.
4397  if (Context.getCanonicalType(T2) == Context.OverloadTy) {
4398    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
4399                                                          ICS != 0);
4400    if (Fn) {
4401      // Since we're performing this reference-initialization for
4402      // real, update the initializer with the resulting function.
4403      if (!ICS) {
4404        if (DiagnoseUseOfDecl(Fn, DeclLoc))
4405          return true;
4406
4407        Init = FixOverloadedFunctionReference(Init, Fn);
4408      }
4409
4410      T2 = Fn->getType();
4411    }
4412  }
4413
4414  // Compute some basic properties of the types and the initializer.
4415  bool isRValRef = DeclType->isRValueReferenceType();
4416  bool DerivedToBase = false;
4417  Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
4418                                                  Init->isLvalue(Context);
4419  ReferenceCompareResult RefRelationship
4420    = CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
4421
4422  // Most paths end in a failed conversion.
4423  if (ICS) {
4424    ICS->setBad(BadConversionSequence::no_conversion, Init, DeclType);
4425  }
4426
4427  // C++ [dcl.init.ref]p5:
4428  //   A reference to type "cv1 T1" is initialized by an expression
4429  //   of type "cv2 T2" as follows:
4430
4431  //     -- If the initializer expression
4432
4433  // Rvalue references cannot bind to lvalues (N2812).
4434  // There is absolutely no situation where they can. In particular, note that
4435  // this is ill-formed, even if B has a user-defined conversion to A&&:
4436  //   B b;
4437  //   A&& r = b;
4438  if (isRValRef && InitLvalue == Expr::LV_Valid) {
4439    if (!ICS)
4440      Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4441        << Init->getSourceRange();
4442    return true;
4443  }
4444
4445  bool BindsDirectly = false;
4446  //       -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4447  //          reference-compatible with "cv2 T2," or
4448  //
4449  // Note that the bit-field check is skipped if we are just computing
4450  // the implicit conversion sequence (C++ [over.best.ics]p2).
4451  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
4452      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4453    BindsDirectly = true;
4454
4455    if (ICS) {
4456      // C++ [over.ics.ref]p1:
4457      //   When a parameter of reference type binds directly (8.5.3)
4458      //   to an argument expression, the implicit conversion sequence
4459      //   is the identity conversion, unless the argument expression
4460      //   has a type that is a derived class of the parameter type,
4461      //   in which case the implicit conversion sequence is a
4462      //   derived-to-base Conversion (13.3.3.1).
4463      ICS->setStandard();
4464      ICS->Standard.First = ICK_Identity;
4465      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4466      ICS->Standard.Third = ICK_Identity;
4467      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4468      ICS->Standard.setToType(0, T2);
4469      ICS->Standard.setToType(1, T1);
4470      ICS->Standard.setToType(2, T1);
4471      ICS->Standard.ReferenceBinding = true;
4472      ICS->Standard.DirectBinding = true;
4473      ICS->Standard.RRefBinding = false;
4474      ICS->Standard.CopyConstructor = 0;
4475
4476      // Nothing more to do: the inaccessibility/ambiguity check for
4477      // derived-to-base conversions is suppressed when we're
4478      // computing the implicit conversion sequence (C++
4479      // [over.best.ics]p2).
4480      return false;
4481    } else {
4482      // Perform the conversion.
4483      CastExpr::CastKind CK = CastExpr::CK_NoOp;
4484      if (DerivedToBase)
4485        CK = CastExpr::CK_DerivedToBase;
4486      else if(CheckExceptionSpecCompatibility(Init, T1))
4487        return true;
4488      ImpCastExprToType(Init, T1, CK, /*isLvalue=*/true);
4489    }
4490  }
4491
4492  //       -- has a class type (i.e., T2 is a class type) and can be
4493  //          implicitly converted to an lvalue of type "cv3 T3,"
4494  //          where "cv1 T1" is reference-compatible with "cv3 T3"
4495  //          92) (this conversion is selected by enumerating the
4496  //          applicable conversion functions (13.3.1.6) and choosing
4497  //          the best one through overload resolution (13.3)),
4498  if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
4499      !RequireCompleteType(DeclLoc, T2, 0)) {
4500    CXXRecordDecl *T2RecordDecl
4501      = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4502
4503    OverloadCandidateSet CandidateSet(DeclLoc);
4504    const UnresolvedSetImpl *Conversions
4505      = T2RecordDecl->getVisibleConversionFunctions();
4506    for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4507           E = Conversions->end(); I != E; ++I) {
4508      NamedDecl *D = *I;
4509      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4510      if (isa<UsingShadowDecl>(D))
4511        D = cast<UsingShadowDecl>(D)->getTargetDecl();
4512
4513      FunctionTemplateDecl *ConvTemplate
4514        = dyn_cast<FunctionTemplateDecl>(D);
4515      CXXConversionDecl *Conv;
4516      if (ConvTemplate)
4517        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4518      else
4519        Conv = cast<CXXConversionDecl>(D);
4520
4521      // If the conversion function doesn't return a reference type,
4522      // it can't be considered for this conversion.
4523      if (Conv->getConversionType()->isLValueReferenceType() &&
4524          (AllowExplicit || !Conv->isExplicit())) {
4525        if (ConvTemplate)
4526          AddTemplateConversionCandidate(ConvTemplate, I.getAccess(), ActingDC,
4527                                         Init, DeclType, CandidateSet);
4528        else
4529          AddConversionCandidate(Conv, I.getAccess(), ActingDC, Init,
4530                                 DeclType, CandidateSet);
4531      }
4532    }
4533
4534    OverloadCandidateSet::iterator Best;
4535    switch (BestViableFunction(CandidateSet, DeclLoc, Best)) {
4536    case OR_Success:
4537      // C++ [over.ics.ref]p1:
4538      //
4539      //   [...] If the parameter binds directly to the result of
4540      //   applying a conversion function to the argument
4541      //   expression, the implicit conversion sequence is a
4542      //   user-defined conversion sequence (13.3.3.1.2), with the
4543      //   second standard conversion sequence either an identity
4544      //   conversion or, if the conversion function returns an
4545      //   entity of a type that is a derived class of the parameter
4546      //   type, a derived-to-base Conversion.
4547      if (!Best->FinalConversion.DirectBinding)
4548        break;
4549
4550      // This is a direct binding.
4551      BindsDirectly = true;
4552
4553      if (ICS) {
4554        ICS->setUserDefined();
4555        ICS->UserDefined.Before = Best->Conversions[0].Standard;
4556        ICS->UserDefined.After = Best->FinalConversion;
4557        ICS->UserDefined.ConversionFunction = Best->Function;
4558        ICS->UserDefined.EllipsisConversion = false;
4559        assert(ICS->UserDefined.After.ReferenceBinding &&
4560               ICS->UserDefined.After.DirectBinding &&
4561               "Expected a direct reference binding!");
4562        return false;
4563      } else {
4564        OwningExprResult InitConversion =
4565          BuildCXXCastArgument(DeclLoc, QualType(),
4566                               CastExpr::CK_UserDefinedConversion,
4567                               cast<CXXMethodDecl>(Best->Function),
4568                               Owned(Init));
4569        Init = InitConversion.takeAs<Expr>();
4570
4571        if (CheckExceptionSpecCompatibility(Init, T1))
4572          return true;
4573        ImpCastExprToType(Init, T1, CastExpr::CK_UserDefinedConversion,
4574                          /*isLvalue=*/true);
4575      }
4576      break;
4577
4578    case OR_Ambiguous:
4579      if (ICS) {
4580        ICS->setAmbiguous();
4581        for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4582             Cand != CandidateSet.end(); ++Cand)
4583          if (Cand->Viable)
4584            ICS->Ambiguous.addConversion(Cand->Function);
4585        break;
4586      }
4587      Diag(DeclLoc, diag::err_ref_init_ambiguous) << DeclType << Init->getType()
4588            << Init->getSourceRange();
4589      PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Init, 1);
4590      return true;
4591
4592    case OR_No_Viable_Function:
4593    case OR_Deleted:
4594      // There was no suitable conversion, or we found a deleted
4595      // conversion; continue with other checks.
4596      break;
4597    }
4598  }
4599
4600  if (BindsDirectly) {
4601    // C++ [dcl.init.ref]p4:
4602    //   [...] In all cases where the reference-related or
4603    //   reference-compatible relationship of two types is used to
4604    //   establish the validity of a reference binding, and T1 is a
4605    //   base class of T2, a program that necessitates such a binding
4606    //   is ill-formed if T1 is an inaccessible (clause 11) or
4607    //   ambiguous (10.2) base class of T2.
4608    //
4609    // Note that we only check this condition when we're allowed to
4610    // complain about errors, because we should not be checking for
4611    // ambiguity (or inaccessibility) unless the reference binding
4612    // actually happens.
4613    if (DerivedToBase)
4614      return CheckDerivedToBaseConversion(T2, T1, DeclLoc,
4615                                          Init->getSourceRange(),
4616                                          IgnoreBaseAccess);
4617    else
4618      return false;
4619  }
4620
4621  //     -- Otherwise, the reference shall be to a non-volatile const
4622  //        type (i.e., cv1 shall be const), or the reference shall be an
4623  //        rvalue reference and the initializer expression shall be an rvalue.
4624  if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const) {
4625    if (!ICS)
4626      Diag(DeclLoc, diag::err_not_reference_to_const_init)
4627        << T1.isVolatileQualified()
4628        << T1 << int(InitLvalue != Expr::LV_Valid)
4629        << T2 << Init->getSourceRange();
4630    return true;
4631  }
4632
4633  //       -- If the initializer expression is an rvalue, with T2 a
4634  //          class type, and "cv1 T1" is reference-compatible with
4635  //          "cv2 T2," the reference is bound in one of the
4636  //          following ways (the choice is implementation-defined):
4637  //
4638  //          -- The reference is bound to the object represented by
4639  //             the rvalue (see 3.10) or to a sub-object within that
4640  //             object.
4641  //
4642  //          -- A temporary of type "cv1 T2" [sic] is created, and
4643  //             a constructor is called to copy the entire rvalue
4644  //             object into the temporary. The reference is bound to
4645  //             the temporary or to a sub-object within the
4646  //             temporary.
4647  //
4648  //          The constructor that would be used to make the copy
4649  //          shall be callable whether or not the copy is actually
4650  //          done.
4651  //
4652  // Note that C++0x [dcl.init.ref]p5 takes away this implementation
4653  // freedom, so we will always take the first option and never build
4654  // a temporary in this case. FIXME: We will, however, have to check
4655  // for the presence of a copy constructor in C++98/03 mode.
4656  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
4657      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
4658    if (ICS) {
4659      ICS->setStandard();
4660      ICS->Standard.First = ICK_Identity;
4661      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
4662      ICS->Standard.Third = ICK_Identity;
4663      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
4664      ICS->Standard.setToType(0, T2);
4665      ICS->Standard.setToType(1, T1);
4666      ICS->Standard.setToType(2, T1);
4667      ICS->Standard.ReferenceBinding = true;
4668      ICS->Standard.DirectBinding = false;
4669      ICS->Standard.RRefBinding = isRValRef;
4670      ICS->Standard.CopyConstructor = 0;
4671    } else {
4672      CastExpr::CastKind CK = CastExpr::CK_NoOp;
4673      if (DerivedToBase)
4674        CK = CastExpr::CK_DerivedToBase;
4675      else if(CheckExceptionSpecCompatibility(Init, T1))
4676        return true;
4677      ImpCastExprToType(Init, T1, CK, /*isLvalue=*/false);
4678    }
4679    return false;
4680  }
4681
4682  //       -- Otherwise, a temporary of type "cv1 T1" is created and
4683  //          initialized from the initializer expression using the
4684  //          rules for a non-reference copy initialization (8.5). The
4685  //          reference is then bound to the temporary. If T1 is
4686  //          reference-related to T2, cv1 must be the same
4687  //          cv-qualification as, or greater cv-qualification than,
4688  //          cv2; otherwise, the program is ill-formed.
4689  if (RefRelationship == Ref_Related) {
4690    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4691    // we would be reference-compatible or reference-compatible with
4692    // added qualification. But that wasn't the case, so the reference
4693    // initialization fails.
4694    if (!ICS)
4695      Diag(DeclLoc, diag::err_reference_init_drops_quals)
4696        << T1 << int(InitLvalue != Expr::LV_Valid)
4697        << T2 << Init->getSourceRange();
4698    return true;
4699  }
4700
4701  // If at least one of the types is a class type, the types are not
4702  // related, and we aren't allowed any user conversions, the
4703  // reference binding fails. This case is important for breaking
4704  // recursion, since TryImplicitConversion below will attempt to
4705  // create a temporary through the use of a copy constructor.
4706  if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
4707      (T1->isRecordType() || T2->isRecordType())) {
4708    if (!ICS)
4709      Diag(DeclLoc, diag::err_typecheck_convert_incompatible)
4710        << DeclType << Init->getType() << AA_Initializing << Init->getSourceRange();
4711    return true;
4712  }
4713
4714  // Actually try to convert the initializer to T1.
4715  if (ICS) {
4716    // C++ [over.ics.ref]p2:
4717    //
4718    //   When a parameter of reference type is not bound directly to
4719    //   an argument expression, the conversion sequence is the one
4720    //   required to convert the argument expression to the
4721    //   underlying type of the reference according to
4722    //   13.3.3.1. Conceptually, this conversion sequence corresponds
4723    //   to copy-initializing a temporary of the underlying type with
4724    //   the argument expression. Any difference in top-level
4725    //   cv-qualification is subsumed by the initialization itself
4726    //   and does not constitute a conversion.
4727    *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
4728                                 /*AllowExplicit=*/false,
4729                                 /*ForceRValue=*/false,
4730                                 /*InOverloadResolution=*/false);
4731
4732    // Of course, that's still a reference binding.
4733    if (ICS->isStandard()) {
4734      ICS->Standard.ReferenceBinding = true;
4735      ICS->Standard.RRefBinding = isRValRef;
4736    } else if (ICS->isUserDefined()) {
4737      ICS->UserDefined.After.ReferenceBinding = true;
4738      ICS->UserDefined.After.RRefBinding = isRValRef;
4739    }
4740    return ICS->isBad();
4741  } else {
4742    ImplicitConversionSequence Conversions;
4743    bool badConversion = PerformImplicitConversion(Init, T1, AA_Initializing,
4744                                                   false, false,
4745                                                   Conversions);
4746    if (badConversion) {
4747      if (Conversions.isAmbiguous()) {
4748        Diag(DeclLoc,
4749             diag::err_lvalue_to_rvalue_ambig_ref) << Init->getSourceRange();
4750        for (int j = Conversions.Ambiguous.conversions().size()-1;
4751             j >= 0; j--) {
4752          FunctionDecl *Func = Conversions.Ambiguous.conversions()[j];
4753          NoteOverloadCandidate(Func);
4754        }
4755      }
4756      else {
4757        if (isRValRef)
4758          Diag(DeclLoc, diag::err_lvalue_to_rvalue_ref)
4759            << Init->getSourceRange();
4760        else
4761          Diag(DeclLoc, diag::err_invalid_initialization)
4762            << DeclType << Init->getType() << Init->getSourceRange();
4763      }
4764    }
4765    return badConversion;
4766  }
4767}
4768
4769static inline bool
4770CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4771                                       const FunctionDecl *FnDecl) {
4772  const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4773  if (isa<NamespaceDecl>(DC)) {
4774    return SemaRef.Diag(FnDecl->getLocation(),
4775                        diag::err_operator_new_delete_declared_in_namespace)
4776      << FnDecl->getDeclName();
4777  }
4778
4779  if (isa<TranslationUnitDecl>(DC) &&
4780      FnDecl->getStorageClass() == FunctionDecl::Static) {
4781    return SemaRef.Diag(FnDecl->getLocation(),
4782                        diag::err_operator_new_delete_declared_static)
4783      << FnDecl->getDeclName();
4784  }
4785
4786  return false;
4787}
4788
4789static inline bool
4790CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4791                            CanQualType ExpectedResultType,
4792                            CanQualType ExpectedFirstParamType,
4793                            unsigned DependentParamTypeDiag,
4794                            unsigned InvalidParamTypeDiag) {
4795  QualType ResultType =
4796    FnDecl->getType()->getAs<FunctionType>()->getResultType();
4797
4798  // Check that the result type is not dependent.
4799  if (ResultType->isDependentType())
4800    return SemaRef.Diag(FnDecl->getLocation(),
4801                        diag::err_operator_new_delete_dependent_result_type)
4802    << FnDecl->getDeclName() << ExpectedResultType;
4803
4804  // Check that the result type is what we expect.
4805  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4806    return SemaRef.Diag(FnDecl->getLocation(),
4807                        diag::err_operator_new_delete_invalid_result_type)
4808    << FnDecl->getDeclName() << ExpectedResultType;
4809
4810  // A function template must have at least 2 parameters.
4811  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4812    return SemaRef.Diag(FnDecl->getLocation(),
4813                      diag::err_operator_new_delete_template_too_few_parameters)
4814        << FnDecl->getDeclName();
4815
4816  // The function decl must have at least 1 parameter.
4817  if (FnDecl->getNumParams() == 0)
4818    return SemaRef.Diag(FnDecl->getLocation(),
4819                        diag::err_operator_new_delete_too_few_parameters)
4820      << FnDecl->getDeclName();
4821
4822  // Check the the first parameter type is not dependent.
4823  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4824  if (FirstParamType->isDependentType())
4825    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4826      << FnDecl->getDeclName() << ExpectedFirstParamType;
4827
4828  // Check that the first parameter type is what we expect.
4829  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
4830      ExpectedFirstParamType)
4831    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4832    << FnDecl->getDeclName() << ExpectedFirstParamType;
4833
4834  return false;
4835}
4836
4837static bool
4838CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4839  // C++ [basic.stc.dynamic.allocation]p1:
4840  //   A program is ill-formed if an allocation function is declared in a
4841  //   namespace scope other than global scope or declared static in global
4842  //   scope.
4843  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4844    return true;
4845
4846  CanQualType SizeTy =
4847    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4848
4849  // C++ [basic.stc.dynamic.allocation]p1:
4850  //  The return type shall be void*. The first parameter shall have type
4851  //  std::size_t.
4852  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4853                                  SizeTy,
4854                                  diag::err_operator_new_dependent_param_type,
4855                                  diag::err_operator_new_param_type))
4856    return true;
4857
4858  // C++ [basic.stc.dynamic.allocation]p1:
4859  //  The first parameter shall not have an associated default argument.
4860  if (FnDecl->getParamDecl(0)->hasDefaultArg())
4861    return SemaRef.Diag(FnDecl->getLocation(),
4862                        diag::err_operator_new_default_arg)
4863      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4864
4865  return false;
4866}
4867
4868static bool
4869CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4870  // C++ [basic.stc.dynamic.deallocation]p1:
4871  //   A program is ill-formed if deallocation functions are declared in a
4872  //   namespace scope other than global scope or declared static in global
4873  //   scope.
4874  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4875    return true;
4876
4877  // C++ [basic.stc.dynamic.deallocation]p2:
4878  //   Each deallocation function shall return void and its first parameter
4879  //   shall be void*.
4880  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4881                                  SemaRef.Context.VoidPtrTy,
4882                                 diag::err_operator_delete_dependent_param_type,
4883                                 diag::err_operator_delete_param_type))
4884    return true;
4885
4886  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4887  if (FirstParamType->isDependentType())
4888    return SemaRef.Diag(FnDecl->getLocation(),
4889                        diag::err_operator_delete_dependent_param_type)
4890    << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4891
4892  if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4893      SemaRef.Context.VoidPtrTy)
4894    return SemaRef.Diag(FnDecl->getLocation(),
4895                        diag::err_operator_delete_param_type)
4896      << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4897
4898  return false;
4899}
4900
4901/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4902/// of this overloaded operator is well-formed. If so, returns false;
4903/// otherwise, emits appropriate diagnostics and returns true.
4904bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
4905  assert(FnDecl && FnDecl->isOverloadedOperator() &&
4906         "Expected an overloaded operator declaration");
4907
4908  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4909
4910  // C++ [over.oper]p5:
4911  //   The allocation and deallocation functions, operator new,
4912  //   operator new[], operator delete and operator delete[], are
4913  //   described completely in 3.7.3. The attributes and restrictions
4914  //   found in the rest of this subclause do not apply to them unless
4915  //   explicitly stated in 3.7.3.
4916  if (Op == OO_Delete || Op == OO_Array_Delete)
4917    return CheckOperatorDeleteDeclaration(*this, FnDecl);
4918
4919  if (Op == OO_New || Op == OO_Array_New)
4920    return CheckOperatorNewDeclaration(*this, FnDecl);
4921
4922  // C++ [over.oper]p6:
4923  //   An operator function shall either be a non-static member
4924  //   function or be a non-member function and have at least one
4925  //   parameter whose type is a class, a reference to a class, an
4926  //   enumeration, or a reference to an enumeration.
4927  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4928    if (MethodDecl->isStatic())
4929      return Diag(FnDecl->getLocation(),
4930                  diag::err_operator_overload_static) << FnDecl->getDeclName();
4931  } else {
4932    bool ClassOrEnumParam = false;
4933    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4934                                   ParamEnd = FnDecl->param_end();
4935         Param != ParamEnd; ++Param) {
4936      QualType ParamType = (*Param)->getType().getNonReferenceType();
4937      if (ParamType->isDependentType() || ParamType->isRecordType() ||
4938          ParamType->isEnumeralType()) {
4939        ClassOrEnumParam = true;
4940        break;
4941      }
4942    }
4943
4944    if (!ClassOrEnumParam)
4945      return Diag(FnDecl->getLocation(),
4946                  diag::err_operator_overload_needs_class_or_enum)
4947        << FnDecl->getDeclName();
4948  }
4949
4950  // C++ [over.oper]p8:
4951  //   An operator function cannot have default arguments (8.3.6),
4952  //   except where explicitly stated below.
4953  //
4954  // Only the function-call operator allows default arguments
4955  // (C++ [over.call]p1).
4956  if (Op != OO_Call) {
4957    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4958         Param != FnDecl->param_end(); ++Param) {
4959      if ((*Param)->hasDefaultArg())
4960        return Diag((*Param)->getLocation(),
4961                    diag::err_operator_overload_default_arg)
4962          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
4963    }
4964  }
4965
4966  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4967    { false, false, false }
4968#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4969    , { Unary, Binary, MemberOnly }
4970#include "clang/Basic/OperatorKinds.def"
4971  };
4972
4973  bool CanBeUnaryOperator = OperatorUses[Op][0];
4974  bool CanBeBinaryOperator = OperatorUses[Op][1];
4975  bool MustBeMemberOperator = OperatorUses[Op][2];
4976
4977  // C++ [over.oper]p8:
4978  //   [...] Operator functions cannot have more or fewer parameters
4979  //   than the number required for the corresponding operator, as
4980  //   described in the rest of this subclause.
4981  unsigned NumParams = FnDecl->getNumParams()
4982                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
4983  if (Op != OO_Call &&
4984      ((NumParams == 1 && !CanBeUnaryOperator) ||
4985       (NumParams == 2 && !CanBeBinaryOperator) ||
4986       (NumParams < 1) || (NumParams > 2))) {
4987    // We have the wrong number of parameters.
4988    unsigned ErrorKind;
4989    if (CanBeUnaryOperator && CanBeBinaryOperator) {
4990      ErrorKind = 2;  // 2 -> unary or binary.
4991    } else if (CanBeUnaryOperator) {
4992      ErrorKind = 0;  // 0 -> unary
4993    } else {
4994      assert(CanBeBinaryOperator &&
4995             "All non-call overloaded operators are unary or binary!");
4996      ErrorKind = 1;  // 1 -> binary
4997    }
4998
4999    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
5000      << FnDecl->getDeclName() << NumParams << ErrorKind;
5001  }
5002
5003  // Overloaded operators other than operator() cannot be variadic.
5004  if (Op != OO_Call &&
5005      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
5006    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
5007      << FnDecl->getDeclName();
5008  }
5009
5010  // Some operators must be non-static member functions.
5011  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5012    return Diag(FnDecl->getLocation(),
5013                diag::err_operator_overload_must_be_member)
5014      << FnDecl->getDeclName();
5015  }
5016
5017  // C++ [over.inc]p1:
5018  //   The user-defined function called operator++ implements the
5019  //   prefix and postfix ++ operator. If this function is a member
5020  //   function with no parameters, or a non-member function with one
5021  //   parameter of class or enumeration type, it defines the prefix
5022  //   increment operator ++ for objects of that type. If the function
5023  //   is a member function with one parameter (which shall be of type
5024  //   int) or a non-member function with two parameters (the second
5025  //   of which shall be of type int), it defines the postfix
5026  //   increment operator ++ for objects of that type.
5027  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5028    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5029    bool ParamIsInt = false;
5030    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
5031      ParamIsInt = BT->getKind() == BuiltinType::Int;
5032
5033    if (!ParamIsInt)
5034      return Diag(LastParam->getLocation(),
5035                  diag::err_operator_overload_post_incdec_must_be_int)
5036        << LastParam->getType() << (Op == OO_MinusMinus);
5037  }
5038
5039  // Notify the class if it got an assignment operator.
5040  if (Op == OO_Equal) {
5041    // Would have returned earlier otherwise.
5042    assert(isa<CXXMethodDecl>(FnDecl) &&
5043      "Overloaded = not member, but not filtered.");
5044    CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5045    Method->getParent()->addedAssignmentOperator(Context, Method);
5046  }
5047
5048  return false;
5049}
5050
5051/// CheckLiteralOperatorDeclaration - Check whether the declaration
5052/// of this literal operator function is well-formed. If so, returns
5053/// false; otherwise, emits appropriate diagnostics and returns true.
5054bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5055  DeclContext *DC = FnDecl->getDeclContext();
5056  Decl::Kind Kind = DC->getDeclKind();
5057  if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5058      Kind != Decl::LinkageSpec) {
5059    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5060      << FnDecl->getDeclName();
5061    return true;
5062  }
5063
5064  bool Valid = false;
5065
5066  // FIXME: Check for the one valid template signature
5067  // template <char...> type operator "" name();
5068
5069  if (FunctionDecl::param_iterator Param = FnDecl->param_begin()) {
5070    // Check the first parameter
5071    QualType T = (*Param)->getType();
5072
5073    // unsigned long long int and long double are allowed, but only
5074    // alone.
5075    // We also allow any character type; their omission seems to be a bug
5076    // in n3000
5077    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5078        Context.hasSameType(T, Context.LongDoubleTy) ||
5079        Context.hasSameType(T, Context.CharTy) ||
5080        Context.hasSameType(T, Context.WCharTy) ||
5081        Context.hasSameType(T, Context.Char16Ty) ||
5082        Context.hasSameType(T, Context.Char32Ty)) {
5083      if (++Param == FnDecl->param_end())
5084        Valid = true;
5085      goto FinishedParams;
5086    }
5087
5088    // Otherwise it must be a pointer to const; let's strip those.
5089    const PointerType *PT = T->getAs<PointerType>();
5090    if (!PT)
5091      goto FinishedParams;
5092    T = PT->getPointeeType();
5093    if (!T.isConstQualified())
5094      goto FinishedParams;
5095    T = T.getUnqualifiedType();
5096
5097    // Move on to the second parameter;
5098    ++Param;
5099
5100    // If there is no second parameter, the first must be a const char *
5101    if (Param == FnDecl->param_end()) {
5102      if (Context.hasSameType(T, Context.CharTy))
5103        Valid = true;
5104      goto FinishedParams;
5105    }
5106
5107    // const char *, const wchar_t*, const char16_t*, and const char32_t*
5108    // are allowed as the first parameter to a two-parameter function
5109    if (!(Context.hasSameType(T, Context.CharTy) ||
5110          Context.hasSameType(T, Context.WCharTy) ||
5111          Context.hasSameType(T, Context.Char16Ty) ||
5112          Context.hasSameType(T, Context.Char32Ty)))
5113      goto FinishedParams;
5114
5115    // The second and final parameter must be an std::size_t
5116    T = (*Param)->getType().getUnqualifiedType();
5117    if (Context.hasSameType(T, Context.getSizeType()) &&
5118        ++Param == FnDecl->param_end())
5119      Valid = true;
5120  }
5121
5122  // FIXME: This diagnostic is absolutely terrible.
5123FinishedParams:
5124  if (!Valid) {
5125    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5126      << FnDecl->getDeclName();
5127    return true;
5128  }
5129
5130  return false;
5131}
5132
5133/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5134/// linkage specification, including the language and (if present)
5135/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5136/// the location of the language string literal, which is provided
5137/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5138/// the '{' brace. Otherwise, this linkage specification does not
5139/// have any braces.
5140Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5141                                                     SourceLocation ExternLoc,
5142                                                     SourceLocation LangLoc,
5143                                                     const char *Lang,
5144                                                     unsigned StrSize,
5145                                                     SourceLocation LBraceLoc) {
5146  LinkageSpecDecl::LanguageIDs Language;
5147  if (strncmp(Lang, "\"C\"", StrSize) == 0)
5148    Language = LinkageSpecDecl::lang_c;
5149  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
5150    Language = LinkageSpecDecl::lang_cxx;
5151  else {
5152    Diag(LangLoc, diag::err_bad_language);
5153    return DeclPtrTy();
5154  }
5155
5156  // FIXME: Add all the various semantics of linkage specifications
5157
5158  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
5159                                               LangLoc, Language,
5160                                               LBraceLoc.isValid());
5161  CurContext->addDecl(D);
5162  PushDeclContext(S, D);
5163  return DeclPtrTy::make(D);
5164}
5165
5166/// ActOnFinishLinkageSpecification - Completely the definition of
5167/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5168/// valid, it's the position of the closing '}' brace in a linkage
5169/// specification that uses braces.
5170Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5171                                                      DeclPtrTy LinkageSpec,
5172                                                      SourceLocation RBraceLoc) {
5173  if (LinkageSpec)
5174    PopDeclContext();
5175  return LinkageSpec;
5176}
5177
5178/// \brief Perform semantic analysis for the variable declaration that
5179/// occurs within a C++ catch clause, returning the newly-created
5180/// variable.
5181VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
5182                                         TypeSourceInfo *TInfo,
5183                                         IdentifierInfo *Name,
5184                                         SourceLocation Loc,
5185                                         SourceRange Range) {
5186  bool Invalid = false;
5187
5188  // Arrays and functions decay.
5189  if (ExDeclType->isArrayType())
5190    ExDeclType = Context.getArrayDecayedType(ExDeclType);
5191  else if (ExDeclType->isFunctionType())
5192    ExDeclType = Context.getPointerType(ExDeclType);
5193
5194  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5195  // The exception-declaration shall not denote a pointer or reference to an
5196  // incomplete type, other than [cv] void*.
5197  // N2844 forbids rvalue references.
5198  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
5199    Diag(Loc, diag::err_catch_rvalue_ref) << Range;
5200    Invalid = true;
5201  }
5202
5203  // GCC allows catching pointers and references to incomplete types
5204  // as an extension; so do we, but we warn by default.
5205
5206  QualType BaseType = ExDeclType;
5207  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
5208  unsigned DK = diag::err_catch_incomplete;
5209  bool IncompleteCatchIsInvalid = true;
5210  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
5211    BaseType = Ptr->getPointeeType();
5212    Mode = 1;
5213    DK = diag::ext_catch_incomplete_ptr;
5214    IncompleteCatchIsInvalid = false;
5215  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
5216    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
5217    BaseType = Ref->getPointeeType();
5218    Mode = 2;
5219    DK = diag::ext_catch_incomplete_ref;
5220    IncompleteCatchIsInvalid = false;
5221  }
5222  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
5223      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
5224      IncompleteCatchIsInvalid)
5225    Invalid = true;
5226
5227  if (!Invalid && !ExDeclType->isDependentType() &&
5228      RequireNonAbstractType(Loc, ExDeclType,
5229                             diag::err_abstract_type_in_decl,
5230                             AbstractVariableType))
5231    Invalid = true;
5232
5233  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
5234                                    Name, ExDeclType, TInfo, VarDecl::None);
5235
5236  if (!Invalid) {
5237    if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
5238      // C++ [except.handle]p16:
5239      //   The object declared in an exception-declaration or, if the
5240      //   exception-declaration does not specify a name, a temporary (12.2) is
5241      //   copy-initialized (8.5) from the exception object. [...]
5242      //   The object is destroyed when the handler exits, after the destruction
5243      //   of any automatic objects initialized within the handler.
5244      //
5245      // We just pretend to initialize the object with itself, then make sure
5246      // it can be destroyed later.
5247      InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
5248      Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
5249                                            Loc, ExDeclType, 0);
5250      InitializationKind Kind = InitializationKind::CreateCopy(Loc,
5251                                                               SourceLocation());
5252      InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
5253      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5254                                    MultiExprArg(*this, (void**)&ExDeclRef, 1));
5255      if (Result.isInvalid())
5256        Invalid = true;
5257      else
5258        FinalizeVarWithDestructor(ExDecl, RecordTy);
5259    }
5260  }
5261
5262  if (Invalid)
5263    ExDecl->setInvalidDecl();
5264
5265  return ExDecl;
5266}
5267
5268/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5269/// handler.
5270Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
5271  TypeSourceInfo *TInfo = 0;
5272  QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
5273
5274  bool Invalid = D.isInvalidType();
5275  IdentifierInfo *II = D.getIdentifier();
5276  if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
5277    // The scope should be freshly made just for us. There is just no way
5278    // it contains any previous declaration.
5279    assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
5280    if (PrevDecl->isTemplateParameter()) {
5281      // Maybe we will complain about the shadowed template parameter.
5282      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5283    }
5284  }
5285
5286  if (D.getCXXScopeSpec().isSet() && !Invalid) {
5287    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5288      << D.getCXXScopeSpec().getRange();
5289    Invalid = true;
5290  }
5291
5292  VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
5293                                              D.getIdentifier(),
5294                                              D.getIdentifierLoc(),
5295                                            D.getDeclSpec().getSourceRange());
5296
5297  if (Invalid)
5298    ExDecl->setInvalidDecl();
5299
5300  // Add the exception declaration into this scope.
5301  if (II)
5302    PushOnScopeChains(ExDecl, S);
5303  else
5304    CurContext->addDecl(ExDecl);
5305
5306  ProcessDeclAttributes(S, ExDecl, D);
5307  return DeclPtrTy::make(ExDecl);
5308}
5309
5310Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
5311                                                   ExprArg assertexpr,
5312                                                   ExprArg assertmessageexpr) {
5313  Expr *AssertExpr = (Expr *)assertexpr.get();
5314  StringLiteral *AssertMessage =
5315    cast<StringLiteral>((Expr *)assertmessageexpr.get());
5316
5317  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5318    llvm::APSInt Value(32);
5319    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5320      Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5321        AssertExpr->getSourceRange();
5322      return DeclPtrTy();
5323    }
5324
5325    if (Value == 0) {
5326      Diag(AssertLoc, diag::err_static_assert_failed)
5327        << AssertMessage->getString() << AssertExpr->getSourceRange();
5328    }
5329  }
5330
5331  assertexpr.release();
5332  assertmessageexpr.release();
5333  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
5334                                        AssertExpr, AssertMessage);
5335
5336  CurContext->addDecl(Decl);
5337  return DeclPtrTy::make(Decl);
5338}
5339
5340/// Handle a friend type declaration.  This works in tandem with
5341/// ActOnTag.
5342///
5343/// Notes on friend class templates:
5344///
5345/// We generally treat friend class declarations as if they were
5346/// declaring a class.  So, for example, the elaborated type specifier
5347/// in a friend declaration is required to obey the restrictions of a
5348/// class-head (i.e. no typedefs in the scope chain), template
5349/// parameters are required to match up with simple template-ids, &c.
5350/// However, unlike when declaring a template specialization, it's
5351/// okay to refer to a template specialization without an empty
5352/// template parameter declaration, e.g.
5353///   friend class A<T>::B<unsigned>;
5354/// We permit this as a special case; if there are any template
5355/// parameters present at all, require proper matching, i.e.
5356///   template <> template <class T> friend class A<int>::B;
5357Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5358                                          MultiTemplateParamsArg TempParams) {
5359  SourceLocation Loc = DS.getSourceRange().getBegin();
5360
5361  assert(DS.isFriendSpecified());
5362  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5363
5364  // Try to convert the decl specifier to a type.  This works for
5365  // friend templates because ActOnTag never produces a ClassTemplateDecl
5366  // for a TUK_Friend.
5367  Declarator TheDeclarator(DS, Declarator::MemberContext);
5368  QualType T = GetTypeForDeclarator(TheDeclarator, S);
5369  if (TheDeclarator.isInvalidType())
5370    return DeclPtrTy();
5371
5372  // This is definitely an error in C++98.  It's probably meant to
5373  // be forbidden in C++0x, too, but the specification is just
5374  // poorly written.
5375  //
5376  // The problem is with declarations like the following:
5377  //   template <T> friend A<T>::foo;
5378  // where deciding whether a class C is a friend or not now hinges
5379  // on whether there exists an instantiation of A that causes
5380  // 'foo' to equal C.  There are restrictions on class-heads
5381  // (which we declare (by fiat) elaborated friend declarations to
5382  // be) that makes this tractable.
5383  //
5384  // FIXME: handle "template <> friend class A<T>;", which
5385  // is possibly well-formed?  Who even knows?
5386  if (TempParams.size() && !isa<ElaboratedType>(T)) {
5387    Diag(Loc, diag::err_tagless_friend_type_template)
5388      << DS.getSourceRange();
5389    return DeclPtrTy();
5390  }
5391
5392  // C++ [class.friend]p2:
5393  //   An elaborated-type-specifier shall be used in a friend declaration
5394  //   for a class.*
5395  //   * The class-key of the elaborated-type-specifier is required.
5396  // This is one of the rare places in Clang where it's legitimate to
5397  // ask about the "spelling" of the type.
5398  if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) {
5399    // If we evaluated the type to a record type, suggest putting
5400    // a tag in front.
5401    if (const RecordType *RT = T->getAs<RecordType>()) {
5402      RecordDecl *RD = RT->getDecl();
5403
5404      std::string InsertionText = std::string(" ") + RD->getKindName();
5405
5406      Diag(DS.getTypeSpecTypeLoc(), diag::err_unelaborated_friend_type)
5407        << (unsigned) RD->getTagKind()
5408        << T
5409        << SourceRange(DS.getFriendSpecLoc())
5410        << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
5411                                                 InsertionText);
5412      return DeclPtrTy();
5413    }else {
5414      Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
5415          << DS.getSourceRange();
5416      return DeclPtrTy();
5417    }
5418  }
5419
5420  // Enum types cannot be friends.
5421  if (T->getAs<EnumType>()) {
5422    Diag(DS.getTypeSpecTypeLoc(), diag::err_enum_friend)
5423      << SourceRange(DS.getFriendSpecLoc());
5424    return DeclPtrTy();
5425  }
5426
5427  // C++98 [class.friend]p1: A friend of a class is a function
5428  //   or class that is not a member of the class . . .
5429  // This is fixed in DR77, which just barely didn't make the C++03
5430  // deadline.  It's also a very silly restriction that seriously
5431  // affects inner classes and which nobody else seems to implement;
5432  // thus we never diagnose it, not even in -pedantic.
5433
5434  Decl *D;
5435  if (TempParams.size())
5436    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5437                                   TempParams.size(),
5438                                 (TemplateParameterList**) TempParams.release(),
5439                                   T.getTypePtr(),
5440                                   DS.getFriendSpecLoc());
5441  else
5442    D = FriendDecl::Create(Context, CurContext, Loc, T.getTypePtr(),
5443                           DS.getFriendSpecLoc());
5444  D->setAccess(AS_public);
5445  CurContext->addDecl(D);
5446
5447  return DeclPtrTy::make(D);
5448}
5449
5450Sema::DeclPtrTy
5451Sema::ActOnFriendFunctionDecl(Scope *S,
5452                              Declarator &D,
5453                              bool IsDefinition,
5454                              MultiTemplateParamsArg TemplateParams) {
5455  const DeclSpec &DS = D.getDeclSpec();
5456
5457  assert(DS.isFriendSpecified());
5458  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5459
5460  SourceLocation Loc = D.getIdentifierLoc();
5461  TypeSourceInfo *TInfo = 0;
5462  QualType T = GetTypeForDeclarator(D, S, &TInfo);
5463
5464  // C++ [class.friend]p1
5465  //   A friend of a class is a function or class....
5466  // Note that this sees through typedefs, which is intended.
5467  // It *doesn't* see through dependent types, which is correct
5468  // according to [temp.arg.type]p3:
5469  //   If a declaration acquires a function type through a
5470  //   type dependent on a template-parameter and this causes
5471  //   a declaration that does not use the syntactic form of a
5472  //   function declarator to have a function type, the program
5473  //   is ill-formed.
5474  if (!T->isFunctionType()) {
5475    Diag(Loc, diag::err_unexpected_friend);
5476
5477    // It might be worthwhile to try to recover by creating an
5478    // appropriate declaration.
5479    return DeclPtrTy();
5480  }
5481
5482  // C++ [namespace.memdef]p3
5483  //  - If a friend declaration in a non-local class first declares a
5484  //    class or function, the friend class or function is a member
5485  //    of the innermost enclosing namespace.
5486  //  - The name of the friend is not found by simple name lookup
5487  //    until a matching declaration is provided in that namespace
5488  //    scope (either before or after the class declaration granting
5489  //    friendship).
5490  //  - If a friend function is called, its name may be found by the
5491  //    name lookup that considers functions from namespaces and
5492  //    classes associated with the types of the function arguments.
5493  //  - When looking for a prior declaration of a class or a function
5494  //    declared as a friend, scopes outside the innermost enclosing
5495  //    namespace scope are not considered.
5496
5497  CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5498  DeclarationName Name = GetNameForDeclarator(D);
5499  assert(Name);
5500
5501  // The context we found the declaration in, or in which we should
5502  // create the declaration.
5503  DeclContext *DC;
5504
5505  // FIXME: handle local classes
5506
5507  // Recover from invalid scope qualifiers as if they just weren't there.
5508  LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5509                        ForRedeclaration);
5510  if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
5511    // FIXME: RequireCompleteDeclContext
5512    DC = computeDeclContext(ScopeQual);
5513
5514    // FIXME: handle dependent contexts
5515    if (!DC) return DeclPtrTy();
5516
5517    LookupQualifiedName(Previous, DC);
5518
5519    // If searching in that context implicitly found a declaration in
5520    // a different context, treat it like it wasn't found at all.
5521    // TODO: better diagnostics for this case.  Suggesting the right
5522    // qualified scope would be nice...
5523    // FIXME: getRepresentativeDecl() is not right here at all
5524    if (Previous.empty() ||
5525        !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
5526      D.setInvalidType();
5527      Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5528      return DeclPtrTy();
5529    }
5530
5531    // C++ [class.friend]p1: A friend of a class is a function or
5532    //   class that is not a member of the class . . .
5533    if (DC->Equals(CurContext))
5534      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5535
5536  // Otherwise walk out to the nearest namespace scope looking for matches.
5537  } else {
5538    // TODO: handle local class contexts.
5539
5540    DC = CurContext;
5541    while (true) {
5542      // Skip class contexts.  If someone can cite chapter and verse
5543      // for this behavior, that would be nice --- it's what GCC and
5544      // EDG do, and it seems like a reasonable intent, but the spec
5545      // really only says that checks for unqualified existing
5546      // declarations should stop at the nearest enclosing namespace,
5547      // not that they should only consider the nearest enclosing
5548      // namespace.
5549      while (DC->isRecord())
5550        DC = DC->getParent();
5551
5552      LookupQualifiedName(Previous, DC);
5553
5554      // TODO: decide what we think about using declarations.
5555      if (!Previous.empty())
5556        break;
5557
5558      if (DC->isFileContext()) break;
5559      DC = DC->getParent();
5560    }
5561
5562    // C++ [class.friend]p1: A friend of a class is a function or
5563    //   class that is not a member of the class . . .
5564    // C++0x changes this for both friend types and functions.
5565    // Most C++ 98 compilers do seem to give an error here, so
5566    // we do, too.
5567    if (!Previous.empty() && DC->Equals(CurContext)
5568        && !getLangOptions().CPlusPlus0x)
5569      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5570  }
5571
5572  if (DC->isFileContext()) {
5573    // This implies that it has to be an operator or function.
5574    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5575        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5576        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
5577      Diag(Loc, diag::err_introducing_special_friend) <<
5578        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5579         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
5580      return DeclPtrTy();
5581    }
5582  }
5583
5584  bool Redeclaration = false;
5585  NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
5586                                          move(TemplateParams),
5587                                          IsDefinition,
5588                                          Redeclaration);
5589  if (!ND) return DeclPtrTy();
5590
5591  assert(ND->getDeclContext() == DC);
5592  assert(ND->getLexicalDeclContext() == CurContext);
5593
5594  // Add the function declaration to the appropriate lookup tables,
5595  // adjusting the redeclarations list as necessary.  We don't
5596  // want to do this yet if the friending class is dependent.
5597  //
5598  // Also update the scope-based lookup if the target context's
5599  // lookup context is in lexical scope.
5600  if (!CurContext->isDependentContext()) {
5601    DC = DC->getLookupContext();
5602    DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
5603    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
5604      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
5605  }
5606
5607  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
5608                                       D.getIdentifierLoc(), ND,
5609                                       DS.getFriendSpecLoc());
5610  FrD->setAccess(AS_public);
5611  CurContext->addDecl(FrD);
5612
5613  if (D.getName().getKind() == UnqualifiedId::IK_TemplateId)
5614    FrD->setSpecialization(true);
5615
5616  return DeclPtrTy::make(ND);
5617}
5618
5619void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
5620  AdjustDeclIfTemplate(dcl);
5621
5622  Decl *Dcl = dcl.getAs<Decl>();
5623  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5624  if (!Fn) {
5625    Diag(DelLoc, diag::err_deleted_non_function);
5626    return;
5627  }
5628  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5629    Diag(DelLoc, diag::err_deleted_decl_not_first);
5630    Diag(Prev->getLocation(), diag::note_previous_declaration);
5631    // If the declaration wasn't the first, we delete the function anyway for
5632    // recovery.
5633  }
5634  Fn->setDeleted();
5635}
5636
5637static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5638  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5639       ++CI) {
5640    Stmt *SubStmt = *CI;
5641    if (!SubStmt)
5642      continue;
5643    if (isa<ReturnStmt>(SubStmt))
5644      Self.Diag(SubStmt->getSourceRange().getBegin(),
5645           diag::err_return_in_constructor_handler);
5646    if (!isa<Expr>(SubStmt))
5647      SearchForReturnInStmt(Self, SubStmt);
5648  }
5649}
5650
5651void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5652  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5653    CXXCatchStmt *Handler = TryBlock->getHandler(I);
5654    SearchForReturnInStmt(*this, Handler);
5655  }
5656}
5657
5658bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5659                                             const CXXMethodDecl *Old) {
5660  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5661  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
5662
5663  if (Context.hasSameType(NewTy, OldTy) ||
5664      NewTy->isDependentType() || OldTy->isDependentType())
5665    return false;
5666
5667  // Check if the return types are covariant
5668  QualType NewClassTy, OldClassTy;
5669
5670  /// Both types must be pointers or references to classes.
5671  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5672    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
5673      NewClassTy = NewPT->getPointeeType();
5674      OldClassTy = OldPT->getPointeeType();
5675    }
5676  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5677    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5678      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5679        NewClassTy = NewRT->getPointeeType();
5680        OldClassTy = OldRT->getPointeeType();
5681      }
5682    }
5683  }
5684
5685  // The return types aren't either both pointers or references to a class type.
5686  if (NewClassTy.isNull()) {
5687    Diag(New->getLocation(),
5688         diag::err_different_return_type_for_overriding_virtual_function)
5689      << New->getDeclName() << NewTy << OldTy;
5690    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5691
5692    return true;
5693  }
5694
5695  // C++ [class.virtual]p6:
5696  //   If the return type of D::f differs from the return type of B::f, the
5697  //   class type in the return type of D::f shall be complete at the point of
5698  //   declaration of D::f or shall be the class type D.
5699  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5700    if (!RT->isBeingDefined() &&
5701        RequireCompleteType(New->getLocation(), NewClassTy,
5702                            PDiag(diag::err_covariant_return_incomplete)
5703                              << New->getDeclName()))
5704    return true;
5705  }
5706
5707  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
5708    // Check if the new class derives from the old class.
5709    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5710      Diag(New->getLocation(),
5711           diag::err_covariant_return_not_derived)
5712      << New->getDeclName() << NewTy << OldTy;
5713      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5714      return true;
5715    }
5716
5717    // Check if we the conversion from derived to base is valid.
5718    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, ADK_covariance,
5719                      diag::err_covariant_return_ambiguous_derived_to_base_conv,
5720                      // FIXME: Should this point to the return type?
5721                      New->getLocation(), SourceRange(), New->getDeclName())) {
5722      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5723      return true;
5724    }
5725  }
5726
5727  // The qualifiers of the return types must be the same.
5728  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
5729    Diag(New->getLocation(),
5730         diag::err_covariant_return_type_different_qualifications)
5731    << New->getDeclName() << NewTy << OldTy;
5732    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5733    return true;
5734  };
5735
5736
5737  // The new class type must have the same or less qualifiers as the old type.
5738  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5739    Diag(New->getLocation(),
5740         diag::err_covariant_return_type_class_type_more_qualified)
5741    << New->getDeclName() << NewTy << OldTy;
5742    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5743    return true;
5744  };
5745
5746  return false;
5747}
5748
5749bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5750                                             const CXXMethodDecl *Old)
5751{
5752  if (Old->hasAttr<FinalAttr>()) {
5753    Diag(New->getLocation(), diag::err_final_function_overridden)
5754      << New->getDeclName();
5755    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5756    return true;
5757  }
5758
5759  return false;
5760}
5761
5762/// \brief Mark the given method pure.
5763///
5764/// \param Method the method to be marked pure.
5765///
5766/// \param InitRange the source range that covers the "0" initializer.
5767bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5768  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5769    Method->setPure();
5770
5771    // A class is abstract if at least one function is pure virtual.
5772    Method->getParent()->setAbstract(true);
5773    return false;
5774  }
5775
5776  if (!Method->isInvalidDecl())
5777    Diag(Method->getLocation(), diag::err_non_virtual_pure)
5778      << Method->getDeclName() << InitRange;
5779  return true;
5780}
5781
5782/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5783/// an initializer for the out-of-line declaration 'Dcl'.  The scope
5784/// is a fresh scope pushed for just this purpose.
5785///
5786/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5787/// static data member of class X, names should be looked up in the scope of
5788/// class X.
5789void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
5790  // If there is no declaration, there was an error parsing it.
5791  Decl *D = Dcl.getAs<Decl>();
5792  if (D == 0) return;
5793
5794  // We should only get called for declarations with scope specifiers, like:
5795  //   int foo::bar;
5796  assert(D->isOutOfLine());
5797  EnterDeclaratorContext(S, D->getDeclContext());
5798}
5799
5800/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5801/// initializer for the out-of-line declaration 'Dcl'.
5802void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
5803  // If there is no declaration, there was an error parsing it.
5804  Decl *D = Dcl.getAs<Decl>();
5805  if (D == 0) return;
5806
5807  assert(D->isOutOfLine());
5808  ExitDeclaratorContext(S);
5809}
5810
5811/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5812/// C++ if/switch/while/for statement.
5813/// e.g: "if (int x = f()) {...}"
5814Action::DeclResult
5815Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5816  // C++ 6.4p2:
5817  // The declarator shall not specify a function or an array.
5818  // The type-specifier-seq shall not contain typedef and shall not declare a
5819  // new class or enumeration.
5820  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5821         "Parser allowed 'typedef' as storage class of condition decl.");
5822
5823  TypeSourceInfo *TInfo = 0;
5824  TagDecl *OwnedTag = 0;
5825  QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
5826
5827  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5828                              // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5829                              // would be created and CXXConditionDeclExpr wants a VarDecl.
5830    Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5831      << D.getSourceRange();
5832    return DeclResult();
5833  } else if (OwnedTag && OwnedTag->isDefinition()) {
5834    // The type-specifier-seq shall not declare a new class or enumeration.
5835    Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5836  }
5837
5838  DeclPtrTy Dcl = ActOnDeclarator(S, D);
5839  if (!Dcl)
5840    return DeclResult();
5841
5842  VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5843  VD->setDeclaredInCondition(true);
5844  return Dcl;
5845}
5846
5847static bool needsVtable(CXXMethodDecl *MD, ASTContext &Context) {
5848  // Ignore dependent types.
5849  if (MD->isDependentContext())
5850    return false;
5851
5852  // Ignore declarations that are not definitions.
5853  if (!MD->isThisDeclarationADefinition())
5854    return false;
5855
5856  CXXRecordDecl *RD = MD->getParent();
5857
5858  // Ignore classes without a vtable.
5859  if (!RD->isDynamicClass())
5860    return false;
5861
5862  switch (MD->getParent()->getTemplateSpecializationKind()) {
5863  case TSK_Undeclared:
5864  case TSK_ExplicitSpecialization:
5865    // Classes that aren't instantiations of templates don't need their
5866    // virtual methods marked until we see the definition of the key
5867    // function.
5868    break;
5869
5870  case TSK_ImplicitInstantiation:
5871    // This is a constructor of a class template; mark all of the virtual
5872    // members as referenced to ensure that they get instantiatied.
5873    if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
5874      return true;
5875    break;
5876
5877  case TSK_ExplicitInstantiationDeclaration:
5878    return true; //FIXME: This looks wrong.
5879
5880  case TSK_ExplicitInstantiationDefinition:
5881    // This is method of a explicit instantiation; mark all of the virtual
5882    // members as referenced to ensure that they get instantiatied.
5883    return true;
5884  }
5885
5886  // Consider only out-of-line definitions of member functions. When we see
5887  // an inline definition, it's too early to compute the key function.
5888  if (!MD->isOutOfLine())
5889    return false;
5890
5891  const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5892
5893  // If there is no key function, we will need a copy of the vtable.
5894  if (!KeyFunction)
5895    return true;
5896
5897  // If this is the key function, we need to mark virtual members.
5898  if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
5899    return true;
5900
5901  return false;
5902}
5903
5904void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5905                                             CXXMethodDecl *MD) {
5906  CXXRecordDecl *RD = MD->getParent();
5907
5908  // We will need to mark all of the virtual members as referenced to build the
5909  // vtable.
5910  if (!needsVtable(MD, Context))
5911    return;
5912
5913  TemplateSpecializationKind kind = RD->getTemplateSpecializationKind();
5914  if (kind == TSK_ImplicitInstantiation)
5915    ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
5916  else
5917    MarkVirtualMembersReferenced(Loc, RD);
5918}
5919
5920bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5921  if (ClassesWithUnmarkedVirtualMembers.empty())
5922    return false;
5923
5924  while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5925    CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5926    SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5927    ClassesWithUnmarkedVirtualMembers.pop_back();
5928    MarkVirtualMembersReferenced(Loc, RD);
5929  }
5930
5931  return true;
5932}
5933
5934void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, CXXRecordDecl *RD) {
5935  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5936       e = RD->method_end(); i != e; ++i) {
5937    CXXMethodDecl *MD = *i;
5938
5939    // C++ [basic.def.odr]p2:
5940    //   [...] A virtual member function is used if it is not pure. [...]
5941    if (MD->isVirtual() && !MD->isPure())
5942      MarkDeclarationReferenced(Loc, MD);
5943  }
5944}
5945