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