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