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