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