SemaDeclCXX.cpp revision 9aca87d4b48058d56a48d62435ad6a871cc62ad1
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 "clang/Sema/SemaInternal.h"
15#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
17#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
19#include "clang/AST/ASTConsumer.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/ASTMutationListener.h"
22#include "clang/AST/CharUnits.h"
23#include "clang/AST/CXXInheritance.h"
24#include "clang/AST/DeclVisitor.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/AST/TypeOrdering.h"
30#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
32#include "clang/Basic/PartialDiagnostic.h"
33#include "clang/Lex/Preprocessor.h"
34#include "llvm/ADT/DenseSet.h"
35#include "llvm/ADT/STLExtras.h"
36#include <map>
37#include <set>
38
39using namespace clang;
40
41//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
45namespace {
46  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47  /// the default argument of a parameter to determine whether it
48  /// contains any ill-formed subexpressions. For example, this will
49  /// diagnose the use of local variables or parameters within the
50  /// default argument expression.
51  class CheckDefaultArgumentVisitor
52    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
53    Expr *DefaultArg;
54    Sema *S;
55
56  public:
57    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
58      : DefaultArg(defarg), S(s) {}
59
60    bool VisitExpr(Expr *Node);
61    bool VisitDeclRefExpr(DeclRefExpr *DRE);
62    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
63  };
64
65  /// VisitExpr - Visit all of the children of this expression.
66  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67    bool IsInvalid = false;
68    for (Stmt::child_range I = Node->children(); I; ++I)
69      IsInvalid |= Visit(*I);
70    return IsInvalid;
71  }
72
73  /// VisitDeclRefExpr - Visit a reference to a declaration, to
74  /// determine whether this declaration can be used in the default
75  /// argument expression.
76  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
77    NamedDecl *Decl = DRE->getDecl();
78    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79      // C++ [dcl.fct.default]p9
80      //   Default arguments are evaluated each time the function is
81      //   called. The order of evaluation of function arguments is
82      //   unspecified. Consequently, parameters of a function shall not
83      //   be used in default argument expressions, even if they are not
84      //   evaluated. Parameters of a function declared before a default
85      //   argument expression are in scope and can hide namespace and
86      //   class member names.
87      return S->Diag(DRE->getSourceRange().getBegin(),
88                     diag::err_param_default_argument_references_param)
89         << Param->getDeclName() << DefaultArg->getSourceRange();
90    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
91      // C++ [dcl.fct.default]p7
92      //   Local variables shall not be used in default argument
93      //   expressions.
94      if (VDecl->isLocalVarDecl())
95        return S->Diag(DRE->getSourceRange().getBegin(),
96                       diag::err_param_default_argument_references_local)
97          << VDecl->getDeclName() << DefaultArg->getSourceRange();
98    }
99
100    return false;
101  }
102
103  /// VisitCXXThisExpr - Visit a C++ "this" expression.
104  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105    // C++ [dcl.fct.default]p8:
106    //   The keyword this shall not be used in a default argument of a
107    //   member function.
108    return S->Diag(ThisE->getSourceRange().getBegin(),
109                   diag::err_param_default_argument_references_this)
110               << ThisE->getSourceRange();
111  }
112}
113
114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
115  assert(Context && "ImplicitExceptionSpecification without an ASTContext");
116  // If we have an MSAny or unknown spec already, don't bother.
117  if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
118    return;
119
120  const FunctionProtoType *Proto
121    = Method->getType()->getAs<FunctionProtoType>();
122
123  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
124
125  // If this function can throw any exceptions, make a note of that.
126  if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
127    ClearExceptions();
128    ComputedEST = EST;
129    return;
130  }
131
132  // FIXME: If the call to this decl is using any of its default arguments, we
133  // need to search them for potentially-throwing calls.
134
135  // If this function has a basic noexcept, it doesn't affect the outcome.
136  if (EST == EST_BasicNoexcept)
137    return;
138
139  // If we have a throw-all spec at this point, ignore the function.
140  if (ComputedEST == EST_None)
141    return;
142
143  // If we're still at noexcept(true) and there's a nothrow() callee,
144  // change to that specification.
145  if (EST == EST_DynamicNone) {
146    if (ComputedEST == EST_BasicNoexcept)
147      ComputedEST = EST_DynamicNone;
148    return;
149  }
150
151  // Check out noexcept specs.
152  if (EST == EST_ComputedNoexcept) {
153    FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
154    assert(NR != FunctionProtoType::NR_NoNoexcept &&
155           "Must have noexcept result for EST_ComputedNoexcept.");
156    assert(NR != FunctionProtoType::NR_Dependent &&
157           "Should not generate implicit declarations for dependent cases, "
158           "and don't know how to handle them anyway.");
159
160    // noexcept(false) -> no spec on the new function
161    if (NR == FunctionProtoType::NR_Throw) {
162      ClearExceptions();
163      ComputedEST = EST_None;
164    }
165    // noexcept(true) won't change anything either.
166    return;
167  }
168
169  assert(EST == EST_Dynamic && "EST case not considered earlier.");
170  assert(ComputedEST != EST_None &&
171         "Shouldn't collect exceptions when throw-all is guaranteed.");
172  ComputedEST = EST_Dynamic;
173  // Record the exceptions in this function's exception specification.
174  for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
175                                          EEnd = Proto->exception_end();
176       E != EEnd; ++E)
177    if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
178      Exceptions.push_back(*E);
179}
180
181void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
182  if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
183    return;
184
185  // FIXME:
186  //
187  // C++0x [except.spec]p14:
188  //   [An] implicit exception-specification specifies the type-id T if and
189  // only if T is allowed by the exception-specification of a function directly
190  // invoked by f's implicit definition; f shall allow all exceptions if any
191  // function it directly invokes allows all exceptions, and f shall allow no
192  // exceptions if every function it directly invokes allows no exceptions.
193  //
194  // Note in particular that if an implicit exception-specification is generated
195  // for a function containing a throw-expression, that specification can still
196  // be noexcept(true).
197  //
198  // Note also that 'directly invoked' is not defined in the standard, and there
199  // is no indication that we should only consider potentially-evaluated calls.
200  //
201  // Ultimately we should implement the intent of the standard: the exception
202  // specification should be the set of exceptions which can be thrown by the
203  // implicit definition. For now, we assume that any non-nothrow expression can
204  // throw any exception.
205
206  if (E->CanThrow(*Context))
207    ComputedEST = EST_None;
208}
209
210bool
211Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
212                              SourceLocation EqualLoc) {
213  if (RequireCompleteType(Param->getLocation(), Param->getType(),
214                          diag::err_typecheck_decl_incomplete_type)) {
215    Param->setInvalidDecl();
216    return true;
217  }
218
219  // C++ [dcl.fct.default]p5
220  //   A default argument expression is implicitly converted (clause
221  //   4) to the parameter type. The default argument expression has
222  //   the same semantic constraints as the initializer expression in
223  //   a declaration of a variable of the parameter type, using the
224  //   copy-initialization semantics (8.5).
225  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
226                                                                    Param);
227  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
228                                                           EqualLoc);
229  InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
230  ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
231                                      MultiExprArg(*this, &Arg, 1));
232  if (Result.isInvalid())
233    return true;
234  Arg = Result.takeAs<Expr>();
235
236  CheckImplicitConversions(Arg, EqualLoc);
237  Arg = MaybeCreateExprWithCleanups(Arg);
238
239  // Okay: add the default argument to the parameter
240  Param->setDefaultArg(Arg);
241
242  // We have already instantiated this parameter; provide each of the
243  // instantiations with the uninstantiated default argument.
244  UnparsedDefaultArgInstantiationsMap::iterator InstPos
245    = UnparsedDefaultArgInstantiations.find(Param);
246  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
247    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
248      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
249
250    // We're done tracking this parameter's instantiations.
251    UnparsedDefaultArgInstantiations.erase(InstPos);
252  }
253
254  return false;
255}
256
257/// ActOnParamDefaultArgument - Check whether the default argument
258/// provided for a function parameter is well-formed. If so, attach it
259/// to the parameter declaration.
260void
261Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
262                                Expr *DefaultArg) {
263  if (!param || !DefaultArg)
264    return;
265
266  ParmVarDecl *Param = cast<ParmVarDecl>(param);
267  UnparsedDefaultArgLocs.erase(Param);
268
269  // Default arguments are only permitted in C++
270  if (!getLangOptions().CPlusPlus) {
271    Diag(EqualLoc, diag::err_param_default_argument)
272      << DefaultArg->getSourceRange();
273    Param->setInvalidDecl();
274    return;
275  }
276
277  // Check for unexpanded parameter packs.
278  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
279    Param->setInvalidDecl();
280    return;
281  }
282
283  // Check that the default argument is well-formed
284  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285  if (DefaultArgChecker.Visit(DefaultArg)) {
286    Param->setInvalidDecl();
287    return;
288  }
289
290  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
291}
292
293/// ActOnParamUnparsedDefaultArgument - We've seen a default
294/// argument for a function parameter, but we can't parse it yet
295/// because we're inside a class definition. Note that this default
296/// argument will be parsed later.
297void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
298                                             SourceLocation EqualLoc,
299                                             SourceLocation ArgLoc) {
300  if (!param)
301    return;
302
303  ParmVarDecl *Param = cast<ParmVarDecl>(param);
304  if (Param)
305    Param->setUnparsedDefaultArg();
306
307  UnparsedDefaultArgLocs[Param] = ArgLoc;
308}
309
310/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311/// the default argument for the parameter param failed.
312void Sema::ActOnParamDefaultArgumentError(Decl *param) {
313  if (!param)
314    return;
315
316  ParmVarDecl *Param = cast<ParmVarDecl>(param);
317
318  Param->setInvalidDecl();
319
320  UnparsedDefaultArgLocs.erase(Param);
321}
322
323/// CheckExtraCXXDefaultArguments - Check for any extra default
324/// arguments in the declarator, which is not a function declaration
325/// or definition and therefore is not permitted to have default
326/// arguments. This routine should be invoked for every declarator
327/// that is not a function declaration or definition.
328void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
329  // C++ [dcl.fct.default]p3
330  //   A default argument expression shall be specified only in the
331  //   parameter-declaration-clause of a function declaration or in a
332  //   template-parameter (14.1). It shall not be specified for a
333  //   parameter pack. If it is specified in a
334  //   parameter-declaration-clause, it shall not occur within a
335  //   declarator or abstract-declarator of a parameter-declaration.
336  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
337    DeclaratorChunk &chunk = D.getTypeObject(i);
338    if (chunk.Kind == DeclaratorChunk::Function) {
339      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
340        ParmVarDecl *Param =
341          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
342        if (Param->hasUnparsedDefaultArg()) {
343          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
344          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
345            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
346          delete Toks;
347          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
348        } else if (Param->getDefaultArg()) {
349          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
350            << Param->getDefaultArg()->getSourceRange();
351          Param->setDefaultArg(0);
352        }
353      }
354    }
355  }
356}
357
358// MergeCXXFunctionDecl - Merge two declarations of the same C++
359// function, once we already know that they have the same
360// type. Subroutine of MergeFunctionDecl. Returns true if there was an
361// error, false otherwise.
362bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
363  bool Invalid = false;
364
365  // C++ [dcl.fct.default]p4:
366  //   For non-template functions, default arguments can be added in
367  //   later declarations of a function in the same
368  //   scope. Declarations in different scopes have completely
369  //   distinct sets of default arguments. That is, declarations in
370  //   inner scopes do not acquire default arguments from
371  //   declarations in outer scopes, and vice versa. In a given
372  //   function declaration, all parameters subsequent to a
373  //   parameter with a default argument shall have default
374  //   arguments supplied in this or previous declarations. A
375  //   default argument shall not be redefined by a later
376  //   declaration (not even to the same value).
377  //
378  // C++ [dcl.fct.default]p6:
379  //   Except for member functions of class templates, the default arguments
380  //   in a member function definition that appears outside of the class
381  //   definition are added to the set of default arguments provided by the
382  //   member function declaration in the class definition.
383  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
384    ParmVarDecl *OldParam = Old->getParamDecl(p);
385    ParmVarDecl *NewParam = New->getParamDecl(p);
386
387    if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
388
389      unsigned DiagDefaultParamID =
390        diag::err_param_default_argument_redefinition;
391
392      // MSVC accepts that default parameters be redefined for member functions
393      // of template class. The new default parameter's value is ignored.
394      Invalid = true;
395      if (getLangOptions().MicrosoftExt) {
396        CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
397        if (MD && MD->getParent()->getDescribedClassTemplate()) {
398          // Merge the old default argument into the new parameter.
399          NewParam->setHasInheritedDefaultArg();
400          if (OldParam->hasUninstantiatedDefaultArg())
401            NewParam->setUninstantiatedDefaultArg(
402                                      OldParam->getUninstantiatedDefaultArg());
403          else
404            NewParam->setDefaultArg(OldParam->getInit());
405          DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
406          Invalid = false;
407        }
408      }
409
410      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
411      // hint here. Alternatively, we could walk the type-source information
412      // for NewParam to find the last source location in the type... but it
413      // isn't worth the effort right now. This is the kind of test case that
414      // is hard to get right:
415      //   int f(int);
416      //   void g(int (*fp)(int) = f);
417      //   void g(int (*fp)(int) = &f);
418      Diag(NewParam->getLocation(), DiagDefaultParamID)
419        << NewParam->getDefaultArgRange();
420
421      // Look for the function declaration where the default argument was
422      // actually written, which may be a declaration prior to Old.
423      for (FunctionDecl *Older = Old->getPreviousDeclaration();
424           Older; Older = Older->getPreviousDeclaration()) {
425        if (!Older->getParamDecl(p)->hasDefaultArg())
426          break;
427
428        OldParam = Older->getParamDecl(p);
429      }
430
431      Diag(OldParam->getLocation(), diag::note_previous_definition)
432        << OldParam->getDefaultArgRange();
433    } else if (OldParam->hasDefaultArg()) {
434      // Merge the old default argument into the new parameter.
435      // It's important to use getInit() here;  getDefaultArg()
436      // strips off any top-level ExprWithCleanups.
437      NewParam->setHasInheritedDefaultArg();
438      if (OldParam->hasUninstantiatedDefaultArg())
439        NewParam->setUninstantiatedDefaultArg(
440                                      OldParam->getUninstantiatedDefaultArg());
441      else
442        NewParam->setDefaultArg(OldParam->getInit());
443    } else if (NewParam->hasDefaultArg()) {
444      if (New->getDescribedFunctionTemplate()) {
445        // Paragraph 4, quoted above, only applies to non-template functions.
446        Diag(NewParam->getLocation(),
447             diag::err_param_default_argument_template_redecl)
448          << NewParam->getDefaultArgRange();
449        Diag(Old->getLocation(), diag::note_template_prev_declaration)
450          << false;
451      } else if (New->getTemplateSpecializationKind()
452                   != TSK_ImplicitInstantiation &&
453                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
454        // C++ [temp.expr.spec]p21:
455        //   Default function arguments shall not be specified in a declaration
456        //   or a definition for one of the following explicit specializations:
457        //     - the explicit specialization of a function template;
458        //     - the explicit specialization of a member function template;
459        //     - the explicit specialization of a member function of a class
460        //       template where the class template specialization to which the
461        //       member function specialization belongs is implicitly
462        //       instantiated.
463        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
464          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
465          << New->getDeclName()
466          << NewParam->getDefaultArgRange();
467      } else if (New->getDeclContext()->isDependentContext()) {
468        // C++ [dcl.fct.default]p6 (DR217):
469        //   Default arguments for a member function of a class template shall
470        //   be specified on the initial declaration of the member function
471        //   within the class template.
472        //
473        // Reading the tea leaves a bit in DR217 and its reference to DR205
474        // leads me to the conclusion that one cannot add default function
475        // arguments for an out-of-line definition of a member function of a
476        // dependent type.
477        int WhichKind = 2;
478        if (CXXRecordDecl *Record
479              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
480          if (Record->getDescribedClassTemplate())
481            WhichKind = 0;
482          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
483            WhichKind = 1;
484          else
485            WhichKind = 2;
486        }
487
488        Diag(NewParam->getLocation(),
489             diag::err_param_default_argument_member_template_redecl)
490          << WhichKind
491          << NewParam->getDefaultArgRange();
492      } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
493        CXXSpecialMember NewSM = getSpecialMember(Ctor),
494                         OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
495        if (NewSM != OldSM) {
496          Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
497            << NewParam->getDefaultArgRange() << NewSM;
498          Diag(Old->getLocation(), diag::note_previous_declaration_special)
499            << OldSM;
500        }
501      }
502    }
503  }
504
505  if (CheckEquivalentExceptionSpec(Old, New))
506    Invalid = true;
507
508  return Invalid;
509}
510
511/// \brief Merge the exception specifications of two variable declarations.
512///
513/// This is called when there's a redeclaration of a VarDecl. The function
514/// checks if the redeclaration might have an exception specification and
515/// validates compatibility and merges the specs if necessary.
516void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
517  // Shortcut if exceptions are disabled.
518  if (!getLangOptions().CXXExceptions)
519    return;
520
521  assert(Context.hasSameType(New->getType(), Old->getType()) &&
522         "Should only be called if types are otherwise the same.");
523
524  QualType NewType = New->getType();
525  QualType OldType = Old->getType();
526
527  // We're only interested in pointers and references to functions, as well
528  // as pointers to member functions.
529  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
530    NewType = R->getPointeeType();
531    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
532  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
533    NewType = P->getPointeeType();
534    OldType = OldType->getAs<PointerType>()->getPointeeType();
535  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
536    NewType = M->getPointeeType();
537    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
538  }
539
540  if (!NewType->isFunctionProtoType())
541    return;
542
543  // There's lots of special cases for functions. For function pointers, system
544  // libraries are hopefully not as broken so that we don't need these
545  // workarounds.
546  if (CheckEquivalentExceptionSpec(
547        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
548        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
549    New->setInvalidDecl();
550  }
551}
552
553/// CheckCXXDefaultArguments - Verify that the default arguments for a
554/// function declaration are well-formed according to C++
555/// [dcl.fct.default].
556void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
557  unsigned NumParams = FD->getNumParams();
558  unsigned p;
559
560  // Find first parameter with a default argument
561  for (p = 0; p < NumParams; ++p) {
562    ParmVarDecl *Param = FD->getParamDecl(p);
563    if (Param->hasDefaultArg())
564      break;
565  }
566
567  // C++ [dcl.fct.default]p4:
568  //   In a given function declaration, all parameters
569  //   subsequent to a parameter with a default argument shall
570  //   have default arguments supplied in this or previous
571  //   declarations. A default argument shall not be redefined
572  //   by a later declaration (not even to the same value).
573  unsigned LastMissingDefaultArg = 0;
574  for (; p < NumParams; ++p) {
575    ParmVarDecl *Param = FD->getParamDecl(p);
576    if (!Param->hasDefaultArg()) {
577      if (Param->isInvalidDecl())
578        /* We already complained about this parameter. */;
579      else if (Param->getIdentifier())
580        Diag(Param->getLocation(),
581             diag::err_param_default_argument_missing_name)
582          << Param->getIdentifier();
583      else
584        Diag(Param->getLocation(),
585             diag::err_param_default_argument_missing);
586
587      LastMissingDefaultArg = p;
588    }
589  }
590
591  if (LastMissingDefaultArg > 0) {
592    // Some default arguments were missing. Clear out all of the
593    // default arguments up to (and including) the last missing
594    // default argument, so that we leave the function parameters
595    // in a semantically valid state.
596    for (p = 0; p <= LastMissingDefaultArg; ++p) {
597      ParmVarDecl *Param = FD->getParamDecl(p);
598      if (Param->hasDefaultArg()) {
599        Param->setDefaultArg(0);
600      }
601    }
602  }
603}
604
605/// isCurrentClassName - Determine whether the identifier II is the
606/// name of the class type currently being defined. In the case of
607/// nested classes, this will only return true if II is the name of
608/// the innermost class.
609bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
610                              const CXXScopeSpec *SS) {
611  assert(getLangOptions().CPlusPlus && "No class names in C!");
612
613  CXXRecordDecl *CurDecl;
614  if (SS && SS->isSet() && !SS->isInvalid()) {
615    DeclContext *DC = computeDeclContext(*SS, true);
616    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
617  } else
618    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
619
620  if (CurDecl && CurDecl->getIdentifier())
621    return &II == CurDecl->getIdentifier();
622  else
623    return false;
624}
625
626/// \brief Check the validity of a C++ base class specifier.
627///
628/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
629/// and returns NULL otherwise.
630CXXBaseSpecifier *
631Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
632                         SourceRange SpecifierRange,
633                         bool Virtual, AccessSpecifier Access,
634                         TypeSourceInfo *TInfo,
635                         SourceLocation EllipsisLoc) {
636  QualType BaseType = TInfo->getType();
637
638  // C++ [class.union]p1:
639  //   A union shall not have base classes.
640  if (Class->isUnion()) {
641    Diag(Class->getLocation(), diag::err_base_clause_on_union)
642      << SpecifierRange;
643    return 0;
644  }
645
646  if (EllipsisLoc.isValid() &&
647      !TInfo->getType()->containsUnexpandedParameterPack()) {
648    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
649      << TInfo->getTypeLoc().getSourceRange();
650    EllipsisLoc = SourceLocation();
651  }
652
653  if (BaseType->isDependentType())
654    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
655                                          Class->getTagKind() == TTK_Class,
656                                          Access, TInfo, EllipsisLoc);
657
658  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
659
660  // Base specifiers must be record types.
661  if (!BaseType->isRecordType()) {
662    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
663    return 0;
664  }
665
666  // C++ [class.union]p1:
667  //   A union shall not be used as a base class.
668  if (BaseType->isUnionType()) {
669    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
670    return 0;
671  }
672
673  // C++ [class.derived]p2:
674  //   The class-name in a base-specifier shall not be an incompletely
675  //   defined class.
676  if (RequireCompleteType(BaseLoc, BaseType,
677                          PDiag(diag::err_incomplete_base_class)
678                            << SpecifierRange)) {
679    Class->setInvalidDecl();
680    return 0;
681  }
682
683  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
684  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
685  assert(BaseDecl && "Record type has no declaration");
686  BaseDecl = BaseDecl->getDefinition();
687  assert(BaseDecl && "Base type is not incomplete, but has no definition");
688  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
689  assert(CXXBaseDecl && "Base type is not a C++ type");
690
691  // C++ [class]p3:
692  //   If a class is marked final and it appears as a base-type-specifier in
693  //   base-clause, the program is ill-formed.
694  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
695    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
696      << CXXBaseDecl->getDeclName();
697    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
698      << CXXBaseDecl->getDeclName();
699    return 0;
700  }
701
702  if (BaseDecl->isInvalidDecl())
703    Class->setInvalidDecl();
704
705  // Create the base specifier.
706  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
707                                        Class->getTagKind() == TTK_Class,
708                                        Access, TInfo, EllipsisLoc);
709}
710
711/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
712/// one entry in the base class list of a class specifier, for
713/// example:
714///    class foo : public bar, virtual private baz {
715/// 'public bar' and 'virtual private baz' are each base-specifiers.
716BaseResult
717Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
718                         bool Virtual, AccessSpecifier Access,
719                         ParsedType basetype, SourceLocation BaseLoc,
720                         SourceLocation EllipsisLoc) {
721  if (!classdecl)
722    return true;
723
724  AdjustDeclIfTemplate(classdecl);
725  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
726  if (!Class)
727    return true;
728
729  TypeSourceInfo *TInfo = 0;
730  GetTypeFromParser(basetype, &TInfo);
731
732  if (EllipsisLoc.isInvalid() &&
733      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
734                                      UPPC_BaseType))
735    return true;
736
737  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
738                                                      Virtual, Access, TInfo,
739                                                      EllipsisLoc))
740    return BaseSpec;
741
742  return true;
743}
744
745/// \brief Performs the actual work of attaching the given base class
746/// specifiers to a C++ class.
747bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
748                                unsigned NumBases) {
749 if (NumBases == 0)
750    return false;
751
752  // Used to keep track of which base types we have already seen, so
753  // that we can properly diagnose redundant direct base types. Note
754  // that the key is always the unqualified canonical type of the base
755  // class.
756  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
757
758  // Copy non-redundant base specifiers into permanent storage.
759  unsigned NumGoodBases = 0;
760  bool Invalid = false;
761  for (unsigned idx = 0; idx < NumBases; ++idx) {
762    QualType NewBaseType
763      = Context.getCanonicalType(Bases[idx]->getType());
764    NewBaseType = NewBaseType.getLocalUnqualifiedType();
765    if (KnownBaseTypes[NewBaseType]) {
766      // C++ [class.mi]p3:
767      //   A class shall not be specified as a direct base class of a
768      //   derived class more than once.
769      Diag(Bases[idx]->getSourceRange().getBegin(),
770           diag::err_duplicate_base_class)
771        << KnownBaseTypes[NewBaseType]->getType()
772        << Bases[idx]->getSourceRange();
773
774      // Delete the duplicate base class specifier; we're going to
775      // overwrite its pointer later.
776      Context.Deallocate(Bases[idx]);
777
778      Invalid = true;
779    } else {
780      // Okay, add this new base class.
781      KnownBaseTypes[NewBaseType] = Bases[idx];
782      Bases[NumGoodBases++] = Bases[idx];
783    }
784  }
785
786  // Attach the remaining base class specifiers to the derived class.
787  Class->setBases(Bases, NumGoodBases);
788
789  // Delete the remaining (good) base class specifiers, since their
790  // data has been copied into the CXXRecordDecl.
791  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
792    Context.Deallocate(Bases[idx]);
793
794  return Invalid;
795}
796
797/// ActOnBaseSpecifiers - Attach the given base specifiers to the
798/// class, after checking whether there are any duplicate base
799/// classes.
800void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
801                               unsigned NumBases) {
802  if (!ClassDecl || !Bases || !NumBases)
803    return;
804
805  AdjustDeclIfTemplate(ClassDecl);
806  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
807                       (CXXBaseSpecifier**)(Bases), NumBases);
808}
809
810static CXXRecordDecl *GetClassForType(QualType T) {
811  if (const RecordType *RT = T->getAs<RecordType>())
812    return cast<CXXRecordDecl>(RT->getDecl());
813  else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
814    return ICT->getDecl();
815  else
816    return 0;
817}
818
819/// \brief Determine whether the type \p Derived is a C++ class that is
820/// derived from the type \p Base.
821bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
822  if (!getLangOptions().CPlusPlus)
823    return false;
824
825  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
826  if (!DerivedRD)
827    return false;
828
829  CXXRecordDecl *BaseRD = GetClassForType(Base);
830  if (!BaseRD)
831    return false;
832
833  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
834  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
835}
836
837/// \brief Determine whether the type \p Derived is a C++ class that is
838/// derived from the type \p Base.
839bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
840  if (!getLangOptions().CPlusPlus)
841    return false;
842
843  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
844  if (!DerivedRD)
845    return false;
846
847  CXXRecordDecl *BaseRD = GetClassForType(Base);
848  if (!BaseRD)
849    return false;
850
851  return DerivedRD->isDerivedFrom(BaseRD, Paths);
852}
853
854void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
855                              CXXCastPath &BasePathArray) {
856  assert(BasePathArray.empty() && "Base path array must be empty!");
857  assert(Paths.isRecordingPaths() && "Must record paths!");
858
859  const CXXBasePath &Path = Paths.front();
860
861  // We first go backward and check if we have a virtual base.
862  // FIXME: It would be better if CXXBasePath had the base specifier for
863  // the nearest virtual base.
864  unsigned Start = 0;
865  for (unsigned I = Path.size(); I != 0; --I) {
866    if (Path[I - 1].Base->isVirtual()) {
867      Start = I - 1;
868      break;
869    }
870  }
871
872  // Now add all bases.
873  for (unsigned I = Start, E = Path.size(); I != E; ++I)
874    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
875}
876
877/// \brief Determine whether the given base path includes a virtual
878/// base class.
879bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
880  for (CXXCastPath::const_iterator B = BasePath.begin(),
881                                BEnd = BasePath.end();
882       B != BEnd; ++B)
883    if ((*B)->isVirtual())
884      return true;
885
886  return false;
887}
888
889/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
890/// conversion (where Derived and Base are class types) is
891/// well-formed, meaning that the conversion is unambiguous (and
892/// that all of the base classes are accessible). Returns true
893/// and emits a diagnostic if the code is ill-formed, returns false
894/// otherwise. Loc is the location where this routine should point to
895/// if there is an error, and Range is the source range to highlight
896/// if there is an error.
897bool
898Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
899                                   unsigned InaccessibleBaseID,
900                                   unsigned AmbigiousBaseConvID,
901                                   SourceLocation Loc, SourceRange Range,
902                                   DeclarationName Name,
903                                   CXXCastPath *BasePath) {
904  // First, determine whether the path from Derived to Base is
905  // ambiguous. This is slightly more expensive than checking whether
906  // the Derived to Base conversion exists, because here we need to
907  // explore multiple paths to determine if there is an ambiguity.
908  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
909                     /*DetectVirtual=*/false);
910  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
911  assert(DerivationOkay &&
912         "Can only be used with a derived-to-base conversion");
913  (void)DerivationOkay;
914
915  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
916    if (InaccessibleBaseID) {
917      // Check that the base class can be accessed.
918      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
919                                   InaccessibleBaseID)) {
920        case AR_inaccessible:
921          return true;
922        case AR_accessible:
923        case AR_dependent:
924        case AR_delayed:
925          break;
926      }
927    }
928
929    // Build a base path if necessary.
930    if (BasePath)
931      BuildBasePathArray(Paths, *BasePath);
932    return false;
933  }
934
935  // We know that the derived-to-base conversion is ambiguous, and
936  // we're going to produce a diagnostic. Perform the derived-to-base
937  // search just one more time to compute all of the possible paths so
938  // that we can print them out. This is more expensive than any of
939  // the previous derived-to-base checks we've done, but at this point
940  // performance isn't as much of an issue.
941  Paths.clear();
942  Paths.setRecordingPaths(true);
943  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
944  assert(StillOkay && "Can only be used with a derived-to-base conversion");
945  (void)StillOkay;
946
947  // Build up a textual representation of the ambiguous paths, e.g.,
948  // D -> B -> A, that will be used to illustrate the ambiguous
949  // conversions in the diagnostic. We only print one of the paths
950  // to each base class subobject.
951  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
952
953  Diag(Loc, AmbigiousBaseConvID)
954  << Derived << Base << PathDisplayStr << Range << Name;
955  return true;
956}
957
958bool
959Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
960                                   SourceLocation Loc, SourceRange Range,
961                                   CXXCastPath *BasePath,
962                                   bool IgnoreAccess) {
963  return CheckDerivedToBaseConversion(Derived, Base,
964                                      IgnoreAccess ? 0
965                                       : diag::err_upcast_to_inaccessible_base,
966                                      diag::err_ambiguous_derived_to_base_conv,
967                                      Loc, Range, DeclarationName(),
968                                      BasePath);
969}
970
971
972/// @brief Builds a string representing ambiguous paths from a
973/// specific derived class to different subobjects of the same base
974/// class.
975///
976/// This function builds a string that can be used in error messages
977/// to show the different paths that one can take through the
978/// inheritance hierarchy to go from the derived class to different
979/// subobjects of a base class. The result looks something like this:
980/// @code
981/// struct D -> struct B -> struct A
982/// struct D -> struct C -> struct A
983/// @endcode
984std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
985  std::string PathDisplayStr;
986  std::set<unsigned> DisplayedPaths;
987  for (CXXBasePaths::paths_iterator Path = Paths.begin();
988       Path != Paths.end(); ++Path) {
989    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
990      // We haven't displayed a path to this particular base
991      // class subobject yet.
992      PathDisplayStr += "\n    ";
993      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
994      for (CXXBasePath::const_iterator Element = Path->begin();
995           Element != Path->end(); ++Element)
996        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
997    }
998  }
999
1000  return PathDisplayStr;
1001}
1002
1003//===----------------------------------------------------------------------===//
1004// C++ class member Handling
1005//===----------------------------------------------------------------------===//
1006
1007/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1008Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1009                                 SourceLocation ASLoc,
1010                                 SourceLocation ColonLoc) {
1011  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1012  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1013                                                  ASLoc, ColonLoc);
1014  CurContext->addHiddenDecl(ASDecl);
1015  return ASDecl;
1016}
1017
1018/// CheckOverrideControl - Check C++0x override control semantics.
1019void Sema::CheckOverrideControl(const Decl *D) {
1020  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1021  if (!MD || !MD->isVirtual())
1022    return;
1023
1024  if (MD->isDependentContext())
1025    return;
1026
1027  // C++0x [class.virtual]p3:
1028  //   If a virtual function is marked with the virt-specifier override and does
1029  //   not override a member function of a base class,
1030  //   the program is ill-formed.
1031  bool HasOverriddenMethods =
1032    MD->begin_overridden_methods() != MD->end_overridden_methods();
1033  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
1034    Diag(MD->getLocation(),
1035                 diag::err_function_marked_override_not_overriding)
1036      << MD->getDeclName();
1037    return;
1038  }
1039}
1040
1041/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1042/// function overrides a virtual member function marked 'final', according to
1043/// C++0x [class.virtual]p3.
1044bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1045                                                  const CXXMethodDecl *Old) {
1046  if (!Old->hasAttr<FinalAttr>())
1047    return false;
1048
1049  Diag(New->getLocation(), diag::err_final_function_overridden)
1050    << New->getDeclName();
1051  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1052  return true;
1053}
1054
1055/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1056/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1057/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1058/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1059/// present but parsing it has been deferred.
1060Decl *
1061Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1062                               MultiTemplateParamsArg TemplateParameterLists,
1063                               Expr *BW, const VirtSpecifiers &VS,
1064                               Expr *InitExpr, bool HasDeferredInit,
1065                               bool IsDefinition) {
1066  const DeclSpec &DS = D.getDeclSpec();
1067  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1068  DeclarationName Name = NameInfo.getName();
1069  SourceLocation Loc = NameInfo.getLoc();
1070
1071  // For anonymous bitfields, the location should point to the type.
1072  if (Loc.isInvalid())
1073    Loc = D.getSourceRange().getBegin();
1074
1075  Expr *BitWidth = static_cast<Expr*>(BW);
1076  Expr *Init = static_cast<Expr*>(InitExpr);
1077
1078  assert(isa<CXXRecordDecl>(CurContext));
1079  assert(!DS.isFriendSpecified());
1080  assert(!Init || !HasDeferredInit);
1081
1082  bool isFunc = D.isDeclarationOfFunction();
1083
1084  // C++ 9.2p6: A member shall not be declared to have automatic storage
1085  // duration (auto, register) or with the extern storage-class-specifier.
1086  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1087  // data members and cannot be applied to names declared const or static,
1088  // and cannot be applied to reference members.
1089  switch (DS.getStorageClassSpec()) {
1090    case DeclSpec::SCS_unspecified:
1091    case DeclSpec::SCS_typedef:
1092    case DeclSpec::SCS_static:
1093      // FALL THROUGH.
1094      break;
1095    case DeclSpec::SCS_mutable:
1096      if (isFunc) {
1097        if (DS.getStorageClassSpecLoc().isValid())
1098          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1099        else
1100          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1101
1102        // FIXME: It would be nicer if the keyword was ignored only for this
1103        // declarator. Otherwise we could get follow-up errors.
1104        D.getMutableDeclSpec().ClearStorageClassSpecs();
1105      }
1106      break;
1107    default:
1108      if (DS.getStorageClassSpecLoc().isValid())
1109        Diag(DS.getStorageClassSpecLoc(),
1110             diag::err_storageclass_invalid_for_member);
1111      else
1112        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1113      D.getMutableDeclSpec().ClearStorageClassSpecs();
1114  }
1115
1116  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1117                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1118                      !isFunc);
1119
1120  Decl *Member;
1121  if (isInstField) {
1122    CXXScopeSpec &SS = D.getCXXScopeSpec();
1123
1124    if (SS.isSet() && !SS.isInvalid()) {
1125      // The user provided a superfluous scope specifier inside a class
1126      // definition:
1127      //
1128      // class X {
1129      //   int X::member;
1130      // };
1131      DeclContext *DC = 0;
1132      if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1133        Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1134        << Name << FixItHint::CreateRemoval(SS.getRange());
1135      else
1136        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1137          << Name << SS.getRange();
1138
1139      SS.clear();
1140    }
1141
1142    // FIXME: Check for template parameters!
1143    // FIXME: Check that the name is an identifier!
1144    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1145                         HasDeferredInit, AS);
1146    assert(Member && "HandleField never returns null");
1147  } else {
1148    assert(!HasDeferredInit);
1149
1150    Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
1151    if (!Member) {
1152      return 0;
1153    }
1154
1155    // Non-instance-fields can't have a bitfield.
1156    if (BitWidth) {
1157      if (Member->isInvalidDecl()) {
1158        // don't emit another diagnostic.
1159      } else if (isa<VarDecl>(Member)) {
1160        // C++ 9.6p3: A bit-field shall not be a static member.
1161        // "static member 'A' cannot be a bit-field"
1162        Diag(Loc, diag::err_static_not_bitfield)
1163          << Name << BitWidth->getSourceRange();
1164      } else if (isa<TypedefDecl>(Member)) {
1165        // "typedef member 'x' cannot be a bit-field"
1166        Diag(Loc, diag::err_typedef_not_bitfield)
1167          << Name << BitWidth->getSourceRange();
1168      } else {
1169        // A function typedef ("typedef int f(); f a;").
1170        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1171        Diag(Loc, diag::err_not_integral_type_bitfield)
1172          << Name << cast<ValueDecl>(Member)->getType()
1173          << BitWidth->getSourceRange();
1174      }
1175
1176      BitWidth = 0;
1177      Member->setInvalidDecl();
1178    }
1179
1180    Member->setAccess(AS);
1181
1182    // If we have declared a member function template, set the access of the
1183    // templated declaration as well.
1184    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1185      FunTmpl->getTemplatedDecl()->setAccess(AS);
1186  }
1187
1188  if (VS.isOverrideSpecified()) {
1189    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1190    if (!MD || !MD->isVirtual()) {
1191      Diag(Member->getLocStart(),
1192           diag::override_keyword_only_allowed_on_virtual_member_functions)
1193        << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
1194    } else
1195      MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1196  }
1197  if (VS.isFinalSpecified()) {
1198    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1199    if (!MD || !MD->isVirtual()) {
1200      Diag(Member->getLocStart(),
1201           diag::override_keyword_only_allowed_on_virtual_member_functions)
1202      << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
1203    } else
1204      MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1205  }
1206
1207  if (VS.getLastLocation().isValid()) {
1208    // Update the end location of a method that has a virt-specifiers.
1209    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1210      MD->setRangeEnd(VS.getLastLocation());
1211  }
1212
1213  CheckOverrideControl(Member);
1214
1215  assert((Name || isInstField) && "No identifier for non-field ?");
1216
1217  if (Init)
1218    AddInitializerToDecl(Member, Init, false,
1219                         DS.getTypeSpecType() == DeclSpec::TST_auto);
1220  else if (DS.getTypeSpecType() == DeclSpec::TST_auto &&
1221           DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1222    // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static
1223    // data member if a brace-or-equal-initializer is provided.
1224    Diag(Loc, diag::err_auto_var_requires_init)
1225      << Name << cast<ValueDecl>(Member)->getType();
1226    Member->setInvalidDecl();
1227  }
1228
1229  FinalizeDeclaration(Member);
1230
1231  if (isInstField)
1232    FieldCollector->Add(cast<FieldDecl>(Member));
1233  return Member;
1234}
1235
1236/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1237/// in-class initializer for a non-static C++ class member, and after
1238/// instantiating an in-class initializer in a class template. Such actions
1239/// are deferred until the class is complete.
1240void
1241Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1242                                       Expr *InitExpr) {
1243  FieldDecl *FD = cast<FieldDecl>(D);
1244
1245  if (!InitExpr) {
1246    FD->setInvalidDecl();
1247    FD->removeInClassInitializer();
1248    return;
1249  }
1250
1251  ExprResult Init = InitExpr;
1252  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1253    // FIXME: if there is no EqualLoc, this is list-initialization.
1254    Init = PerformCopyInitialization(
1255      InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1256    if (Init.isInvalid()) {
1257      FD->setInvalidDecl();
1258      return;
1259    }
1260
1261    CheckImplicitConversions(Init.get(), EqualLoc);
1262  }
1263
1264  // C++0x [class.base.init]p7:
1265  //   The initialization of each base and member constitutes a
1266  //   full-expression.
1267  Init = MaybeCreateExprWithCleanups(Init);
1268  if (Init.isInvalid()) {
1269    FD->setInvalidDecl();
1270    return;
1271  }
1272
1273  InitExpr = Init.release();
1274
1275  FD->setInClassInitializer(InitExpr);
1276}
1277
1278/// \brief Find the direct and/or virtual base specifiers that
1279/// correspond to the given base type, for use in base initialization
1280/// within a constructor.
1281static bool FindBaseInitializer(Sema &SemaRef,
1282                                CXXRecordDecl *ClassDecl,
1283                                QualType BaseType,
1284                                const CXXBaseSpecifier *&DirectBaseSpec,
1285                                const CXXBaseSpecifier *&VirtualBaseSpec) {
1286  // First, check for a direct base class.
1287  DirectBaseSpec = 0;
1288  for (CXXRecordDecl::base_class_const_iterator Base
1289         = ClassDecl->bases_begin();
1290       Base != ClassDecl->bases_end(); ++Base) {
1291    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1292      // We found a direct base of this type. That's what we're
1293      // initializing.
1294      DirectBaseSpec = &*Base;
1295      break;
1296    }
1297  }
1298
1299  // Check for a virtual base class.
1300  // FIXME: We might be able to short-circuit this if we know in advance that
1301  // there are no virtual bases.
1302  VirtualBaseSpec = 0;
1303  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1304    // We haven't found a base yet; search the class hierarchy for a
1305    // virtual base class.
1306    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1307                       /*DetectVirtual=*/false);
1308    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1309                              BaseType, Paths)) {
1310      for (CXXBasePaths::paths_iterator Path = Paths.begin();
1311           Path != Paths.end(); ++Path) {
1312        if (Path->back().Base->isVirtual()) {
1313          VirtualBaseSpec = Path->back().Base;
1314          break;
1315        }
1316      }
1317    }
1318  }
1319
1320  return DirectBaseSpec || VirtualBaseSpec;
1321}
1322
1323/// ActOnMemInitializer - Handle a C++ member initializer.
1324MemInitResult
1325Sema::ActOnMemInitializer(Decl *ConstructorD,
1326                          Scope *S,
1327                          CXXScopeSpec &SS,
1328                          IdentifierInfo *MemberOrBase,
1329                          ParsedType TemplateTypeTy,
1330                          SourceLocation IdLoc,
1331                          SourceLocation LParenLoc,
1332                          Expr **Args, unsigned NumArgs,
1333                          SourceLocation RParenLoc,
1334                          SourceLocation EllipsisLoc) {
1335  if (!ConstructorD)
1336    return true;
1337
1338  AdjustDeclIfTemplate(ConstructorD);
1339
1340  CXXConstructorDecl *Constructor
1341    = dyn_cast<CXXConstructorDecl>(ConstructorD);
1342  if (!Constructor) {
1343    // The user wrote a constructor initializer on a function that is
1344    // not a C++ constructor. Ignore the error for now, because we may
1345    // have more member initializers coming; we'll diagnose it just
1346    // once in ActOnMemInitializers.
1347    return true;
1348  }
1349
1350  CXXRecordDecl *ClassDecl = Constructor->getParent();
1351
1352  // C++ [class.base.init]p2:
1353  //   Names in a mem-initializer-id are looked up in the scope of the
1354  //   constructor's class and, if not found in that scope, are looked
1355  //   up in the scope containing the constructor's definition.
1356  //   [Note: if the constructor's class contains a member with the
1357  //   same name as a direct or virtual base class of the class, a
1358  //   mem-initializer-id naming the member or base class and composed
1359  //   of a single identifier refers to the class member. A
1360  //   mem-initializer-id for the hidden base class may be specified
1361  //   using a qualified name. ]
1362  if (!SS.getScopeRep() && !TemplateTypeTy) {
1363    // Look for a member, first.
1364    FieldDecl *Member = 0;
1365    DeclContext::lookup_result Result
1366      = ClassDecl->lookup(MemberOrBase);
1367    if (Result.first != Result.second) {
1368      Member = dyn_cast<FieldDecl>(*Result.first);
1369
1370      if (Member) {
1371        if (EllipsisLoc.isValid())
1372          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1373            << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1374
1375        return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1376                                    LParenLoc, RParenLoc);
1377      }
1378
1379      // Handle anonymous union case.
1380      if (IndirectFieldDecl* IndirectField
1381            = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1382        if (EllipsisLoc.isValid())
1383          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1384            << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1385
1386         return BuildMemberInitializer(IndirectField, (Expr**)Args,
1387                                       NumArgs, IdLoc,
1388                                       LParenLoc, RParenLoc);
1389      }
1390    }
1391  }
1392  // It didn't name a member, so see if it names a class.
1393  QualType BaseType;
1394  TypeSourceInfo *TInfo = 0;
1395
1396  if (TemplateTypeTy) {
1397    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1398  } else {
1399    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1400    LookupParsedName(R, S, &SS);
1401
1402    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1403    if (!TyD) {
1404      if (R.isAmbiguous()) return true;
1405
1406      // We don't want access-control diagnostics here.
1407      R.suppressDiagnostics();
1408
1409      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1410        bool NotUnknownSpecialization = false;
1411        DeclContext *DC = computeDeclContext(SS, false);
1412        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1413          NotUnknownSpecialization = !Record->hasAnyDependentBases();
1414
1415        if (!NotUnknownSpecialization) {
1416          // When the scope specifier can refer to a member of an unknown
1417          // specialization, we take it as a type name.
1418          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1419                                       SS.getWithLocInContext(Context),
1420                                       *MemberOrBase, IdLoc);
1421          if (BaseType.isNull())
1422            return true;
1423
1424          R.clear();
1425          R.setLookupName(MemberOrBase);
1426        }
1427      }
1428
1429      // If no results were found, try to correct typos.
1430      TypoCorrection Corr;
1431      if (R.empty() && BaseType.isNull() &&
1432          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1433                              ClassDecl, false, CTC_NoKeywords))) {
1434        std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1435        std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1436        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
1437          if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
1438            // We have found a non-static data member with a similar
1439            // name to what was typed; complain and initialize that
1440            // member.
1441            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1442              << MemberOrBase << true << CorrectedQuotedStr
1443              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1444            Diag(Member->getLocation(), diag::note_previous_decl)
1445              << CorrectedQuotedStr;
1446
1447            return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1448                                          LParenLoc, RParenLoc);
1449          }
1450        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
1451          const CXXBaseSpecifier *DirectBaseSpec;
1452          const CXXBaseSpecifier *VirtualBaseSpec;
1453          if (FindBaseInitializer(*this, ClassDecl,
1454                                  Context.getTypeDeclType(Type),
1455                                  DirectBaseSpec, VirtualBaseSpec)) {
1456            // We have found a direct or virtual base class with a
1457            // similar name to what was typed; complain and initialize
1458            // that base class.
1459            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1460              << MemberOrBase << false << CorrectedQuotedStr
1461              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1462
1463            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1464                                                             : VirtualBaseSpec;
1465            Diag(BaseSpec->getSourceRange().getBegin(),
1466                 diag::note_base_class_specified_here)
1467              << BaseSpec->getType()
1468              << BaseSpec->getSourceRange();
1469
1470            TyD = Type;
1471          }
1472        }
1473      }
1474
1475      if (!TyD && BaseType.isNull()) {
1476        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1477          << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1478        return true;
1479      }
1480    }
1481
1482    if (BaseType.isNull()) {
1483      BaseType = Context.getTypeDeclType(TyD);
1484      if (SS.isSet()) {
1485        NestedNameSpecifier *Qualifier =
1486          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1487
1488        // FIXME: preserve source range information
1489        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
1490      }
1491    }
1492  }
1493
1494  if (!TInfo)
1495    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1496
1497  return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
1498                              LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
1499}
1500
1501/// Checks a member initializer expression for cases where reference (or
1502/// pointer) members are bound to by-value parameters (or their addresses).
1503static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1504                                               Expr *Init,
1505                                               SourceLocation IdLoc) {
1506  QualType MemberTy = Member->getType();
1507
1508  // We only handle pointers and references currently.
1509  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1510  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1511    return;
1512
1513  const bool IsPointer = MemberTy->isPointerType();
1514  if (IsPointer) {
1515    if (const UnaryOperator *Op
1516          = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1517      // The only case we're worried about with pointers requires taking the
1518      // address.
1519      if (Op->getOpcode() != UO_AddrOf)
1520        return;
1521
1522      Init = Op->getSubExpr();
1523    } else {
1524      // We only handle address-of expression initializers for pointers.
1525      return;
1526    }
1527  }
1528
1529  if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1530    // Taking the address of a temporary will be diagnosed as a hard error.
1531    if (IsPointer)
1532      return;
1533
1534    S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1535      << Member << Init->getSourceRange();
1536  } else if (const DeclRefExpr *DRE
1537               = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1538    // We only warn when referring to a non-reference parameter declaration.
1539    const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1540    if (!Parameter || Parameter->getType()->isReferenceType())
1541      return;
1542
1543    S.Diag(Init->getExprLoc(),
1544           IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1545                     : diag::warn_bind_ref_member_to_parameter)
1546      << Member << Parameter << Init->getSourceRange();
1547  } else {
1548    // Other initializers are fine.
1549    return;
1550  }
1551
1552  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
1553    << (unsigned)IsPointer;
1554}
1555
1556/// Checks an initializer expression for use of uninitialized fields, such as
1557/// containing the field that is being initialized. Returns true if there is an
1558/// uninitialized field was used an updates the SourceLocation parameter; false
1559/// otherwise.
1560static bool InitExprContainsUninitializedFields(const Stmt *S,
1561                                                const ValueDecl *LhsField,
1562                                                SourceLocation *L) {
1563  assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1564
1565  if (isa<CallExpr>(S)) {
1566    // Do not descend into function calls or constructors, as the use
1567    // of an uninitialized field may be valid. One would have to inspect
1568    // the contents of the function/ctor to determine if it is safe or not.
1569    // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1570    // may be safe, depending on what the function/ctor does.
1571    return false;
1572  }
1573  if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1574    const NamedDecl *RhsField = ME->getMemberDecl();
1575
1576    if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1577      // The member expression points to a static data member.
1578      assert(VD->isStaticDataMember() &&
1579             "Member points to non-static data member!");
1580      (void)VD;
1581      return false;
1582    }
1583
1584    if (isa<EnumConstantDecl>(RhsField)) {
1585      // The member expression points to an enum.
1586      return false;
1587    }
1588
1589    if (RhsField == LhsField) {
1590      // Initializing a field with itself. Throw a warning.
1591      // But wait; there are exceptions!
1592      // Exception #1:  The field may not belong to this record.
1593      // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1594      const Expr *base = ME->getBase();
1595      if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1596        // Even though the field matches, it does not belong to this record.
1597        return false;
1598      }
1599      // None of the exceptions triggered; return true to indicate an
1600      // uninitialized field was used.
1601      *L = ME->getMemberLoc();
1602      return true;
1603    }
1604  } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
1605    // sizeof/alignof doesn't reference contents, do not warn.
1606    return false;
1607  } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1608    // address-of doesn't reference contents (the pointer may be dereferenced
1609    // in the same expression but it would be rare; and weird).
1610    if (UOE->getOpcode() == UO_AddrOf)
1611      return false;
1612  }
1613  for (Stmt::const_child_range it = S->children(); it; ++it) {
1614    if (!*it) {
1615      // An expression such as 'member(arg ?: "")' may trigger this.
1616      continue;
1617    }
1618    if (InitExprContainsUninitializedFields(*it, LhsField, L))
1619      return true;
1620  }
1621  return false;
1622}
1623
1624MemInitResult
1625Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
1626                             unsigned NumArgs, SourceLocation IdLoc,
1627                             SourceLocation LParenLoc,
1628                             SourceLocation RParenLoc) {
1629  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1630  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1631  assert((DirectMember || IndirectMember) &&
1632         "Member must be a FieldDecl or IndirectFieldDecl");
1633
1634  if (Member->isInvalidDecl())
1635    return true;
1636
1637  // Diagnose value-uses of fields to initialize themselves, e.g.
1638  //   foo(foo)
1639  // where foo is not also a parameter to the constructor.
1640  // TODO: implement -Wuninitialized and fold this into that framework.
1641  for (unsigned i = 0; i < NumArgs; ++i) {
1642    SourceLocation L;
1643    if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1644      // FIXME: Return true in the case when other fields are used before being
1645      // uninitialized. For example, let this field be the i'th field. When
1646      // initializing the i'th field, throw a warning if any of the >= i'th
1647      // fields are used, as they are not yet initialized.
1648      // Right now we are only handling the case where the i'th field uses
1649      // itself in its initializer.
1650      Diag(L, diag::warn_field_is_uninit);
1651    }
1652  }
1653
1654  bool HasDependentArg = false;
1655  for (unsigned i = 0; i < NumArgs; i++)
1656    HasDependentArg |= Args[i]->isTypeDependent();
1657
1658  Expr *Init;
1659  if (Member->getType()->isDependentType() || HasDependentArg) {
1660    // Can't check initialization for a member of dependent type or when
1661    // any of the arguments are type-dependent expressions.
1662    Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1663                                       RParenLoc,
1664                                       Member->getType().getNonReferenceType());
1665
1666    DiscardCleanupsInEvaluationContext();
1667  } else {
1668    // Initialize the member.
1669    InitializedEntity MemberEntity =
1670      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1671                   : InitializedEntity::InitializeMember(IndirectMember, 0);
1672    InitializationKind Kind =
1673      InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1674
1675    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1676
1677    ExprResult MemberInit =
1678      InitSeq.Perform(*this, MemberEntity, Kind,
1679                      MultiExprArg(*this, Args, NumArgs), 0);
1680    if (MemberInit.isInvalid())
1681      return true;
1682
1683    CheckImplicitConversions(MemberInit.get(), LParenLoc);
1684
1685    // C++0x [class.base.init]p7:
1686    //   The initialization of each base and member constitutes a
1687    //   full-expression.
1688    MemberInit = MaybeCreateExprWithCleanups(MemberInit);
1689    if (MemberInit.isInvalid())
1690      return true;
1691
1692    // If we are in a dependent context, template instantiation will
1693    // perform this type-checking again. Just save the arguments that we
1694    // received in a ParenListExpr.
1695    // FIXME: This isn't quite ideal, since our ASTs don't capture all
1696    // of the information that we have about the member
1697    // initializer. However, deconstructing the ASTs is a dicey process,
1698    // and this approach is far more likely to get the corner cases right.
1699    if (CurContext->isDependentContext()) {
1700      Init = new (Context) ParenListExpr(
1701          Context, LParenLoc, Args, NumArgs, RParenLoc,
1702          Member->getType().getNonReferenceType());
1703    } else {
1704      Init = MemberInit.get();
1705      CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
1706    }
1707  }
1708
1709  if (DirectMember) {
1710    return new (Context) CXXCtorInitializer(Context, DirectMember,
1711                                                    IdLoc, LParenLoc, Init,
1712                                                    RParenLoc);
1713  } else {
1714    return new (Context) CXXCtorInitializer(Context, IndirectMember,
1715                                                    IdLoc, LParenLoc, Init,
1716                                                    RParenLoc);
1717  }
1718}
1719
1720MemInitResult
1721Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1722                                 Expr **Args, unsigned NumArgs,
1723                                 SourceLocation NameLoc,
1724                                 SourceLocation LParenLoc,
1725                                 SourceLocation RParenLoc,
1726                                 CXXRecordDecl *ClassDecl) {
1727  SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1728  if (!LangOpts.CPlusPlus0x)
1729    return Diag(Loc, diag::err_delegation_0x_only)
1730      << TInfo->getTypeLoc().getLocalSourceRange();
1731
1732  // Initialize the object.
1733  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1734                                     QualType(ClassDecl->getTypeForDecl(), 0));
1735  InitializationKind Kind =
1736    InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1737
1738  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1739
1740  ExprResult DelegationInit =
1741    InitSeq.Perform(*this, DelegationEntity, Kind,
1742                    MultiExprArg(*this, Args, NumArgs), 0);
1743  if (DelegationInit.isInvalid())
1744    return true;
1745
1746  CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
1747  CXXConstructorDecl *Constructor
1748    = ConExpr->getConstructor();
1749  assert(Constructor && "Delegating constructor with no target?");
1750
1751  CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1752
1753  // C++0x [class.base.init]p7:
1754  //   The initialization of each base and member constitutes a
1755  //   full-expression.
1756  DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1757  if (DelegationInit.isInvalid())
1758    return true;
1759
1760  assert(!CurContext->isDependentContext());
1761  return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1762                                          DelegationInit.takeAs<Expr>(),
1763                                          RParenLoc);
1764}
1765
1766MemInitResult
1767Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
1768                           Expr **Args, unsigned NumArgs,
1769                           SourceLocation LParenLoc, SourceLocation RParenLoc,
1770                           CXXRecordDecl *ClassDecl,
1771                           SourceLocation EllipsisLoc) {
1772  bool HasDependentArg = false;
1773  for (unsigned i = 0; i < NumArgs; i++)
1774    HasDependentArg |= Args[i]->isTypeDependent();
1775
1776  SourceLocation BaseLoc
1777    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1778
1779  if (!BaseType->isDependentType() && !BaseType->isRecordType())
1780    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1781             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1782
1783  // C++ [class.base.init]p2:
1784  //   [...] Unless the mem-initializer-id names a nonstatic data
1785  //   member of the constructor's class or a direct or virtual base
1786  //   of that class, the mem-initializer is ill-formed. A
1787  //   mem-initializer-list can initialize a base class using any
1788  //   name that denotes that base class type.
1789  bool Dependent = BaseType->isDependentType() || HasDependentArg;
1790
1791  if (EllipsisLoc.isValid()) {
1792    // This is a pack expansion.
1793    if (!BaseType->containsUnexpandedParameterPack())  {
1794      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1795        << SourceRange(BaseLoc, RParenLoc);
1796
1797      EllipsisLoc = SourceLocation();
1798    }
1799  } else {
1800    // Check for any unexpanded parameter packs.
1801    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1802      return true;
1803
1804    for (unsigned I = 0; I != NumArgs; ++I)
1805      if (DiagnoseUnexpandedParameterPack(Args[I]))
1806        return true;
1807  }
1808
1809  // Check for direct and virtual base classes.
1810  const CXXBaseSpecifier *DirectBaseSpec = 0;
1811  const CXXBaseSpecifier *VirtualBaseSpec = 0;
1812  if (!Dependent) {
1813    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1814                                       BaseType))
1815      return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1816                                        LParenLoc, RParenLoc, ClassDecl);
1817
1818    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1819                        VirtualBaseSpec);
1820
1821    // C++ [base.class.init]p2:
1822    // Unless the mem-initializer-id names a nonstatic data member of the
1823    // constructor's class or a direct or virtual base of that class, the
1824    // mem-initializer is ill-formed.
1825    if (!DirectBaseSpec && !VirtualBaseSpec) {
1826      // If the class has any dependent bases, then it's possible that
1827      // one of those types will resolve to the same type as
1828      // BaseType. Therefore, just treat this as a dependent base
1829      // class initialization.  FIXME: Should we try to check the
1830      // initialization anyway? It seems odd.
1831      if (ClassDecl->hasAnyDependentBases())
1832        Dependent = true;
1833      else
1834        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1835          << BaseType << Context.getTypeDeclType(ClassDecl)
1836          << BaseTInfo->getTypeLoc().getLocalSourceRange();
1837    }
1838  }
1839
1840  if (Dependent) {
1841    // Can't check initialization for a base of dependent type or when
1842    // any of the arguments are type-dependent expressions.
1843    ExprResult BaseInit
1844      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1845                                          RParenLoc, BaseType));
1846
1847    DiscardCleanupsInEvaluationContext();
1848
1849    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1850                                                    /*IsVirtual=*/false,
1851                                                    LParenLoc,
1852                                                    BaseInit.takeAs<Expr>(),
1853                                                    RParenLoc,
1854                                                    EllipsisLoc);
1855  }
1856
1857  // C++ [base.class.init]p2:
1858  //   If a mem-initializer-id is ambiguous because it designates both
1859  //   a direct non-virtual base class and an inherited virtual base
1860  //   class, the mem-initializer is ill-formed.
1861  if (DirectBaseSpec && VirtualBaseSpec)
1862    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1863      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1864
1865  CXXBaseSpecifier *BaseSpec
1866    = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1867  if (!BaseSpec)
1868    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1869
1870  // Initialize the base.
1871  InitializedEntity BaseEntity =
1872    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
1873  InitializationKind Kind =
1874    InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1875
1876  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1877
1878  ExprResult BaseInit =
1879    InitSeq.Perform(*this, BaseEntity, Kind,
1880                    MultiExprArg(*this, Args, NumArgs), 0);
1881  if (BaseInit.isInvalid())
1882    return true;
1883
1884  CheckImplicitConversions(BaseInit.get(), LParenLoc);
1885
1886  // C++0x [class.base.init]p7:
1887  //   The initialization of each base and member constitutes a
1888  //   full-expression.
1889  BaseInit = MaybeCreateExprWithCleanups(BaseInit);
1890  if (BaseInit.isInvalid())
1891    return true;
1892
1893  // If we are in a dependent context, template instantiation will
1894  // perform this type-checking again. Just save the arguments that we
1895  // received in a ParenListExpr.
1896  // FIXME: This isn't quite ideal, since our ASTs don't capture all
1897  // of the information that we have about the base
1898  // initializer. However, deconstructing the ASTs is a dicey process,
1899  // and this approach is far more likely to get the corner cases right.
1900  if (CurContext->isDependentContext()) {
1901    ExprResult Init
1902      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1903                                          RParenLoc, BaseType));
1904    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1905                                                    BaseSpec->isVirtual(),
1906                                                    LParenLoc,
1907                                                    Init.takeAs<Expr>(),
1908                                                    RParenLoc,
1909                                                    EllipsisLoc);
1910  }
1911
1912  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1913                                                  BaseSpec->isVirtual(),
1914                                                  LParenLoc,
1915                                                  BaseInit.takeAs<Expr>(),
1916                                                  RParenLoc,
1917                                                  EllipsisLoc);
1918}
1919
1920// Create a static_cast\<T&&>(expr).
1921static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
1922  QualType ExprType = E->getType();
1923  QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
1924  SourceLocation ExprLoc = E->getLocStart();
1925  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
1926      TargetType, ExprLoc);
1927
1928  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1929                                   SourceRange(ExprLoc, ExprLoc),
1930                                   E->getSourceRange()).take();
1931}
1932
1933/// ImplicitInitializerKind - How an implicit base or member initializer should
1934/// initialize its base or member.
1935enum ImplicitInitializerKind {
1936  IIK_Default,
1937  IIK_Copy,
1938  IIK_Move
1939};
1940
1941static bool
1942BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1943                             ImplicitInitializerKind ImplicitInitKind,
1944                             CXXBaseSpecifier *BaseSpec,
1945                             bool IsInheritedVirtualBase,
1946                             CXXCtorInitializer *&CXXBaseInit) {
1947  InitializedEntity InitEntity
1948    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1949                                        IsInheritedVirtualBase);
1950
1951  ExprResult BaseInit;
1952
1953  switch (ImplicitInitKind) {
1954  case IIK_Default: {
1955    InitializationKind InitKind
1956      = InitializationKind::CreateDefault(Constructor->getLocation());
1957    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1958    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1959                               MultiExprArg(SemaRef, 0, 0));
1960    break;
1961  }
1962
1963  case IIK_Move:
1964  case IIK_Copy: {
1965    bool Moving = ImplicitInitKind == IIK_Move;
1966    ParmVarDecl *Param = Constructor->getParamDecl(0);
1967    QualType ParamType = Param->getType().getNonReferenceType();
1968
1969    Expr *CopyCtorArg =
1970      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
1971                          Constructor->getLocation(), ParamType,
1972                          VK_LValue, 0);
1973
1974    // Cast to the base class to avoid ambiguities.
1975    QualType ArgTy =
1976      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1977                                       ParamType.getQualifiers());
1978
1979    if (Moving) {
1980      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
1981    }
1982
1983    CXXCastPath BasePath;
1984    BasePath.push_back(BaseSpec);
1985    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1986                                            CK_UncheckedDerivedToBase,
1987                                            Moving ? VK_XValue : VK_LValue,
1988                                            &BasePath).take();
1989
1990    InitializationKind InitKind
1991      = InitializationKind::CreateDirect(Constructor->getLocation(),
1992                                         SourceLocation(), SourceLocation());
1993    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1994                                   &CopyCtorArg, 1);
1995    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1996                               MultiExprArg(&CopyCtorArg, 1));
1997    break;
1998  }
1999  }
2000
2001  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2002  if (BaseInit.isInvalid())
2003    return true;
2004
2005  CXXBaseInit =
2006    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2007               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2008                                                        SourceLocation()),
2009                                             BaseSpec->isVirtual(),
2010                                             SourceLocation(),
2011                                             BaseInit.takeAs<Expr>(),
2012                                             SourceLocation(),
2013                                             SourceLocation());
2014
2015  return false;
2016}
2017
2018static bool RefersToRValueRef(Expr *MemRef) {
2019  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2020  return Referenced->getType()->isRValueReferenceType();
2021}
2022
2023static bool
2024BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2025                               ImplicitInitializerKind ImplicitInitKind,
2026                               FieldDecl *Field, IndirectFieldDecl *Indirect,
2027                               CXXCtorInitializer *&CXXMemberInit) {
2028  if (Field->isInvalidDecl())
2029    return true;
2030
2031  SourceLocation Loc = Constructor->getLocation();
2032
2033  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2034    bool Moving = ImplicitInitKind == IIK_Move;
2035    ParmVarDecl *Param = Constructor->getParamDecl(0);
2036    QualType ParamType = Param->getType().getNonReferenceType();
2037
2038    // Suppress copying zero-width bitfields.
2039    if (const Expr *Width = Field->getBitWidth())
2040      if (Width->EvaluateAsInt(SemaRef.Context) == 0)
2041        return false;
2042
2043    Expr *MemberExprBase =
2044      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
2045                          Loc, ParamType, VK_LValue, 0);
2046
2047    if (Moving) {
2048      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2049    }
2050
2051    // Build a reference to this field within the parameter.
2052    CXXScopeSpec SS;
2053    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2054                              Sema::LookupMemberName);
2055    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2056                                  : cast<ValueDecl>(Field), AS_public);
2057    MemberLookup.resolveKind();
2058    ExprResult CtorArg
2059      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2060                                         ParamType, Loc,
2061                                         /*IsArrow=*/false,
2062                                         SS,
2063                                         /*FirstQualifierInScope=*/0,
2064                                         MemberLookup,
2065                                         /*TemplateArgs=*/0);
2066    if (CtorArg.isInvalid())
2067      return true;
2068
2069    // C++11 [class.copy]p15:
2070    //   - if a member m has rvalue reference type T&&, it is direct-initialized
2071    //     with static_cast<T&&>(x.m);
2072    if (RefersToRValueRef(CtorArg.get())) {
2073      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2074    }
2075
2076    // When the field we are copying is an array, create index variables for
2077    // each dimension of the array. We use these index variables to subscript
2078    // the source array, and other clients (e.g., CodeGen) will perform the
2079    // necessary iteration with these index variables.
2080    SmallVector<VarDecl *, 4> IndexVariables;
2081    QualType BaseType = Field->getType();
2082    QualType SizeType = SemaRef.Context.getSizeType();
2083    bool InitializingArray = false;
2084    while (const ConstantArrayType *Array
2085                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2086      InitializingArray = true;
2087      // Create the iteration variable for this array index.
2088      IdentifierInfo *IterationVarName = 0;
2089      {
2090        llvm::SmallString<8> Str;
2091        llvm::raw_svector_ostream OS(Str);
2092        OS << "__i" << IndexVariables.size();
2093        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2094      }
2095      VarDecl *IterationVar
2096        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2097                          IterationVarName, SizeType,
2098                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2099                          SC_None, SC_None);
2100      IndexVariables.push_back(IterationVar);
2101
2102      // Create a reference to the iteration variable.
2103      ExprResult IterationVarRef
2104        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
2105      assert(!IterationVarRef.isInvalid() &&
2106             "Reference to invented variable cannot fail!");
2107
2108      // Subscript the array with this iteration variable.
2109      CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
2110                                                        IterationVarRef.take(),
2111                                                        Loc);
2112      if (CtorArg.isInvalid())
2113        return true;
2114
2115      BaseType = Array->getElementType();
2116    }
2117
2118    // The array subscript expression is an lvalue, which is wrong for moving.
2119    if (Moving && InitializingArray)
2120      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2121
2122    // Construct the entity that we will be initializing. For an array, this
2123    // will be first element in the array, which may require several levels
2124    // of array-subscript entities.
2125    SmallVector<InitializedEntity, 4> Entities;
2126    Entities.reserve(1 + IndexVariables.size());
2127    if (Indirect)
2128      Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2129    else
2130      Entities.push_back(InitializedEntity::InitializeMember(Field));
2131    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2132      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2133                                                              0,
2134                                                              Entities.back()));
2135
2136    // Direct-initialize to use the copy constructor.
2137    InitializationKind InitKind =
2138      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2139
2140    Expr *CtorArgE = CtorArg.takeAs<Expr>();
2141    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2142                                   &CtorArgE, 1);
2143
2144    ExprResult MemberInit
2145      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2146                        MultiExprArg(&CtorArgE, 1));
2147    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2148    if (MemberInit.isInvalid())
2149      return true;
2150
2151    if (Indirect) {
2152      assert(IndexVariables.size() == 0 &&
2153             "Indirect field improperly initialized");
2154      CXXMemberInit
2155        = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2156                                                   Loc, Loc,
2157                                                   MemberInit.takeAs<Expr>(),
2158                                                   Loc);
2159    } else
2160      CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2161                                                 Loc, MemberInit.takeAs<Expr>(),
2162                                                 Loc,
2163                                                 IndexVariables.data(),
2164                                                 IndexVariables.size());
2165    return false;
2166  }
2167
2168  assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2169
2170  QualType FieldBaseElementType =
2171    SemaRef.Context.getBaseElementType(Field->getType());
2172
2173  if (FieldBaseElementType->isRecordType()) {
2174    InitializedEntity InitEntity
2175      = Indirect? InitializedEntity::InitializeMember(Indirect)
2176                : InitializedEntity::InitializeMember(Field);
2177    InitializationKind InitKind =
2178      InitializationKind::CreateDefault(Loc);
2179
2180    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2181    ExprResult MemberInit =
2182      InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2183
2184    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2185    if (MemberInit.isInvalid())
2186      return true;
2187
2188    if (Indirect)
2189      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2190                                                               Indirect, Loc,
2191                                                               Loc,
2192                                                               MemberInit.get(),
2193                                                               Loc);
2194    else
2195      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2196                                                               Field, Loc, Loc,
2197                                                               MemberInit.get(),
2198                                                               Loc);
2199    return false;
2200  }
2201
2202  if (!Field->getParent()->isUnion()) {
2203    if (FieldBaseElementType->isReferenceType()) {
2204      SemaRef.Diag(Constructor->getLocation(),
2205                   diag::err_uninitialized_member_in_ctor)
2206      << (int)Constructor->isImplicit()
2207      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2208      << 0 << Field->getDeclName();
2209      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2210      return true;
2211    }
2212
2213    if (FieldBaseElementType.isConstQualified()) {
2214      SemaRef.Diag(Constructor->getLocation(),
2215                   diag::err_uninitialized_member_in_ctor)
2216      << (int)Constructor->isImplicit()
2217      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2218      << 1 << Field->getDeclName();
2219      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2220      return true;
2221    }
2222  }
2223
2224  if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2225      FieldBaseElementType->isObjCRetainableType() &&
2226      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2227      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2228    // Instant objects:
2229    //   Default-initialize Objective-C pointers to NULL.
2230    CXXMemberInit
2231      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2232                                                 Loc, Loc,
2233                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2234                                                 Loc);
2235    return false;
2236  }
2237
2238  // Nothing to initialize.
2239  CXXMemberInit = 0;
2240  return false;
2241}
2242
2243namespace {
2244struct BaseAndFieldInfo {
2245  Sema &S;
2246  CXXConstructorDecl *Ctor;
2247  bool AnyErrorsInInits;
2248  ImplicitInitializerKind IIK;
2249  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2250  SmallVector<CXXCtorInitializer*, 8> AllToInit;
2251
2252  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2253    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2254    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2255    if (Generated && Ctor->isCopyConstructor())
2256      IIK = IIK_Copy;
2257    else if (Generated && Ctor->isMoveConstructor())
2258      IIK = IIK_Move;
2259    else
2260      IIK = IIK_Default;
2261  }
2262};
2263}
2264
2265static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
2266                                    FieldDecl *Field,
2267                                    IndirectFieldDecl *Indirect = 0) {
2268
2269  // Overwhelmingly common case: we have a direct initializer for this field.
2270  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
2271    Info.AllToInit.push_back(Init);
2272    return false;
2273  }
2274
2275  // C++0x [class.base.init]p8: if the entity is a non-static data member that
2276  // has a brace-or-equal-initializer, the entity is initialized as specified
2277  // in [dcl.init].
2278  if (Field->hasInClassInitializer()) {
2279    CXXCtorInitializer *Init;
2280    if (Indirect)
2281      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2282                                                      SourceLocation(),
2283                                                      SourceLocation(), 0,
2284                                                      SourceLocation());
2285    else
2286      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2287                                                      SourceLocation(),
2288                                                      SourceLocation(), 0,
2289                                                      SourceLocation());
2290    Info.AllToInit.push_back(Init);
2291    return false;
2292  }
2293
2294  // Don't build an implicit initializer for union members if none was
2295  // explicitly specified.
2296  if (Field->getParent()->isUnion())
2297    return false;
2298
2299  // Don't try to build an implicit initializer if there were semantic
2300  // errors in any of the initializers (and therefore we might be
2301  // missing some that the user actually wrote).
2302  if (Info.AnyErrorsInInits || Field->isInvalidDecl())
2303    return false;
2304
2305  CXXCtorInitializer *Init = 0;
2306  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2307                                     Indirect, Init))
2308    return true;
2309
2310  if (Init)
2311    Info.AllToInit.push_back(Init);
2312
2313  return false;
2314}
2315
2316bool
2317Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2318                               CXXCtorInitializer *Initializer) {
2319  assert(Initializer->isDelegatingInitializer());
2320  Constructor->setNumCtorInitializers(1);
2321  CXXCtorInitializer **initializer =
2322    new (Context) CXXCtorInitializer*[1];
2323  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2324  Constructor->setCtorInitializers(initializer);
2325
2326  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2327    MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2328    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2329  }
2330
2331  DelegatingCtorDecls.push_back(Constructor);
2332
2333  return false;
2334}
2335
2336bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2337                               CXXCtorInitializer **Initializers,
2338                               unsigned NumInitializers,
2339                               bool AnyErrors) {
2340  if (Constructor->getDeclContext()->isDependentContext()) {
2341    // Just store the initializers as written, they will be checked during
2342    // instantiation.
2343    if (NumInitializers > 0) {
2344      Constructor->setNumCtorInitializers(NumInitializers);
2345      CXXCtorInitializer **baseOrMemberInitializers =
2346        new (Context) CXXCtorInitializer*[NumInitializers];
2347      memcpy(baseOrMemberInitializers, Initializers,
2348             NumInitializers * sizeof(CXXCtorInitializer*));
2349      Constructor->setCtorInitializers(baseOrMemberInitializers);
2350    }
2351
2352    return false;
2353  }
2354
2355  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
2356
2357  // We need to build the initializer AST according to order of construction
2358  // and not what user specified in the Initializers list.
2359  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
2360  if (!ClassDecl)
2361    return true;
2362
2363  bool HadError = false;
2364
2365  for (unsigned i = 0; i < NumInitializers; i++) {
2366    CXXCtorInitializer *Member = Initializers[i];
2367
2368    if (Member->isBaseInitializer())
2369      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
2370    else
2371      Info.AllBaseFields[Member->getAnyMember()] = Member;
2372  }
2373
2374  // Keep track of the direct virtual bases.
2375  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2376  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2377       E = ClassDecl->bases_end(); I != E; ++I) {
2378    if (I->isVirtual())
2379      DirectVBases.insert(I);
2380  }
2381
2382  // Push virtual bases before others.
2383  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2384       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2385
2386    if (CXXCtorInitializer *Value
2387        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2388      Info.AllToInit.push_back(Value);
2389    } else if (!AnyErrors) {
2390      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
2391      CXXCtorInitializer *CXXBaseInit;
2392      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2393                                       VBase, IsInheritedVirtualBase,
2394                                       CXXBaseInit)) {
2395        HadError = true;
2396        continue;
2397      }
2398
2399      Info.AllToInit.push_back(CXXBaseInit);
2400    }
2401  }
2402
2403  // Non-virtual bases.
2404  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2405       E = ClassDecl->bases_end(); Base != E; ++Base) {
2406    // Virtuals are in the virtual base list and already constructed.
2407    if (Base->isVirtual())
2408      continue;
2409
2410    if (CXXCtorInitializer *Value
2411          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2412      Info.AllToInit.push_back(Value);
2413    } else if (!AnyErrors) {
2414      CXXCtorInitializer *CXXBaseInit;
2415      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2416                                       Base, /*IsInheritedVirtualBase=*/false,
2417                                       CXXBaseInit)) {
2418        HadError = true;
2419        continue;
2420      }
2421
2422      Info.AllToInit.push_back(CXXBaseInit);
2423    }
2424  }
2425
2426  // Fields.
2427  for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2428                               MemEnd = ClassDecl->decls_end();
2429       Mem != MemEnd; ++Mem) {
2430    if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
2431      if (F->getType()->isIncompleteArrayType()) {
2432        assert(ClassDecl->hasFlexibleArrayMember() &&
2433               "Incomplete array type is not valid");
2434        continue;
2435      }
2436
2437      // If we're not generating the implicit copy/move constructor, then we'll
2438      // handle anonymous struct/union fields based on their individual
2439      // indirect fields.
2440      if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2441        continue;
2442
2443      if (CollectFieldInitializer(*this, Info, F))
2444        HadError = true;
2445      continue;
2446    }
2447
2448    // Beyond this point, we only consider default initialization.
2449    if (Info.IIK != IIK_Default)
2450      continue;
2451
2452    if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2453      if (F->getType()->isIncompleteArrayType()) {
2454        assert(ClassDecl->hasFlexibleArrayMember() &&
2455               "Incomplete array type is not valid");
2456        continue;
2457      }
2458
2459      // Initialize each field of an anonymous struct individually.
2460      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2461        HadError = true;
2462
2463      continue;
2464    }
2465  }
2466
2467  NumInitializers = Info.AllToInit.size();
2468  if (NumInitializers > 0) {
2469    Constructor->setNumCtorInitializers(NumInitializers);
2470    CXXCtorInitializer **baseOrMemberInitializers =
2471      new (Context) CXXCtorInitializer*[NumInitializers];
2472    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
2473           NumInitializers * sizeof(CXXCtorInitializer*));
2474    Constructor->setCtorInitializers(baseOrMemberInitializers);
2475
2476    // Constructors implicitly reference the base and member
2477    // destructors.
2478    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2479                                           Constructor->getParent());
2480  }
2481
2482  return HadError;
2483}
2484
2485static void *GetKeyForTopLevelField(FieldDecl *Field) {
2486  // For anonymous unions, use the class declaration as the key.
2487  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
2488    if (RT->getDecl()->isAnonymousStructOrUnion())
2489      return static_cast<void *>(RT->getDecl());
2490  }
2491  return static_cast<void *>(Field);
2492}
2493
2494static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
2495  return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
2496}
2497
2498static void *GetKeyForMember(ASTContext &Context,
2499                             CXXCtorInitializer *Member) {
2500  if (!Member->isAnyMemberInitializer())
2501    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
2502
2503  // For fields injected into the class via declaration of an anonymous union,
2504  // use its anonymous union class declaration as the unique key.
2505  FieldDecl *Field = Member->getAnyMember();
2506
2507  // If the field is a member of an anonymous struct or union, our key
2508  // is the anonymous record decl that's a direct child of the class.
2509  RecordDecl *RD = Field->getParent();
2510  if (RD->isAnonymousStructOrUnion()) {
2511    while (true) {
2512      RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2513      if (Parent->isAnonymousStructOrUnion())
2514        RD = Parent;
2515      else
2516        break;
2517    }
2518
2519    return static_cast<void *>(RD);
2520  }
2521
2522  return static_cast<void *>(Field);
2523}
2524
2525static void
2526DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
2527                                  const CXXConstructorDecl *Constructor,
2528                                  CXXCtorInitializer **Inits,
2529                                  unsigned NumInits) {
2530  if (Constructor->getDeclContext()->isDependentContext())
2531    return;
2532
2533  // Don't check initializers order unless the warning is enabled at the
2534  // location of at least one initializer.
2535  bool ShouldCheckOrder = false;
2536  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2537    CXXCtorInitializer *Init = Inits[InitIndex];
2538    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2539                                         Init->getSourceLocation())
2540          != Diagnostic::Ignored) {
2541      ShouldCheckOrder = true;
2542      break;
2543    }
2544  }
2545  if (!ShouldCheckOrder)
2546    return;
2547
2548  // Build the list of bases and members in the order that they'll
2549  // actually be initialized.  The explicit initializers should be in
2550  // this same order but may be missing things.
2551  SmallVector<const void*, 32> IdealInitKeys;
2552
2553  const CXXRecordDecl *ClassDecl = Constructor->getParent();
2554
2555  // 1. Virtual bases.
2556  for (CXXRecordDecl::base_class_const_iterator VBase =
2557       ClassDecl->vbases_begin(),
2558       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
2559    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
2560
2561  // 2. Non-virtual bases.
2562  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
2563       E = ClassDecl->bases_end(); Base != E; ++Base) {
2564    if (Base->isVirtual())
2565      continue;
2566    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
2567  }
2568
2569  // 3. Direct fields.
2570  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2571       E = ClassDecl->field_end(); Field != E; ++Field)
2572    IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
2573
2574  unsigned NumIdealInits = IdealInitKeys.size();
2575  unsigned IdealIndex = 0;
2576
2577  CXXCtorInitializer *PrevInit = 0;
2578  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2579    CXXCtorInitializer *Init = Inits[InitIndex];
2580    void *InitKey = GetKeyForMember(SemaRef.Context, Init);
2581
2582    // Scan forward to try to find this initializer in the idealized
2583    // initializers list.
2584    for (; IdealIndex != NumIdealInits; ++IdealIndex)
2585      if (InitKey == IdealInitKeys[IdealIndex])
2586        break;
2587
2588    // If we didn't find this initializer, it must be because we
2589    // scanned past it on a previous iteration.  That can only
2590    // happen if we're out of order;  emit a warning.
2591    if (IdealIndex == NumIdealInits && PrevInit) {
2592      Sema::SemaDiagnosticBuilder D =
2593        SemaRef.Diag(PrevInit->getSourceLocation(),
2594                     diag::warn_initializer_out_of_order);
2595
2596      if (PrevInit->isAnyMemberInitializer())
2597        D << 0 << PrevInit->getAnyMember()->getDeclName();
2598      else
2599        D << 1 << PrevInit->getBaseClassInfo()->getType();
2600
2601      if (Init->isAnyMemberInitializer())
2602        D << 0 << Init->getAnyMember()->getDeclName();
2603      else
2604        D << 1 << Init->getBaseClassInfo()->getType();
2605
2606      // Move back to the initializer's location in the ideal list.
2607      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2608        if (InitKey == IdealInitKeys[IdealIndex])
2609          break;
2610
2611      assert(IdealIndex != NumIdealInits &&
2612             "initializer not found in initializer list");
2613    }
2614
2615    PrevInit = Init;
2616  }
2617}
2618
2619namespace {
2620bool CheckRedundantInit(Sema &S,
2621                        CXXCtorInitializer *Init,
2622                        CXXCtorInitializer *&PrevInit) {
2623  if (!PrevInit) {
2624    PrevInit = Init;
2625    return false;
2626  }
2627
2628  if (FieldDecl *Field = Init->getMember())
2629    S.Diag(Init->getSourceLocation(),
2630           diag::err_multiple_mem_initialization)
2631      << Field->getDeclName()
2632      << Init->getSourceRange();
2633  else {
2634    const Type *BaseClass = Init->getBaseClass();
2635    assert(BaseClass && "neither field nor base");
2636    S.Diag(Init->getSourceLocation(),
2637           diag::err_multiple_base_initialization)
2638      << QualType(BaseClass, 0)
2639      << Init->getSourceRange();
2640  }
2641  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2642    << 0 << PrevInit->getSourceRange();
2643
2644  return true;
2645}
2646
2647typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
2648typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2649
2650bool CheckRedundantUnionInit(Sema &S,
2651                             CXXCtorInitializer *Init,
2652                             RedundantUnionMap &Unions) {
2653  FieldDecl *Field = Init->getAnyMember();
2654  RecordDecl *Parent = Field->getParent();
2655  if (!Parent->isAnonymousStructOrUnion())
2656    return false;
2657
2658  NamedDecl *Child = Field;
2659  do {
2660    if (Parent->isUnion()) {
2661      UnionEntry &En = Unions[Parent];
2662      if (En.first && En.first != Child) {
2663        S.Diag(Init->getSourceLocation(),
2664               diag::err_multiple_mem_union_initialization)
2665          << Field->getDeclName()
2666          << Init->getSourceRange();
2667        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2668          << 0 << En.second->getSourceRange();
2669        return true;
2670      } else if (!En.first) {
2671        En.first = Child;
2672        En.second = Init;
2673      }
2674    }
2675
2676    Child = Parent;
2677    Parent = cast<RecordDecl>(Parent->getDeclContext());
2678  } while (Parent->isAnonymousStructOrUnion());
2679
2680  return false;
2681}
2682}
2683
2684/// ActOnMemInitializers - Handle the member initializers for a constructor.
2685void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
2686                                SourceLocation ColonLoc,
2687                                CXXCtorInitializer **meminits,
2688                                unsigned NumMemInits,
2689                                bool AnyErrors) {
2690  if (!ConstructorDecl)
2691    return;
2692
2693  AdjustDeclIfTemplate(ConstructorDecl);
2694
2695  CXXConstructorDecl *Constructor
2696    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
2697
2698  if (!Constructor) {
2699    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2700    return;
2701  }
2702
2703  CXXCtorInitializer **MemInits =
2704    reinterpret_cast<CXXCtorInitializer **>(meminits);
2705
2706  // Mapping for the duplicate initializers check.
2707  // For member initializers, this is keyed with a FieldDecl*.
2708  // For base initializers, this is keyed with a Type*.
2709  llvm::DenseMap<void*, CXXCtorInitializer *> Members;
2710
2711  // Mapping for the inconsistent anonymous-union initializers check.
2712  RedundantUnionMap MemberUnions;
2713
2714  bool HadError = false;
2715  for (unsigned i = 0; i < NumMemInits; i++) {
2716    CXXCtorInitializer *Init = MemInits[i];
2717
2718    // Set the source order index.
2719    Init->setSourceOrder(i);
2720
2721    if (Init->isAnyMemberInitializer()) {
2722      FieldDecl *Field = Init->getAnyMember();
2723      if (CheckRedundantInit(*this, Init, Members[Field]) ||
2724          CheckRedundantUnionInit(*this, Init, MemberUnions))
2725        HadError = true;
2726    } else if (Init->isBaseInitializer()) {
2727      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2728      if (CheckRedundantInit(*this, Init, Members[Key]))
2729        HadError = true;
2730    } else {
2731      assert(Init->isDelegatingInitializer());
2732      // This must be the only initializer
2733      if (i != 0 || NumMemInits > 1) {
2734        Diag(MemInits[0]->getSourceLocation(),
2735             diag::err_delegating_initializer_alone)
2736          << MemInits[0]->getSourceRange();
2737        HadError = true;
2738        // We will treat this as being the only initializer.
2739      }
2740      SetDelegatingInitializer(Constructor, MemInits[i]);
2741      // Return immediately as the initializer is set.
2742      return;
2743    }
2744  }
2745
2746  if (HadError)
2747    return;
2748
2749  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
2750
2751  SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
2752}
2753
2754void
2755Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2756                                             CXXRecordDecl *ClassDecl) {
2757  // Ignore dependent contexts. Also ignore unions, since their members never
2758  // have destructors implicitly called.
2759  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
2760    return;
2761
2762  // FIXME: all the access-control diagnostics are positioned on the
2763  // field/base declaration.  That's probably good; that said, the
2764  // user might reasonably want to know why the destructor is being
2765  // emitted, and we currently don't say.
2766
2767  // Non-static data members.
2768  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2769       E = ClassDecl->field_end(); I != E; ++I) {
2770    FieldDecl *Field = *I;
2771    if (Field->isInvalidDecl())
2772      continue;
2773    QualType FieldType = Context.getBaseElementType(Field->getType());
2774
2775    const RecordType* RT = FieldType->getAs<RecordType>();
2776    if (!RT)
2777      continue;
2778
2779    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2780    if (FieldClassDecl->isInvalidDecl())
2781      continue;
2782    if (FieldClassDecl->hasTrivialDestructor())
2783      continue;
2784
2785    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
2786    assert(Dtor && "No dtor found for FieldClassDecl!");
2787    CheckDestructorAccess(Field->getLocation(), Dtor,
2788                          PDiag(diag::err_access_dtor_field)
2789                            << Field->getDeclName()
2790                            << FieldType);
2791
2792    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2793  }
2794
2795  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2796
2797  // Bases.
2798  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2799       E = ClassDecl->bases_end(); Base != E; ++Base) {
2800    // Bases are always records in a well-formed non-dependent class.
2801    const RecordType *RT = Base->getType()->getAs<RecordType>();
2802
2803    // Remember direct virtual bases.
2804    if (Base->isVirtual())
2805      DirectVirtualBases.insert(RT);
2806
2807    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2808    // If our base class is invalid, we probably can't get its dtor anyway.
2809    if (BaseClassDecl->isInvalidDecl())
2810      continue;
2811    // Ignore trivial destructors.
2812    if (BaseClassDecl->hasTrivialDestructor())
2813      continue;
2814
2815    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2816    assert(Dtor && "No dtor found for BaseClassDecl!");
2817
2818    // FIXME: caret should be on the start of the class name
2819    CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
2820                          PDiag(diag::err_access_dtor_base)
2821                            << Base->getType()
2822                            << Base->getSourceRange());
2823
2824    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2825  }
2826
2827  // Virtual bases.
2828  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2829       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2830
2831    // Bases are always records in a well-formed non-dependent class.
2832    const RecordType *RT = VBase->getType()->getAs<RecordType>();
2833
2834    // Ignore direct virtual bases.
2835    if (DirectVirtualBases.count(RT))
2836      continue;
2837
2838    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2839    // If our base class is invalid, we probably can't get its dtor anyway.
2840    if (BaseClassDecl->isInvalidDecl())
2841      continue;
2842    // Ignore trivial destructors.
2843    if (BaseClassDecl->hasTrivialDestructor())
2844      continue;
2845
2846    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2847    assert(Dtor && "No dtor found for BaseClassDecl!");
2848    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
2849                          PDiag(diag::err_access_dtor_vbase)
2850                            << VBase->getType());
2851
2852    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2853  }
2854}
2855
2856void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
2857  if (!CDtorDecl)
2858    return;
2859
2860  if (CXXConstructorDecl *Constructor
2861      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
2862    SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
2863}
2864
2865bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2866                                  unsigned DiagID, AbstractDiagSelID SelID) {
2867  if (SelID == -1)
2868    return RequireNonAbstractType(Loc, T, PDiag(DiagID));
2869  else
2870    return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
2871}
2872
2873bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2874                                  const PartialDiagnostic &PD) {
2875  if (!getLangOptions().CPlusPlus)
2876    return false;
2877
2878  if (const ArrayType *AT = Context.getAsArrayType(T))
2879    return RequireNonAbstractType(Loc, AT->getElementType(), PD);
2880
2881  if (const PointerType *PT = T->getAs<PointerType>()) {
2882    // Find the innermost pointer type.
2883    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
2884      PT = T;
2885
2886    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
2887      return RequireNonAbstractType(Loc, AT->getElementType(), PD);
2888  }
2889
2890  const RecordType *RT = T->getAs<RecordType>();
2891  if (!RT)
2892    return false;
2893
2894  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2895
2896  // We can't answer whether something is abstract until it has a
2897  // definition.  If it's currently being defined, we'll walk back
2898  // over all the declarations when we have a full definition.
2899  const CXXRecordDecl *Def = RD->getDefinition();
2900  if (!Def || Def->isBeingDefined())
2901    return false;
2902
2903  if (!RD->isAbstract())
2904    return false;
2905
2906  Diag(Loc, PD) << RD->getDeclName();
2907  DiagnoseAbstractType(RD);
2908
2909  return true;
2910}
2911
2912void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2913  // Check if we've already emitted the list of pure virtual functions
2914  // for this class.
2915  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2916    return;
2917
2918  CXXFinalOverriderMap FinalOverriders;
2919  RD->getFinalOverriders(FinalOverriders);
2920
2921  // Keep a set of seen pure methods so we won't diagnose the same method
2922  // more than once.
2923  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2924
2925  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2926                                   MEnd = FinalOverriders.end();
2927       M != MEnd;
2928       ++M) {
2929    for (OverridingMethods::iterator SO = M->second.begin(),
2930                                  SOEnd = M->second.end();
2931         SO != SOEnd; ++SO) {
2932      // C++ [class.abstract]p4:
2933      //   A class is abstract if it contains or inherits at least one
2934      //   pure virtual function for which the final overrider is pure
2935      //   virtual.
2936
2937      //
2938      if (SO->second.size() != 1)
2939        continue;
2940
2941      if (!SO->second.front().Method->isPure())
2942        continue;
2943
2944      if (!SeenPureMethods.insert(SO->second.front().Method))
2945        continue;
2946
2947      Diag(SO->second.front().Method->getLocation(),
2948           diag::note_pure_virtual_function)
2949        << SO->second.front().Method->getDeclName() << RD->getDeclName();
2950    }
2951  }
2952
2953  if (!PureVirtualClassDiagSet)
2954    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2955  PureVirtualClassDiagSet->insert(RD);
2956}
2957
2958namespace {
2959struct AbstractUsageInfo {
2960  Sema &S;
2961  CXXRecordDecl *Record;
2962  CanQualType AbstractType;
2963  bool Invalid;
2964
2965  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2966    : S(S), Record(Record),
2967      AbstractType(S.Context.getCanonicalType(
2968                   S.Context.getTypeDeclType(Record))),
2969      Invalid(false) {}
2970
2971  void DiagnoseAbstractType() {
2972    if (Invalid) return;
2973    S.DiagnoseAbstractType(Record);
2974    Invalid = true;
2975  }
2976
2977  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2978};
2979
2980struct CheckAbstractUsage {
2981  AbstractUsageInfo &Info;
2982  const NamedDecl *Ctx;
2983
2984  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2985    : Info(Info), Ctx(Ctx) {}
2986
2987  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2988    switch (TL.getTypeLocClass()) {
2989#define ABSTRACT_TYPELOC(CLASS, PARENT)
2990#define TYPELOC(CLASS, PARENT) \
2991    case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2992#include "clang/AST/TypeLocNodes.def"
2993    }
2994  }
2995
2996  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2997    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2998    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2999      if (!TL.getArg(I))
3000        continue;
3001
3002      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3003      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3004    }
3005  }
3006
3007  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3008    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3009  }
3010
3011  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3012    // Visit the type parameters from a permissive context.
3013    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3014      TemplateArgumentLoc TAL = TL.getArgLoc(I);
3015      if (TAL.getArgument().getKind() == TemplateArgument::Type)
3016        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3017          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3018      // TODO: other template argument types?
3019    }
3020  }
3021
3022  // Visit pointee types from a permissive context.
3023#define CheckPolymorphic(Type) \
3024  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3025    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3026  }
3027  CheckPolymorphic(PointerTypeLoc)
3028  CheckPolymorphic(ReferenceTypeLoc)
3029  CheckPolymorphic(MemberPointerTypeLoc)
3030  CheckPolymorphic(BlockPointerTypeLoc)
3031
3032  /// Handle all the types we haven't given a more specific
3033  /// implementation for above.
3034  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3035    // Every other kind of type that we haven't called out already
3036    // that has an inner type is either (1) sugar or (2) contains that
3037    // inner type in some way as a subobject.
3038    if (TypeLoc Next = TL.getNextTypeLoc())
3039      return Visit(Next, Sel);
3040
3041    // If there's no inner type and we're in a permissive context,
3042    // don't diagnose.
3043    if (Sel == Sema::AbstractNone) return;
3044
3045    // Check whether the type matches the abstract type.
3046    QualType T = TL.getType();
3047    if (T->isArrayType()) {
3048      Sel = Sema::AbstractArrayType;
3049      T = Info.S.Context.getBaseElementType(T);
3050    }
3051    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3052    if (CT != Info.AbstractType) return;
3053
3054    // It matched; do some magic.
3055    if (Sel == Sema::AbstractArrayType) {
3056      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3057        << T << TL.getSourceRange();
3058    } else {
3059      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3060        << Sel << T << TL.getSourceRange();
3061    }
3062    Info.DiagnoseAbstractType();
3063  }
3064};
3065
3066void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3067                                  Sema::AbstractDiagSelID Sel) {
3068  CheckAbstractUsage(*this, D).Visit(TL, Sel);
3069}
3070
3071}
3072
3073/// Check for invalid uses of an abstract type in a method declaration.
3074static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3075                                    CXXMethodDecl *MD) {
3076  // No need to do the check on definitions, which require that
3077  // the return/param types be complete.
3078  if (MD->doesThisDeclarationHaveABody())
3079    return;
3080
3081  // For safety's sake, just ignore it if we don't have type source
3082  // information.  This should never happen for non-implicit methods,
3083  // but...
3084  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3085    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3086}
3087
3088/// Check for invalid uses of an abstract type within a class definition.
3089static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3090                                    CXXRecordDecl *RD) {
3091  for (CXXRecordDecl::decl_iterator
3092         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3093    Decl *D = *I;
3094    if (D->isImplicit()) continue;
3095
3096    // Methods and method templates.
3097    if (isa<CXXMethodDecl>(D)) {
3098      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3099    } else if (isa<FunctionTemplateDecl>(D)) {
3100      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3101      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3102
3103    // Fields and static variables.
3104    } else if (isa<FieldDecl>(D)) {
3105      FieldDecl *FD = cast<FieldDecl>(D);
3106      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3107        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3108    } else if (isa<VarDecl>(D)) {
3109      VarDecl *VD = cast<VarDecl>(D);
3110      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3111        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3112
3113    // Nested classes and class templates.
3114    } else if (isa<CXXRecordDecl>(D)) {
3115      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3116    } else if (isa<ClassTemplateDecl>(D)) {
3117      CheckAbstractClassUsage(Info,
3118                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3119    }
3120  }
3121}
3122
3123/// \brief Perform semantic checks on a class definition that has been
3124/// completing, introducing implicitly-declared members, checking for
3125/// abstract types, etc.
3126void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3127  if (!Record)
3128    return;
3129
3130  if (Record->isAbstract() && !Record->isInvalidDecl()) {
3131    AbstractUsageInfo Info(*this, Record);
3132    CheckAbstractClassUsage(Info, Record);
3133  }
3134
3135  // If this is not an aggregate type and has no user-declared constructor,
3136  // complain about any non-static data members of reference or const scalar
3137  // type, since they will never get initializers.
3138  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3139      !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3140    bool Complained = false;
3141    for (RecordDecl::field_iterator F = Record->field_begin(),
3142                                 FEnd = Record->field_end();
3143         F != FEnd; ++F) {
3144      if (F->hasInClassInitializer())
3145        continue;
3146
3147      if (F->getType()->isReferenceType() ||
3148          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3149        if (!Complained) {
3150          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3151            << Record->getTagKind() << Record;
3152          Complained = true;
3153        }
3154
3155        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3156          << F->getType()->isReferenceType()
3157          << F->getDeclName();
3158      }
3159    }
3160  }
3161
3162  if (Record->isDynamicClass() && !Record->isDependentType())
3163    DynamicClasses.push_back(Record);
3164
3165  if (Record->getIdentifier()) {
3166    // C++ [class.mem]p13:
3167    //   If T is the name of a class, then each of the following shall have a
3168    //   name different from T:
3169    //     - every member of every anonymous union that is a member of class T.
3170    //
3171    // C++ [class.mem]p14:
3172    //   In addition, if class T has a user-declared constructor (12.1), every
3173    //   non-static data member of class T shall have a name different from T.
3174    for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3175         R.first != R.second; ++R.first) {
3176      NamedDecl *D = *R.first;
3177      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3178          isa<IndirectFieldDecl>(D)) {
3179        Diag(D->getLocation(), diag::err_member_name_of_class)
3180          << D->getDeclName();
3181        break;
3182      }
3183    }
3184  }
3185
3186  // Warn if the class has virtual methods but non-virtual public destructor.
3187  if (Record->isPolymorphic() && !Record->isDependentType()) {
3188    CXXDestructorDecl *dtor = Record->getDestructor();
3189    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3190      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3191           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3192  }
3193
3194  // See if a method overloads virtual methods in a base
3195  /// class without overriding any.
3196  if (!Record->isDependentType()) {
3197    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3198                                     MEnd = Record->method_end();
3199         M != MEnd; ++M) {
3200      if (!(*M)->isStatic())
3201        DiagnoseHiddenVirtualMethods(Record, *M);
3202    }
3203  }
3204
3205  // Declare inherited constructors. We do this eagerly here because:
3206  // - The standard requires an eager diagnostic for conflicting inherited
3207  //   constructors from different classes.
3208  // - The lazy declaration of the other implicit constructors is so as to not
3209  //   waste space and performance on classes that are not meant to be
3210  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
3211  //   have inherited constructors.
3212  DeclareInheritedConstructors(Record);
3213
3214  if (!Record->isDependentType())
3215    CheckExplicitlyDefaultedMethods(Record);
3216}
3217
3218void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3219  for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3220                                      ME = Record->method_end();
3221       MI != ME; ++MI) {
3222    if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3223      switch (getSpecialMember(*MI)) {
3224      case CXXDefaultConstructor:
3225        CheckExplicitlyDefaultedDefaultConstructor(
3226                                                  cast<CXXConstructorDecl>(*MI));
3227        break;
3228
3229      case CXXDestructor:
3230        CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3231        break;
3232
3233      case CXXCopyConstructor:
3234        CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3235        break;
3236
3237      case CXXCopyAssignment:
3238        CheckExplicitlyDefaultedCopyAssignment(*MI);
3239        break;
3240
3241      case CXXMoveConstructor:
3242        CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
3243        break;
3244
3245      case CXXMoveAssignment:
3246        CheckExplicitlyDefaultedMoveAssignment(*MI);
3247        break;
3248
3249      case CXXInvalid:
3250        llvm_unreachable("non-special member explicitly defaulted!");
3251      }
3252    }
3253  }
3254
3255}
3256
3257void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3258  assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3259
3260  // Whether this was the first-declared instance of the constructor.
3261  // This affects whether we implicitly add an exception spec (and, eventually,
3262  // constexpr). It is also ill-formed to explicitly default a constructor such
3263  // that it would be deleted. (C++0x [decl.fct.def.default])
3264  bool First = CD == CD->getCanonicalDecl();
3265
3266  bool HadError = false;
3267  if (CD->getNumParams() != 0) {
3268    Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3269      << CD->getSourceRange();
3270    HadError = true;
3271  }
3272
3273  ImplicitExceptionSpecification Spec
3274    = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3275  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3276  if (EPI.ExceptionSpecType == EST_Delayed) {
3277    // Exception specification depends on some deferred part of the class. We'll
3278    // try again when the class's definition has been fully processed.
3279    return;
3280  }
3281  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3282                          *ExceptionType = Context.getFunctionType(
3283                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3284
3285  if (CtorType->hasExceptionSpec()) {
3286    if (CheckEquivalentExceptionSpec(
3287          PDiag(diag::err_incorrect_defaulted_exception_spec)
3288            << CXXDefaultConstructor,
3289          PDiag(),
3290          ExceptionType, SourceLocation(),
3291          CtorType, CD->getLocation())) {
3292      HadError = true;
3293    }
3294  } else if (First) {
3295    // We set the declaration to have the computed exception spec here.
3296    // We know there are no parameters.
3297    EPI.ExtInfo = CtorType->getExtInfo();
3298    CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3299  }
3300
3301  if (HadError) {
3302    CD->setInvalidDecl();
3303    return;
3304  }
3305
3306  if (ShouldDeleteDefaultConstructor(CD)) {
3307    if (First) {
3308      CD->setDeletedAsWritten();
3309    } else {
3310      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3311        << CXXDefaultConstructor;
3312      CD->setInvalidDecl();
3313    }
3314  }
3315}
3316
3317void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3318  assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3319
3320  // Whether this was the first-declared instance of the constructor.
3321  bool First = CD == CD->getCanonicalDecl();
3322
3323  bool HadError = false;
3324  if (CD->getNumParams() != 1) {
3325    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3326      << CD->getSourceRange();
3327    HadError = true;
3328  }
3329
3330  ImplicitExceptionSpecification Spec(Context);
3331  bool Const;
3332  llvm::tie(Spec, Const) =
3333    ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3334
3335  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3336  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3337                          *ExceptionType = Context.getFunctionType(
3338                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3339
3340  // Check for parameter type matching.
3341  // This is a copy ctor so we know it's a cv-qualified reference to T.
3342  QualType ArgType = CtorType->getArgType(0);
3343  if (ArgType->getPointeeType().isVolatileQualified()) {
3344    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3345    HadError = true;
3346  }
3347  if (ArgType->getPointeeType().isConstQualified() && !Const) {
3348    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3349    HadError = true;
3350  }
3351
3352  if (CtorType->hasExceptionSpec()) {
3353    if (CheckEquivalentExceptionSpec(
3354          PDiag(diag::err_incorrect_defaulted_exception_spec)
3355            << CXXCopyConstructor,
3356          PDiag(),
3357          ExceptionType, SourceLocation(),
3358          CtorType, CD->getLocation())) {
3359      HadError = true;
3360    }
3361  } else if (First) {
3362    // We set the declaration to have the computed exception spec here.
3363    // We duplicate the one parameter type.
3364    EPI.ExtInfo = CtorType->getExtInfo();
3365    CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3366  }
3367
3368  if (HadError) {
3369    CD->setInvalidDecl();
3370    return;
3371  }
3372
3373  if (ShouldDeleteCopyConstructor(CD)) {
3374    if (First) {
3375      CD->setDeletedAsWritten();
3376    } else {
3377      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3378        << CXXCopyConstructor;
3379      CD->setInvalidDecl();
3380    }
3381  }
3382}
3383
3384void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3385  assert(MD->isExplicitlyDefaulted());
3386
3387  // Whether this was the first-declared instance of the operator
3388  bool First = MD == MD->getCanonicalDecl();
3389
3390  bool HadError = false;
3391  if (MD->getNumParams() != 1) {
3392    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3393      << MD->getSourceRange();
3394    HadError = true;
3395  }
3396
3397  QualType ReturnType =
3398    MD->getType()->getAs<FunctionType>()->getResultType();
3399  if (!ReturnType->isLValueReferenceType() ||
3400      !Context.hasSameType(
3401        Context.getCanonicalType(ReturnType->getPointeeType()),
3402        Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3403    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3404    HadError = true;
3405  }
3406
3407  ImplicitExceptionSpecification Spec(Context);
3408  bool Const;
3409  llvm::tie(Spec, Const) =
3410    ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3411
3412  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3413  const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3414                          *ExceptionType = Context.getFunctionType(
3415                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3416
3417  QualType ArgType = OperType->getArgType(0);
3418  if (!ArgType->isLValueReferenceType()) {
3419    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
3420    HadError = true;
3421  } else {
3422    if (ArgType->getPointeeType().isVolatileQualified()) {
3423      Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3424      HadError = true;
3425    }
3426    if (ArgType->getPointeeType().isConstQualified() && !Const) {
3427      Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3428      HadError = true;
3429    }
3430  }
3431
3432  if (OperType->getTypeQuals()) {
3433    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3434    HadError = true;
3435  }
3436
3437  if (OperType->hasExceptionSpec()) {
3438    if (CheckEquivalentExceptionSpec(
3439          PDiag(diag::err_incorrect_defaulted_exception_spec)
3440            << CXXCopyAssignment,
3441          PDiag(),
3442          ExceptionType, SourceLocation(),
3443          OperType, MD->getLocation())) {
3444      HadError = true;
3445    }
3446  } else if (First) {
3447    // We set the declaration to have the computed exception spec here.
3448    // We duplicate the one parameter type.
3449    EPI.RefQualifier = OperType->getRefQualifier();
3450    EPI.ExtInfo = OperType->getExtInfo();
3451    MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3452  }
3453
3454  if (HadError) {
3455    MD->setInvalidDecl();
3456    return;
3457  }
3458
3459  if (ShouldDeleteCopyAssignmentOperator(MD)) {
3460    if (First) {
3461      MD->setDeletedAsWritten();
3462    } else {
3463      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3464        << CXXCopyAssignment;
3465      MD->setInvalidDecl();
3466    }
3467  }
3468}
3469
3470void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
3471  assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
3472
3473  // Whether this was the first-declared instance of the constructor.
3474  bool First = CD == CD->getCanonicalDecl();
3475
3476  bool HadError = false;
3477  if (CD->getNumParams() != 1) {
3478    Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
3479      << CD->getSourceRange();
3480    HadError = true;
3481  }
3482
3483  ImplicitExceptionSpecification Spec(
3484      ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
3485
3486  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3487  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3488                          *ExceptionType = Context.getFunctionType(
3489                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3490
3491  // Check for parameter type matching.
3492  // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
3493  QualType ArgType = CtorType->getArgType(0);
3494  if (ArgType->getPointeeType().isVolatileQualified()) {
3495    Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
3496    HadError = true;
3497  }
3498  if (ArgType->getPointeeType().isConstQualified()) {
3499    Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
3500    HadError = true;
3501  }
3502
3503  if (CtorType->hasExceptionSpec()) {
3504    if (CheckEquivalentExceptionSpec(
3505          PDiag(diag::err_incorrect_defaulted_exception_spec)
3506            << CXXMoveConstructor,
3507          PDiag(),
3508          ExceptionType, SourceLocation(),
3509          CtorType, CD->getLocation())) {
3510      HadError = true;
3511    }
3512  } else if (First) {
3513    // We set the declaration to have the computed exception spec here.
3514    // We duplicate the one parameter type.
3515    EPI.ExtInfo = CtorType->getExtInfo();
3516    CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3517  }
3518
3519  if (HadError) {
3520    CD->setInvalidDecl();
3521    return;
3522  }
3523
3524  if (ShouldDeleteMoveConstructor(CD)) {
3525    if (First) {
3526      CD->setDeletedAsWritten();
3527    } else {
3528      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3529        << CXXMoveConstructor;
3530      CD->setInvalidDecl();
3531    }
3532  }
3533}
3534
3535void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
3536  assert(MD->isExplicitlyDefaulted());
3537
3538  // Whether this was the first-declared instance of the operator
3539  bool First = MD == MD->getCanonicalDecl();
3540
3541  bool HadError = false;
3542  if (MD->getNumParams() != 1) {
3543    Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
3544      << MD->getSourceRange();
3545    HadError = true;
3546  }
3547
3548  QualType ReturnType =
3549    MD->getType()->getAs<FunctionType>()->getResultType();
3550  if (!ReturnType->isLValueReferenceType() ||
3551      !Context.hasSameType(
3552        Context.getCanonicalType(ReturnType->getPointeeType()),
3553        Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3554    Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
3555    HadError = true;
3556  }
3557
3558  ImplicitExceptionSpecification Spec(
3559      ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
3560
3561  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3562  const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3563                          *ExceptionType = Context.getFunctionType(
3564                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3565
3566  QualType ArgType = OperType->getArgType(0);
3567  if (!ArgType->isRValueReferenceType()) {
3568    Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
3569    HadError = true;
3570  } else {
3571    if (ArgType->getPointeeType().isVolatileQualified()) {
3572      Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
3573      HadError = true;
3574    }
3575    if (ArgType->getPointeeType().isConstQualified()) {
3576      Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
3577      HadError = true;
3578    }
3579  }
3580
3581  if (OperType->getTypeQuals()) {
3582    Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
3583    HadError = true;
3584  }
3585
3586  if (OperType->hasExceptionSpec()) {
3587    if (CheckEquivalentExceptionSpec(
3588          PDiag(diag::err_incorrect_defaulted_exception_spec)
3589            << CXXMoveAssignment,
3590          PDiag(),
3591          ExceptionType, SourceLocation(),
3592          OperType, MD->getLocation())) {
3593      HadError = true;
3594    }
3595  } else if (First) {
3596    // We set the declaration to have the computed exception spec here.
3597    // We duplicate the one parameter type.
3598    EPI.RefQualifier = OperType->getRefQualifier();
3599    EPI.ExtInfo = OperType->getExtInfo();
3600    MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3601  }
3602
3603  if (HadError) {
3604    MD->setInvalidDecl();
3605    return;
3606  }
3607
3608  if (ShouldDeleteMoveAssignmentOperator(MD)) {
3609    if (First) {
3610      MD->setDeletedAsWritten();
3611    } else {
3612      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3613        << CXXMoveAssignment;
3614      MD->setInvalidDecl();
3615    }
3616  }
3617}
3618
3619void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3620  assert(DD->isExplicitlyDefaulted());
3621
3622  // Whether this was the first-declared instance of the destructor.
3623  bool First = DD == DD->getCanonicalDecl();
3624
3625  ImplicitExceptionSpecification Spec
3626    = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3627  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3628  const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3629                          *ExceptionType = Context.getFunctionType(
3630                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3631
3632  if (DtorType->hasExceptionSpec()) {
3633    if (CheckEquivalentExceptionSpec(
3634          PDiag(diag::err_incorrect_defaulted_exception_spec)
3635            << CXXDestructor,
3636          PDiag(),
3637          ExceptionType, SourceLocation(),
3638          DtorType, DD->getLocation())) {
3639      DD->setInvalidDecl();
3640      return;
3641    }
3642  } else if (First) {
3643    // We set the declaration to have the computed exception spec here.
3644    // There are no parameters.
3645    EPI.ExtInfo = DtorType->getExtInfo();
3646    DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3647  }
3648
3649  if (ShouldDeleteDestructor(DD)) {
3650    if (First) {
3651      DD->setDeletedAsWritten();
3652    } else {
3653      Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
3654        << CXXDestructor;
3655      DD->setInvalidDecl();
3656    }
3657  }
3658}
3659
3660bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3661  CXXRecordDecl *RD = CD->getParent();
3662  assert(!RD->isDependentType() && "do deletion after instantiation");
3663  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
3664    return false;
3665
3666  SourceLocation Loc = CD->getLocation();
3667
3668  // Do access control from the constructor
3669  ContextRAII CtorContext(*this, CD);
3670
3671  bool Union = RD->isUnion();
3672  bool AllConst = true;
3673
3674  // We do this because we should never actually use an anonymous
3675  // union's constructor.
3676  if (Union && RD->isAnonymousStructOrUnion())
3677    return false;
3678
3679  // FIXME: We should put some diagnostic logic right into this function.
3680
3681  // C++0x [class.ctor]/5
3682  //    A defaulted default constructor for class X is defined as deleted if:
3683
3684  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3685                                          BE = RD->bases_end();
3686       BI != BE; ++BI) {
3687    // We'll handle this one later
3688    if (BI->isVirtual())
3689      continue;
3690
3691    CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3692    assert(BaseDecl && "base isn't a CXXRecordDecl");
3693
3694    // -- any [direct base class] has a type with a destructor that is
3695    //    deleted or inaccessible from the defaulted default constructor
3696    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3697    if (BaseDtor->isDeleted())
3698      return true;
3699    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3700        AR_accessible)
3701      return true;
3702
3703    // -- any [direct base class either] has no default constructor or
3704    //    overload resolution as applied to [its] default constructor
3705    //    results in an ambiguity or in a function that is deleted or
3706    //    inaccessible from the defaulted default constructor
3707    CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3708    if (!BaseDefault || BaseDefault->isDeleted())
3709      return true;
3710
3711    if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3712                               PDiag()) != AR_accessible)
3713      return true;
3714  }
3715
3716  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3717                                          BE = RD->vbases_end();
3718       BI != BE; ++BI) {
3719    CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3720    assert(BaseDecl && "base isn't a CXXRecordDecl");
3721
3722    // -- any [virtual base class] has a type with a destructor that is
3723    //    delete or inaccessible from the defaulted default constructor
3724    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3725    if (BaseDtor->isDeleted())
3726      return true;
3727    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3728        AR_accessible)
3729      return true;
3730
3731    // -- any [virtual base class either] has no default constructor or
3732    //    overload resolution as applied to [its] default constructor
3733    //    results in an ambiguity or in a function that is deleted or
3734    //    inaccessible from the defaulted default constructor
3735    CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3736    if (!BaseDefault || BaseDefault->isDeleted())
3737      return true;
3738
3739    if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3740                               PDiag()) != AR_accessible)
3741      return true;
3742  }
3743
3744  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3745                                     FE = RD->field_end();
3746       FI != FE; ++FI) {
3747    if (FI->isInvalidDecl())
3748      continue;
3749
3750    QualType FieldType = Context.getBaseElementType(FI->getType());
3751    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3752
3753    // -- any non-static data member with no brace-or-equal-initializer is of
3754    //    reference type
3755    if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
3756      return true;
3757
3758    // -- X is a union and all its variant members are of const-qualified type
3759    //    (or array thereof)
3760    if (Union && !FieldType.isConstQualified())
3761      AllConst = false;
3762
3763    if (FieldRecord) {
3764      // -- X is a union-like class that has a variant member with a non-trivial
3765      //    default constructor
3766      if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3767        return true;
3768
3769      CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3770      if (FieldDtor->isDeleted())
3771        return true;
3772      if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
3773          AR_accessible)
3774        return true;
3775
3776      // -- any non-variant non-static data member of const-qualified type (or
3777      //    array thereof) with no brace-or-equal-initializer does not have a
3778      //    user-provided default constructor
3779      if (FieldType.isConstQualified() &&
3780          !FI->hasInClassInitializer() &&
3781          !FieldRecord->hasUserProvidedDefaultConstructor())
3782        return true;
3783
3784      if (!Union && FieldRecord->isUnion() &&
3785          FieldRecord->isAnonymousStructOrUnion()) {
3786        // We're okay to reuse AllConst here since we only care about the
3787        // value otherwise if we're in a union.
3788        AllConst = true;
3789
3790        for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3791                                           UE = FieldRecord->field_end();
3792             UI != UE; ++UI) {
3793          QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3794          CXXRecordDecl *UnionFieldRecord =
3795            UnionFieldType->getAsCXXRecordDecl();
3796
3797          if (!UnionFieldType.isConstQualified())
3798            AllConst = false;
3799
3800          if (UnionFieldRecord &&
3801              !UnionFieldRecord->hasTrivialDefaultConstructor())
3802            return true;
3803        }
3804
3805        if (AllConst)
3806          return true;
3807
3808        // Don't try to initialize the anonymous union
3809        // This is technically non-conformant, but sanity demands it.
3810        continue;
3811      }
3812
3813      // -- any non-static data member with no brace-or-equal-initializer has
3814      //    class type M (or array thereof) and either M has no default
3815      //    constructor or overload resolution as applied to M's default
3816      //    constructor results in an ambiguity or in a function that is deleted
3817      //    or inaccessible from the defaulted default constructor.
3818      if (!FI->hasInClassInitializer()) {
3819        CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3820        if (!FieldDefault || FieldDefault->isDeleted())
3821          return true;
3822        if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3823                                   PDiag()) != AR_accessible)
3824          return true;
3825      }
3826    } else if (!Union && FieldType.isConstQualified() &&
3827               !FI->hasInClassInitializer()) {
3828      // -- any non-variant non-static data member of const-qualified type (or
3829      //    array thereof) with no brace-or-equal-initializer does not have a
3830      //    user-provided default constructor
3831      return true;
3832    }
3833  }
3834
3835  if (Union && AllConst)
3836    return true;
3837
3838  return false;
3839}
3840
3841bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
3842  CXXRecordDecl *RD = CD->getParent();
3843  assert(!RD->isDependentType() && "do deletion after instantiation");
3844  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
3845    return false;
3846
3847  SourceLocation Loc = CD->getLocation();
3848
3849  // Do access control from the constructor
3850  ContextRAII CtorContext(*this, CD);
3851
3852  bool Union = RD->isUnion();
3853
3854  assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3855         "copy assignment arg has no pointee type");
3856  unsigned ArgQuals =
3857    CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3858      Qualifiers::Const : 0;
3859
3860  // We do this because we should never actually use an anonymous
3861  // union's constructor.
3862  if (Union && RD->isAnonymousStructOrUnion())
3863    return false;
3864
3865  // FIXME: We should put some diagnostic logic right into this function.
3866
3867  // C++0x [class.copy]/11
3868  //    A defaulted [copy] constructor for class X is defined as delete if X has:
3869
3870  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3871                                          BE = RD->bases_end();
3872       BI != BE; ++BI) {
3873    // We'll handle this one later
3874    if (BI->isVirtual())
3875      continue;
3876
3877    QualType BaseType = BI->getType();
3878    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3879    assert(BaseDecl && "base isn't a CXXRecordDecl");
3880
3881    // -- any [direct base class] of a type with a destructor that is deleted or
3882    //    inaccessible from the defaulted constructor
3883    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3884    if (BaseDtor->isDeleted())
3885      return true;
3886    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3887        AR_accessible)
3888      return true;
3889
3890    // -- a [direct base class] B that cannot be [copied] because overload
3891    //    resolution, as applied to B's [copy] constructor, results in an
3892    //    ambiguity or a function that is deleted or inaccessible from the
3893    //    defaulted constructor
3894    CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
3895    if (!BaseCtor || BaseCtor->isDeleted())
3896      return true;
3897    if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3898        AR_accessible)
3899      return true;
3900  }
3901
3902  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3903                                          BE = RD->vbases_end();
3904       BI != BE; ++BI) {
3905    QualType BaseType = BI->getType();
3906    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3907    assert(BaseDecl && "base isn't a CXXRecordDecl");
3908
3909    // -- any [virtual base class] of a type with a destructor that is deleted or
3910    //    inaccessible from the defaulted constructor
3911    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3912    if (BaseDtor->isDeleted())
3913      return true;
3914    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3915        AR_accessible)
3916      return true;
3917
3918    // -- a [virtual base class] B that cannot be [copied] because overload
3919    //    resolution, as applied to B's [copy] constructor, results in an
3920    //    ambiguity or a function that is deleted or inaccessible from the
3921    //    defaulted constructor
3922    CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
3923    if (!BaseCtor || BaseCtor->isDeleted())
3924      return true;
3925    if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3926        AR_accessible)
3927      return true;
3928  }
3929
3930  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3931                                     FE = RD->field_end();
3932       FI != FE; ++FI) {
3933    QualType FieldType = Context.getBaseElementType(FI->getType());
3934
3935    // -- for a copy constructor, a non-static data member of rvalue reference
3936    //    type
3937    if (FieldType->isRValueReferenceType())
3938      return true;
3939
3940    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3941
3942    if (FieldRecord) {
3943      // This is an anonymous union
3944      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3945        // Anonymous unions inside unions do not variant members create
3946        if (!Union) {
3947          for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3948                                             UE = FieldRecord->field_end();
3949               UI != UE; ++UI) {
3950            QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3951            CXXRecordDecl *UnionFieldRecord =
3952              UnionFieldType->getAsCXXRecordDecl();
3953
3954            // -- a variant member with a non-trivial [copy] constructor and X
3955            //    is a union-like class
3956            if (UnionFieldRecord &&
3957                !UnionFieldRecord->hasTrivialCopyConstructor())
3958              return true;
3959          }
3960        }
3961
3962        // Don't try to initalize an anonymous union
3963        continue;
3964      } else {
3965         // -- a variant member with a non-trivial [copy] constructor and X is a
3966         //    union-like class
3967        if (Union && !FieldRecord->hasTrivialCopyConstructor())
3968          return true;
3969
3970        // -- any [non-static data member] of a type with a destructor that is
3971        //    deleted or inaccessible from the defaulted constructor
3972        CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3973        if (FieldDtor->isDeleted())
3974          return true;
3975        if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
3976            AR_accessible)
3977          return true;
3978      }
3979
3980    // -- a [non-static data member of class type (or array thereof)] B that
3981    //    cannot be [copied] because overload resolution, as applied to B's
3982    //    [copy] constructor, results in an ambiguity or a function that is
3983    //    deleted or inaccessible from the defaulted constructor
3984      CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
3985                                                               ArgQuals);
3986      if (!FieldCtor || FieldCtor->isDeleted())
3987        return true;
3988      if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
3989                                 PDiag()) != AR_accessible)
3990        return true;
3991    }
3992  }
3993
3994  return false;
3995}
3996
3997bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3998  CXXRecordDecl *RD = MD->getParent();
3999  assert(!RD->isDependentType() && "do deletion after instantiation");
4000  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4001    return false;
4002
4003  SourceLocation Loc = MD->getLocation();
4004
4005  // Do access control from the constructor
4006  ContextRAII MethodContext(*this, MD);
4007
4008  bool Union = RD->isUnion();
4009
4010  unsigned ArgQuals =
4011    MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4012      Qualifiers::Const : 0;
4013
4014  // We do this because we should never actually use an anonymous
4015  // union's constructor.
4016  if (Union && RD->isAnonymousStructOrUnion())
4017    return false;
4018
4019  // FIXME: We should put some diagnostic logic right into this function.
4020
4021  // C++0x [class.copy]/20
4022  //    A defaulted [copy] assignment operator for class X is defined as deleted
4023  //    if X has:
4024
4025  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4026                                          BE = RD->bases_end();
4027       BI != BE; ++BI) {
4028    // We'll handle this one later
4029    if (BI->isVirtual())
4030      continue;
4031
4032    QualType BaseType = BI->getType();
4033    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4034    assert(BaseDecl && "base isn't a CXXRecordDecl");
4035
4036    // -- a [direct base class] B that cannot be [copied] because overload
4037    //    resolution, as applied to B's [copy] assignment operator, results in
4038    //    an ambiguity or a function that is deleted or inaccessible from the
4039    //    assignment operator
4040    CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4041                                                      0);
4042    if (!CopyOper || CopyOper->isDeleted())
4043      return true;
4044    if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
4045      return true;
4046  }
4047
4048  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4049                                          BE = RD->vbases_end();
4050       BI != BE; ++BI) {
4051    QualType BaseType = BI->getType();
4052    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4053    assert(BaseDecl && "base isn't a CXXRecordDecl");
4054
4055    // -- a [virtual base class] B that cannot be [copied] because overload
4056    //    resolution, as applied to B's [copy] assignment operator, results in
4057    //    an ambiguity or a function that is deleted or inaccessible from the
4058    //    assignment operator
4059    CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4060                                                      0);
4061    if (!CopyOper || CopyOper->isDeleted())
4062      return true;
4063    if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
4064      return true;
4065  }
4066
4067  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4068                                     FE = RD->field_end();
4069       FI != FE; ++FI) {
4070    QualType FieldType = Context.getBaseElementType(FI->getType());
4071
4072    // -- a non-static data member of reference type
4073    if (FieldType->isReferenceType())
4074      return true;
4075
4076    // -- a non-static data member of const non-class type (or array thereof)
4077    if (FieldType.isConstQualified() && !FieldType->isRecordType())
4078      return true;
4079
4080    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4081
4082    if (FieldRecord) {
4083      // This is an anonymous union
4084      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4085        // Anonymous unions inside unions do not variant members create
4086        if (!Union) {
4087          for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4088                                             UE = FieldRecord->field_end();
4089               UI != UE; ++UI) {
4090            QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4091            CXXRecordDecl *UnionFieldRecord =
4092              UnionFieldType->getAsCXXRecordDecl();
4093
4094            // -- a variant member with a non-trivial [copy] assignment operator
4095            //    and X is a union-like class
4096            if (UnionFieldRecord &&
4097                !UnionFieldRecord->hasTrivialCopyAssignment())
4098              return true;
4099          }
4100        }
4101
4102        // Don't try to initalize an anonymous union
4103        continue;
4104      // -- a variant member with a non-trivial [copy] assignment operator
4105      //    and X is a union-like class
4106      } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4107          return true;
4108      }
4109
4110      CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4111                                                        false, 0);
4112      if (!CopyOper || CopyOper->isDeleted())
4113        return true;
4114      if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
4115        return true;
4116    }
4117  }
4118
4119  return false;
4120}
4121
4122bool Sema::ShouldDeleteMoveConstructor(CXXConstructorDecl *CD) {
4123  CXXRecordDecl *RD = CD->getParent();
4124  assert(!RD->isDependentType() && "do deletion after instantiation");
4125  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4126    return false;
4127
4128  SourceLocation Loc = CD->getLocation();
4129
4130  // Do access control from the constructor
4131  ContextRAII CtorContext(*this, CD);
4132
4133  bool Union = RD->isUnion();
4134
4135  assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
4136         "copy assignment arg has no pointee type");
4137
4138  // We do this because we should never actually use an anonymous
4139  // union's constructor.
4140  if (Union && RD->isAnonymousStructOrUnion())
4141    return false;
4142
4143  // C++0x [class.copy]/11
4144  //    A defaulted [move] constructor for class X is defined as deleted
4145  //    if X has:
4146
4147  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4148                                          BE = RD->bases_end();
4149       BI != BE; ++BI) {
4150    // We'll handle this one later
4151    if (BI->isVirtual())
4152      continue;
4153
4154    QualType BaseType = BI->getType();
4155    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4156    assert(BaseDecl && "base isn't a CXXRecordDecl");
4157
4158    // -- any [direct base class] of a type with a destructor that is deleted or
4159    //    inaccessible from the defaulted constructor
4160    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4161    if (BaseDtor->isDeleted())
4162      return true;
4163    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4164        AR_accessible)
4165      return true;
4166
4167    // -- a [direct base class] B that cannot be [moved] because overload
4168    //    resolution, as applied to B's [move] constructor, results in an
4169    //    ambiguity or a function that is deleted or inaccessible from the
4170    //    defaulted constructor
4171    CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4172    if (!BaseCtor || BaseCtor->isDeleted())
4173      return true;
4174    if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4175        AR_accessible)
4176      return true;
4177
4178    // -- for a move constructor, a [direct base class] with a type that
4179    //    does not have a move constructor and is not trivially copyable.
4180    // If the field isn't a record, it's always trivially copyable.
4181    // A moving constructor could be a copy constructor instead.
4182    if (!BaseCtor->isMoveConstructor() &&
4183        !BaseDecl->isTriviallyCopyable())
4184      return true;
4185  }
4186
4187  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4188                                          BE = RD->vbases_end();
4189       BI != BE; ++BI) {
4190    QualType BaseType = BI->getType();
4191    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4192    assert(BaseDecl && "base isn't a CXXRecordDecl");
4193
4194    // -- any [virtual base class] of a type with a destructor that is deleted
4195    //    or inaccessible from the defaulted constructor
4196    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4197    if (BaseDtor->isDeleted())
4198      return true;
4199    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4200        AR_accessible)
4201      return true;
4202
4203    // -- a [virtual base class] B that cannot be [moved] because overload
4204    //    resolution, as applied to B's [move] constructor, results in an
4205    //    ambiguity or a function that is deleted or inaccessible from the
4206    //    defaulted constructor
4207    CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4208    if (!BaseCtor || BaseCtor->isDeleted())
4209      return true;
4210    if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4211        AR_accessible)
4212      return true;
4213
4214    // -- for a move constructor, a [virtual base class] with a type that
4215    //    does not have a move constructor and is not trivially copyable.
4216    // If the field isn't a record, it's always trivially copyable.
4217    // A moving constructor could be a copy constructor instead.
4218    if (!BaseCtor->isMoveConstructor() &&
4219        !BaseDecl->isTriviallyCopyable())
4220      return true;
4221  }
4222
4223  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4224                                     FE = RD->field_end();
4225       FI != FE; ++FI) {
4226    QualType FieldType = Context.getBaseElementType(FI->getType());
4227
4228    if (CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl()) {
4229      // This is an anonymous union
4230      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4231        // Anonymous unions inside unions do not variant members create
4232        if (!Union) {
4233          for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4234                                             UE = FieldRecord->field_end();
4235               UI != UE; ++UI) {
4236            QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4237            CXXRecordDecl *UnionFieldRecord =
4238              UnionFieldType->getAsCXXRecordDecl();
4239
4240            // -- a variant member with a non-trivial [move] constructor and X
4241            //    is a union-like class
4242            if (UnionFieldRecord &&
4243                !UnionFieldRecord->hasTrivialMoveConstructor())
4244              return true;
4245          }
4246        }
4247
4248        // Don't try to initalize an anonymous union
4249        continue;
4250      } else {
4251         // -- a variant member with a non-trivial [move] constructor and X is a
4252         //    union-like class
4253        if (Union && !FieldRecord->hasTrivialMoveConstructor())
4254          return true;
4255
4256        // -- any [non-static data member] of a type with a destructor that is
4257        //    deleted or inaccessible from the defaulted constructor
4258        CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4259        if (FieldDtor->isDeleted())
4260          return true;
4261        if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4262            AR_accessible)
4263          return true;
4264      }
4265
4266      // -- a [non-static data member of class type (or array thereof)] B that
4267      //    cannot be [moved] because overload resolution, as applied to B's
4268      //    [move] constructor, results in an ambiguity or a function that is
4269      //    deleted or inaccessible from the defaulted constructor
4270      CXXConstructorDecl *FieldCtor = LookupMovingConstructor(FieldRecord);
4271      if (!FieldCtor || FieldCtor->isDeleted())
4272        return true;
4273      if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4274                                 PDiag()) != AR_accessible)
4275        return true;
4276
4277      // -- for a move constructor, a [non-static data member] with a type that
4278      //    does not have a move constructor and is not trivially copyable.
4279      // If the field isn't a record, it's always trivially copyable.
4280      // A moving constructor could be a copy constructor instead.
4281      if (!FieldCtor->isMoveConstructor() &&
4282          !FieldRecord->isTriviallyCopyable())
4283        return true;
4284    }
4285  }
4286
4287  return false;
4288}
4289
4290bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4291  CXXRecordDecl *RD = MD->getParent();
4292  assert(!RD->isDependentType() && "do deletion after instantiation");
4293  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4294    return false;
4295
4296  SourceLocation Loc = MD->getLocation();
4297
4298  // Do access control from the constructor
4299  ContextRAII MethodContext(*this, MD);
4300
4301  bool Union = RD->isUnion();
4302
4303  // We do this because we should never actually use an anonymous
4304  // union's constructor.
4305  if (Union && RD->isAnonymousStructOrUnion())
4306    return false;
4307
4308  // C++0x [class.copy]/20
4309  //    A defaulted [move] assignment operator for class X is defined as deleted
4310  //    if X has:
4311
4312  //    -- for the move constructor, [...] any direct or indirect virtual base
4313  //       class.
4314  if (RD->getNumVBases() != 0)
4315    return true;
4316
4317  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4318                                          BE = RD->bases_end();
4319       BI != BE; ++BI) {
4320
4321    QualType BaseType = BI->getType();
4322    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4323    assert(BaseDecl && "base isn't a CXXRecordDecl");
4324
4325    // -- a [direct base class] B that cannot be [moved] because overload
4326    //    resolution, as applied to B's [move] assignment operator, results in
4327    //    an ambiguity or a function that is deleted or inaccessible from the
4328    //    assignment operator
4329    CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4330    if (!MoveOper || MoveOper->isDeleted())
4331      return true;
4332    if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4333      return true;
4334
4335    // -- for the move assignment operator, a [direct base class] with a type
4336    //    that does not have a move assignment operator and is not trivially
4337    //    copyable.
4338    if (!MoveOper->isMoveAssignmentOperator() &&
4339        !BaseDecl->isTriviallyCopyable())
4340      return true;
4341  }
4342
4343  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4344                                     FE = RD->field_end();
4345       FI != FE; ++FI) {
4346    QualType FieldType = Context.getBaseElementType(FI->getType());
4347
4348    // -- a non-static data member of reference type
4349    if (FieldType->isReferenceType())
4350      return true;
4351
4352    // -- a non-static data member of const non-class type (or array thereof)
4353    if (FieldType.isConstQualified() && !FieldType->isRecordType())
4354      return true;
4355
4356    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4357
4358    if (FieldRecord) {
4359      // This is an anonymous union
4360      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4361        // Anonymous unions inside unions do not variant members create
4362        if (!Union) {
4363          for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4364                                             UE = FieldRecord->field_end();
4365               UI != UE; ++UI) {
4366            QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4367            CXXRecordDecl *UnionFieldRecord =
4368              UnionFieldType->getAsCXXRecordDecl();
4369
4370            // -- a variant member with a non-trivial [move] assignment operator
4371            //    and X is a union-like class
4372            if (UnionFieldRecord &&
4373                !UnionFieldRecord->hasTrivialMoveAssignment())
4374              return true;
4375          }
4376        }
4377
4378        // Don't try to initalize an anonymous union
4379        continue;
4380      // -- a variant member with a non-trivial [move] assignment operator
4381      //    and X is a union-like class
4382      } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4383          return true;
4384      }
4385
4386      CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4387      if (!MoveOper || MoveOper->isDeleted())
4388        return true;
4389      if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4390        return true;
4391
4392      // -- for the move assignment operator, a [non-static data member] with a
4393      //    type that does not have a move assignment operator and is not
4394      //    trivially copyable.
4395      if (!MoveOper->isMoveAssignmentOperator() &&
4396          !FieldRecord->isTriviallyCopyable())
4397        return true;
4398    }
4399  }
4400
4401  return false;
4402}
4403
4404bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4405  CXXRecordDecl *RD = DD->getParent();
4406  assert(!RD->isDependentType() && "do deletion after instantiation");
4407  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4408    return false;
4409
4410  SourceLocation Loc = DD->getLocation();
4411
4412  // Do access control from the destructor
4413  ContextRAII CtorContext(*this, DD);
4414
4415  bool Union = RD->isUnion();
4416
4417  // We do this because we should never actually use an anonymous
4418  // union's destructor.
4419  if (Union && RD->isAnonymousStructOrUnion())
4420    return false;
4421
4422  // C++0x [class.dtor]p5
4423  //    A defaulted destructor for a class X is defined as deleted if:
4424  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4425                                          BE = RD->bases_end();
4426       BI != BE; ++BI) {
4427    // We'll handle this one later
4428    if (BI->isVirtual())
4429      continue;
4430
4431    CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4432    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4433    assert(BaseDtor && "base has no destructor");
4434
4435    // -- any direct or virtual base class has a deleted destructor or
4436    //    a destructor that is inaccessible from the defaulted destructor
4437    if (BaseDtor->isDeleted())
4438      return true;
4439    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4440        AR_accessible)
4441      return true;
4442  }
4443
4444  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4445                                          BE = RD->vbases_end();
4446       BI != BE; ++BI) {
4447    CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4448    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4449    assert(BaseDtor && "base has no destructor");
4450
4451    // -- any direct or virtual base class has a deleted destructor or
4452    //    a destructor that is inaccessible from the defaulted destructor
4453    if (BaseDtor->isDeleted())
4454      return true;
4455    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4456        AR_accessible)
4457      return true;
4458  }
4459
4460  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4461                                     FE = RD->field_end();
4462       FI != FE; ++FI) {
4463    QualType FieldType = Context.getBaseElementType(FI->getType());
4464    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4465    if (FieldRecord) {
4466      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4467         for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4468                                            UE = FieldRecord->field_end();
4469              UI != UE; ++UI) {
4470           QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4471           CXXRecordDecl *UnionFieldRecord =
4472             UnionFieldType->getAsCXXRecordDecl();
4473
4474           // -- X is a union-like class that has a variant member with a non-
4475           //    trivial destructor.
4476           if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4477             return true;
4478         }
4479      // Technically we are supposed to do this next check unconditionally.
4480      // But that makes absolutely no sense.
4481      } else {
4482        CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4483
4484        // -- any of the non-static data members has class type M (or array
4485        //    thereof) and M has a deleted destructor or a destructor that is
4486        //    inaccessible from the defaulted destructor
4487        if (FieldDtor->isDeleted())
4488          return true;
4489        if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4490          AR_accessible)
4491        return true;
4492
4493        // -- X is a union-like class that has a variant member with a non-
4494        //    trivial destructor.
4495        if (Union && !FieldDtor->isTrivial())
4496          return true;
4497      }
4498    }
4499  }
4500
4501  if (DD->isVirtual()) {
4502    FunctionDecl *OperatorDelete = 0;
4503    DeclarationName Name =
4504      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4505    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
4506          false))
4507      return true;
4508  }
4509
4510
4511  return false;
4512}
4513
4514/// \brief Data used with FindHiddenVirtualMethod
4515namespace {
4516  struct FindHiddenVirtualMethodData {
4517    Sema *S;
4518    CXXMethodDecl *Method;
4519    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4520    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4521  };
4522}
4523
4524/// \brief Member lookup function that determines whether a given C++
4525/// method overloads virtual methods in a base class without overriding any,
4526/// to be used with CXXRecordDecl::lookupInBases().
4527static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4528                                    CXXBasePath &Path,
4529                                    void *UserData) {
4530  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4531
4532  FindHiddenVirtualMethodData &Data
4533    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4534
4535  DeclarationName Name = Data.Method->getDeclName();
4536  assert(Name.getNameKind() == DeclarationName::Identifier);
4537
4538  bool foundSameNameMethod = false;
4539  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4540  for (Path.Decls = BaseRecord->lookup(Name);
4541       Path.Decls.first != Path.Decls.second;
4542       ++Path.Decls.first) {
4543    NamedDecl *D = *Path.Decls.first;
4544    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4545      MD = MD->getCanonicalDecl();
4546      foundSameNameMethod = true;
4547      // Interested only in hidden virtual methods.
4548      if (!MD->isVirtual())
4549        continue;
4550      // If the method we are checking overrides a method from its base
4551      // don't warn about the other overloaded methods.
4552      if (!Data.S->IsOverload(Data.Method, MD, false))
4553        return true;
4554      // Collect the overload only if its hidden.
4555      if (!Data.OverridenAndUsingBaseMethods.count(MD))
4556        overloadedMethods.push_back(MD);
4557    }
4558  }
4559
4560  if (foundSameNameMethod)
4561    Data.OverloadedMethods.append(overloadedMethods.begin(),
4562                                   overloadedMethods.end());
4563  return foundSameNameMethod;
4564}
4565
4566/// \brief See if a method overloads virtual methods in a base class without
4567/// overriding any.
4568void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4569  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4570                               MD->getLocation()) == Diagnostic::Ignored)
4571    return;
4572  if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4573    return;
4574
4575  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4576                     /*bool RecordPaths=*/false,
4577                     /*bool DetectVirtual=*/false);
4578  FindHiddenVirtualMethodData Data;
4579  Data.Method = MD;
4580  Data.S = this;
4581
4582  // Keep the base methods that were overriden or introduced in the subclass
4583  // by 'using' in a set. A base method not in this set is hidden.
4584  for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4585       res.first != res.second; ++res.first) {
4586    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4587      for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4588                                          E = MD->end_overridden_methods();
4589           I != E; ++I)
4590        Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
4591    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4592      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
4593        Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
4594  }
4595
4596  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4597      !Data.OverloadedMethods.empty()) {
4598    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4599      << MD << (Data.OverloadedMethods.size() > 1);
4600
4601    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4602      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4603      Diag(overloadedMD->getLocation(),
4604           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4605    }
4606  }
4607}
4608
4609void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4610                                             Decl *TagDecl,
4611                                             SourceLocation LBrac,
4612                                             SourceLocation RBrac,
4613                                             AttributeList *AttrList) {
4614  if (!TagDecl)
4615    return;
4616
4617  AdjustDeclIfTemplate(TagDecl);
4618
4619  ActOnFields(S, RLoc, TagDecl,
4620              // strict aliasing violation!
4621              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
4622              FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
4623
4624  CheckCompletedCXXClass(
4625                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
4626}
4627
4628/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4629/// special functions, such as the default constructor, copy
4630/// constructor, or destructor, to the given C++ class (C++
4631/// [special]p1).  This routine can only be executed just before the
4632/// definition of the class is complete.
4633void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
4634  if (!ClassDecl->hasUserDeclaredConstructor())
4635    ++ASTContext::NumImplicitDefaultConstructors;
4636
4637  if (!ClassDecl->hasUserDeclaredCopyConstructor())
4638    ++ASTContext::NumImplicitCopyConstructors;
4639
4640  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4641    ++ASTContext::NumImplicitCopyAssignmentOperators;
4642
4643    // If we have a dynamic class, then the copy assignment operator may be
4644    // virtual, so we have to declare it immediately. This ensures that, e.g.,
4645    // it shows up in the right place in the vtable and that we diagnose
4646    // problems with the implicit exception specification.
4647    if (ClassDecl->isDynamicClass())
4648      DeclareImplicitCopyAssignment(ClassDecl);
4649  }
4650
4651  if (!ClassDecl->hasUserDeclaredDestructor()) {
4652    ++ASTContext::NumImplicitDestructors;
4653
4654    // If we have a dynamic class, then the destructor may be virtual, so we
4655    // have to declare the destructor immediately. This ensures that, e.g., it
4656    // shows up in the right place in the vtable and that we diagnose problems
4657    // with the implicit exception specification.
4658    if (ClassDecl->isDynamicClass())
4659      DeclareImplicitDestructor(ClassDecl);
4660  }
4661}
4662
4663void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4664  if (!D)
4665    return;
4666
4667  int NumParamList = D->getNumTemplateParameterLists();
4668  for (int i = 0; i < NumParamList; i++) {
4669    TemplateParameterList* Params = D->getTemplateParameterList(i);
4670    for (TemplateParameterList::iterator Param = Params->begin(),
4671                                      ParamEnd = Params->end();
4672          Param != ParamEnd; ++Param) {
4673      NamedDecl *Named = cast<NamedDecl>(*Param);
4674      if (Named->getDeclName()) {
4675        S->AddDecl(Named);
4676        IdResolver.AddDecl(Named);
4677      }
4678    }
4679  }
4680}
4681
4682void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
4683  if (!D)
4684    return;
4685
4686  TemplateParameterList *Params = 0;
4687  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4688    Params = Template->getTemplateParameters();
4689  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4690           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4691    Params = PartialSpec->getTemplateParameters();
4692  else
4693    return;
4694
4695  for (TemplateParameterList::iterator Param = Params->begin(),
4696                                    ParamEnd = Params->end();
4697       Param != ParamEnd; ++Param) {
4698    NamedDecl *Named = cast<NamedDecl>(*Param);
4699    if (Named->getDeclName()) {
4700      S->AddDecl(Named);
4701      IdResolver.AddDecl(Named);
4702    }
4703  }
4704}
4705
4706void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4707  if (!RecordD) return;
4708  AdjustDeclIfTemplate(RecordD);
4709  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
4710  PushDeclContext(S, Record);
4711}
4712
4713void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4714  if (!RecordD) return;
4715  PopDeclContext();
4716}
4717
4718/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4719/// parsing a top-level (non-nested) C++ class, and we are now
4720/// parsing those parts of the given Method declaration that could
4721/// not be parsed earlier (C++ [class.mem]p2), such as default
4722/// arguments. This action should enter the scope of the given
4723/// Method declaration as if we had just parsed the qualified method
4724/// name. However, it should not bring the parameters into scope;
4725/// that will be performed by ActOnDelayedCXXMethodParameter.
4726void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4727}
4728
4729/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4730/// C++ method declaration. We're (re-)introducing the given
4731/// function parameter into scope for use in parsing later parts of
4732/// the method declaration. For example, we could see an
4733/// ActOnParamDefaultArgument event for this parameter.
4734void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
4735  if (!ParamD)
4736    return;
4737
4738  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
4739
4740  // If this parameter has an unparsed default argument, clear it out
4741  // to make way for the parsed default argument.
4742  if (Param->hasUnparsedDefaultArg())
4743    Param->setDefaultArg(0);
4744
4745  S->AddDecl(Param);
4746  if (Param->getDeclName())
4747    IdResolver.AddDecl(Param);
4748}
4749
4750/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4751/// processing the delayed method declaration for Method. The method
4752/// declaration is now considered finished. There may be a separate
4753/// ActOnStartOfFunctionDef action later (not necessarily
4754/// immediately!) for this method, if it was also defined inside the
4755/// class body.
4756void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4757  if (!MethodD)
4758    return;
4759
4760  AdjustDeclIfTemplate(MethodD);
4761
4762  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
4763
4764  // Now that we have our default arguments, check the constructor
4765  // again. It could produce additional diagnostics or affect whether
4766  // the class has implicitly-declared destructors, among other
4767  // things.
4768  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4769    CheckConstructor(Constructor);
4770
4771  // Check the default arguments, which we may have added.
4772  if (!Method->isInvalidDecl())
4773    CheckCXXDefaultArguments(Method);
4774}
4775
4776/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
4777/// the well-formedness of the constructor declarator @p D with type @p
4778/// R. If there are any errors in the declarator, this routine will
4779/// emit diagnostics and set the invalid bit to true.  In any case, the type
4780/// will be updated to reflect a well-formed type for the constructor and
4781/// returned.
4782QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
4783                                          StorageClass &SC) {
4784  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4785
4786  // C++ [class.ctor]p3:
4787  //   A constructor shall not be virtual (10.3) or static (9.4). A
4788  //   constructor can be invoked for a const, volatile or const
4789  //   volatile object. A constructor shall not be declared const,
4790  //   volatile, or const volatile (9.3.2).
4791  if (isVirtual) {
4792    if (!D.isInvalidType())
4793      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4794        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4795        << SourceRange(D.getIdentifierLoc());
4796    D.setInvalidType();
4797  }
4798  if (SC == SC_Static) {
4799    if (!D.isInvalidType())
4800      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4801        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4802        << SourceRange(D.getIdentifierLoc());
4803    D.setInvalidType();
4804    SC = SC_None;
4805  }
4806
4807  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4808  if (FTI.TypeQuals != 0) {
4809    if (FTI.TypeQuals & Qualifiers::Const)
4810      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4811        << "const" << SourceRange(D.getIdentifierLoc());
4812    if (FTI.TypeQuals & Qualifiers::Volatile)
4813      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4814        << "volatile" << SourceRange(D.getIdentifierLoc());
4815    if (FTI.TypeQuals & Qualifiers::Restrict)
4816      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4817        << "restrict" << SourceRange(D.getIdentifierLoc());
4818    D.setInvalidType();
4819  }
4820
4821  // C++0x [class.ctor]p4:
4822  //   A constructor shall not be declared with a ref-qualifier.
4823  if (FTI.hasRefQualifier()) {
4824    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4825      << FTI.RefQualifierIsLValueRef
4826      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4827    D.setInvalidType();
4828  }
4829
4830  // Rebuild the function type "R" without any type qualifiers (in
4831  // case any of the errors above fired) and with "void" as the
4832  // return type, since constructors don't have return types.
4833  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4834  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4835    return R;
4836
4837  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4838  EPI.TypeQuals = 0;
4839  EPI.RefQualifier = RQ_None;
4840
4841  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
4842                                 Proto->getNumArgs(), EPI);
4843}
4844
4845/// CheckConstructor - Checks a fully-formed constructor for
4846/// well-formedness, issuing any diagnostics required. Returns true if
4847/// the constructor declarator is invalid.
4848void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
4849  CXXRecordDecl *ClassDecl
4850    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4851  if (!ClassDecl)
4852    return Constructor->setInvalidDecl();
4853
4854  // C++ [class.copy]p3:
4855  //   A declaration of a constructor for a class X is ill-formed if
4856  //   its first parameter is of type (optionally cv-qualified) X and
4857  //   either there are no other parameters or else all other
4858  //   parameters have default arguments.
4859  if (!Constructor->isInvalidDecl() &&
4860      ((Constructor->getNumParams() == 1) ||
4861       (Constructor->getNumParams() > 1 &&
4862        Constructor->getParamDecl(1)->hasDefaultArg())) &&
4863      Constructor->getTemplateSpecializationKind()
4864                                              != TSK_ImplicitInstantiation) {
4865    QualType ParamType = Constructor->getParamDecl(0)->getType();
4866    QualType ClassTy = Context.getTagDeclType(ClassDecl);
4867    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
4868      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
4869      const char *ConstRef
4870        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4871                                                        : " const &";
4872      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
4873        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
4874
4875      // FIXME: Rather that making the constructor invalid, we should endeavor
4876      // to fix the type.
4877      Constructor->setInvalidDecl();
4878    }
4879  }
4880}
4881
4882/// CheckDestructor - Checks a fully-formed destructor definition for
4883/// well-formedness, issuing any diagnostics required.  Returns true
4884/// on error.
4885bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
4886  CXXRecordDecl *RD = Destructor->getParent();
4887
4888  if (Destructor->isVirtual()) {
4889    SourceLocation Loc;
4890
4891    if (!Destructor->isImplicit())
4892      Loc = Destructor->getLocation();
4893    else
4894      Loc = RD->getLocation();
4895
4896    // If we have a virtual destructor, look up the deallocation function
4897    FunctionDecl *OperatorDelete = 0;
4898    DeclarationName Name =
4899    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4900    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
4901      return true;
4902
4903    MarkDeclarationReferenced(Loc, OperatorDelete);
4904
4905    Destructor->setOperatorDelete(OperatorDelete);
4906  }
4907
4908  return false;
4909}
4910
4911static inline bool
4912FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4913  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4914          FTI.ArgInfo[0].Param &&
4915          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
4916}
4917
4918/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4919/// the well-formednes of the destructor declarator @p D with type @p
4920/// R. If there are any errors in the declarator, this routine will
4921/// emit diagnostics and set the declarator to invalid.  Even if this happens,
4922/// will be updated to reflect a well-formed type for the destructor and
4923/// returned.
4924QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
4925                                         StorageClass& SC) {
4926  // C++ [class.dtor]p1:
4927  //   [...] A typedef-name that names a class is a class-name
4928  //   (7.1.3); however, a typedef-name that names a class shall not
4929  //   be used as the identifier in the declarator for a destructor
4930  //   declaration.
4931  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
4932  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
4933    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4934      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
4935  else if (const TemplateSpecializationType *TST =
4936             DeclaratorType->getAs<TemplateSpecializationType>())
4937    if (TST->isTypeAlias())
4938      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4939        << DeclaratorType << 1;
4940
4941  // C++ [class.dtor]p2:
4942  //   A destructor is used to destroy objects of its class type. A
4943  //   destructor takes no parameters, and no return type can be
4944  //   specified for it (not even void). The address of a destructor
4945  //   shall not be taken. A destructor shall not be static. A
4946  //   destructor can be invoked for a const, volatile or const
4947  //   volatile object. A destructor shall not be declared const,
4948  //   volatile or const volatile (9.3.2).
4949  if (SC == SC_Static) {
4950    if (!D.isInvalidType())
4951      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4952        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4953        << SourceRange(D.getIdentifierLoc())
4954        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4955
4956    SC = SC_None;
4957  }
4958  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
4959    // Destructors don't have return types, but the parser will
4960    // happily parse something like:
4961    //
4962    //   class X {
4963    //     float ~X();
4964    //   };
4965    //
4966    // The return type will be eliminated later.
4967    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4968      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4969      << SourceRange(D.getIdentifierLoc());
4970  }
4971
4972  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4973  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
4974    if (FTI.TypeQuals & Qualifiers::Const)
4975      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4976        << "const" << SourceRange(D.getIdentifierLoc());
4977    if (FTI.TypeQuals & Qualifiers::Volatile)
4978      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4979        << "volatile" << SourceRange(D.getIdentifierLoc());
4980    if (FTI.TypeQuals & Qualifiers::Restrict)
4981      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4982        << "restrict" << SourceRange(D.getIdentifierLoc());
4983    D.setInvalidType();
4984  }
4985
4986  // C++0x [class.dtor]p2:
4987  //   A destructor shall not be declared with a ref-qualifier.
4988  if (FTI.hasRefQualifier()) {
4989    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4990      << FTI.RefQualifierIsLValueRef
4991      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4992    D.setInvalidType();
4993  }
4994
4995  // Make sure we don't have any parameters.
4996  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
4997    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4998
4999    // Delete the parameters.
5000    FTI.freeArgs();
5001    D.setInvalidType();
5002  }
5003
5004  // Make sure the destructor isn't variadic.
5005  if (FTI.isVariadic) {
5006    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5007    D.setInvalidType();
5008  }
5009
5010  // Rebuild the function type "R" without any type qualifiers or
5011  // parameters (in case any of the errors above fired) and with
5012  // "void" as the return type, since destructors don't have return
5013  // types.
5014  if (!D.isInvalidType())
5015    return R;
5016
5017  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5018  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5019  EPI.Variadic = false;
5020  EPI.TypeQuals = 0;
5021  EPI.RefQualifier = RQ_None;
5022  return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
5023}
5024
5025/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5026/// well-formednes of the conversion function declarator @p D with
5027/// type @p R. If there are any errors in the declarator, this routine
5028/// will emit diagnostics and return true. Otherwise, it will return
5029/// false. Either way, the type @p R will be updated to reflect a
5030/// well-formed type for the conversion operator.
5031void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
5032                                     StorageClass& SC) {
5033  // C++ [class.conv.fct]p1:
5034  //   Neither parameter types nor return type can be specified. The
5035  //   type of a conversion function (8.3.5) is "function taking no
5036  //   parameter returning conversion-type-id."
5037  if (SC == SC_Static) {
5038    if (!D.isInvalidType())
5039      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5040        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5041        << SourceRange(D.getIdentifierLoc());
5042    D.setInvalidType();
5043    SC = SC_None;
5044  }
5045
5046  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5047
5048  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5049    // Conversion functions don't have return types, but the parser will
5050    // happily parse something like:
5051    //
5052    //   class X {
5053    //     float operator bool();
5054    //   };
5055    //
5056    // The return type will be changed later anyway.
5057    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5058      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5059      << SourceRange(D.getIdentifierLoc());
5060    D.setInvalidType();
5061  }
5062
5063  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5064
5065  // Make sure we don't have any parameters.
5066  if (Proto->getNumArgs() > 0) {
5067    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5068
5069    // Delete the parameters.
5070    D.getFunctionTypeInfo().freeArgs();
5071    D.setInvalidType();
5072  } else if (Proto->isVariadic()) {
5073    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
5074    D.setInvalidType();
5075  }
5076
5077  // Diagnose "&operator bool()" and other such nonsense.  This
5078  // is actually a gcc extension which we don't support.
5079  if (Proto->getResultType() != ConvType) {
5080    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5081      << Proto->getResultType();
5082    D.setInvalidType();
5083    ConvType = Proto->getResultType();
5084  }
5085
5086  // C++ [class.conv.fct]p4:
5087  //   The conversion-type-id shall not represent a function type nor
5088  //   an array type.
5089  if (ConvType->isArrayType()) {
5090    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5091    ConvType = Context.getPointerType(ConvType);
5092    D.setInvalidType();
5093  } else if (ConvType->isFunctionType()) {
5094    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5095    ConvType = Context.getPointerType(ConvType);
5096    D.setInvalidType();
5097  }
5098
5099  // Rebuild the function type "R" without any parameters (in case any
5100  // of the errors above fired) and with the conversion type as the
5101  // return type.
5102  if (D.isInvalidType())
5103    R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
5104
5105  // C++0x explicit conversion operators.
5106  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
5107    Diag(D.getDeclSpec().getExplicitSpecLoc(),
5108         diag::warn_explicit_conversion_functions)
5109      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
5110}
5111
5112/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5113/// the declaration of the given C++ conversion function. This routine
5114/// is responsible for recording the conversion function in the C++
5115/// class, if possible.
5116Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
5117  assert(Conversion && "Expected to receive a conversion function declaration");
5118
5119  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
5120
5121  // Make sure we aren't redeclaring the conversion function.
5122  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
5123
5124  // C++ [class.conv.fct]p1:
5125  //   [...] A conversion function is never used to convert a
5126  //   (possibly cv-qualified) object to the (possibly cv-qualified)
5127  //   same object type (or a reference to it), to a (possibly
5128  //   cv-qualified) base class of that type (or a reference to it),
5129  //   or to (possibly cv-qualified) void.
5130  // FIXME: Suppress this warning if the conversion function ends up being a
5131  // virtual function that overrides a virtual function in a base class.
5132  QualType ClassType
5133    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5134  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
5135    ConvType = ConvTypeRef->getPointeeType();
5136  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5137      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5138    /* Suppress diagnostics for instantiations. */;
5139  else if (ConvType->isRecordType()) {
5140    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5141    if (ConvType == ClassType)
5142      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
5143        << ClassType;
5144    else if (IsDerivedFrom(ClassType, ConvType))
5145      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
5146        <<  ClassType << ConvType;
5147  } else if (ConvType->isVoidType()) {
5148    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
5149      << ClassType << ConvType;
5150  }
5151
5152  if (FunctionTemplateDecl *ConversionTemplate
5153                                = Conversion->getDescribedFunctionTemplate())
5154    return ConversionTemplate;
5155
5156  return Conversion;
5157}
5158
5159//===----------------------------------------------------------------------===//
5160// Namespace Handling
5161//===----------------------------------------------------------------------===//
5162
5163
5164
5165/// ActOnStartNamespaceDef - This is called at the start of a namespace
5166/// definition.
5167Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
5168                                   SourceLocation InlineLoc,
5169                                   SourceLocation NamespaceLoc,
5170                                   SourceLocation IdentLoc,
5171                                   IdentifierInfo *II,
5172                                   SourceLocation LBrace,
5173                                   AttributeList *AttrList) {
5174  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5175  // For anonymous namespace, take the location of the left brace.
5176  SourceLocation Loc = II ? IdentLoc : LBrace;
5177  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
5178                                                 StartLoc, Loc, II);
5179  Namespc->setInline(InlineLoc.isValid());
5180
5181  Scope *DeclRegionScope = NamespcScope->getParent();
5182
5183  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5184
5185  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5186    PushNamespaceVisibilityAttr(Attr);
5187
5188  if (II) {
5189    // C++ [namespace.def]p2:
5190    //   The identifier in an original-namespace-definition shall not
5191    //   have been previously defined in the declarative region in
5192    //   which the original-namespace-definition appears. The
5193    //   identifier in an original-namespace-definition is the name of
5194    //   the namespace. Subsequently in that declarative region, it is
5195    //   treated as an original-namespace-name.
5196    //
5197    // Since namespace names are unique in their scope, and we don't
5198    // look through using directives, just look for any ordinary names.
5199
5200    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5201      Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5202      Decl::IDNS_Namespace;
5203    NamedDecl *PrevDecl = 0;
5204    for (DeclContext::lookup_result R
5205            = CurContext->getRedeclContext()->lookup(II);
5206         R.first != R.second; ++R.first) {
5207      if ((*R.first)->getIdentifierNamespace() & IDNS) {
5208        PrevDecl = *R.first;
5209        break;
5210      }
5211    }
5212
5213    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
5214      // This is an extended namespace definition.
5215      if (Namespc->isInline() != OrigNS->isInline()) {
5216        // inline-ness must match
5217        if (OrigNS->isInline()) {
5218          // The user probably just forgot the 'inline', so suggest that it
5219          // be added back.
5220          Diag(Namespc->getLocation(),
5221               diag::warn_inline_namespace_reopened_noninline)
5222            << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5223        } else {
5224          Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5225            << Namespc->isInline();
5226        }
5227        Diag(OrigNS->getLocation(), diag::note_previous_definition);
5228
5229        // Recover by ignoring the new namespace's inline status.
5230        Namespc->setInline(OrigNS->isInline());
5231      }
5232
5233      // Attach this namespace decl to the chain of extended namespace
5234      // definitions.
5235      OrigNS->setNextNamespace(Namespc);
5236      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
5237
5238      // Remove the previous declaration from the scope.
5239      if (DeclRegionScope->isDeclScope(OrigNS)) {
5240        IdResolver.RemoveDecl(OrigNS);
5241        DeclRegionScope->RemoveDecl(OrigNS);
5242      }
5243    } else if (PrevDecl) {
5244      // This is an invalid name redefinition.
5245      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
5246       << Namespc->getDeclName();
5247      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5248      Namespc->setInvalidDecl();
5249      // Continue on to push Namespc as current DeclContext and return it.
5250    } else if (II->isStr("std") &&
5251               CurContext->getRedeclContext()->isTranslationUnit()) {
5252      // This is the first "real" definition of the namespace "std", so update
5253      // our cache of the "std" namespace to point at this definition.
5254      if (NamespaceDecl *StdNS = getStdNamespace()) {
5255        // We had already defined a dummy namespace "std". Link this new
5256        // namespace definition to the dummy namespace "std".
5257        StdNS->setNextNamespace(Namespc);
5258        StdNS->setLocation(IdentLoc);
5259        Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
5260      }
5261
5262      // Make our StdNamespace cache point at the first real definition of the
5263      // "std" namespace.
5264      StdNamespace = Namespc;
5265
5266      // Add this instance of "std" to the set of known namespaces
5267      KnownNamespaces[Namespc] = false;
5268    } else if (!Namespc->isInline()) {
5269      // Since this is an "original" namespace, add it to the known set of
5270      // namespaces if it is not an inline namespace.
5271      KnownNamespaces[Namespc] = false;
5272    }
5273
5274    PushOnScopeChains(Namespc, DeclRegionScope);
5275  } else {
5276    // Anonymous namespaces.
5277    assert(Namespc->isAnonymousNamespace());
5278
5279    // Link the anonymous namespace into its parent.
5280    NamespaceDecl *PrevDecl;
5281    DeclContext *Parent = CurContext->getRedeclContext();
5282    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5283      PrevDecl = TU->getAnonymousNamespace();
5284      TU->setAnonymousNamespace(Namespc);
5285    } else {
5286      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5287      PrevDecl = ND->getAnonymousNamespace();
5288      ND->setAnonymousNamespace(Namespc);
5289    }
5290
5291    // Link the anonymous namespace with its previous declaration.
5292    if (PrevDecl) {
5293      assert(PrevDecl->isAnonymousNamespace());
5294      assert(!PrevDecl->getNextNamespace());
5295      Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
5296      PrevDecl->setNextNamespace(Namespc);
5297
5298      if (Namespc->isInline() != PrevDecl->isInline()) {
5299        // inline-ness must match
5300        Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5301          << Namespc->isInline();
5302        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5303        Namespc->setInvalidDecl();
5304        // Recover by ignoring the new namespace's inline status.
5305        Namespc->setInline(PrevDecl->isInline());
5306      }
5307    }
5308
5309    CurContext->addDecl(Namespc);
5310
5311    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
5312    //   behaves as if it were replaced by
5313    //     namespace unique { /* empty body */ }
5314    //     using namespace unique;
5315    //     namespace unique { namespace-body }
5316    //   where all occurrences of 'unique' in a translation unit are
5317    //   replaced by the same identifier and this identifier differs
5318    //   from all other identifiers in the entire program.
5319
5320    // We just create the namespace with an empty name and then add an
5321    // implicit using declaration, just like the standard suggests.
5322    //
5323    // CodeGen enforces the "universally unique" aspect by giving all
5324    // declarations semantically contained within an anonymous
5325    // namespace internal linkage.
5326
5327    if (!PrevDecl) {
5328      UsingDirectiveDecl* UD
5329        = UsingDirectiveDecl::Create(Context, CurContext,
5330                                     /* 'using' */ LBrace,
5331                                     /* 'namespace' */ SourceLocation(),
5332                                     /* qualifier */ NestedNameSpecifierLoc(),
5333                                     /* identifier */ SourceLocation(),
5334                                     Namespc,
5335                                     /* Ancestor */ CurContext);
5336      UD->setImplicit();
5337      CurContext->addDecl(UD);
5338    }
5339  }
5340
5341  // Although we could have an invalid decl (i.e. the namespace name is a
5342  // redefinition), push it as current DeclContext and try to continue parsing.
5343  // FIXME: We should be able to push Namespc here, so that the each DeclContext
5344  // for the namespace has the declarations that showed up in that particular
5345  // namespace definition.
5346  PushDeclContext(NamespcScope, Namespc);
5347  return Namespc;
5348}
5349
5350/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5351/// is a namespace alias, returns the namespace it points to.
5352static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5353  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5354    return AD->getNamespace();
5355  return dyn_cast_or_null<NamespaceDecl>(D);
5356}
5357
5358/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5359/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5360void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
5361  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5362  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
5363  Namespc->setRBraceLoc(RBrace);
5364  PopDeclContext();
5365  if (Namespc->hasAttr<VisibilityAttr>())
5366    PopPragmaVisibility();
5367}
5368
5369CXXRecordDecl *Sema::getStdBadAlloc() const {
5370  return cast_or_null<CXXRecordDecl>(
5371                                  StdBadAlloc.get(Context.getExternalSource()));
5372}
5373
5374NamespaceDecl *Sema::getStdNamespace() const {
5375  return cast_or_null<NamespaceDecl>(
5376                                 StdNamespace.get(Context.getExternalSource()));
5377}
5378
5379/// \brief Retrieve the special "std" namespace, which may require us to
5380/// implicitly define the namespace.
5381NamespaceDecl *Sema::getOrCreateStdNamespace() {
5382  if (!StdNamespace) {
5383    // The "std" namespace has not yet been defined, so build one implicitly.
5384    StdNamespace = NamespaceDecl::Create(Context,
5385                                         Context.getTranslationUnitDecl(),
5386                                         SourceLocation(), SourceLocation(),
5387                                         &PP.getIdentifierTable().get("std"));
5388    getStdNamespace()->setImplicit(true);
5389  }
5390
5391  return getStdNamespace();
5392}
5393
5394/// \brief Determine whether a using statement is in a context where it will be
5395/// apply in all contexts.
5396static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5397  switch (CurContext->getDeclKind()) {
5398    case Decl::TranslationUnit:
5399      return true;
5400    case Decl::LinkageSpec:
5401      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5402    default:
5403      return false;
5404  }
5405}
5406
5407static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5408                                       CXXScopeSpec &SS,
5409                                       SourceLocation IdentLoc,
5410                                       IdentifierInfo *Ident) {
5411  R.clear();
5412  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5413                                               R.getLookupKind(), Sc, &SS, NULL,
5414                                               false, S.CTC_NoKeywords, NULL)) {
5415    if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
5416        Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
5417      std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5418      std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5419      if (DeclContext *DC = S.computeDeclContext(SS, false))
5420        S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5421          << Ident << DC << CorrectedQuotedStr << SS.getRange()
5422          << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5423      else
5424        S.Diag(IdentLoc, diag::err_using_directive_suggest)
5425          << Ident << CorrectedQuotedStr
5426          << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5427
5428      S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5429           diag::note_namespace_defined_here) << CorrectedQuotedStr;
5430
5431      Ident = Corrected.getCorrectionAsIdentifierInfo();
5432      R.addDecl(Corrected.getCorrectionDecl());
5433      return true;
5434    }
5435    R.setLookupName(Ident);
5436  }
5437  return false;
5438}
5439
5440Decl *Sema::ActOnUsingDirective(Scope *S,
5441                                          SourceLocation UsingLoc,
5442                                          SourceLocation NamespcLoc,
5443                                          CXXScopeSpec &SS,
5444                                          SourceLocation IdentLoc,
5445                                          IdentifierInfo *NamespcName,
5446                                          AttributeList *AttrList) {
5447  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5448  assert(NamespcName && "Invalid NamespcName.");
5449  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
5450
5451  // This can only happen along a recovery path.
5452  while (S->getFlags() & Scope::TemplateParamScope)
5453    S = S->getParent();
5454  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5455
5456  UsingDirectiveDecl *UDir = 0;
5457  NestedNameSpecifier *Qualifier = 0;
5458  if (SS.isSet())
5459    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5460
5461  // Lookup namespace name.
5462  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5463  LookupParsedName(R, S, &SS);
5464  if (R.isAmbiguous())
5465    return 0;
5466
5467  if (R.empty()) {
5468    R.clear();
5469    // Allow "using namespace std;" or "using namespace ::std;" even if
5470    // "std" hasn't been defined yet, for GCC compatibility.
5471    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5472        NamespcName->isStr("std")) {
5473      Diag(IdentLoc, diag::ext_using_undefined_std);
5474      R.addDecl(getOrCreateStdNamespace());
5475      R.resolveKind();
5476    }
5477    // Otherwise, attempt typo correction.
5478    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
5479  }
5480
5481  if (!R.empty()) {
5482    NamedDecl *Named = R.getFoundDecl();
5483    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5484        && "expected namespace decl");
5485    // C++ [namespace.udir]p1:
5486    //   A using-directive specifies that the names in the nominated
5487    //   namespace can be used in the scope in which the
5488    //   using-directive appears after the using-directive. During
5489    //   unqualified name lookup (3.4.1), the names appear as if they
5490    //   were declared in the nearest enclosing namespace which
5491    //   contains both the using-directive and the nominated
5492    //   namespace. [Note: in this context, "contains" means "contains
5493    //   directly or indirectly". ]
5494
5495    // Find enclosing context containing both using-directive and
5496    // nominated namespace.
5497    NamespaceDecl *NS = getNamespaceDecl(Named);
5498    DeclContext *CommonAncestor = cast<DeclContext>(NS);
5499    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5500      CommonAncestor = CommonAncestor->getParent();
5501
5502    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
5503                                      SS.getWithLocInContext(Context),
5504                                      IdentLoc, Named, CommonAncestor);
5505
5506    if (IsUsingDirectiveInToplevelContext(CurContext) &&
5507        !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
5508      Diag(IdentLoc, diag::warn_using_directive_in_header);
5509    }
5510
5511    PushUsingDirective(S, UDir);
5512  } else {
5513    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
5514  }
5515
5516  // FIXME: We ignore attributes for now.
5517  return UDir;
5518}
5519
5520void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5521  // If scope has associated entity, then using directive is at namespace
5522  // or translation unit scope. We add UsingDirectiveDecls, into
5523  // it's lookup structure.
5524  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
5525    Ctx->addDecl(UDir);
5526  else
5527    // Otherwise it is block-sope. using-directives will affect lookup
5528    // only to the end of scope.
5529    S->PushUsingDirective(UDir);
5530}
5531
5532
5533Decl *Sema::ActOnUsingDeclaration(Scope *S,
5534                                  AccessSpecifier AS,
5535                                  bool HasUsingKeyword,
5536                                  SourceLocation UsingLoc,
5537                                  CXXScopeSpec &SS,
5538                                  UnqualifiedId &Name,
5539                                  AttributeList *AttrList,
5540                                  bool IsTypeName,
5541                                  SourceLocation TypenameLoc) {
5542  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5543
5544  switch (Name.getKind()) {
5545  case UnqualifiedId::IK_ImplicitSelfParam:
5546  case UnqualifiedId::IK_Identifier:
5547  case UnqualifiedId::IK_OperatorFunctionId:
5548  case UnqualifiedId::IK_LiteralOperatorId:
5549  case UnqualifiedId::IK_ConversionFunctionId:
5550    break;
5551
5552  case UnqualifiedId::IK_ConstructorName:
5553  case UnqualifiedId::IK_ConstructorTemplateId:
5554    // C++0x inherited constructors.
5555    if (getLangOptions().CPlusPlus0x) break;
5556
5557    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5558      << SS.getRange();
5559    return 0;
5560
5561  case UnqualifiedId::IK_DestructorName:
5562    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5563      << SS.getRange();
5564    return 0;
5565
5566  case UnqualifiedId::IK_TemplateId:
5567    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5568      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
5569    return 0;
5570  }
5571
5572  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5573  DeclarationName TargetName = TargetNameInfo.getName();
5574  if (!TargetName)
5575    return 0;
5576
5577  // Warn about using declarations.
5578  // TODO: store that the declaration was written without 'using' and
5579  // talk about access decls instead of using decls in the
5580  // diagnostics.
5581  if (!HasUsingKeyword) {
5582    UsingLoc = Name.getSourceRange().getBegin();
5583
5584    Diag(UsingLoc, diag::warn_access_decl_deprecated)
5585      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
5586  }
5587
5588  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5589      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5590    return 0;
5591
5592  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
5593                                        TargetNameInfo, AttrList,
5594                                        /* IsInstantiation */ false,
5595                                        IsTypeName, TypenameLoc);
5596  if (UD)
5597    PushOnScopeChains(UD, S, /*AddToContext*/ false);
5598
5599  return UD;
5600}
5601
5602/// \brief Determine whether a using declaration considers the given
5603/// declarations as "equivalent", e.g., if they are redeclarations of
5604/// the same entity or are both typedefs of the same type.
5605static bool
5606IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5607                         bool &SuppressRedeclaration) {
5608  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5609    SuppressRedeclaration = false;
5610    return true;
5611  }
5612
5613  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5614    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
5615      SuppressRedeclaration = true;
5616      return Context.hasSameType(TD1->getUnderlyingType(),
5617                                 TD2->getUnderlyingType());
5618    }
5619
5620  return false;
5621}
5622
5623
5624/// Determines whether to create a using shadow decl for a particular
5625/// decl, given the set of decls existing prior to this using lookup.
5626bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5627                                const LookupResult &Previous) {
5628  // Diagnose finding a decl which is not from a base class of the
5629  // current class.  We do this now because there are cases where this
5630  // function will silently decide not to build a shadow decl, which
5631  // will pre-empt further diagnostics.
5632  //
5633  // We don't need to do this in C++0x because we do the check once on
5634  // the qualifier.
5635  //
5636  // FIXME: diagnose the following if we care enough:
5637  //   struct A { int foo; };
5638  //   struct B : A { using A::foo; };
5639  //   template <class T> struct C : A {};
5640  //   template <class T> struct D : C<T> { using B::foo; } // <---
5641  // This is invalid (during instantiation) in C++03 because B::foo
5642  // resolves to the using decl in B, which is not a base class of D<T>.
5643  // We can't diagnose it immediately because C<T> is an unknown
5644  // specialization.  The UsingShadowDecl in D<T> then points directly
5645  // to A::foo, which will look well-formed when we instantiate.
5646  // The right solution is to not collapse the shadow-decl chain.
5647  if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5648    DeclContext *OrigDC = Orig->getDeclContext();
5649
5650    // Handle enums and anonymous structs.
5651    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5652    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5653    while (OrigRec->isAnonymousStructOrUnion())
5654      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5655
5656    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5657      if (OrigDC == CurContext) {
5658        Diag(Using->getLocation(),
5659             diag::err_using_decl_nested_name_specifier_is_current_class)
5660          << Using->getQualifierLoc().getSourceRange();
5661        Diag(Orig->getLocation(), diag::note_using_decl_target);
5662        return true;
5663      }
5664
5665      Diag(Using->getQualifierLoc().getBeginLoc(),
5666           diag::err_using_decl_nested_name_specifier_is_not_base_class)
5667        << Using->getQualifier()
5668        << cast<CXXRecordDecl>(CurContext)
5669        << Using->getQualifierLoc().getSourceRange();
5670      Diag(Orig->getLocation(), diag::note_using_decl_target);
5671      return true;
5672    }
5673  }
5674
5675  if (Previous.empty()) return false;
5676
5677  NamedDecl *Target = Orig;
5678  if (isa<UsingShadowDecl>(Target))
5679    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5680
5681  // If the target happens to be one of the previous declarations, we
5682  // don't have a conflict.
5683  //
5684  // FIXME: but we might be increasing its access, in which case we
5685  // should redeclare it.
5686  NamedDecl *NonTag = 0, *Tag = 0;
5687  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5688         I != E; ++I) {
5689    NamedDecl *D = (*I)->getUnderlyingDecl();
5690    bool Result;
5691    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5692      return Result;
5693
5694    (isa<TagDecl>(D) ? Tag : NonTag) = D;
5695  }
5696
5697  if (Target->isFunctionOrFunctionTemplate()) {
5698    FunctionDecl *FD;
5699    if (isa<FunctionTemplateDecl>(Target))
5700      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5701    else
5702      FD = cast<FunctionDecl>(Target);
5703
5704    NamedDecl *OldDecl = 0;
5705    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
5706    case Ovl_Overload:
5707      return false;
5708
5709    case Ovl_NonFunction:
5710      Diag(Using->getLocation(), diag::err_using_decl_conflict);
5711      break;
5712
5713    // We found a decl with the exact signature.
5714    case Ovl_Match:
5715      // If we're in a record, we want to hide the target, so we
5716      // return true (without a diagnostic) to tell the caller not to
5717      // build a shadow decl.
5718      if (CurContext->isRecord())
5719        return true;
5720
5721      // If we're not in a record, this is an error.
5722      Diag(Using->getLocation(), diag::err_using_decl_conflict);
5723      break;
5724    }
5725
5726    Diag(Target->getLocation(), diag::note_using_decl_target);
5727    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5728    return true;
5729  }
5730
5731  // Target is not a function.
5732
5733  if (isa<TagDecl>(Target)) {
5734    // No conflict between a tag and a non-tag.
5735    if (!Tag) return false;
5736
5737    Diag(Using->getLocation(), diag::err_using_decl_conflict);
5738    Diag(Target->getLocation(), diag::note_using_decl_target);
5739    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5740    return true;
5741  }
5742
5743  // No conflict between a tag and a non-tag.
5744  if (!NonTag) return false;
5745
5746  Diag(Using->getLocation(), diag::err_using_decl_conflict);
5747  Diag(Target->getLocation(), diag::note_using_decl_target);
5748  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5749  return true;
5750}
5751
5752/// Builds a shadow declaration corresponding to a 'using' declaration.
5753UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
5754                                            UsingDecl *UD,
5755                                            NamedDecl *Orig) {
5756
5757  // If we resolved to another shadow declaration, just coalesce them.
5758  NamedDecl *Target = Orig;
5759  if (isa<UsingShadowDecl>(Target)) {
5760    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5761    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
5762  }
5763
5764  UsingShadowDecl *Shadow
5765    = UsingShadowDecl::Create(Context, CurContext,
5766                              UD->getLocation(), UD, Target);
5767  UD->addShadowDecl(Shadow);
5768
5769  Shadow->setAccess(UD->getAccess());
5770  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5771    Shadow->setInvalidDecl();
5772
5773  if (S)
5774    PushOnScopeChains(Shadow, S);
5775  else
5776    CurContext->addDecl(Shadow);
5777
5778
5779  return Shadow;
5780}
5781
5782/// Hides a using shadow declaration.  This is required by the current
5783/// using-decl implementation when a resolvable using declaration in a
5784/// class is followed by a declaration which would hide or override
5785/// one or more of the using decl's targets; for example:
5786///
5787///   struct Base { void foo(int); };
5788///   struct Derived : Base {
5789///     using Base::foo;
5790///     void foo(int);
5791///   };
5792///
5793/// The governing language is C++03 [namespace.udecl]p12:
5794///
5795///   When a using-declaration brings names from a base class into a
5796///   derived class scope, member functions in the derived class
5797///   override and/or hide member functions with the same name and
5798///   parameter types in a base class (rather than conflicting).
5799///
5800/// There are two ways to implement this:
5801///   (1) optimistically create shadow decls when they're not hidden
5802///       by existing declarations, or
5803///   (2) don't create any shadow decls (or at least don't make them
5804///       visible) until we've fully parsed/instantiated the class.
5805/// The problem with (1) is that we might have to retroactively remove
5806/// a shadow decl, which requires several O(n) operations because the
5807/// decl structures are (very reasonably) not designed for removal.
5808/// (2) avoids this but is very fiddly and phase-dependent.
5809void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
5810  if (Shadow->getDeclName().getNameKind() ==
5811        DeclarationName::CXXConversionFunctionName)
5812    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5813
5814  // Remove it from the DeclContext...
5815  Shadow->getDeclContext()->removeDecl(Shadow);
5816
5817  // ...and the scope, if applicable...
5818  if (S) {
5819    S->RemoveDecl(Shadow);
5820    IdResolver.RemoveDecl(Shadow);
5821  }
5822
5823  // ...and the using decl.
5824  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5825
5826  // TODO: complain somehow if Shadow was used.  It shouldn't
5827  // be possible for this to happen, because...?
5828}
5829
5830/// Builds a using declaration.
5831///
5832/// \param IsInstantiation - Whether this call arises from an
5833///   instantiation of an unresolved using declaration.  We treat
5834///   the lookup differently for these declarations.
5835NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5836                                       SourceLocation UsingLoc,
5837                                       CXXScopeSpec &SS,
5838                                       const DeclarationNameInfo &NameInfo,
5839                                       AttributeList *AttrList,
5840                                       bool IsInstantiation,
5841                                       bool IsTypeName,
5842                                       SourceLocation TypenameLoc) {
5843  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5844  SourceLocation IdentLoc = NameInfo.getLoc();
5845  assert(IdentLoc.isValid() && "Invalid TargetName location.");
5846
5847  // FIXME: We ignore attributes for now.
5848
5849  if (SS.isEmpty()) {
5850    Diag(IdentLoc, diag::err_using_requires_qualname);
5851    return 0;
5852  }
5853
5854  // Do the redeclaration lookup in the current scope.
5855  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
5856                        ForRedeclaration);
5857  Previous.setHideTags(false);
5858  if (S) {
5859    LookupName(Previous, S);
5860
5861    // It is really dumb that we have to do this.
5862    LookupResult::Filter F = Previous.makeFilter();
5863    while (F.hasNext()) {
5864      NamedDecl *D = F.next();
5865      if (!isDeclInScope(D, CurContext, S))
5866        F.erase();
5867    }
5868    F.done();
5869  } else {
5870    assert(IsInstantiation && "no scope in non-instantiation");
5871    assert(CurContext->isRecord() && "scope not record in instantiation");
5872    LookupQualifiedName(Previous, CurContext);
5873  }
5874
5875  // Check for invalid redeclarations.
5876  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5877    return 0;
5878
5879  // Check for bad qualifiers.
5880  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5881    return 0;
5882
5883  DeclContext *LookupContext = computeDeclContext(SS);
5884  NamedDecl *D;
5885  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
5886  if (!LookupContext) {
5887    if (IsTypeName) {
5888      // FIXME: not all declaration name kinds are legal here
5889      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5890                                              UsingLoc, TypenameLoc,
5891                                              QualifierLoc,
5892                                              IdentLoc, NameInfo.getName());
5893    } else {
5894      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5895                                           QualifierLoc, NameInfo);
5896    }
5897  } else {
5898    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5899                          NameInfo, IsTypeName);
5900  }
5901  D->setAccess(AS);
5902  CurContext->addDecl(D);
5903
5904  if (!LookupContext) return D;
5905  UsingDecl *UD = cast<UsingDecl>(D);
5906
5907  if (RequireCompleteDeclContext(SS, LookupContext)) {
5908    UD->setInvalidDecl();
5909    return UD;
5910  }
5911
5912  // Constructor inheriting using decls get special treatment.
5913  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
5914    if (CheckInheritedConstructorUsingDecl(UD))
5915      UD->setInvalidDecl();
5916    return UD;
5917  }
5918
5919  // Otherwise, look up the target name.
5920
5921  LookupResult R(*this, NameInfo, LookupOrdinaryName);
5922  R.setUsingDeclaration(true);
5923
5924  // Unlike most lookups, we don't always want to hide tag
5925  // declarations: tag names are visible through the using declaration
5926  // even if hidden by ordinary names, *except* in a dependent context
5927  // where it's important for the sanity of two-phase lookup.
5928  if (!IsInstantiation)
5929    R.setHideTags(false);
5930
5931  LookupQualifiedName(R, LookupContext);
5932
5933  if (R.empty()) {
5934    Diag(IdentLoc, diag::err_no_member)
5935      << NameInfo.getName() << LookupContext << SS.getRange();
5936    UD->setInvalidDecl();
5937    return UD;
5938  }
5939
5940  if (R.isAmbiguous()) {
5941    UD->setInvalidDecl();
5942    return UD;
5943  }
5944
5945  if (IsTypeName) {
5946    // If we asked for a typename and got a non-type decl, error out.
5947    if (!R.getAsSingle<TypeDecl>()) {
5948      Diag(IdentLoc, diag::err_using_typename_non_type);
5949      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5950        Diag((*I)->getUnderlyingDecl()->getLocation(),
5951             diag::note_using_decl_target);
5952      UD->setInvalidDecl();
5953      return UD;
5954    }
5955  } else {
5956    // If we asked for a non-typename and we got a type, error out,
5957    // but only if this is an instantiation of an unresolved using
5958    // decl.  Otherwise just silently find the type name.
5959    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
5960      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5961      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
5962      UD->setInvalidDecl();
5963      return UD;
5964    }
5965  }
5966
5967  // C++0x N2914 [namespace.udecl]p6:
5968  // A using-declaration shall not name a namespace.
5969  if (R.getAsSingle<NamespaceDecl>()) {
5970    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5971      << SS.getRange();
5972    UD->setInvalidDecl();
5973    return UD;
5974  }
5975
5976  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5977    if (!CheckUsingShadowDecl(UD, *I, Previous))
5978      BuildUsingShadowDecl(S, UD, *I);
5979  }
5980
5981  return UD;
5982}
5983
5984/// Additional checks for a using declaration referring to a constructor name.
5985bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5986  if (UD->isTypeName()) {
5987    // FIXME: Cannot specify typename when specifying constructor
5988    return true;
5989  }
5990
5991  const Type *SourceType = UD->getQualifier()->getAsType();
5992  assert(SourceType &&
5993         "Using decl naming constructor doesn't have type in scope spec.");
5994  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5995
5996  // Check whether the named type is a direct base class.
5997  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5998  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5999  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6000       BaseIt != BaseE; ++BaseIt) {
6001    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6002    if (CanonicalSourceType == BaseType)
6003      break;
6004  }
6005
6006  if (BaseIt == BaseE) {
6007    // Did not find SourceType in the bases.
6008    Diag(UD->getUsingLocation(),
6009         diag::err_using_decl_constructor_not_in_direct_base)
6010      << UD->getNameInfo().getSourceRange()
6011      << QualType(SourceType, 0) << TargetClass;
6012    return true;
6013  }
6014
6015  BaseIt->setInheritConstructors();
6016
6017  return false;
6018}
6019
6020/// Checks that the given using declaration is not an invalid
6021/// redeclaration.  Note that this is checking only for the using decl
6022/// itself, not for any ill-formedness among the UsingShadowDecls.
6023bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6024                                       bool isTypeName,
6025                                       const CXXScopeSpec &SS,
6026                                       SourceLocation NameLoc,
6027                                       const LookupResult &Prev) {
6028  // C++03 [namespace.udecl]p8:
6029  // C++0x [namespace.udecl]p10:
6030  //   A using-declaration is a declaration and can therefore be used
6031  //   repeatedly where (and only where) multiple declarations are
6032  //   allowed.
6033  //
6034  // That's in non-member contexts.
6035  if (!CurContext->getRedeclContext()->isRecord())
6036    return false;
6037
6038  NestedNameSpecifier *Qual
6039    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6040
6041  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6042    NamedDecl *D = *I;
6043
6044    bool DTypename;
6045    NestedNameSpecifier *DQual;
6046    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6047      DTypename = UD->isTypeName();
6048      DQual = UD->getQualifier();
6049    } else if (UnresolvedUsingValueDecl *UD
6050                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6051      DTypename = false;
6052      DQual = UD->getQualifier();
6053    } else if (UnresolvedUsingTypenameDecl *UD
6054                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6055      DTypename = true;
6056      DQual = UD->getQualifier();
6057    } else continue;
6058
6059    // using decls differ if one says 'typename' and the other doesn't.
6060    // FIXME: non-dependent using decls?
6061    if (isTypeName != DTypename) continue;
6062
6063    // using decls differ if they name different scopes (but note that
6064    // template instantiation can cause this check to trigger when it
6065    // didn't before instantiation).
6066    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6067        Context.getCanonicalNestedNameSpecifier(DQual))
6068      continue;
6069
6070    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
6071    Diag(D->getLocation(), diag::note_using_decl) << 1;
6072    return true;
6073  }
6074
6075  return false;
6076}
6077
6078
6079/// Checks that the given nested-name qualifier used in a using decl
6080/// in the current context is appropriately related to the current
6081/// scope.  If an error is found, diagnoses it and returns true.
6082bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6083                                   const CXXScopeSpec &SS,
6084                                   SourceLocation NameLoc) {
6085  DeclContext *NamedContext = computeDeclContext(SS);
6086
6087  if (!CurContext->isRecord()) {
6088    // C++03 [namespace.udecl]p3:
6089    // C++0x [namespace.udecl]p8:
6090    //   A using-declaration for a class member shall be a member-declaration.
6091
6092    // If we weren't able to compute a valid scope, it must be a
6093    // dependent class scope.
6094    if (!NamedContext || NamedContext->isRecord()) {
6095      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6096        << SS.getRange();
6097      return true;
6098    }
6099
6100    // Otherwise, everything is known to be fine.
6101    return false;
6102  }
6103
6104  // The current scope is a record.
6105
6106  // If the named context is dependent, we can't decide much.
6107  if (!NamedContext) {
6108    // FIXME: in C++0x, we can diagnose if we can prove that the
6109    // nested-name-specifier does not refer to a base class, which is
6110    // still possible in some cases.
6111
6112    // Otherwise we have to conservatively report that things might be
6113    // okay.
6114    return false;
6115  }
6116
6117  if (!NamedContext->isRecord()) {
6118    // Ideally this would point at the last name in the specifier,
6119    // but we don't have that level of source info.
6120    Diag(SS.getRange().getBegin(),
6121         diag::err_using_decl_nested_name_specifier_is_not_class)
6122      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6123    return true;
6124  }
6125
6126  if (!NamedContext->isDependentContext() &&
6127      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6128    return true;
6129
6130  if (getLangOptions().CPlusPlus0x) {
6131    // C++0x [namespace.udecl]p3:
6132    //   In a using-declaration used as a member-declaration, the
6133    //   nested-name-specifier shall name a base class of the class
6134    //   being defined.
6135
6136    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6137                                 cast<CXXRecordDecl>(NamedContext))) {
6138      if (CurContext == NamedContext) {
6139        Diag(NameLoc,
6140             diag::err_using_decl_nested_name_specifier_is_current_class)
6141          << SS.getRange();
6142        return true;
6143      }
6144
6145      Diag(SS.getRange().getBegin(),
6146           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6147        << (NestedNameSpecifier*) SS.getScopeRep()
6148        << cast<CXXRecordDecl>(CurContext)
6149        << SS.getRange();
6150      return true;
6151    }
6152
6153    return false;
6154  }
6155
6156  // C++03 [namespace.udecl]p4:
6157  //   A using-declaration used as a member-declaration shall refer
6158  //   to a member of a base class of the class being defined [etc.].
6159
6160  // Salient point: SS doesn't have to name a base class as long as
6161  // lookup only finds members from base classes.  Therefore we can
6162  // diagnose here only if we can prove that that can't happen,
6163  // i.e. if the class hierarchies provably don't intersect.
6164
6165  // TODO: it would be nice if "definitely valid" results were cached
6166  // in the UsingDecl and UsingShadowDecl so that these checks didn't
6167  // need to be repeated.
6168
6169  struct UserData {
6170    llvm::DenseSet<const CXXRecordDecl*> Bases;
6171
6172    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6173      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6174      Data->Bases.insert(Base);
6175      return true;
6176    }
6177
6178    bool hasDependentBases(const CXXRecordDecl *Class) {
6179      return !Class->forallBases(collect, this);
6180    }
6181
6182    /// Returns true if the base is dependent or is one of the
6183    /// accumulated base classes.
6184    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6185      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6186      return !Data->Bases.count(Base);
6187    }
6188
6189    bool mightShareBases(const CXXRecordDecl *Class) {
6190      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6191    }
6192  };
6193
6194  UserData Data;
6195
6196  // Returns false if we find a dependent base.
6197  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6198    return false;
6199
6200  // Returns false if the class has a dependent base or if it or one
6201  // of its bases is present in the base set of the current context.
6202  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6203    return false;
6204
6205  Diag(SS.getRange().getBegin(),
6206       diag::err_using_decl_nested_name_specifier_is_not_base_class)
6207    << (NestedNameSpecifier*) SS.getScopeRep()
6208    << cast<CXXRecordDecl>(CurContext)
6209    << SS.getRange();
6210
6211  return true;
6212}
6213
6214Decl *Sema::ActOnAliasDeclaration(Scope *S,
6215                                  AccessSpecifier AS,
6216                                  MultiTemplateParamsArg TemplateParamLists,
6217                                  SourceLocation UsingLoc,
6218                                  UnqualifiedId &Name,
6219                                  TypeResult Type) {
6220  // Skip up to the relevant declaration scope.
6221  while (S->getFlags() & Scope::TemplateParamScope)
6222    S = S->getParent();
6223  assert((S->getFlags() & Scope::DeclScope) &&
6224         "got alias-declaration outside of declaration scope");
6225
6226  if (Type.isInvalid())
6227    return 0;
6228
6229  bool Invalid = false;
6230  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6231  TypeSourceInfo *TInfo = 0;
6232  GetTypeFromParser(Type.get(), &TInfo);
6233
6234  if (DiagnoseClassNameShadow(CurContext, NameInfo))
6235    return 0;
6236
6237  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
6238                                      UPPC_DeclarationType)) {
6239    Invalid = true;
6240    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6241                                             TInfo->getTypeLoc().getBeginLoc());
6242  }
6243
6244  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6245  LookupName(Previous, S);
6246
6247  // Warn about shadowing the name of a template parameter.
6248  if (Previous.isSingleResult() &&
6249      Previous.getFoundDecl()->isTemplateParameter()) {
6250    if (DiagnoseTemplateParameterShadow(Name.StartLocation,
6251                                        Previous.getFoundDecl()))
6252      Invalid = true;
6253    Previous.clear();
6254  }
6255
6256  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6257         "name in alias declaration must be an identifier");
6258  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6259                                               Name.StartLocation,
6260                                               Name.Identifier, TInfo);
6261
6262  NewTD->setAccess(AS);
6263
6264  if (Invalid)
6265    NewTD->setInvalidDecl();
6266
6267  CheckTypedefForVariablyModifiedType(S, NewTD);
6268  Invalid |= NewTD->isInvalidDecl();
6269
6270  bool Redeclaration = false;
6271
6272  NamedDecl *NewND;
6273  if (TemplateParamLists.size()) {
6274    TypeAliasTemplateDecl *OldDecl = 0;
6275    TemplateParameterList *OldTemplateParams = 0;
6276
6277    if (TemplateParamLists.size() != 1) {
6278      Diag(UsingLoc, diag::err_alias_template_extra_headers)
6279        << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6280         TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6281    }
6282    TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6283
6284    // Only consider previous declarations in the same scope.
6285    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6286                         /*ExplicitInstantiationOrSpecialization*/false);
6287    if (!Previous.empty()) {
6288      Redeclaration = true;
6289
6290      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6291      if (!OldDecl && !Invalid) {
6292        Diag(UsingLoc, diag::err_redefinition_different_kind)
6293          << Name.Identifier;
6294
6295        NamedDecl *OldD = Previous.getRepresentativeDecl();
6296        if (OldD->getLocation().isValid())
6297          Diag(OldD->getLocation(), diag::note_previous_definition);
6298
6299        Invalid = true;
6300      }
6301
6302      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6303        if (TemplateParameterListsAreEqual(TemplateParams,
6304                                           OldDecl->getTemplateParameters(),
6305                                           /*Complain=*/true,
6306                                           TPL_TemplateMatch))
6307          OldTemplateParams = OldDecl->getTemplateParameters();
6308        else
6309          Invalid = true;
6310
6311        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6312        if (!Invalid &&
6313            !Context.hasSameType(OldTD->getUnderlyingType(),
6314                                 NewTD->getUnderlyingType())) {
6315          // FIXME: The C++0x standard does not clearly say this is ill-formed,
6316          // but we can't reasonably accept it.
6317          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6318            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6319          if (OldTD->getLocation().isValid())
6320            Diag(OldTD->getLocation(), diag::note_previous_definition);
6321          Invalid = true;
6322        }
6323      }
6324    }
6325
6326    // Merge any previous default template arguments into our parameters,
6327    // and check the parameter list.
6328    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6329                                   TPC_TypeAliasTemplate))
6330      return 0;
6331
6332    TypeAliasTemplateDecl *NewDecl =
6333      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6334                                    Name.Identifier, TemplateParams,
6335                                    NewTD);
6336
6337    NewDecl->setAccess(AS);
6338
6339    if (Invalid)
6340      NewDecl->setInvalidDecl();
6341    else if (OldDecl)
6342      NewDecl->setPreviousDeclaration(OldDecl);
6343
6344    NewND = NewDecl;
6345  } else {
6346    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6347    NewND = NewTD;
6348  }
6349
6350  if (!Redeclaration)
6351    PushOnScopeChains(NewND, S);
6352
6353  return NewND;
6354}
6355
6356Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
6357                                             SourceLocation NamespaceLoc,
6358                                             SourceLocation AliasLoc,
6359                                             IdentifierInfo *Alias,
6360                                             CXXScopeSpec &SS,
6361                                             SourceLocation IdentLoc,
6362                                             IdentifierInfo *Ident) {
6363
6364  // Lookup the namespace name.
6365  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6366  LookupParsedName(R, S, &SS);
6367
6368  // Check if we have a previous declaration with the same name.
6369  NamedDecl *PrevDecl
6370    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6371                       ForRedeclaration);
6372  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6373    PrevDecl = 0;
6374
6375  if (PrevDecl) {
6376    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
6377      // We already have an alias with the same name that points to the same
6378      // namespace, so don't create a new one.
6379      // FIXME: At some point, we'll want to create the (redundant)
6380      // declaration to maintain better source information.
6381      if (!R.isAmbiguous() && !R.empty() &&
6382          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
6383        return 0;
6384    }
6385
6386    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6387      diag::err_redefinition_different_kind;
6388    Diag(AliasLoc, DiagID) << Alias;
6389    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6390    return 0;
6391  }
6392
6393  if (R.isAmbiguous())
6394    return 0;
6395
6396  if (R.empty()) {
6397    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
6398      Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
6399      return 0;
6400    }
6401  }
6402
6403  NamespaceAliasDecl *AliasDecl =
6404    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
6405                               Alias, SS.getWithLocInContext(Context),
6406                               IdentLoc, R.getFoundDecl());
6407
6408  PushOnScopeChains(AliasDecl, S);
6409  return AliasDecl;
6410}
6411
6412namespace {
6413  /// \brief Scoped object used to handle the state changes required in Sema
6414  /// to implicitly define the body of a C++ member function;
6415  class ImplicitlyDefinedFunctionScope {
6416    Sema &S;
6417    Sema::ContextRAII SavedContext;
6418
6419  public:
6420    ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
6421      : S(S), SavedContext(S, Method)
6422    {
6423      S.PushFunctionScope();
6424      S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6425    }
6426
6427    ~ImplicitlyDefinedFunctionScope() {
6428      S.PopExpressionEvaluationContext();
6429      S.PopFunctionOrBlockScope();
6430    }
6431  };
6432}
6433
6434Sema::ImplicitExceptionSpecification
6435Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
6436  // C++ [except.spec]p14:
6437  //   An implicitly declared special member function (Clause 12) shall have an
6438  //   exception-specification. [...]
6439  ImplicitExceptionSpecification ExceptSpec(Context);
6440  if (ClassDecl->isInvalidDecl())
6441    return ExceptSpec;
6442
6443  // Direct base-class constructors.
6444  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6445                                       BEnd = ClassDecl->bases_end();
6446       B != BEnd; ++B) {
6447    if (B->isVirtual()) // Handled below.
6448      continue;
6449
6450    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6451      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6452      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6453      // If this is a deleted function, add it anyway. This might be conformant
6454      // with the standard. This might not. I'm not sure. It might not matter.
6455      if (Constructor)
6456        ExceptSpec.CalledDecl(Constructor);
6457    }
6458  }
6459
6460  // Virtual base-class constructors.
6461  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6462                                       BEnd = ClassDecl->vbases_end();
6463       B != BEnd; ++B) {
6464    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6465      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6466      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6467      // If this is a deleted function, add it anyway. This might be conformant
6468      // with the standard. This might not. I'm not sure. It might not matter.
6469      if (Constructor)
6470        ExceptSpec.CalledDecl(Constructor);
6471    }
6472  }
6473
6474  // Field constructors.
6475  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6476                               FEnd = ClassDecl->field_end();
6477       F != FEnd; ++F) {
6478    if (F->hasInClassInitializer()) {
6479      if (Expr *E = F->getInClassInitializer())
6480        ExceptSpec.CalledExpr(E);
6481      else if (!F->isInvalidDecl())
6482        ExceptSpec.SetDelayed();
6483    } else if (const RecordType *RecordTy
6484              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
6485      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6486      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6487      // If this is a deleted function, add it anyway. This might be conformant
6488      // with the standard. This might not. I'm not sure. It might not matter.
6489      // In particular, the problem is that this function never gets called. It
6490      // might just be ill-formed because this function attempts to refer to
6491      // a deleted function here.
6492      if (Constructor)
6493        ExceptSpec.CalledDecl(Constructor);
6494    }
6495  }
6496
6497  return ExceptSpec;
6498}
6499
6500CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6501                                                     CXXRecordDecl *ClassDecl) {
6502  // C++ [class.ctor]p5:
6503  //   A default constructor for a class X is a constructor of class X
6504  //   that can be called without an argument. If there is no
6505  //   user-declared constructor for class X, a default constructor is
6506  //   implicitly declared. An implicitly-declared default constructor
6507  //   is an inline public member of its class.
6508  assert(!ClassDecl->hasUserDeclaredConstructor() &&
6509         "Should not build implicit default constructor!");
6510
6511  ImplicitExceptionSpecification Spec =
6512    ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6513  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6514
6515  // Create the actual constructor declaration.
6516  CanQualType ClassType
6517    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6518  SourceLocation ClassLoc = ClassDecl->getLocation();
6519  DeclarationName Name
6520    = Context.DeclarationNames.getCXXConstructorName(ClassType);
6521  DeclarationNameInfo NameInfo(Name, ClassLoc);
6522  CXXConstructorDecl *DefaultCon
6523    = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
6524                                 Context.getFunctionType(Context.VoidTy,
6525                                                         0, 0, EPI),
6526                                 /*TInfo=*/0,
6527                                 /*isExplicit=*/false,
6528                                 /*isInline=*/true,
6529                                 /*isImplicitlyDeclared=*/true,
6530                                 // FIXME: apply the rules for definitions here
6531                                 /*isConstexpr=*/false);
6532  DefaultCon->setAccess(AS_public);
6533  DefaultCon->setDefaulted();
6534  DefaultCon->setImplicit();
6535  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
6536
6537  // Note that we have declared this constructor.
6538  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6539
6540  if (Scope *S = getScopeForContext(ClassDecl))
6541    PushOnScopeChains(DefaultCon, S, false);
6542  ClassDecl->addDecl(DefaultCon);
6543
6544  if (ShouldDeleteDefaultConstructor(DefaultCon))
6545    DefaultCon->setDeletedAsWritten();
6546
6547  return DefaultCon;
6548}
6549
6550void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6551                                            CXXConstructorDecl *Constructor) {
6552  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6553          !Constructor->doesThisDeclarationHaveABody() &&
6554          !Constructor->isDeleted()) &&
6555    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
6556
6557  CXXRecordDecl *ClassDecl = Constructor->getParent();
6558  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
6559
6560  ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
6561  DiagnosticErrorTrap Trap(Diags);
6562  if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
6563      Trap.hasErrorOccurred()) {
6564    Diag(CurrentLocation, diag::note_member_synthesized_at)
6565      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
6566    Constructor->setInvalidDecl();
6567    return;
6568  }
6569
6570  SourceLocation Loc = Constructor->getLocation();
6571  Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6572
6573  Constructor->setUsed();
6574  MarkVTableUsed(CurrentLocation, ClassDecl);
6575
6576  if (ASTMutationListener *L = getASTMutationListener()) {
6577    L->CompletedImplicitDefinition(Constructor);
6578  }
6579}
6580
6581/// Get any existing defaulted default constructor for the given class. Do not
6582/// implicitly define one if it does not exist.
6583static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6584                                                             CXXRecordDecl *D) {
6585  ASTContext &Context = Self.Context;
6586  QualType ClassType = Context.getTypeDeclType(D);
6587  DeclarationName ConstructorName
6588    = Context.DeclarationNames.getCXXConstructorName(
6589                      Context.getCanonicalType(ClassType.getUnqualifiedType()));
6590
6591  DeclContext::lookup_const_iterator Con, ConEnd;
6592  for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6593       Con != ConEnd; ++Con) {
6594    // A function template cannot be defaulted.
6595    if (isa<FunctionTemplateDecl>(*Con))
6596      continue;
6597
6598    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6599    if (Constructor->isDefaultConstructor())
6600      return Constructor->isDefaulted() ? Constructor : 0;
6601  }
6602  return 0;
6603}
6604
6605void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6606  if (!D) return;
6607  AdjustDeclIfTemplate(D);
6608
6609  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6610  CXXConstructorDecl *CtorDecl
6611    = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6612
6613  if (!CtorDecl) return;
6614
6615  // Compute the exception specification for the default constructor.
6616  const FunctionProtoType *CtorTy =
6617    CtorDecl->getType()->castAs<FunctionProtoType>();
6618  if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6619    ImplicitExceptionSpecification Spec =
6620      ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6621    FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6622    assert(EPI.ExceptionSpecType != EST_Delayed);
6623
6624    CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6625  }
6626
6627  // If the default constructor is explicitly defaulted, checking the exception
6628  // specification is deferred until now.
6629  if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6630      !ClassDecl->isDependentType())
6631    CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6632}
6633
6634void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6635  // We start with an initial pass over the base classes to collect those that
6636  // inherit constructors from. If there are none, we can forgo all further
6637  // processing.
6638  typedef SmallVector<const RecordType *, 4> BasesVector;
6639  BasesVector BasesToInheritFrom;
6640  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6641                                          BaseE = ClassDecl->bases_end();
6642         BaseIt != BaseE; ++BaseIt) {
6643    if (BaseIt->getInheritConstructors()) {
6644      QualType Base = BaseIt->getType();
6645      if (Base->isDependentType()) {
6646        // If we inherit constructors from anything that is dependent, just
6647        // abort processing altogether. We'll get another chance for the
6648        // instantiations.
6649        return;
6650      }
6651      BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6652    }
6653  }
6654  if (BasesToInheritFrom.empty())
6655    return;
6656
6657  // Now collect the constructors that we already have in the current class.
6658  // Those take precedence over inherited constructors.
6659  // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6660  //   unless there is a user-declared constructor with the same signature in
6661  //   the class where the using-declaration appears.
6662  llvm::SmallSet<const Type *, 8> ExistingConstructors;
6663  for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6664                                    CtorE = ClassDecl->ctor_end();
6665       CtorIt != CtorE; ++CtorIt) {
6666    ExistingConstructors.insert(
6667        Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6668  }
6669
6670  Scope *S = getScopeForContext(ClassDecl);
6671  DeclarationName CreatedCtorName =
6672      Context.DeclarationNames.getCXXConstructorName(
6673          ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6674
6675  // Now comes the true work.
6676  // First, we keep a map from constructor types to the base that introduced
6677  // them. Needed for finding conflicting constructors. We also keep the
6678  // actually inserted declarations in there, for pretty diagnostics.
6679  typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6680  typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6681  ConstructorToSourceMap InheritedConstructors;
6682  for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6683                             BaseE = BasesToInheritFrom.end();
6684       BaseIt != BaseE; ++BaseIt) {
6685    const RecordType *Base = *BaseIt;
6686    CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6687    CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6688    for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6689                                      CtorE = BaseDecl->ctor_end();
6690         CtorIt != CtorE; ++CtorIt) {
6691      // Find the using declaration for inheriting this base's constructors.
6692      DeclarationName Name =
6693          Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6694      UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6695          LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6696      SourceLocation UsingLoc = UD ? UD->getLocation() :
6697                                     ClassDecl->getLocation();
6698
6699      // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6700      //   from the class X named in the using-declaration consists of actual
6701      //   constructors and notional constructors that result from the
6702      //   transformation of defaulted parameters as follows:
6703      //   - all non-template default constructors of X, and
6704      //   - for each non-template constructor of X that has at least one
6705      //     parameter with a default argument, the set of constructors that
6706      //     results from omitting any ellipsis parameter specification and
6707      //     successively omitting parameters with a default argument from the
6708      //     end of the parameter-type-list.
6709      CXXConstructorDecl *BaseCtor = *CtorIt;
6710      bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6711      const FunctionProtoType *BaseCtorType =
6712          BaseCtor->getType()->getAs<FunctionProtoType>();
6713
6714      for (unsigned params = BaseCtor->getMinRequiredArguments(),
6715                    maxParams = BaseCtor->getNumParams();
6716           params <= maxParams; ++params) {
6717        // Skip default constructors. They're never inherited.
6718        if (params == 0)
6719          continue;
6720        // Skip copy and move constructors for the same reason.
6721        if (CanBeCopyOrMove && params == 1)
6722          continue;
6723
6724        // Build up a function type for this particular constructor.
6725        // FIXME: The working paper does not consider that the exception spec
6726        // for the inheriting constructor might be larger than that of the
6727        // source. This code doesn't yet, either. When it does, this code will
6728        // need to be delayed until after exception specifications and in-class
6729        // member initializers are attached.
6730        const Type *NewCtorType;
6731        if (params == maxParams)
6732          NewCtorType = BaseCtorType;
6733        else {
6734          SmallVector<QualType, 16> Args;
6735          for (unsigned i = 0; i < params; ++i) {
6736            Args.push_back(BaseCtorType->getArgType(i));
6737          }
6738          FunctionProtoType::ExtProtoInfo ExtInfo =
6739              BaseCtorType->getExtProtoInfo();
6740          ExtInfo.Variadic = false;
6741          NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6742                                                Args.data(), params, ExtInfo)
6743                       .getTypePtr();
6744        }
6745        const Type *CanonicalNewCtorType =
6746            Context.getCanonicalType(NewCtorType);
6747
6748        // Now that we have the type, first check if the class already has a
6749        // constructor with this signature.
6750        if (ExistingConstructors.count(CanonicalNewCtorType))
6751          continue;
6752
6753        // Then we check if we have already declared an inherited constructor
6754        // with this signature.
6755        std::pair<ConstructorToSourceMap::iterator, bool> result =
6756            InheritedConstructors.insert(std::make_pair(
6757                CanonicalNewCtorType,
6758                std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6759        if (!result.second) {
6760          // Already in the map. If it came from a different class, that's an
6761          // error. Not if it's from the same.
6762          CanQualType PreviousBase = result.first->second.first;
6763          if (CanonicalBase != PreviousBase) {
6764            const CXXConstructorDecl *PrevCtor = result.first->second.second;
6765            const CXXConstructorDecl *PrevBaseCtor =
6766                PrevCtor->getInheritedConstructor();
6767            assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6768
6769            Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6770            Diag(BaseCtor->getLocation(),
6771                 diag::note_using_decl_constructor_conflict_current_ctor);
6772            Diag(PrevBaseCtor->getLocation(),
6773                 diag::note_using_decl_constructor_conflict_previous_ctor);
6774            Diag(PrevCtor->getLocation(),
6775                 diag::note_using_decl_constructor_conflict_previous_using);
6776          }
6777          continue;
6778        }
6779
6780        // OK, we're there, now add the constructor.
6781        // C++0x [class.inhctor]p8: [...] that would be performed by a
6782        //   user-written inline constructor [...]
6783        DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6784        CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
6785            Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6786            /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
6787            /*ImplicitlyDeclared=*/true,
6788            // FIXME: Due to a defect in the standard, we treat inherited
6789            // constructors as constexpr even if that makes them ill-formed.
6790            /*Constexpr=*/BaseCtor->isConstexpr());
6791        NewCtor->setAccess(BaseCtor->getAccess());
6792
6793        // Build up the parameter decls and add them.
6794        SmallVector<ParmVarDecl *, 16> ParamDecls;
6795        for (unsigned i = 0; i < params; ++i) {
6796          ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6797                                                   UsingLoc, UsingLoc,
6798                                                   /*IdentifierInfo=*/0,
6799                                                   BaseCtorType->getArgType(i),
6800                                                   /*TInfo=*/0, SC_None,
6801                                                   SC_None, /*DefaultArg=*/0));
6802        }
6803        NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6804        NewCtor->setInheritedConstructor(BaseCtor);
6805
6806        PushOnScopeChains(NewCtor, S, false);
6807        ClassDecl->addDecl(NewCtor);
6808        result.first->second.second = NewCtor;
6809      }
6810    }
6811  }
6812}
6813
6814Sema::ImplicitExceptionSpecification
6815Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
6816  // C++ [except.spec]p14:
6817  //   An implicitly declared special member function (Clause 12) shall have
6818  //   an exception-specification.
6819  ImplicitExceptionSpecification ExceptSpec(Context);
6820  if (ClassDecl->isInvalidDecl())
6821    return ExceptSpec;
6822
6823  // Direct base-class destructors.
6824  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6825                                       BEnd = ClassDecl->bases_end();
6826       B != BEnd; ++B) {
6827    if (B->isVirtual()) // Handled below.
6828      continue;
6829
6830    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6831      ExceptSpec.CalledDecl(
6832                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
6833  }
6834
6835  // Virtual base-class destructors.
6836  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6837                                       BEnd = ClassDecl->vbases_end();
6838       B != BEnd; ++B) {
6839    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6840      ExceptSpec.CalledDecl(
6841                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
6842  }
6843
6844  // Field destructors.
6845  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6846                               FEnd = ClassDecl->field_end();
6847       F != FEnd; ++F) {
6848    if (const RecordType *RecordTy
6849        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6850      ExceptSpec.CalledDecl(
6851                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
6852  }
6853
6854  return ExceptSpec;
6855}
6856
6857CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6858  // C++ [class.dtor]p2:
6859  //   If a class has no user-declared destructor, a destructor is
6860  //   declared implicitly. An implicitly-declared destructor is an
6861  //   inline public member of its class.
6862
6863  ImplicitExceptionSpecification Spec =
6864      ComputeDefaultedDtorExceptionSpec(ClassDecl);
6865  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6866
6867  // Create the actual destructor declaration.
6868  QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
6869
6870  CanQualType ClassType
6871    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6872  SourceLocation ClassLoc = ClassDecl->getLocation();
6873  DeclarationName Name
6874    = Context.DeclarationNames.getCXXDestructorName(ClassType);
6875  DeclarationNameInfo NameInfo(Name, ClassLoc);
6876  CXXDestructorDecl *Destructor
6877      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6878                                  /*isInline=*/true,
6879                                  /*isImplicitlyDeclared=*/true);
6880  Destructor->setAccess(AS_public);
6881  Destructor->setDefaulted();
6882  Destructor->setImplicit();
6883  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
6884
6885  // Note that we have declared this destructor.
6886  ++ASTContext::NumImplicitDestructorsDeclared;
6887
6888  // Introduce this destructor into its scope.
6889  if (Scope *S = getScopeForContext(ClassDecl))
6890    PushOnScopeChains(Destructor, S, false);
6891  ClassDecl->addDecl(Destructor);
6892
6893  // This could be uniqued if it ever proves significant.
6894  Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
6895
6896  if (ShouldDeleteDestructor(Destructor))
6897    Destructor->setDeletedAsWritten();
6898
6899  AddOverriddenMethods(ClassDecl, Destructor);
6900
6901  return Destructor;
6902}
6903
6904void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
6905                                    CXXDestructorDecl *Destructor) {
6906  assert((Destructor->isDefaulted() &&
6907          !Destructor->doesThisDeclarationHaveABody()) &&
6908         "DefineImplicitDestructor - call it for implicit default dtor");
6909  CXXRecordDecl *ClassDecl = Destructor->getParent();
6910  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
6911
6912  if (Destructor->isInvalidDecl())
6913    return;
6914
6915  ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
6916
6917  DiagnosticErrorTrap Trap(Diags);
6918  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6919                                         Destructor->getParent());
6920
6921  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
6922    Diag(CurrentLocation, diag::note_member_synthesized_at)
6923      << CXXDestructor << Context.getTagDeclType(ClassDecl);
6924
6925    Destructor->setInvalidDecl();
6926    return;
6927  }
6928
6929  SourceLocation Loc = Destructor->getLocation();
6930  Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6931
6932  Destructor->setUsed();
6933  MarkVTableUsed(CurrentLocation, ClassDecl);
6934
6935  if (ASTMutationListener *L = getASTMutationListener()) {
6936    L->CompletedImplicitDefinition(Destructor);
6937  }
6938}
6939
6940void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6941                                         CXXDestructorDecl *destructor) {
6942  // C++11 [class.dtor]p3:
6943  //   A declaration of a destructor that does not have an exception-
6944  //   specification is implicitly considered to have the same exception-
6945  //   specification as an implicit declaration.
6946  const FunctionProtoType *dtorType = destructor->getType()->
6947                                        getAs<FunctionProtoType>();
6948  if (dtorType->hasExceptionSpec())
6949    return;
6950
6951  ImplicitExceptionSpecification exceptSpec =
6952      ComputeDefaultedDtorExceptionSpec(classDecl);
6953
6954  // Replace the destructor's type.
6955  FunctionProtoType::ExtProtoInfo epi;
6956  epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6957  epi.NumExceptions = exceptSpec.size();
6958  epi.Exceptions = exceptSpec.data();
6959  QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6960
6961  destructor->setType(ty);
6962
6963  // FIXME: If the destructor has a body that could throw, and the newly created
6964  // spec doesn't allow exceptions, we should emit a warning, because this
6965  // change in behavior can break conforming C++03 programs at runtime.
6966  // However, we don't have a body yet, so it needs to be done somewhere else.
6967}
6968
6969/// \brief Builds a statement that copies/moves the given entity from \p From to
6970/// \c To.
6971///
6972/// This routine is used to copy/move the members of a class with an
6973/// implicitly-declared copy/move assignment operator. When the entities being
6974/// copied are arrays, this routine builds for loops to copy them.
6975///
6976/// \param S The Sema object used for type-checking.
6977///
6978/// \param Loc The location where the implicit copy/move is being generated.
6979///
6980/// \param T The type of the expressions being copied/moved. Both expressions
6981/// must have this type.
6982///
6983/// \param To The expression we are copying/moving to.
6984///
6985/// \param From The expression we are copying/moving from.
6986///
6987/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
6988/// Otherwise, it's a non-static member subobject.
6989///
6990/// \param Copying Whether we're copying or moving.
6991///
6992/// \param Depth Internal parameter recording the depth of the recursion.
6993///
6994/// \returns A statement or a loop that copies the expressions.
6995static StmtResult
6996BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
6997                      Expr *To, Expr *From,
6998                      bool CopyingBaseSubobject, bool Copying,
6999                      unsigned Depth = 0) {
7000  // C++0x [class.copy]p28:
7001  //   Each subobject is assigned in the manner appropriate to its type:
7002  //
7003  //     - if the subobject is of class type, as if by a call to operator= with
7004  //       the subobject as the object expression and the corresponding
7005  //       subobject of x as a single function argument (as if by explicit
7006  //       qualification; that is, ignoring any possible virtual overriding
7007  //       functions in more derived classes);
7008  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7009    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7010
7011    // Look for operator=.
7012    DeclarationName Name
7013      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7014    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7015    S.LookupQualifiedName(OpLookup, ClassDecl, false);
7016
7017    // Filter out any result that isn't a copy/move-assignment operator.
7018    LookupResult::Filter F = OpLookup.makeFilter();
7019    while (F.hasNext()) {
7020      NamedDecl *D = F.next();
7021      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
7022        if (Copying ? Method->isCopyAssignmentOperator() :
7023                      Method->isMoveAssignmentOperator())
7024          continue;
7025
7026      F.erase();
7027    }
7028    F.done();
7029
7030    // Suppress the protected check (C++ [class.protected]) for each of the
7031    // assignment operators we found. This strange dance is required when
7032    // we're assigning via a base classes's copy-assignment operator. To
7033    // ensure that we're getting the right base class subobject (without
7034    // ambiguities), we need to cast "this" to that subobject type; to
7035    // ensure that we don't go through the virtual call mechanism, we need
7036    // to qualify the operator= name with the base class (see below). However,
7037    // this means that if the base class has a protected copy assignment
7038    // operator, the protected member access check will fail. So, we
7039    // rewrite "protected" access to "public" access in this case, since we
7040    // know by construction that we're calling from a derived class.
7041    if (CopyingBaseSubobject) {
7042      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7043           L != LEnd; ++L) {
7044        if (L.getAccess() == AS_protected)
7045          L.setAccess(AS_public);
7046      }
7047    }
7048
7049    // Create the nested-name-specifier that will be used to qualify the
7050    // reference to operator=; this is required to suppress the virtual
7051    // call mechanism.
7052    CXXScopeSpec SS;
7053    SS.MakeTrivial(S.Context,
7054                   NestedNameSpecifier::Create(S.Context, 0, false,
7055                                               T.getTypePtr()),
7056                   Loc);
7057
7058    // Create the reference to operator=.
7059    ExprResult OpEqualRef
7060      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
7061                                   /*FirstQualifierInScope=*/0, OpLookup,
7062                                   /*TemplateArgs=*/0,
7063                                   /*SuppressQualifierCheck=*/true);
7064    if (OpEqualRef.isInvalid())
7065      return StmtError();
7066
7067    // Build the call to the assignment operator.
7068
7069    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
7070                                                  OpEqualRef.takeAs<Expr>(),
7071                                                  Loc, &From, 1, Loc);
7072    if (Call.isInvalid())
7073      return StmtError();
7074
7075    return S.Owned(Call.takeAs<Stmt>());
7076  }
7077
7078  //     - if the subobject is of scalar type, the built-in assignment
7079  //       operator is used.
7080  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7081  if (!ArrayTy) {
7082    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
7083    if (Assignment.isInvalid())
7084      return StmtError();
7085
7086    return S.Owned(Assignment.takeAs<Stmt>());
7087  }
7088
7089  //     - if the subobject is an array, each element is assigned, in the
7090  //       manner appropriate to the element type;
7091
7092  // Construct a loop over the array bounds, e.g.,
7093  //
7094  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7095  //
7096  // that will copy each of the array elements.
7097  QualType SizeType = S.Context.getSizeType();
7098
7099  // Create the iteration variable.
7100  IdentifierInfo *IterationVarName = 0;
7101  {
7102    llvm::SmallString<8> Str;
7103    llvm::raw_svector_ostream OS(Str);
7104    OS << "__i" << Depth;
7105    IterationVarName = &S.Context.Idents.get(OS.str());
7106  }
7107  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
7108                                          IterationVarName, SizeType,
7109                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
7110                                          SC_None, SC_None);
7111
7112  // Initialize the iteration variable to zero.
7113  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
7114  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
7115
7116  // Create a reference to the iteration variable; we'll use this several
7117  // times throughout.
7118  Expr *IterationVarRef
7119    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
7120  assert(IterationVarRef && "Reference to invented variable cannot fail!");
7121
7122  // Create the DeclStmt that holds the iteration variable.
7123  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7124
7125  // Create the comparison against the array bound.
7126  llvm::APInt Upper
7127    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
7128  Expr *Comparison
7129    = new (S.Context) BinaryOperator(IterationVarRef,
7130                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7131                                     BO_NE, S.Context.BoolTy,
7132                                     VK_RValue, OK_Ordinary, Loc);
7133
7134  // Create the pre-increment of the iteration variable.
7135  Expr *Increment
7136    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7137                                    VK_LValue, OK_Ordinary, Loc);
7138
7139  // Subscript the "from" and "to" expressions with the iteration variable.
7140  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7141                                                         IterationVarRef, Loc));
7142  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7143                                                       IterationVarRef, Loc));
7144  if (!Copying) // Cast to rvalue
7145    From = CastForMoving(S, From);
7146
7147  // Build the copy/move for an individual element of the array.
7148  StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7149                                          To, From, CopyingBaseSubobject,
7150                                          Copying, Depth + 1);
7151  if (Copy.isInvalid())
7152    return StmtError();
7153
7154  // Construct the loop that copies all elements of this array.
7155  return S.ActOnForStmt(Loc, Loc, InitStmt,
7156                        S.MakeFullExpr(Comparison),
7157                        0, S.MakeFullExpr(Increment),
7158                        Loc, Copy.take());
7159}
7160
7161std::pair<Sema::ImplicitExceptionSpecification, bool>
7162Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7163                                                   CXXRecordDecl *ClassDecl) {
7164  if (ClassDecl->isInvalidDecl())
7165    return std::make_pair(ImplicitExceptionSpecification(Context), false);
7166
7167  // C++ [class.copy]p10:
7168  //   If the class definition does not explicitly declare a copy
7169  //   assignment operator, one is declared implicitly.
7170  //   The implicitly-defined copy assignment operator for a class X
7171  //   will have the form
7172  //
7173  //       X& X::operator=(const X&)
7174  //
7175  //   if
7176  bool HasConstCopyAssignment = true;
7177
7178  //       -- each direct base class B of X has a copy assignment operator
7179  //          whose parameter is of type const B&, const volatile B& or B,
7180  //          and
7181  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7182                                       BaseEnd = ClassDecl->bases_end();
7183       HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7184    // We'll handle this below
7185    if (LangOpts.CPlusPlus0x && Base->isVirtual())
7186      continue;
7187
7188    assert(!Base->getType()->isDependentType() &&
7189           "Cannot generate implicit members for class with dependent bases.");
7190    CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7191    LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7192                            &HasConstCopyAssignment);
7193  }
7194
7195  // In C++0x, the above citation has "or virtual added"
7196  if (LangOpts.CPlusPlus0x) {
7197    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7198                                         BaseEnd = ClassDecl->vbases_end();
7199         HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7200      assert(!Base->getType()->isDependentType() &&
7201             "Cannot generate implicit members for class with dependent bases.");
7202      CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7203      LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7204                              &HasConstCopyAssignment);
7205    }
7206  }
7207
7208  //       -- for all the nonstatic data members of X that are of a class
7209  //          type M (or array thereof), each such class type has a copy
7210  //          assignment operator whose parameter is of type const M&,
7211  //          const volatile M& or M.
7212  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7213                                  FieldEnd = ClassDecl->field_end();
7214       HasConstCopyAssignment && Field != FieldEnd;
7215       ++Field) {
7216    QualType FieldType = Context.getBaseElementType((*Field)->getType());
7217    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7218      LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7219                              &HasConstCopyAssignment);
7220    }
7221  }
7222
7223  //   Otherwise, the implicitly declared copy assignment operator will
7224  //   have the form
7225  //
7226  //       X& X::operator=(X&)
7227
7228  // C++ [except.spec]p14:
7229  //   An implicitly declared special member function (Clause 12) shall have an
7230  //   exception-specification. [...]
7231
7232  // It is unspecified whether or not an implicit copy assignment operator
7233  // attempts to deduplicate calls to assignment operators of virtual bases are
7234  // made. As such, this exception specification is effectively unspecified.
7235  // Based on a similar decision made for constness in C++0x, we're erring on
7236  // the side of assuming such calls to be made regardless of whether they
7237  // actually happen.
7238  ImplicitExceptionSpecification ExceptSpec(Context);
7239  unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
7240  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7241                                       BaseEnd = ClassDecl->bases_end();
7242       Base != BaseEnd; ++Base) {
7243    if (Base->isVirtual())
7244      continue;
7245
7246    CXXRecordDecl *BaseClassDecl
7247      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7248    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7249                                                            ArgQuals, false, 0))
7250      ExceptSpec.CalledDecl(CopyAssign);
7251  }
7252
7253  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7254                                       BaseEnd = ClassDecl->vbases_end();
7255       Base != BaseEnd; ++Base) {
7256    CXXRecordDecl *BaseClassDecl
7257      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7258    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7259                                                            ArgQuals, false, 0))
7260      ExceptSpec.CalledDecl(CopyAssign);
7261  }
7262
7263  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7264                                  FieldEnd = ClassDecl->field_end();
7265       Field != FieldEnd;
7266       ++Field) {
7267    QualType FieldType = Context.getBaseElementType((*Field)->getType());
7268    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7269      if (CXXMethodDecl *CopyAssign =
7270          LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7271        ExceptSpec.CalledDecl(CopyAssign);
7272    }
7273  }
7274
7275  return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7276}
7277
7278CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7279  // Note: The following rules are largely analoguous to the copy
7280  // constructor rules. Note that virtual bases are not taken into account
7281  // for determining the argument type of the operator. Note also that
7282  // operators taking an object instead of a reference are allowed.
7283
7284  ImplicitExceptionSpecification Spec(Context);
7285  bool Const;
7286  llvm::tie(Spec, Const) =
7287    ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7288
7289  QualType ArgType = Context.getTypeDeclType(ClassDecl);
7290  QualType RetType = Context.getLValueReferenceType(ArgType);
7291  if (Const)
7292    ArgType = ArgType.withConst();
7293  ArgType = Context.getLValueReferenceType(ArgType);
7294
7295  //   An implicitly-declared copy assignment operator is an inline public
7296  //   member of its class.
7297  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7298  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7299  SourceLocation ClassLoc = ClassDecl->getLocation();
7300  DeclarationNameInfo NameInfo(Name, ClassLoc);
7301  CXXMethodDecl *CopyAssignment
7302    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7303                            Context.getFunctionType(RetType, &ArgType, 1, EPI),
7304                            /*TInfo=*/0, /*isStatic=*/false,
7305                            /*StorageClassAsWritten=*/SC_None,
7306                            /*isInline=*/true, /*isConstexpr=*/false,
7307                            SourceLocation());
7308  CopyAssignment->setAccess(AS_public);
7309  CopyAssignment->setDefaulted();
7310  CopyAssignment->setImplicit();
7311  CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
7312
7313  // Add the parameter to the operator.
7314  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
7315                                               ClassLoc, ClassLoc, /*Id=*/0,
7316                                               ArgType, /*TInfo=*/0,
7317                                               SC_None,
7318                                               SC_None, 0);
7319  CopyAssignment->setParams(&FromParam, 1);
7320
7321  // Note that we have added this copy-assignment operator.
7322  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
7323
7324  if (Scope *S = getScopeForContext(ClassDecl))
7325    PushOnScopeChains(CopyAssignment, S, false);
7326  ClassDecl->addDecl(CopyAssignment);
7327
7328  // C++0x [class.copy]p18:
7329  //   ... If the class definition declares a move constructor or move
7330  //   assignment operator, the implicitly declared copy assignment operator is
7331  //   defined as deleted; ...
7332  if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7333      ClassDecl->hasUserDeclaredMoveAssignment() ||
7334      ShouldDeleteCopyAssignmentOperator(CopyAssignment))
7335    CopyAssignment->setDeletedAsWritten();
7336
7337  AddOverriddenMethods(ClassDecl, CopyAssignment);
7338  return CopyAssignment;
7339}
7340
7341void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7342                                        CXXMethodDecl *CopyAssignOperator) {
7343  assert((CopyAssignOperator->isDefaulted() &&
7344          CopyAssignOperator->isOverloadedOperator() &&
7345          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
7346          !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
7347         "DefineImplicitCopyAssignment called for wrong function");
7348
7349  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7350
7351  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7352    CopyAssignOperator->setInvalidDecl();
7353    return;
7354  }
7355
7356  CopyAssignOperator->setUsed();
7357
7358  ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
7359  DiagnosticErrorTrap Trap(Diags);
7360
7361  // C++0x [class.copy]p30:
7362  //   The implicitly-defined or explicitly-defaulted copy assignment operator
7363  //   for a non-union class X performs memberwise copy assignment of its
7364  //   subobjects. The direct base classes of X are assigned first, in the
7365  //   order of their declaration in the base-specifier-list, and then the
7366  //   immediate non-static data members of X are assigned, in the order in
7367  //   which they were declared in the class definition.
7368
7369  // The statements that form the synthesized function body.
7370  ASTOwningVector<Stmt*> Statements(*this);
7371
7372  // The parameter for the "other" object, which we are copying from.
7373  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7374  Qualifiers OtherQuals = Other->getType().getQualifiers();
7375  QualType OtherRefType = Other->getType();
7376  if (const LValueReferenceType *OtherRef
7377                                = OtherRefType->getAs<LValueReferenceType>()) {
7378    OtherRefType = OtherRef->getPointeeType();
7379    OtherQuals = OtherRefType.getQualifiers();
7380  }
7381
7382  // Our location for everything implicitly-generated.
7383  SourceLocation Loc = CopyAssignOperator->getLocation();
7384
7385  // Construct a reference to the "other" object. We'll be using this
7386  // throughout the generated ASTs.
7387  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7388  assert(OtherRef && "Reference to parameter cannot fail!");
7389
7390  // Construct the "this" pointer. We'll be using this throughout the generated
7391  // ASTs.
7392  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7393  assert(This && "Reference to this cannot fail!");
7394
7395  // Assign base classes.
7396  bool Invalid = false;
7397  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7398       E = ClassDecl->bases_end(); Base != E; ++Base) {
7399    // Form the assignment:
7400    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7401    QualType BaseType = Base->getType().getUnqualifiedType();
7402    if (!BaseType->isRecordType()) {
7403      Invalid = true;
7404      continue;
7405    }
7406
7407    CXXCastPath BasePath;
7408    BasePath.push_back(Base);
7409
7410    // Construct the "from" expression, which is an implicit cast to the
7411    // appropriately-qualified base type.
7412    Expr *From = OtherRef;
7413    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7414                             CK_UncheckedDerivedToBase,
7415                             VK_LValue, &BasePath).take();
7416
7417    // Dereference "this".
7418    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7419
7420    // Implicitly cast "this" to the appropriately-qualified base type.
7421    To = ImpCastExprToType(To.take(),
7422                           Context.getCVRQualifiedType(BaseType,
7423                                     CopyAssignOperator->getTypeQualifiers()),
7424                           CK_UncheckedDerivedToBase,
7425                           VK_LValue, &BasePath);
7426
7427    // Build the copy.
7428    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
7429                                            To.get(), From,
7430                                            /*CopyingBaseSubobject=*/true,
7431                                            /*Copying=*/true);
7432    if (Copy.isInvalid()) {
7433      Diag(CurrentLocation, diag::note_member_synthesized_at)
7434        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7435      CopyAssignOperator->setInvalidDecl();
7436      return;
7437    }
7438
7439    // Success! Record the copy.
7440    Statements.push_back(Copy.takeAs<Expr>());
7441  }
7442
7443  // \brief Reference to the __builtin_memcpy function.
7444  Expr *BuiltinMemCpyRef = 0;
7445  // \brief Reference to the __builtin_objc_memmove_collectable function.
7446  Expr *CollectableMemCpyRef = 0;
7447
7448  // Assign non-static members.
7449  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7450                                  FieldEnd = ClassDecl->field_end();
7451       Field != FieldEnd; ++Field) {
7452    // Check for members of reference type; we can't copy those.
7453    if (Field->getType()->isReferenceType()) {
7454      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7455        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7456      Diag(Field->getLocation(), diag::note_declared_at);
7457      Diag(CurrentLocation, diag::note_member_synthesized_at)
7458        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7459      Invalid = true;
7460      continue;
7461    }
7462
7463    // Check for members of const-qualified, non-class type.
7464    QualType BaseType = Context.getBaseElementType(Field->getType());
7465    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7466      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7467        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7468      Diag(Field->getLocation(), diag::note_declared_at);
7469      Diag(CurrentLocation, diag::note_member_synthesized_at)
7470        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7471      Invalid = true;
7472      continue;
7473    }
7474
7475    // Suppress assigning zero-width bitfields.
7476    if (const Expr *Width = Field->getBitWidth())
7477      if (Width->EvaluateAsInt(Context) == 0)
7478        continue;
7479
7480    QualType FieldType = Field->getType().getNonReferenceType();
7481    if (FieldType->isIncompleteArrayType()) {
7482      assert(ClassDecl->hasFlexibleArrayMember() &&
7483             "Incomplete array type is not valid");
7484      continue;
7485    }
7486
7487    // Build references to the field in the object we're copying from and to.
7488    CXXScopeSpec SS; // Intentionally empty
7489    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7490                              LookupMemberName);
7491    MemberLookup.addDecl(*Field);
7492    MemberLookup.resolveKind();
7493    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7494                                               Loc, /*IsArrow=*/false,
7495                                               SS, 0, MemberLookup, 0);
7496    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7497                                             Loc, /*IsArrow=*/true,
7498                                             SS, 0, MemberLookup, 0);
7499    assert(!From.isInvalid() && "Implicit field reference cannot fail");
7500    assert(!To.isInvalid() && "Implicit field reference cannot fail");
7501
7502    // If the field should be copied with __builtin_memcpy rather than via
7503    // explicit assignments, do so. This optimization only applies for arrays
7504    // of scalars and arrays of class type with trivial copy-assignment
7505    // operators.
7506    if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7507        && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
7508      // Compute the size of the memory buffer to be copied.
7509      QualType SizeType = Context.getSizeType();
7510      llvm::APInt Size(Context.getTypeSize(SizeType),
7511                       Context.getTypeSizeInChars(BaseType).getQuantity());
7512      for (const ConstantArrayType *Array
7513              = Context.getAsConstantArrayType(FieldType);
7514           Array;
7515           Array = Context.getAsConstantArrayType(Array->getElementType())) {
7516        llvm::APInt ArraySize
7517          = Array->getSize().zextOrTrunc(Size.getBitWidth());
7518        Size *= ArraySize;
7519      }
7520
7521      // Take the address of the field references for "from" and "to".
7522      From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7523      To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
7524
7525      bool NeedsCollectableMemCpy =
7526          (BaseType->isRecordType() &&
7527           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7528
7529      if (NeedsCollectableMemCpy) {
7530        if (!CollectableMemCpyRef) {
7531          // Create a reference to the __builtin_objc_memmove_collectable function.
7532          LookupResult R(*this,
7533                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
7534                         Loc, LookupOrdinaryName);
7535          LookupName(R, TUScope, true);
7536
7537          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7538          if (!CollectableMemCpy) {
7539            // Something went horribly wrong earlier, and we will have
7540            // complained about it.
7541            Invalid = true;
7542            continue;
7543          }
7544
7545          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7546                                                  CollectableMemCpy->getType(),
7547                                                  VK_LValue, Loc, 0).take();
7548          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7549        }
7550      }
7551      // Create a reference to the __builtin_memcpy builtin function.
7552      else if (!BuiltinMemCpyRef) {
7553        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7554                       LookupOrdinaryName);
7555        LookupName(R, TUScope, true);
7556
7557        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7558        if (!BuiltinMemCpy) {
7559          // Something went horribly wrong earlier, and we will have complained
7560          // about it.
7561          Invalid = true;
7562          continue;
7563        }
7564
7565        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7566                                            BuiltinMemCpy->getType(),
7567                                            VK_LValue, Loc, 0).take();
7568        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7569      }
7570
7571      ASTOwningVector<Expr*> CallArgs(*this);
7572      CallArgs.push_back(To.takeAs<Expr>());
7573      CallArgs.push_back(From.takeAs<Expr>());
7574      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
7575      ExprResult Call = ExprError();
7576      if (NeedsCollectableMemCpy)
7577        Call = ActOnCallExpr(/*Scope=*/0,
7578                             CollectableMemCpyRef,
7579                             Loc, move_arg(CallArgs),
7580                             Loc);
7581      else
7582        Call = ActOnCallExpr(/*Scope=*/0,
7583                             BuiltinMemCpyRef,
7584                             Loc, move_arg(CallArgs),
7585                             Loc);
7586
7587      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7588      Statements.push_back(Call.takeAs<Expr>());
7589      continue;
7590    }
7591
7592    // Build the copy of this field.
7593    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
7594                                            To.get(), From.get(),
7595                                            /*CopyingBaseSubobject=*/false,
7596                                            /*Copying=*/true);
7597    if (Copy.isInvalid()) {
7598      Diag(CurrentLocation, diag::note_member_synthesized_at)
7599        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7600      CopyAssignOperator->setInvalidDecl();
7601      return;
7602    }
7603
7604    // Success! Record the copy.
7605    Statements.push_back(Copy.takeAs<Stmt>());
7606  }
7607
7608  if (!Invalid) {
7609    // Add a "return *this;"
7610    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7611
7612    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
7613    if (Return.isInvalid())
7614      Invalid = true;
7615    else {
7616      Statements.push_back(Return.takeAs<Stmt>());
7617
7618      if (Trap.hasErrorOccurred()) {
7619        Diag(CurrentLocation, diag::note_member_synthesized_at)
7620          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7621        Invalid = true;
7622      }
7623    }
7624  }
7625
7626  if (Invalid) {
7627    CopyAssignOperator->setInvalidDecl();
7628    return;
7629  }
7630
7631  StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7632                                            /*isStmtExpr=*/false);
7633  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7634  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
7635
7636  if (ASTMutationListener *L = getASTMutationListener()) {
7637    L->CompletedImplicitDefinition(CopyAssignOperator);
7638  }
7639}
7640
7641Sema::ImplicitExceptionSpecification
7642Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7643  ImplicitExceptionSpecification ExceptSpec(Context);
7644
7645  if (ClassDecl->isInvalidDecl())
7646    return ExceptSpec;
7647
7648  // C++0x [except.spec]p14:
7649  //   An implicitly declared special member function (Clause 12) shall have an
7650  //   exception-specification. [...]
7651
7652  // It is unspecified whether or not an implicit move assignment operator
7653  // attempts to deduplicate calls to assignment operators of virtual bases are
7654  // made. As such, this exception specification is effectively unspecified.
7655  // Based on a similar decision made for constness in C++0x, we're erring on
7656  // the side of assuming such calls to be made regardless of whether they
7657  // actually happen.
7658  // Note that a move constructor is not implicitly declared when there are
7659  // virtual bases, but it can still be user-declared and explicitly defaulted.
7660  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7661                                       BaseEnd = ClassDecl->bases_end();
7662       Base != BaseEnd; ++Base) {
7663    if (Base->isVirtual())
7664      continue;
7665
7666    CXXRecordDecl *BaseClassDecl
7667      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7668    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7669                                                           false, 0))
7670      ExceptSpec.CalledDecl(MoveAssign);
7671  }
7672
7673  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7674                                       BaseEnd = ClassDecl->vbases_end();
7675       Base != BaseEnd; ++Base) {
7676    CXXRecordDecl *BaseClassDecl
7677      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7678    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7679                                                           false, 0))
7680      ExceptSpec.CalledDecl(MoveAssign);
7681  }
7682
7683  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7684                                  FieldEnd = ClassDecl->field_end();
7685       Field != FieldEnd;
7686       ++Field) {
7687    QualType FieldType = Context.getBaseElementType((*Field)->getType());
7688    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7689      if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
7690                                                             false, 0))
7691        ExceptSpec.CalledDecl(MoveAssign);
7692    }
7693  }
7694
7695  return ExceptSpec;
7696}
7697
7698CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
7699  // Note: The following rules are largely analoguous to the move
7700  // constructor rules.
7701
7702  ImplicitExceptionSpecification Spec(
7703      ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
7704
7705  QualType ArgType = Context.getTypeDeclType(ClassDecl);
7706  QualType RetType = Context.getLValueReferenceType(ArgType);
7707  ArgType = Context.getRValueReferenceType(ArgType);
7708
7709  //   An implicitly-declared move assignment operator is an inline public
7710  //   member of its class.
7711  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7712  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7713  SourceLocation ClassLoc = ClassDecl->getLocation();
7714  DeclarationNameInfo NameInfo(Name, ClassLoc);
7715  CXXMethodDecl *MoveAssignment
7716    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7717                            Context.getFunctionType(RetType, &ArgType, 1, EPI),
7718                            /*TInfo=*/0, /*isStatic=*/false,
7719                            /*StorageClassAsWritten=*/SC_None,
7720                            /*isInline=*/true,
7721                            /*isConstexpr=*/false,
7722                            SourceLocation());
7723  MoveAssignment->setAccess(AS_public);
7724  MoveAssignment->setDefaulted();
7725  MoveAssignment->setImplicit();
7726  MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
7727
7728  // Add the parameter to the operator.
7729  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
7730                                               ClassLoc, ClassLoc, /*Id=*/0,
7731                                               ArgType, /*TInfo=*/0,
7732                                               SC_None,
7733                                               SC_None, 0);
7734  MoveAssignment->setParams(&FromParam, 1);
7735
7736  // Note that we have added this copy-assignment operator.
7737  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
7738
7739  // C++0x [class.copy]p9:
7740  //   If the definition of a class X does not explicitly declare a move
7741  //   assignment operator, one will be implicitly declared as defaulted if and
7742  //   only if:
7743  //   [...]
7744  //   - the move assignment operator would not be implicitly defined as
7745  //     deleted.
7746  if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
7747    // Cache this result so that we don't try to generate this over and over
7748    // on every lookup, leaking memory and wasting time.
7749    ClassDecl->setFailedImplicitMoveAssignment();
7750    return 0;
7751  }
7752
7753  if (Scope *S = getScopeForContext(ClassDecl))
7754    PushOnScopeChains(MoveAssignment, S, false);
7755  ClassDecl->addDecl(MoveAssignment);
7756
7757  AddOverriddenMethods(ClassDecl, MoveAssignment);
7758  return MoveAssignment;
7759}
7760
7761void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
7762                                        CXXMethodDecl *MoveAssignOperator) {
7763  assert((MoveAssignOperator->isDefaulted() &&
7764          MoveAssignOperator->isOverloadedOperator() &&
7765          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
7766          !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
7767         "DefineImplicitMoveAssignment called for wrong function");
7768
7769  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
7770
7771  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
7772    MoveAssignOperator->setInvalidDecl();
7773    return;
7774  }
7775
7776  MoveAssignOperator->setUsed();
7777
7778  ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
7779  DiagnosticErrorTrap Trap(Diags);
7780
7781  // C++0x [class.copy]p28:
7782  //   The implicitly-defined or move assignment operator for a non-union class
7783  //   X performs memberwise move assignment of its subobjects. The direct base
7784  //   classes of X are assigned first, in the order of their declaration in the
7785  //   base-specifier-list, and then the immediate non-static data members of X
7786  //   are assigned, in the order in which they were declared in the class
7787  //   definition.
7788
7789  // The statements that form the synthesized function body.
7790  ASTOwningVector<Stmt*> Statements(*this);
7791
7792  // The parameter for the "other" object, which we are move from.
7793  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
7794  QualType OtherRefType = Other->getType()->
7795      getAs<RValueReferenceType>()->getPointeeType();
7796  assert(OtherRefType.getQualifiers() == 0 &&
7797         "Bad argument type of defaulted move assignment");
7798
7799  // Our location for everything implicitly-generated.
7800  SourceLocation Loc = MoveAssignOperator->getLocation();
7801
7802  // Construct a reference to the "other" object. We'll be using this
7803  // throughout the generated ASTs.
7804  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7805  assert(OtherRef && "Reference to parameter cannot fail!");
7806  // Cast to rvalue.
7807  OtherRef = CastForMoving(*this, OtherRef);
7808
7809  // Construct the "this" pointer. We'll be using this throughout the generated
7810  // ASTs.
7811  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7812  assert(This && "Reference to this cannot fail!");
7813
7814  // Assign base classes.
7815  bool Invalid = false;
7816  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7817       E = ClassDecl->bases_end(); Base != E; ++Base) {
7818    // Form the assignment:
7819    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
7820    QualType BaseType = Base->getType().getUnqualifiedType();
7821    if (!BaseType->isRecordType()) {
7822      Invalid = true;
7823      continue;
7824    }
7825
7826    CXXCastPath BasePath;
7827    BasePath.push_back(Base);
7828
7829    // Construct the "from" expression, which is an implicit cast to the
7830    // appropriately-qualified base type.
7831    Expr *From = OtherRef;
7832    From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
7833                             VK_XValue, &BasePath).take();
7834
7835    // Dereference "this".
7836    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7837
7838    // Implicitly cast "this" to the appropriately-qualified base type.
7839    To = ImpCastExprToType(To.take(),
7840                           Context.getCVRQualifiedType(BaseType,
7841                                     MoveAssignOperator->getTypeQualifiers()),
7842                           CK_UncheckedDerivedToBase,
7843                           VK_LValue, &BasePath);
7844
7845    // Build the move.
7846    StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
7847                                            To.get(), From,
7848                                            /*CopyingBaseSubobject=*/true,
7849                                            /*Copying=*/false);
7850    if (Move.isInvalid()) {
7851      Diag(CurrentLocation, diag::note_member_synthesized_at)
7852        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7853      MoveAssignOperator->setInvalidDecl();
7854      return;
7855    }
7856
7857    // Success! Record the move.
7858    Statements.push_back(Move.takeAs<Expr>());
7859  }
7860
7861  // \brief Reference to the __builtin_memcpy function.
7862  Expr *BuiltinMemCpyRef = 0;
7863  // \brief Reference to the __builtin_objc_memmove_collectable function.
7864  Expr *CollectableMemCpyRef = 0;
7865
7866  // Assign non-static members.
7867  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7868                                  FieldEnd = ClassDecl->field_end();
7869       Field != FieldEnd; ++Field) {
7870    // Check for members of reference type; we can't move those.
7871    if (Field->getType()->isReferenceType()) {
7872      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7873        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7874      Diag(Field->getLocation(), diag::note_declared_at);
7875      Diag(CurrentLocation, diag::note_member_synthesized_at)
7876        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7877      Invalid = true;
7878      continue;
7879    }
7880
7881    // Check for members of const-qualified, non-class type.
7882    QualType BaseType = Context.getBaseElementType(Field->getType());
7883    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7884      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7885        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7886      Diag(Field->getLocation(), diag::note_declared_at);
7887      Diag(CurrentLocation, diag::note_member_synthesized_at)
7888        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7889      Invalid = true;
7890      continue;
7891    }
7892
7893    // Suppress assigning zero-width bitfields.
7894    if (const Expr *Width = Field->getBitWidth())
7895      if (Width->EvaluateAsInt(Context) == 0)
7896        continue;
7897
7898    QualType FieldType = Field->getType().getNonReferenceType();
7899    if (FieldType->isIncompleteArrayType()) {
7900      assert(ClassDecl->hasFlexibleArrayMember() &&
7901             "Incomplete array type is not valid");
7902      continue;
7903    }
7904
7905    // Build references to the field in the object we're copying from and to.
7906    CXXScopeSpec SS; // Intentionally empty
7907    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7908                              LookupMemberName);
7909    MemberLookup.addDecl(*Field);
7910    MemberLookup.resolveKind();
7911    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7912                                               Loc, /*IsArrow=*/false,
7913                                               SS, 0, MemberLookup, 0);
7914    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7915                                             Loc, /*IsArrow=*/true,
7916                                             SS, 0, MemberLookup, 0);
7917    assert(!From.isInvalid() && "Implicit field reference cannot fail");
7918    assert(!To.isInvalid() && "Implicit field reference cannot fail");
7919
7920    assert(!From.get()->isLValue() && // could be xvalue or prvalue
7921        "Member reference with rvalue base must be rvalue except for reference "
7922        "members, which aren't allowed for move assignment.");
7923
7924    // If the field should be copied with __builtin_memcpy rather than via
7925    // explicit assignments, do so. This optimization only applies for arrays
7926    // of scalars and arrays of class type with trivial move-assignment
7927    // operators.
7928    if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7929        && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
7930      // Compute the size of the memory buffer to be copied.
7931      QualType SizeType = Context.getSizeType();
7932      llvm::APInt Size(Context.getTypeSize(SizeType),
7933                       Context.getTypeSizeInChars(BaseType).getQuantity());
7934      for (const ConstantArrayType *Array
7935              = Context.getAsConstantArrayType(FieldType);
7936           Array;
7937           Array = Context.getAsConstantArrayType(Array->getElementType())) {
7938        llvm::APInt ArraySize
7939          = Array->getSize().zextOrTrunc(Size.getBitWidth());
7940        Size *= ArraySize;
7941      }
7942
7943      // Take the address of the field references for "from" and "to". We
7944      // directly construct UnaryOperators here because semantic analysis
7945      // does not permit us to take the address of an xvalue.
7946      From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
7947                             Context.getPointerType(From.get()->getType()),
7948                             VK_RValue, OK_Ordinary, Loc);
7949      To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
7950                           Context.getPointerType(To.get()->getType()),
7951                           VK_RValue, OK_Ordinary, Loc);
7952
7953      bool NeedsCollectableMemCpy =
7954          (BaseType->isRecordType() &&
7955           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7956
7957      if (NeedsCollectableMemCpy) {
7958        if (!CollectableMemCpyRef) {
7959          // Create a reference to the __builtin_objc_memmove_collectable function.
7960          LookupResult R(*this,
7961                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
7962                         Loc, LookupOrdinaryName);
7963          LookupName(R, TUScope, true);
7964
7965          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7966          if (!CollectableMemCpy) {
7967            // Something went horribly wrong earlier, and we will have
7968            // complained about it.
7969            Invalid = true;
7970            continue;
7971          }
7972
7973          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7974                                                  CollectableMemCpy->getType(),
7975                                                  VK_LValue, Loc, 0).take();
7976          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7977        }
7978      }
7979      // Create a reference to the __builtin_memcpy builtin function.
7980      else if (!BuiltinMemCpyRef) {
7981        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7982                       LookupOrdinaryName);
7983        LookupName(R, TUScope, true);
7984
7985        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7986        if (!BuiltinMemCpy) {
7987          // Something went horribly wrong earlier, and we will have complained
7988          // about it.
7989          Invalid = true;
7990          continue;
7991        }
7992
7993        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7994                                            BuiltinMemCpy->getType(),
7995                                            VK_LValue, Loc, 0).take();
7996        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7997      }
7998
7999      ASTOwningVector<Expr*> CallArgs(*this);
8000      CallArgs.push_back(To.takeAs<Expr>());
8001      CallArgs.push_back(From.takeAs<Expr>());
8002      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8003      ExprResult Call = ExprError();
8004      if (NeedsCollectableMemCpy)
8005        Call = ActOnCallExpr(/*Scope=*/0,
8006                             CollectableMemCpyRef,
8007                             Loc, move_arg(CallArgs),
8008                             Loc);
8009      else
8010        Call = ActOnCallExpr(/*Scope=*/0,
8011                             BuiltinMemCpyRef,
8012                             Loc, move_arg(CallArgs),
8013                             Loc);
8014
8015      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8016      Statements.push_back(Call.takeAs<Expr>());
8017      continue;
8018    }
8019
8020    // Build the move of this field.
8021    StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8022                                            To.get(), From.get(),
8023                                            /*CopyingBaseSubobject=*/false,
8024                                            /*Copying=*/false);
8025    if (Move.isInvalid()) {
8026      Diag(CurrentLocation, diag::note_member_synthesized_at)
8027        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8028      MoveAssignOperator->setInvalidDecl();
8029      return;
8030    }
8031
8032    // Success! Record the copy.
8033    Statements.push_back(Move.takeAs<Stmt>());
8034  }
8035
8036  if (!Invalid) {
8037    // Add a "return *this;"
8038    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8039
8040    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8041    if (Return.isInvalid())
8042      Invalid = true;
8043    else {
8044      Statements.push_back(Return.takeAs<Stmt>());
8045
8046      if (Trap.hasErrorOccurred()) {
8047        Diag(CurrentLocation, diag::note_member_synthesized_at)
8048          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8049        Invalid = true;
8050      }
8051    }
8052  }
8053
8054  if (Invalid) {
8055    MoveAssignOperator->setInvalidDecl();
8056    return;
8057  }
8058
8059  StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8060                                            /*isStmtExpr=*/false);
8061  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8062  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8063
8064  if (ASTMutationListener *L = getASTMutationListener()) {
8065    L->CompletedImplicitDefinition(MoveAssignOperator);
8066  }
8067}
8068
8069std::pair<Sema::ImplicitExceptionSpecification, bool>
8070Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
8071  if (ClassDecl->isInvalidDecl())
8072    return std::make_pair(ImplicitExceptionSpecification(Context), false);
8073
8074  // C++ [class.copy]p5:
8075  //   The implicitly-declared copy constructor for a class X will
8076  //   have the form
8077  //
8078  //       X::X(const X&)
8079  //
8080  //   if
8081  // FIXME: It ought to be possible to store this on the record.
8082  bool HasConstCopyConstructor = true;
8083
8084  //     -- each direct or virtual base class B of X has a copy
8085  //        constructor whose first parameter is of type const B& or
8086  //        const volatile B&, and
8087  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8088                                       BaseEnd = ClassDecl->bases_end();
8089       HasConstCopyConstructor && Base != BaseEnd;
8090       ++Base) {
8091    // Virtual bases are handled below.
8092    if (Base->isVirtual())
8093      continue;
8094
8095    CXXRecordDecl *BaseClassDecl
8096      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8097    LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8098                             &HasConstCopyConstructor);
8099  }
8100
8101  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8102                                       BaseEnd = ClassDecl->vbases_end();
8103       HasConstCopyConstructor && Base != BaseEnd;
8104       ++Base) {
8105    CXXRecordDecl *BaseClassDecl
8106      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8107    LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8108                             &HasConstCopyConstructor);
8109  }
8110
8111  //     -- for all the nonstatic data members of X that are of a
8112  //        class type M (or array thereof), each such class type
8113  //        has a copy constructor whose first parameter is of type
8114  //        const M& or const volatile M&.
8115  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8116                                  FieldEnd = ClassDecl->field_end();
8117       HasConstCopyConstructor && Field != FieldEnd;
8118       ++Field) {
8119    QualType FieldType = Context.getBaseElementType((*Field)->getType());
8120    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8121      LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8122                               &HasConstCopyConstructor);
8123    }
8124  }
8125  //   Otherwise, the implicitly declared copy constructor will have
8126  //   the form
8127  //
8128  //       X::X(X&)
8129
8130  // C++ [except.spec]p14:
8131  //   An implicitly declared special member function (Clause 12) shall have an
8132  //   exception-specification. [...]
8133  ImplicitExceptionSpecification ExceptSpec(Context);
8134  unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8135  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8136                                       BaseEnd = ClassDecl->bases_end();
8137       Base != BaseEnd;
8138       ++Base) {
8139    // Virtual bases are handled below.
8140    if (Base->isVirtual())
8141      continue;
8142
8143    CXXRecordDecl *BaseClassDecl
8144      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8145    if (CXXConstructorDecl *CopyConstructor =
8146          LookupCopyingConstructor(BaseClassDecl, Quals))
8147      ExceptSpec.CalledDecl(CopyConstructor);
8148  }
8149  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8150                                       BaseEnd = ClassDecl->vbases_end();
8151       Base != BaseEnd;
8152       ++Base) {
8153    CXXRecordDecl *BaseClassDecl
8154      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8155    if (CXXConstructorDecl *CopyConstructor =
8156          LookupCopyingConstructor(BaseClassDecl, Quals))
8157      ExceptSpec.CalledDecl(CopyConstructor);
8158  }
8159  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8160                                  FieldEnd = ClassDecl->field_end();
8161       Field != FieldEnd;
8162       ++Field) {
8163    QualType FieldType = Context.getBaseElementType((*Field)->getType());
8164    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8165      if (CXXConstructorDecl *CopyConstructor =
8166        LookupCopyingConstructor(FieldClassDecl, Quals))
8167      ExceptSpec.CalledDecl(CopyConstructor);
8168    }
8169  }
8170
8171  return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8172}
8173
8174CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8175                                                    CXXRecordDecl *ClassDecl) {
8176  // C++ [class.copy]p4:
8177  //   If the class definition does not explicitly declare a copy
8178  //   constructor, one is declared implicitly.
8179
8180  ImplicitExceptionSpecification Spec(Context);
8181  bool Const;
8182  llvm::tie(Spec, Const) =
8183    ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8184
8185  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8186  QualType ArgType = ClassType;
8187  if (Const)
8188    ArgType = ArgType.withConst();
8189  ArgType = Context.getLValueReferenceType(ArgType);
8190
8191  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8192
8193  DeclarationName Name
8194    = Context.DeclarationNames.getCXXConstructorName(
8195                                           Context.getCanonicalType(ClassType));
8196  SourceLocation ClassLoc = ClassDecl->getLocation();
8197  DeclarationNameInfo NameInfo(Name, ClassLoc);
8198
8199  //   An implicitly-declared copy constructor is an inline public
8200  //   member of its class.
8201  CXXConstructorDecl *CopyConstructor
8202    = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8203                                 Context.getFunctionType(Context.VoidTy,
8204                                                         &ArgType, 1, EPI),
8205                                 /*TInfo=*/0,
8206                                 /*isExplicit=*/false,
8207                                 /*isInline=*/true,
8208                                 /*isImplicitlyDeclared=*/true,
8209                                 // FIXME: apply the rules for definitions here
8210                                 /*isConstexpr=*/false);
8211  CopyConstructor->setAccess(AS_public);
8212  CopyConstructor->setDefaulted();
8213  CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8214
8215  // Note that we have declared this constructor.
8216  ++ASTContext::NumImplicitCopyConstructorsDeclared;
8217
8218  // Add the parameter to the constructor.
8219  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
8220                                               ClassLoc, ClassLoc,
8221                                               /*IdentifierInfo=*/0,
8222                                               ArgType, /*TInfo=*/0,
8223                                               SC_None,
8224                                               SC_None, 0);
8225  CopyConstructor->setParams(&FromParam, 1);
8226
8227  if (Scope *S = getScopeForContext(ClassDecl))
8228    PushOnScopeChains(CopyConstructor, S, false);
8229  ClassDecl->addDecl(CopyConstructor);
8230
8231  // C++0x [class.copy]p7:
8232  //   ... If the class definition declares a move constructor or move
8233  //   assignment operator, the implicitly declared constructor is defined as
8234  //   deleted; ...
8235  if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8236      ClassDecl->hasUserDeclaredMoveAssignment() ||
8237      ShouldDeleteCopyConstructor(CopyConstructor))
8238    CopyConstructor->setDeletedAsWritten();
8239
8240  return CopyConstructor;
8241}
8242
8243void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
8244                                   CXXConstructorDecl *CopyConstructor) {
8245  assert((CopyConstructor->isDefaulted() &&
8246          CopyConstructor->isCopyConstructor() &&
8247          !CopyConstructor->doesThisDeclarationHaveABody()) &&
8248         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
8249
8250  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
8251  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
8252
8253  ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
8254  DiagnosticErrorTrap Trap(Diags);
8255
8256  if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
8257      Trap.hasErrorOccurred()) {
8258    Diag(CurrentLocation, diag::note_member_synthesized_at)
8259      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
8260    CopyConstructor->setInvalidDecl();
8261  }  else {
8262    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8263                                               CopyConstructor->getLocation(),
8264                                               MultiStmtArg(*this, 0, 0),
8265                                               /*isStmtExpr=*/false)
8266                                                              .takeAs<Stmt>());
8267  }
8268
8269  CopyConstructor->setUsed();
8270
8271  if (ASTMutationListener *L = getASTMutationListener()) {
8272    L->CompletedImplicitDefinition(CopyConstructor);
8273  }
8274}
8275
8276Sema::ImplicitExceptionSpecification
8277Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8278  // C++ [except.spec]p14:
8279  //   An implicitly declared special member function (Clause 12) shall have an
8280  //   exception-specification. [...]
8281  ImplicitExceptionSpecification ExceptSpec(Context);
8282  if (ClassDecl->isInvalidDecl())
8283    return ExceptSpec;
8284
8285  // Direct base-class constructors.
8286  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8287                                       BEnd = ClassDecl->bases_end();
8288       B != BEnd; ++B) {
8289    if (B->isVirtual()) // Handled below.
8290      continue;
8291
8292    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8293      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8294      CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8295      // If this is a deleted function, add it anyway. This might be conformant
8296      // with the standard. This might not. I'm not sure. It might not matter.
8297      if (Constructor)
8298        ExceptSpec.CalledDecl(Constructor);
8299    }
8300  }
8301
8302  // Virtual base-class constructors.
8303  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8304                                       BEnd = ClassDecl->vbases_end();
8305       B != BEnd; ++B) {
8306    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8307      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8308      CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8309      // If this is a deleted function, add it anyway. This might be conformant
8310      // with the standard. This might not. I'm not sure. It might not matter.
8311      if (Constructor)
8312        ExceptSpec.CalledDecl(Constructor);
8313    }
8314  }
8315
8316  // Field constructors.
8317  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8318                               FEnd = ClassDecl->field_end();
8319       F != FEnd; ++F) {
8320    if (F->hasInClassInitializer()) {
8321      if (Expr *E = F->getInClassInitializer())
8322        ExceptSpec.CalledExpr(E);
8323      else if (!F->isInvalidDecl())
8324        ExceptSpec.SetDelayed();
8325    } else if (const RecordType *RecordTy
8326              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8327      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8328      CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8329      // If this is a deleted function, add it anyway. This might be conformant
8330      // with the standard. This might not. I'm not sure. It might not matter.
8331      // In particular, the problem is that this function never gets called. It
8332      // might just be ill-formed because this function attempts to refer to
8333      // a deleted function here.
8334      if (Constructor)
8335        ExceptSpec.CalledDecl(Constructor);
8336    }
8337  }
8338
8339  return ExceptSpec;
8340}
8341
8342CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8343                                                    CXXRecordDecl *ClassDecl) {
8344  ImplicitExceptionSpecification Spec(
8345      ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8346
8347  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8348  QualType ArgType = Context.getRValueReferenceType(ClassType);
8349
8350  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8351
8352  DeclarationName Name
8353    = Context.DeclarationNames.getCXXConstructorName(
8354                                           Context.getCanonicalType(ClassType));
8355  SourceLocation ClassLoc = ClassDecl->getLocation();
8356  DeclarationNameInfo NameInfo(Name, ClassLoc);
8357
8358  // C++0x [class.copy]p11:
8359  //   An implicitly-declared copy/move constructor is an inline public
8360  //   member of its class.
8361  CXXConstructorDecl *MoveConstructor
8362    = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8363                                 Context.getFunctionType(Context.VoidTy,
8364                                                         &ArgType, 1, EPI),
8365                                 /*TInfo=*/0,
8366                                 /*isExplicit=*/false,
8367                                 /*isInline=*/true,
8368                                 /*isImplicitlyDeclared=*/true,
8369                                 // FIXME: apply the rules for definitions here
8370                                 /*isConstexpr=*/false);
8371  MoveConstructor->setAccess(AS_public);
8372  MoveConstructor->setDefaulted();
8373  MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8374
8375  // Add the parameter to the constructor.
8376  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8377                                               ClassLoc, ClassLoc,
8378                                               /*IdentifierInfo=*/0,
8379                                               ArgType, /*TInfo=*/0,
8380                                               SC_None,
8381                                               SC_None, 0);
8382  MoveConstructor->setParams(&FromParam, 1);
8383
8384  // C++0x [class.copy]p9:
8385  //   If the definition of a class X does not explicitly declare a move
8386  //   constructor, one will be implicitly declared as defaulted if and only if:
8387  //   [...]
8388  //   - the move constructor would not be implicitly defined as deleted.
8389  if (ShouldDeleteMoveConstructor(MoveConstructor)) {
8390    // Cache this result so that we don't try to generate this over and over
8391    // on every lookup, leaking memory and wasting time.
8392    ClassDecl->setFailedImplicitMoveConstructor();
8393    return 0;
8394  }
8395
8396  // Note that we have declared this constructor.
8397  ++ASTContext::NumImplicitMoveConstructorsDeclared;
8398
8399  if (Scope *S = getScopeForContext(ClassDecl))
8400    PushOnScopeChains(MoveConstructor, S, false);
8401  ClassDecl->addDecl(MoveConstructor);
8402
8403  return MoveConstructor;
8404}
8405
8406void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8407                                   CXXConstructorDecl *MoveConstructor) {
8408  assert((MoveConstructor->isDefaulted() &&
8409          MoveConstructor->isMoveConstructor() &&
8410          !MoveConstructor->doesThisDeclarationHaveABody()) &&
8411         "DefineImplicitMoveConstructor - call it for implicit move ctor");
8412
8413  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8414  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8415
8416  ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8417  DiagnosticErrorTrap Trap(Diags);
8418
8419  if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8420      Trap.hasErrorOccurred()) {
8421    Diag(CurrentLocation, diag::note_member_synthesized_at)
8422      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8423    MoveConstructor->setInvalidDecl();
8424  }  else {
8425    MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8426                                               MoveConstructor->getLocation(),
8427                                               MultiStmtArg(*this, 0, 0),
8428                                               /*isStmtExpr=*/false)
8429                                                              .takeAs<Stmt>());
8430  }
8431
8432  MoveConstructor->setUsed();
8433
8434  if (ASTMutationListener *L = getASTMutationListener()) {
8435    L->CompletedImplicitDefinition(MoveConstructor);
8436  }
8437}
8438
8439ExprResult
8440Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8441                            CXXConstructorDecl *Constructor,
8442                            MultiExprArg ExprArgs,
8443                            bool RequiresZeroInit,
8444                            unsigned ConstructKind,
8445                            SourceRange ParenRange) {
8446  bool Elidable = false;
8447
8448  // C++0x [class.copy]p34:
8449  //   When certain criteria are met, an implementation is allowed to
8450  //   omit the copy/move construction of a class object, even if the
8451  //   copy/move constructor and/or destructor for the object have
8452  //   side effects. [...]
8453  //     - when a temporary class object that has not been bound to a
8454  //       reference (12.2) would be copied/moved to a class object
8455  //       with the same cv-unqualified type, the copy/move operation
8456  //       can be omitted by constructing the temporary object
8457  //       directly into the target of the omitted copy/move
8458  if (ConstructKind == CXXConstructExpr::CK_Complete &&
8459      Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
8460    Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
8461    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
8462  }
8463
8464  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
8465                               Elidable, move(ExprArgs), RequiresZeroInit,
8466                               ConstructKind, ParenRange);
8467}
8468
8469/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8470/// including handling of its default argument expressions.
8471ExprResult
8472Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8473                            CXXConstructorDecl *Constructor, bool Elidable,
8474                            MultiExprArg ExprArgs,
8475                            bool RequiresZeroInit,
8476                            unsigned ConstructKind,
8477                            SourceRange ParenRange) {
8478  unsigned NumExprs = ExprArgs.size();
8479  Expr **Exprs = (Expr **)ExprArgs.release();
8480
8481  for (specific_attr_iterator<NonNullAttr>
8482           i = Constructor->specific_attr_begin<NonNullAttr>(),
8483           e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8484    const NonNullAttr *NonNull = *i;
8485    CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8486  }
8487
8488  MarkDeclarationReferenced(ConstructLoc, Constructor);
8489  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
8490                                        Constructor, Elidable, Exprs, NumExprs,
8491                                        RequiresZeroInit,
8492              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8493                                        ParenRange));
8494}
8495
8496bool Sema::InitializeVarWithConstructor(VarDecl *VD,
8497                                        CXXConstructorDecl *Constructor,
8498                                        MultiExprArg Exprs) {
8499  // FIXME: Provide the correct paren SourceRange when available.
8500  ExprResult TempResult =
8501    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
8502                          move(Exprs), false, CXXConstructExpr::CK_Complete,
8503                          SourceRange());
8504  if (TempResult.isInvalid())
8505    return true;
8506
8507  Expr *Temp = TempResult.takeAs<Expr>();
8508  CheckImplicitConversions(Temp, VD->getLocation());
8509  MarkDeclarationReferenced(VD->getLocation(), Constructor);
8510  Temp = MaybeCreateExprWithCleanups(Temp);
8511  VD->setInit(Temp);
8512
8513  return false;
8514}
8515
8516void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
8517  if (VD->isInvalidDecl()) return;
8518
8519  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
8520  if (ClassDecl->isInvalidDecl()) return;
8521  if (ClassDecl->hasTrivialDestructor()) return;
8522  if (ClassDecl->isDependentContext()) return;
8523
8524  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8525  MarkDeclarationReferenced(VD->getLocation(), Destructor);
8526  CheckDestructorAccess(VD->getLocation(), Destructor,
8527                        PDiag(diag::err_access_dtor_var)
8528                        << VD->getDeclName()
8529                        << VD->getType());
8530
8531  if (!VD->hasGlobalStorage()) return;
8532
8533  // Emit warning for non-trivial dtor in global scope (a real global,
8534  // class-static, function-static).
8535  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8536
8537  // TODO: this should be re-enabled for static locals by !CXAAtExit
8538  if (!VD->isStaticLocal())
8539    Diag(VD->getLocation(), diag::warn_global_destructor);
8540}
8541
8542/// AddCXXDirectInitializerToDecl - This action is called immediately after
8543/// ActOnDeclarator, when a C++ direct initializer is present.
8544/// e.g: "int x(1);"
8545void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
8546                                         SourceLocation LParenLoc,
8547                                         MultiExprArg Exprs,
8548                                         SourceLocation RParenLoc,
8549                                         bool TypeMayContainAuto) {
8550  assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
8551
8552  // If there is no declaration, there was an error parsing it.  Just ignore
8553  // the initializer.
8554  if (RealDecl == 0)
8555    return;
8556
8557  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8558  if (!VDecl) {
8559    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8560    RealDecl->setInvalidDecl();
8561    return;
8562  }
8563
8564  // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8565  if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
8566    // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
8567    if (Exprs.size() > 1) {
8568      Diag(Exprs.get()[1]->getSourceRange().getBegin(),
8569           diag::err_auto_var_init_multiple_expressions)
8570        << VDecl->getDeclName() << VDecl->getType()
8571        << VDecl->getSourceRange();
8572      RealDecl->setInvalidDecl();
8573      return;
8574    }
8575
8576    Expr *Init = Exprs.get()[0];
8577    TypeSourceInfo *DeducedType = 0;
8578    if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
8579      Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
8580        << VDecl->getDeclName() << VDecl->getType() << Init->getType()
8581        << Init->getSourceRange();
8582    if (!DeducedType) {
8583      RealDecl->setInvalidDecl();
8584      return;
8585    }
8586    VDecl->setTypeSourceInfo(DeducedType);
8587    VDecl->setType(DeducedType->getType());
8588
8589    // In ARC, infer lifetime.
8590    if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8591      VDecl->setInvalidDecl();
8592
8593    // If this is a redeclaration, check that the type we just deduced matches
8594    // the previously declared type.
8595    if (VarDecl *Old = VDecl->getPreviousDeclaration())
8596      MergeVarDeclTypes(VDecl, Old);
8597  }
8598
8599  // We will represent direct-initialization similarly to copy-initialization:
8600  //    int x(1);  -as-> int x = 1;
8601  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8602  //
8603  // Clients that want to distinguish between the two forms, can check for
8604  // direct initializer using VarDecl::hasCXXDirectInitializer().
8605  // A major benefit is that clients that don't particularly care about which
8606  // exactly form was it (like the CodeGen) can handle both cases without
8607  // special case code.
8608
8609  // C++ 8.5p11:
8610  // The form of initialization (using parentheses or '=') is generally
8611  // insignificant, but does matter when the entity being initialized has a
8612  // class type.
8613
8614  if (!VDecl->getType()->isDependentType() &&
8615      RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
8616                          diag::err_typecheck_decl_incomplete_type)) {
8617    VDecl->setInvalidDecl();
8618    return;
8619  }
8620
8621  // The variable can not have an abstract class type.
8622  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8623                             diag::err_abstract_type_in_decl,
8624                             AbstractVariableType))
8625    VDecl->setInvalidDecl();
8626
8627  const VarDecl *Def;
8628  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8629    Diag(VDecl->getLocation(), diag::err_redefinition)
8630    << VDecl->getDeclName();
8631    Diag(Def->getLocation(), diag::note_previous_definition);
8632    VDecl->setInvalidDecl();
8633    return;
8634  }
8635
8636  // C++ [class.static.data]p4
8637  //   If a static data member is of const integral or const
8638  //   enumeration type, its declaration in the class definition can
8639  //   specify a constant-initializer which shall be an integral
8640  //   constant expression (5.19). In that case, the member can appear
8641  //   in integral constant expressions. The member shall still be
8642  //   defined in a namespace scope if it is used in the program and the
8643  //   namespace scope definition shall not contain an initializer.
8644  //
8645  // We already performed a redefinition check above, but for static
8646  // data members we also need to check whether there was an in-class
8647  // declaration with an initializer.
8648  const VarDecl* PrevInit = 0;
8649  if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8650    Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
8651    Diag(PrevInit->getLocation(), diag::note_previous_definition);
8652    return;
8653  }
8654
8655  bool IsDependent = false;
8656  for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
8657    if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
8658      VDecl->setInvalidDecl();
8659      return;
8660    }
8661
8662    if (Exprs.get()[I]->isTypeDependent())
8663      IsDependent = true;
8664  }
8665
8666  // If either the declaration has a dependent type or if any of the
8667  // expressions is type-dependent, we represent the initialization
8668  // via a ParenListExpr for later use during template instantiation.
8669  if (VDecl->getType()->isDependentType() || IsDependent) {
8670    // Let clients know that initialization was done with a direct initializer.
8671    VDecl->setCXXDirectInitializer(true);
8672
8673    // Store the initialization expressions as a ParenListExpr.
8674    unsigned NumExprs = Exprs.size();
8675    VDecl->setInit(new (Context) ParenListExpr(
8676        Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
8677        VDecl->getType().getNonReferenceType()));
8678    return;
8679  }
8680
8681  // Capture the variable that is being initialized and the style of
8682  // initialization.
8683  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8684
8685  // FIXME: Poor source location information.
8686  InitializationKind Kind
8687    = InitializationKind::CreateDirect(VDecl->getLocation(),
8688                                       LParenLoc, RParenLoc);
8689
8690  InitializationSequence InitSeq(*this, Entity, Kind,
8691                                 Exprs.get(), Exprs.size());
8692  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
8693  if (Result.isInvalid()) {
8694    VDecl->setInvalidDecl();
8695    return;
8696  }
8697
8698  CheckImplicitConversions(Result.get(), LParenLoc);
8699
8700  Result = MaybeCreateExprWithCleanups(Result);
8701  VDecl->setInit(Result.takeAs<Expr>());
8702  VDecl->setCXXDirectInitializer(true);
8703
8704  CheckCompleteVariableDeclaration(VDecl);
8705}
8706
8707/// \brief Given a constructor and the set of arguments provided for the
8708/// constructor, convert the arguments and add any required default arguments
8709/// to form a proper call to this constructor.
8710///
8711/// \returns true if an error occurred, false otherwise.
8712bool
8713Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
8714                              MultiExprArg ArgsPtr,
8715                              SourceLocation Loc,
8716                              ASTOwningVector<Expr*> &ConvertedArgs) {
8717  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
8718  unsigned NumArgs = ArgsPtr.size();
8719  Expr **Args = (Expr **)ArgsPtr.get();
8720
8721  const FunctionProtoType *Proto
8722    = Constructor->getType()->getAs<FunctionProtoType>();
8723  assert(Proto && "Constructor without a prototype?");
8724  unsigned NumArgsInProto = Proto->getNumArgs();
8725
8726  // If too few arguments are available, we'll fill in the rest with defaults.
8727  if (NumArgs < NumArgsInProto)
8728    ConvertedArgs.reserve(NumArgsInProto);
8729  else
8730    ConvertedArgs.reserve(NumArgs);
8731
8732  VariadicCallType CallType =
8733    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
8734  SmallVector<Expr *, 8> AllArgs;
8735  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
8736                                        Proto, 0, Args, NumArgs, AllArgs,
8737                                        CallType);
8738  for (unsigned i =0, size = AllArgs.size(); i < size; i++)
8739    ConvertedArgs.push_back(AllArgs[i]);
8740  return Invalid;
8741}
8742
8743static inline bool
8744CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
8745                                       const FunctionDecl *FnDecl) {
8746  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
8747  if (isa<NamespaceDecl>(DC)) {
8748    return SemaRef.Diag(FnDecl->getLocation(),
8749                        diag::err_operator_new_delete_declared_in_namespace)
8750      << FnDecl->getDeclName();
8751  }
8752
8753  if (isa<TranslationUnitDecl>(DC) &&
8754      FnDecl->getStorageClass() == SC_Static) {
8755    return SemaRef.Diag(FnDecl->getLocation(),
8756                        diag::err_operator_new_delete_declared_static)
8757      << FnDecl->getDeclName();
8758  }
8759
8760  return false;
8761}
8762
8763static inline bool
8764CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
8765                            CanQualType ExpectedResultType,
8766                            CanQualType ExpectedFirstParamType,
8767                            unsigned DependentParamTypeDiag,
8768                            unsigned InvalidParamTypeDiag) {
8769  QualType ResultType =
8770    FnDecl->getType()->getAs<FunctionType>()->getResultType();
8771
8772  // Check that the result type is not dependent.
8773  if (ResultType->isDependentType())
8774    return SemaRef.Diag(FnDecl->getLocation(),
8775                        diag::err_operator_new_delete_dependent_result_type)
8776    << FnDecl->getDeclName() << ExpectedResultType;
8777
8778  // Check that the result type is what we expect.
8779  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
8780    return SemaRef.Diag(FnDecl->getLocation(),
8781                        diag::err_operator_new_delete_invalid_result_type)
8782    << FnDecl->getDeclName() << ExpectedResultType;
8783
8784  // A function template must have at least 2 parameters.
8785  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
8786    return SemaRef.Diag(FnDecl->getLocation(),
8787                      diag::err_operator_new_delete_template_too_few_parameters)
8788        << FnDecl->getDeclName();
8789
8790  // The function decl must have at least 1 parameter.
8791  if (FnDecl->getNumParams() == 0)
8792    return SemaRef.Diag(FnDecl->getLocation(),
8793                        diag::err_operator_new_delete_too_few_parameters)
8794      << FnDecl->getDeclName();
8795
8796  // Check the the first parameter type is not dependent.
8797  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
8798  if (FirstParamType->isDependentType())
8799    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
8800      << FnDecl->getDeclName() << ExpectedFirstParamType;
8801
8802  // Check that the first parameter type is what we expect.
8803  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
8804      ExpectedFirstParamType)
8805    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
8806    << FnDecl->getDeclName() << ExpectedFirstParamType;
8807
8808  return false;
8809}
8810
8811static bool
8812CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
8813  // C++ [basic.stc.dynamic.allocation]p1:
8814  //   A program is ill-formed if an allocation function is declared in a
8815  //   namespace scope other than global scope or declared static in global
8816  //   scope.
8817  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8818    return true;
8819
8820  CanQualType SizeTy =
8821    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
8822
8823  // C++ [basic.stc.dynamic.allocation]p1:
8824  //  The return type shall be void*. The first parameter shall have type
8825  //  std::size_t.
8826  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
8827                                  SizeTy,
8828                                  diag::err_operator_new_dependent_param_type,
8829                                  diag::err_operator_new_param_type))
8830    return true;
8831
8832  // C++ [basic.stc.dynamic.allocation]p1:
8833  //  The first parameter shall not have an associated default argument.
8834  if (FnDecl->getParamDecl(0)->hasDefaultArg())
8835    return SemaRef.Diag(FnDecl->getLocation(),
8836                        diag::err_operator_new_default_arg)
8837      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
8838
8839  return false;
8840}
8841
8842static bool
8843CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
8844  // C++ [basic.stc.dynamic.deallocation]p1:
8845  //   A program is ill-formed if deallocation functions are declared in a
8846  //   namespace scope other than global scope or declared static in global
8847  //   scope.
8848  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8849    return true;
8850
8851  // C++ [basic.stc.dynamic.deallocation]p2:
8852  //   Each deallocation function shall return void and its first parameter
8853  //   shall be void*.
8854  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
8855                                  SemaRef.Context.VoidPtrTy,
8856                                 diag::err_operator_delete_dependent_param_type,
8857                                 diag::err_operator_delete_param_type))
8858    return true;
8859
8860  return false;
8861}
8862
8863/// CheckOverloadedOperatorDeclaration - Check whether the declaration
8864/// of this overloaded operator is well-formed. If so, returns false;
8865/// otherwise, emits appropriate diagnostics and returns true.
8866bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
8867  assert(FnDecl && FnDecl->isOverloadedOperator() &&
8868         "Expected an overloaded operator declaration");
8869
8870  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
8871
8872  // C++ [over.oper]p5:
8873  //   The allocation and deallocation functions, operator new,
8874  //   operator new[], operator delete and operator delete[], are
8875  //   described completely in 3.7.3. The attributes and restrictions
8876  //   found in the rest of this subclause do not apply to them unless
8877  //   explicitly stated in 3.7.3.
8878  if (Op == OO_Delete || Op == OO_Array_Delete)
8879    return CheckOperatorDeleteDeclaration(*this, FnDecl);
8880
8881  if (Op == OO_New || Op == OO_Array_New)
8882    return CheckOperatorNewDeclaration(*this, FnDecl);
8883
8884  // C++ [over.oper]p6:
8885  //   An operator function shall either be a non-static member
8886  //   function or be a non-member function and have at least one
8887  //   parameter whose type is a class, a reference to a class, an
8888  //   enumeration, or a reference to an enumeration.
8889  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
8890    if (MethodDecl->isStatic())
8891      return Diag(FnDecl->getLocation(),
8892                  diag::err_operator_overload_static) << FnDecl->getDeclName();
8893  } else {
8894    bool ClassOrEnumParam = false;
8895    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
8896                                   ParamEnd = FnDecl->param_end();
8897         Param != ParamEnd; ++Param) {
8898      QualType ParamType = (*Param)->getType().getNonReferenceType();
8899      if (ParamType->isDependentType() || ParamType->isRecordType() ||
8900          ParamType->isEnumeralType()) {
8901        ClassOrEnumParam = true;
8902        break;
8903      }
8904    }
8905
8906    if (!ClassOrEnumParam)
8907      return Diag(FnDecl->getLocation(),
8908                  diag::err_operator_overload_needs_class_or_enum)
8909        << FnDecl->getDeclName();
8910  }
8911
8912  // C++ [over.oper]p8:
8913  //   An operator function cannot have default arguments (8.3.6),
8914  //   except where explicitly stated below.
8915  //
8916  // Only the function-call operator allows default arguments
8917  // (C++ [over.call]p1).
8918  if (Op != OO_Call) {
8919    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
8920         Param != FnDecl->param_end(); ++Param) {
8921      if ((*Param)->hasDefaultArg())
8922        return Diag((*Param)->getLocation(),
8923                    diag::err_operator_overload_default_arg)
8924          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
8925    }
8926  }
8927
8928  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
8929    { false, false, false }
8930#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
8931    , { Unary, Binary, MemberOnly }
8932#include "clang/Basic/OperatorKinds.def"
8933  };
8934
8935  bool CanBeUnaryOperator = OperatorUses[Op][0];
8936  bool CanBeBinaryOperator = OperatorUses[Op][1];
8937  bool MustBeMemberOperator = OperatorUses[Op][2];
8938
8939  // C++ [over.oper]p8:
8940  //   [...] Operator functions cannot have more or fewer parameters
8941  //   than the number required for the corresponding operator, as
8942  //   described in the rest of this subclause.
8943  unsigned NumParams = FnDecl->getNumParams()
8944                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
8945  if (Op != OO_Call &&
8946      ((NumParams == 1 && !CanBeUnaryOperator) ||
8947       (NumParams == 2 && !CanBeBinaryOperator) ||
8948       (NumParams < 1) || (NumParams > 2))) {
8949    // We have the wrong number of parameters.
8950    unsigned ErrorKind;
8951    if (CanBeUnaryOperator && CanBeBinaryOperator) {
8952      ErrorKind = 2;  // 2 -> unary or binary.
8953    } else if (CanBeUnaryOperator) {
8954      ErrorKind = 0;  // 0 -> unary
8955    } else {
8956      assert(CanBeBinaryOperator &&
8957             "All non-call overloaded operators are unary or binary!");
8958      ErrorKind = 1;  // 1 -> binary
8959    }
8960
8961    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
8962      << FnDecl->getDeclName() << NumParams << ErrorKind;
8963  }
8964
8965  // Overloaded operators other than operator() cannot be variadic.
8966  if (Op != OO_Call &&
8967      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
8968    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
8969      << FnDecl->getDeclName();
8970  }
8971
8972  // Some operators must be non-static member functions.
8973  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
8974    return Diag(FnDecl->getLocation(),
8975                diag::err_operator_overload_must_be_member)
8976      << FnDecl->getDeclName();
8977  }
8978
8979  // C++ [over.inc]p1:
8980  //   The user-defined function called operator++ implements the
8981  //   prefix and postfix ++ operator. If this function is a member
8982  //   function with no parameters, or a non-member function with one
8983  //   parameter of class or enumeration type, it defines the prefix
8984  //   increment operator ++ for objects of that type. If the function
8985  //   is a member function with one parameter (which shall be of type
8986  //   int) or a non-member function with two parameters (the second
8987  //   of which shall be of type int), it defines the postfix
8988  //   increment operator ++ for objects of that type.
8989  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
8990    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
8991    bool ParamIsInt = false;
8992    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
8993      ParamIsInt = BT->getKind() == BuiltinType::Int;
8994
8995    if (!ParamIsInt)
8996      return Diag(LastParam->getLocation(),
8997                  diag::err_operator_overload_post_incdec_must_be_int)
8998        << LastParam->getType() << (Op == OO_MinusMinus);
8999  }
9000
9001  return false;
9002}
9003
9004/// CheckLiteralOperatorDeclaration - Check whether the declaration
9005/// of this literal operator function is well-formed. If so, returns
9006/// false; otherwise, emits appropriate diagnostics and returns true.
9007bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9008  DeclContext *DC = FnDecl->getDeclContext();
9009  Decl::Kind Kind = DC->getDeclKind();
9010  if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9011      Kind != Decl::LinkageSpec) {
9012    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9013      << FnDecl->getDeclName();
9014    return true;
9015  }
9016
9017  bool Valid = false;
9018
9019  // template <char...> type operator "" name() is the only valid template
9020  // signature, and the only valid signature with no parameters.
9021  if (FnDecl->param_size() == 0) {
9022    if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9023      // Must have only one template parameter
9024      TemplateParameterList *Params = TpDecl->getTemplateParameters();
9025      if (Params->size() == 1) {
9026        NonTypeTemplateParmDecl *PmDecl =
9027          cast<NonTypeTemplateParmDecl>(Params->getParam(0));
9028
9029        // The template parameter must be a char parameter pack.
9030        if (PmDecl && PmDecl->isTemplateParameterPack() &&
9031            Context.hasSameType(PmDecl->getType(), Context.CharTy))
9032          Valid = true;
9033      }
9034    }
9035  } else {
9036    // Check the first parameter
9037    FunctionDecl::param_iterator Param = FnDecl->param_begin();
9038
9039    QualType T = (*Param)->getType();
9040
9041    // unsigned long long int, long double, and any character type are allowed
9042    // as the only parameters.
9043    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9044        Context.hasSameType(T, Context.LongDoubleTy) ||
9045        Context.hasSameType(T, Context.CharTy) ||
9046        Context.hasSameType(T, Context.WCharTy) ||
9047        Context.hasSameType(T, Context.Char16Ty) ||
9048        Context.hasSameType(T, Context.Char32Ty)) {
9049      if (++Param == FnDecl->param_end())
9050        Valid = true;
9051      goto FinishedParams;
9052    }
9053
9054    // Otherwise it must be a pointer to const; let's strip those qualifiers.
9055    const PointerType *PT = T->getAs<PointerType>();
9056    if (!PT)
9057      goto FinishedParams;
9058    T = PT->getPointeeType();
9059    if (!T.isConstQualified())
9060      goto FinishedParams;
9061    T = T.getUnqualifiedType();
9062
9063    // Move on to the second parameter;
9064    ++Param;
9065
9066    // If there is no second parameter, the first must be a const char *
9067    if (Param == FnDecl->param_end()) {
9068      if (Context.hasSameType(T, Context.CharTy))
9069        Valid = true;
9070      goto FinishedParams;
9071    }
9072
9073    // const char *, const wchar_t*, const char16_t*, and const char32_t*
9074    // are allowed as the first parameter to a two-parameter function
9075    if (!(Context.hasSameType(T, Context.CharTy) ||
9076          Context.hasSameType(T, Context.WCharTy) ||
9077          Context.hasSameType(T, Context.Char16Ty) ||
9078          Context.hasSameType(T, Context.Char32Ty)))
9079      goto FinishedParams;
9080
9081    // The second and final parameter must be an std::size_t
9082    T = (*Param)->getType().getUnqualifiedType();
9083    if (Context.hasSameType(T, Context.getSizeType()) &&
9084        ++Param == FnDecl->param_end())
9085      Valid = true;
9086  }
9087
9088  // FIXME: This diagnostic is absolutely terrible.
9089FinishedParams:
9090  if (!Valid) {
9091    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9092      << FnDecl->getDeclName();
9093    return true;
9094  }
9095
9096  StringRef LiteralName
9097    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9098  if (LiteralName[0] != '_') {
9099    // C++0x [usrlit.suffix]p1:
9100    //   Literal suffix identifiers that do not start with an underscore are
9101    //   reserved for future standardization.
9102    bool IsHexFloat = true;
9103    if (LiteralName.size() > 1 &&
9104        (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9105      for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9106        if (!isdigit(LiteralName[I])) {
9107          IsHexFloat = false;
9108          break;
9109        }
9110      }
9111    }
9112
9113    if (IsHexFloat)
9114      Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9115        << LiteralName;
9116    else
9117      Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9118  }
9119
9120  return false;
9121}
9122
9123/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9124/// linkage specification, including the language and (if present)
9125/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9126/// the location of the language string literal, which is provided
9127/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9128/// the '{' brace. Otherwise, this linkage specification does not
9129/// have any braces.
9130Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9131                                           SourceLocation LangLoc,
9132                                           StringRef Lang,
9133                                           SourceLocation LBraceLoc) {
9134  LinkageSpecDecl::LanguageIDs Language;
9135  if (Lang == "\"C\"")
9136    Language = LinkageSpecDecl::lang_c;
9137  else if (Lang == "\"C++\"")
9138    Language = LinkageSpecDecl::lang_cxx;
9139  else {
9140    Diag(LangLoc, diag::err_bad_language);
9141    return 0;
9142  }
9143
9144  // FIXME: Add all the various semantics of linkage specifications
9145
9146  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
9147                                               ExternLoc, LangLoc, Language);
9148  CurContext->addDecl(D);
9149  PushDeclContext(S, D);
9150  return D;
9151}
9152
9153/// ActOnFinishLinkageSpecification - Complete the definition of
9154/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9155/// valid, it's the position of the closing '}' brace in a linkage
9156/// specification that uses braces.
9157Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
9158                                            Decl *LinkageSpec,
9159                                            SourceLocation RBraceLoc) {
9160  if (LinkageSpec) {
9161    if (RBraceLoc.isValid()) {
9162      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9163      LSDecl->setRBraceLoc(RBraceLoc);
9164    }
9165    PopDeclContext();
9166  }
9167  return LinkageSpec;
9168}
9169
9170/// \brief Perform semantic analysis for the variable declaration that
9171/// occurs within a C++ catch clause, returning the newly-created
9172/// variable.
9173VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
9174                                         TypeSourceInfo *TInfo,
9175                                         SourceLocation StartLoc,
9176                                         SourceLocation Loc,
9177                                         IdentifierInfo *Name) {
9178  bool Invalid = false;
9179  QualType ExDeclType = TInfo->getType();
9180
9181  // Arrays and functions decay.
9182  if (ExDeclType->isArrayType())
9183    ExDeclType = Context.getArrayDecayedType(ExDeclType);
9184  else if (ExDeclType->isFunctionType())
9185    ExDeclType = Context.getPointerType(ExDeclType);
9186
9187  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9188  // The exception-declaration shall not denote a pointer or reference to an
9189  // incomplete type, other than [cv] void*.
9190  // N2844 forbids rvalue references.
9191  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
9192    Diag(Loc, diag::err_catch_rvalue_ref);
9193    Invalid = true;
9194  }
9195
9196  // GCC allows catching pointers and references to incomplete types
9197  // as an extension; so do we, but we warn by default.
9198
9199  QualType BaseType = ExDeclType;
9200  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
9201  unsigned DK = diag::err_catch_incomplete;
9202  bool IncompleteCatchIsInvalid = true;
9203  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
9204    BaseType = Ptr->getPointeeType();
9205    Mode = 1;
9206    DK = diag::ext_catch_incomplete_ptr;
9207    IncompleteCatchIsInvalid = false;
9208  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
9209    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
9210    BaseType = Ref->getPointeeType();
9211    Mode = 2;
9212    DK = diag::ext_catch_incomplete_ref;
9213    IncompleteCatchIsInvalid = false;
9214  }
9215  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
9216      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
9217      IncompleteCatchIsInvalid)
9218    Invalid = true;
9219
9220  if (!Invalid && !ExDeclType->isDependentType() &&
9221      RequireNonAbstractType(Loc, ExDeclType,
9222                             diag::err_abstract_type_in_decl,
9223                             AbstractVariableType))
9224    Invalid = true;
9225
9226  // Only the non-fragile NeXT runtime currently supports C++ catches
9227  // of ObjC types, and no runtime supports catching ObjC types by value.
9228  if (!Invalid && getLangOptions().ObjC1) {
9229    QualType T = ExDeclType;
9230    if (const ReferenceType *RT = T->getAs<ReferenceType>())
9231      T = RT->getPointeeType();
9232
9233    if (T->isObjCObjectType()) {
9234      Diag(Loc, diag::err_objc_object_catch);
9235      Invalid = true;
9236    } else if (T->isObjCObjectPointerType()) {
9237      if (!getLangOptions().ObjCNonFragileABI)
9238        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
9239    }
9240  }
9241
9242  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9243                                    ExDeclType, TInfo, SC_None, SC_None);
9244  ExDecl->setExceptionVariable(true);
9245
9246  if (!Invalid && !ExDeclType->isDependentType()) {
9247    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
9248      // C++ [except.handle]p16:
9249      //   The object declared in an exception-declaration or, if the
9250      //   exception-declaration does not specify a name, a temporary (12.2) is
9251      //   copy-initialized (8.5) from the exception object. [...]
9252      //   The object is destroyed when the handler exits, after the destruction
9253      //   of any automatic objects initialized within the handler.
9254      //
9255      // We just pretend to initialize the object with itself, then make sure
9256      // it can be destroyed later.
9257      QualType initType = ExDeclType;
9258
9259      InitializedEntity entity =
9260        InitializedEntity::InitializeVariable(ExDecl);
9261      InitializationKind initKind =
9262        InitializationKind::CreateCopy(Loc, SourceLocation());
9263
9264      Expr *opaqueValue =
9265        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9266      InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9267      ExprResult result = sequence.Perform(*this, entity, initKind,
9268                                           MultiExprArg(&opaqueValue, 1));
9269      if (result.isInvalid())
9270        Invalid = true;
9271      else {
9272        // If the constructor used was non-trivial, set this as the
9273        // "initializer".
9274        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9275        if (!construct->getConstructor()->isTrivial()) {
9276          Expr *init = MaybeCreateExprWithCleanups(construct);
9277          ExDecl->setInit(init);
9278        }
9279
9280        // And make sure it's destructable.
9281        FinalizeVarWithDestructor(ExDecl, recordType);
9282      }
9283    }
9284  }
9285
9286  if (Invalid)
9287    ExDecl->setInvalidDecl();
9288
9289  return ExDecl;
9290}
9291
9292/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9293/// handler.
9294Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
9295  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9296  bool Invalid = D.isInvalidType();
9297
9298  // Check for unexpanded parameter packs.
9299  if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9300                                               UPPC_ExceptionType)) {
9301    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9302                                             D.getIdentifierLoc());
9303    Invalid = true;
9304  }
9305
9306  IdentifierInfo *II = D.getIdentifier();
9307  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
9308                                             LookupOrdinaryName,
9309                                             ForRedeclaration)) {
9310    // The scope should be freshly made just for us. There is just no way
9311    // it contains any previous declaration.
9312    assert(!S->isDeclScope(PrevDecl));
9313    if (PrevDecl->isTemplateParameter()) {
9314      // Maybe we will complain about the shadowed template parameter.
9315      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9316    }
9317  }
9318
9319  if (D.getCXXScopeSpec().isSet() && !Invalid) {
9320    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9321      << D.getCXXScopeSpec().getRange();
9322    Invalid = true;
9323  }
9324
9325  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
9326                                              D.getSourceRange().getBegin(),
9327                                              D.getIdentifierLoc(),
9328                                              D.getIdentifier());
9329  if (Invalid)
9330    ExDecl->setInvalidDecl();
9331
9332  // Add the exception declaration into this scope.
9333  if (II)
9334    PushOnScopeChains(ExDecl, S);
9335  else
9336    CurContext->addDecl(ExDecl);
9337
9338  ProcessDeclAttributes(S, ExDecl, D);
9339  return ExDecl;
9340}
9341
9342Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9343                                         Expr *AssertExpr,
9344                                         Expr *AssertMessageExpr_,
9345                                         SourceLocation RParenLoc) {
9346  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
9347
9348  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9349    llvm::APSInt Value(32);
9350    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
9351      Diag(StaticAssertLoc,
9352           diag::err_static_assert_expression_is_not_constant) <<
9353        AssertExpr->getSourceRange();
9354      return 0;
9355    }
9356
9357    if (Value == 0) {
9358      Diag(StaticAssertLoc, diag::err_static_assert_failed)
9359        << AssertMessage->getString() << AssertExpr->getSourceRange();
9360    }
9361  }
9362
9363  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9364    return 0;
9365
9366  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9367                                        AssertExpr, AssertMessage, RParenLoc);
9368
9369  CurContext->addDecl(Decl);
9370  return Decl;
9371}
9372
9373/// \brief Perform semantic analysis of the given friend type declaration.
9374///
9375/// \returns A friend declaration that.
9376FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
9377                                      TypeSourceInfo *TSInfo) {
9378  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9379
9380  QualType T = TSInfo->getType();
9381  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
9382
9383  if (!getLangOptions().CPlusPlus0x) {
9384    // C++03 [class.friend]p2:
9385    //   An elaborated-type-specifier shall be used in a friend declaration
9386    //   for a class.*
9387    //
9388    //   * The class-key of the elaborated-type-specifier is required.
9389    if (!ActiveTemplateInstantiations.empty()) {
9390      // Do not complain about the form of friend template types during
9391      // template instantiation; we will already have complained when the
9392      // template was declared.
9393    } else if (!T->isElaboratedTypeSpecifier()) {
9394      // If we evaluated the type to a record type, suggest putting
9395      // a tag in front.
9396      if (const RecordType *RT = T->getAs<RecordType>()) {
9397        RecordDecl *RD = RT->getDecl();
9398
9399        std::string InsertionText = std::string(" ") + RD->getKindName();
9400
9401        Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
9402          << (unsigned) RD->getTagKind()
9403          << T
9404          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9405                                        InsertionText);
9406      } else {
9407        Diag(FriendLoc, diag::ext_nonclass_type_friend)
9408          << T
9409          << SourceRange(FriendLoc, TypeRange.getEnd());
9410      }
9411    } else if (T->getAs<EnumType>()) {
9412      Diag(FriendLoc, diag::ext_enum_friend)
9413        << T
9414        << SourceRange(FriendLoc, TypeRange.getEnd());
9415    }
9416  }
9417
9418  // C++0x [class.friend]p3:
9419  //   If the type specifier in a friend declaration designates a (possibly
9420  //   cv-qualified) class type, that class is declared as a friend; otherwise,
9421  //   the friend declaration is ignored.
9422
9423  // FIXME: C++0x has some syntactic restrictions on friend type declarations
9424  // in [class.friend]p3 that we do not implement.
9425
9426  return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
9427}
9428
9429/// Handle a friend tag declaration where the scope specifier was
9430/// templated.
9431Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9432                                    unsigned TagSpec, SourceLocation TagLoc,
9433                                    CXXScopeSpec &SS,
9434                                    IdentifierInfo *Name, SourceLocation NameLoc,
9435                                    AttributeList *Attr,
9436                                    MultiTemplateParamsArg TempParamLists) {
9437  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9438
9439  bool isExplicitSpecialization = false;
9440  bool Invalid = false;
9441
9442  if (TemplateParameterList *TemplateParams
9443        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
9444                                                  TempParamLists.get(),
9445                                                  TempParamLists.size(),
9446                                                  /*friend*/ true,
9447                                                  isExplicitSpecialization,
9448                                                  Invalid)) {
9449    if (TemplateParams->size() > 0) {
9450      // This is a declaration of a class template.
9451      if (Invalid)
9452        return 0;
9453
9454      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9455                                SS, Name, NameLoc, Attr,
9456                                TemplateParams, AS_public,
9457                                /*ModulePrivateLoc=*/SourceLocation(),
9458                                TempParamLists.size() - 1,
9459                   (TemplateParameterList**) TempParamLists.release()).take();
9460    } else {
9461      // The "template<>" header is extraneous.
9462      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9463        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9464      isExplicitSpecialization = true;
9465    }
9466  }
9467
9468  if (Invalid) return 0;
9469
9470  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9471
9472  bool isAllExplicitSpecializations = true;
9473  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
9474    if (TempParamLists.get()[I]->size()) {
9475      isAllExplicitSpecializations = false;
9476      break;
9477    }
9478  }
9479
9480  // FIXME: don't ignore attributes.
9481
9482  // If it's explicit specializations all the way down, just forget
9483  // about the template header and build an appropriate non-templated
9484  // friend.  TODO: for source fidelity, remember the headers.
9485  if (isAllExplicitSpecializations) {
9486    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9487    ElaboratedTypeKeyword Keyword
9488      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9489    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
9490                                   *Name, NameLoc);
9491    if (T.isNull())
9492      return 0;
9493
9494    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9495    if (isa<DependentNameType>(T)) {
9496      DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9497      TL.setKeywordLoc(TagLoc);
9498      TL.setQualifierLoc(QualifierLoc);
9499      TL.setNameLoc(NameLoc);
9500    } else {
9501      ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9502      TL.setKeywordLoc(TagLoc);
9503      TL.setQualifierLoc(QualifierLoc);
9504      cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9505    }
9506
9507    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9508                                            TSI, FriendLoc);
9509    Friend->setAccess(AS_public);
9510    CurContext->addDecl(Friend);
9511    return Friend;
9512  }
9513
9514  // Handle the case of a templated-scope friend class.  e.g.
9515  //   template <class T> class A<T>::B;
9516  // FIXME: we don't support these right now.
9517  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9518  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9519  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9520  DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9521  TL.setKeywordLoc(TagLoc);
9522  TL.setQualifierLoc(SS.getWithLocInContext(Context));
9523  TL.setNameLoc(NameLoc);
9524
9525  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9526                                          TSI, FriendLoc);
9527  Friend->setAccess(AS_public);
9528  Friend->setUnsupportedFriend(true);
9529  CurContext->addDecl(Friend);
9530  return Friend;
9531}
9532
9533
9534/// Handle a friend type declaration.  This works in tandem with
9535/// ActOnTag.
9536///
9537/// Notes on friend class templates:
9538///
9539/// We generally treat friend class declarations as if they were
9540/// declaring a class.  So, for example, the elaborated type specifier
9541/// in a friend declaration is required to obey the restrictions of a
9542/// class-head (i.e. no typedefs in the scope chain), template
9543/// parameters are required to match up with simple template-ids, &c.
9544/// However, unlike when declaring a template specialization, it's
9545/// okay to refer to a template specialization without an empty
9546/// template parameter declaration, e.g.
9547///   friend class A<T>::B<unsigned>;
9548/// We permit this as a special case; if there are any template
9549/// parameters present at all, require proper matching, i.e.
9550///   template <> template <class T> friend class A<int>::B;
9551Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
9552                                MultiTemplateParamsArg TempParams) {
9553  SourceLocation Loc = DS.getSourceRange().getBegin();
9554
9555  assert(DS.isFriendSpecified());
9556  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9557
9558  // Try to convert the decl specifier to a type.  This works for
9559  // friend templates because ActOnTag never produces a ClassTemplateDecl
9560  // for a TUK_Friend.
9561  Declarator TheDeclarator(DS, Declarator::MemberContext);
9562  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9563  QualType T = TSI->getType();
9564  if (TheDeclarator.isInvalidType())
9565    return 0;
9566
9567  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9568    return 0;
9569
9570  // This is definitely an error in C++98.  It's probably meant to
9571  // be forbidden in C++0x, too, but the specification is just
9572  // poorly written.
9573  //
9574  // The problem is with declarations like the following:
9575  //   template <T> friend A<T>::foo;
9576  // where deciding whether a class C is a friend or not now hinges
9577  // on whether there exists an instantiation of A that causes
9578  // 'foo' to equal C.  There are restrictions on class-heads
9579  // (which we declare (by fiat) elaborated friend declarations to
9580  // be) that makes this tractable.
9581  //
9582  // FIXME: handle "template <> friend class A<T>;", which
9583  // is possibly well-formed?  Who even knows?
9584  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
9585    Diag(Loc, diag::err_tagless_friend_type_template)
9586      << DS.getSourceRange();
9587    return 0;
9588  }
9589
9590  // C++98 [class.friend]p1: A friend of a class is a function
9591  //   or class that is not a member of the class . . .
9592  // This is fixed in DR77, which just barely didn't make the C++03
9593  // deadline.  It's also a very silly restriction that seriously
9594  // affects inner classes and which nobody else seems to implement;
9595  // thus we never diagnose it, not even in -pedantic.
9596  //
9597  // But note that we could warn about it: it's always useless to
9598  // friend one of your own members (it's not, however, worthless to
9599  // friend a member of an arbitrary specialization of your template).
9600
9601  Decl *D;
9602  if (unsigned NumTempParamLists = TempParams.size())
9603    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
9604                                   NumTempParamLists,
9605                                   TempParams.release(),
9606                                   TSI,
9607                                   DS.getFriendSpecLoc());
9608  else
9609    D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
9610
9611  if (!D)
9612    return 0;
9613
9614  D->setAccess(AS_public);
9615  CurContext->addDecl(D);
9616
9617  return D;
9618}
9619
9620Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
9621                                    MultiTemplateParamsArg TemplateParams) {
9622  const DeclSpec &DS = D.getDeclSpec();
9623
9624  assert(DS.isFriendSpecified());
9625  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9626
9627  SourceLocation Loc = D.getIdentifierLoc();
9628  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9629  QualType T = TInfo->getType();
9630
9631  // C++ [class.friend]p1
9632  //   A friend of a class is a function or class....
9633  // Note that this sees through typedefs, which is intended.
9634  // It *doesn't* see through dependent types, which is correct
9635  // according to [temp.arg.type]p3:
9636  //   If a declaration acquires a function type through a
9637  //   type dependent on a template-parameter and this causes
9638  //   a declaration that does not use the syntactic form of a
9639  //   function declarator to have a function type, the program
9640  //   is ill-formed.
9641  if (!T->isFunctionType()) {
9642    Diag(Loc, diag::err_unexpected_friend);
9643
9644    // It might be worthwhile to try to recover by creating an
9645    // appropriate declaration.
9646    return 0;
9647  }
9648
9649  // C++ [namespace.memdef]p3
9650  //  - If a friend declaration in a non-local class first declares a
9651  //    class or function, the friend class or function is a member
9652  //    of the innermost enclosing namespace.
9653  //  - The name of the friend is not found by simple name lookup
9654  //    until a matching declaration is provided in that namespace
9655  //    scope (either before or after the class declaration granting
9656  //    friendship).
9657  //  - If a friend function is called, its name may be found by the
9658  //    name lookup that considers functions from namespaces and
9659  //    classes associated with the types of the function arguments.
9660  //  - When looking for a prior declaration of a class or a function
9661  //    declared as a friend, scopes outside the innermost enclosing
9662  //    namespace scope are not considered.
9663
9664  CXXScopeSpec &SS = D.getCXXScopeSpec();
9665  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9666  DeclarationName Name = NameInfo.getName();
9667  assert(Name);
9668
9669  // Check for unexpanded parameter packs.
9670  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
9671      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
9672      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
9673    return 0;
9674
9675  // The context we found the declaration in, or in which we should
9676  // create the declaration.
9677  DeclContext *DC;
9678  Scope *DCScope = S;
9679  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9680                        ForRedeclaration);
9681
9682  // FIXME: there are different rules in local classes
9683
9684  // There are four cases here.
9685  //   - There's no scope specifier, in which case we just go to the
9686  //     appropriate scope and look for a function or function template
9687  //     there as appropriate.
9688  // Recover from invalid scope qualifiers as if they just weren't there.
9689  if (SS.isInvalid() || !SS.isSet()) {
9690    // C++0x [namespace.memdef]p3:
9691    //   If the name in a friend declaration is neither qualified nor
9692    //   a template-id and the declaration is a function or an
9693    //   elaborated-type-specifier, the lookup to determine whether
9694    //   the entity has been previously declared shall not consider
9695    //   any scopes outside the innermost enclosing namespace.
9696    // C++0x [class.friend]p11:
9697    //   If a friend declaration appears in a local class and the name
9698    //   specified is an unqualified name, a prior declaration is
9699    //   looked up without considering scopes that are outside the
9700    //   innermost enclosing non-class scope. For a friend function
9701    //   declaration, if there is no prior declaration, the program is
9702    //   ill-formed.
9703    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
9704    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
9705
9706    // Find the appropriate context according to the above.
9707    DC = CurContext;
9708    while (true) {
9709      // Skip class contexts.  If someone can cite chapter and verse
9710      // for this behavior, that would be nice --- it's what GCC and
9711      // EDG do, and it seems like a reasonable intent, but the spec
9712      // really only says that checks for unqualified existing
9713      // declarations should stop at the nearest enclosing namespace,
9714      // not that they should only consider the nearest enclosing
9715      // namespace.
9716      while (DC->isRecord())
9717        DC = DC->getParent();
9718
9719      LookupQualifiedName(Previous, DC);
9720
9721      // TODO: decide what we think about using declarations.
9722      if (isLocal || !Previous.empty())
9723        break;
9724
9725      if (isTemplateId) {
9726        if (isa<TranslationUnitDecl>(DC)) break;
9727      } else {
9728        if (DC->isFileContext()) break;
9729      }
9730      DC = DC->getParent();
9731    }
9732
9733    // C++ [class.friend]p1: A friend of a class is a function or
9734    //   class that is not a member of the class . . .
9735    // C++0x changes this for both friend types and functions.
9736    // Most C++ 98 compilers do seem to give an error here, so
9737    // we do, too.
9738    if (!Previous.empty() && DC->Equals(CurContext)
9739        && !getLangOptions().CPlusPlus0x)
9740      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
9741
9742    DCScope = getScopeForDeclContext(S, DC);
9743
9744  //   - There's a non-dependent scope specifier, in which case we
9745  //     compute it and do a previous lookup there for a function
9746  //     or function template.
9747  } else if (!SS.getScopeRep()->isDependent()) {
9748    DC = computeDeclContext(SS);
9749    if (!DC) return 0;
9750
9751    if (RequireCompleteDeclContext(SS, DC)) return 0;
9752
9753    LookupQualifiedName(Previous, DC);
9754
9755    // Ignore things found implicitly in the wrong scope.
9756    // TODO: better diagnostics for this case.  Suggesting the right
9757    // qualified scope would be nice...
9758    LookupResult::Filter F = Previous.makeFilter();
9759    while (F.hasNext()) {
9760      NamedDecl *D = F.next();
9761      if (!DC->InEnclosingNamespaceSetOf(
9762              D->getDeclContext()->getRedeclContext()))
9763        F.erase();
9764    }
9765    F.done();
9766
9767    if (Previous.empty()) {
9768      D.setInvalidType();
9769      Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
9770      return 0;
9771    }
9772
9773    // C++ [class.friend]p1: A friend of a class is a function or
9774    //   class that is not a member of the class . . .
9775    if (DC->Equals(CurContext))
9776      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
9777
9778  //   - There's a scope specifier that does not match any template
9779  //     parameter lists, in which case we use some arbitrary context,
9780  //     create a method or method template, and wait for instantiation.
9781  //   - There's a scope specifier that does match some template
9782  //     parameter lists, which we don't handle right now.
9783  } else {
9784    DC = CurContext;
9785    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
9786  }
9787
9788  if (!DC->isRecord()) {
9789    // This implies that it has to be an operator or function.
9790    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
9791        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
9792        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
9793      Diag(Loc, diag::err_introducing_special_friend) <<
9794        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
9795         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
9796      return 0;
9797    }
9798  }
9799
9800  bool Redeclaration = false;
9801  bool AddToScope = true;
9802  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
9803                                          move(TemplateParams),
9804                                          IsDefinition,
9805                                          Redeclaration, AddToScope);
9806  if (!ND) return 0;
9807
9808  assert(ND->getDeclContext() == DC);
9809  assert(ND->getLexicalDeclContext() == CurContext);
9810
9811  // Add the function declaration to the appropriate lookup tables,
9812  // adjusting the redeclarations list as necessary.  We don't
9813  // want to do this yet if the friending class is dependent.
9814  //
9815  // Also update the scope-based lookup if the target context's
9816  // lookup context is in lexical scope.
9817  if (!CurContext->isDependentContext()) {
9818    DC = DC->getRedeclContext();
9819    DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
9820    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
9821      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
9822  }
9823
9824  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
9825                                       D.getIdentifierLoc(), ND,
9826                                       DS.getFriendSpecLoc());
9827  FrD->setAccess(AS_public);
9828  CurContext->addDecl(FrD);
9829
9830  if (ND->isInvalidDecl())
9831    FrD->setInvalidDecl();
9832  else {
9833    FunctionDecl *FD;
9834    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9835      FD = FTD->getTemplatedDecl();
9836    else
9837      FD = cast<FunctionDecl>(ND);
9838
9839    // Mark templated-scope function declarations as unsupported.
9840    if (FD->getNumTemplateParameterLists())
9841      FrD->setUnsupportedFriend(true);
9842  }
9843
9844  return ND;
9845}
9846
9847void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
9848  AdjustDeclIfTemplate(Dcl);
9849
9850  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
9851  if (!Fn) {
9852    Diag(DelLoc, diag::err_deleted_non_function);
9853    return;
9854  }
9855  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
9856    Diag(DelLoc, diag::err_deleted_decl_not_first);
9857    Diag(Prev->getLocation(), diag::note_previous_declaration);
9858    // If the declaration wasn't the first, we delete the function anyway for
9859    // recovery.
9860  }
9861  Fn->setDeletedAsWritten();
9862}
9863
9864void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
9865  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
9866
9867  if (MD) {
9868    if (MD->getParent()->isDependentType()) {
9869      MD->setDefaulted();
9870      MD->setExplicitlyDefaulted();
9871      return;
9872    }
9873
9874    CXXSpecialMember Member = getSpecialMember(MD);
9875    if (Member == CXXInvalid) {
9876      Diag(DefaultLoc, diag::err_default_special_members);
9877      return;
9878    }
9879
9880    MD->setDefaulted();
9881    MD->setExplicitlyDefaulted();
9882
9883    // If this definition appears within the record, do the checking when
9884    // the record is complete.
9885    const FunctionDecl *Primary = MD;
9886    if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
9887      // Find the uninstantiated declaration that actually had the '= default'
9888      // on it.
9889      MD->getTemplateInstantiationPattern()->isDefined(Primary);
9890
9891    if (Primary == Primary->getCanonicalDecl())
9892      return;
9893
9894    switch (Member) {
9895    case CXXDefaultConstructor: {
9896      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9897      CheckExplicitlyDefaultedDefaultConstructor(CD);
9898      if (!CD->isInvalidDecl())
9899        DefineImplicitDefaultConstructor(DefaultLoc, CD);
9900      break;
9901    }
9902
9903    case CXXCopyConstructor: {
9904      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9905      CheckExplicitlyDefaultedCopyConstructor(CD);
9906      if (!CD->isInvalidDecl())
9907        DefineImplicitCopyConstructor(DefaultLoc, CD);
9908      break;
9909    }
9910
9911    case CXXCopyAssignment: {
9912      CheckExplicitlyDefaultedCopyAssignment(MD);
9913      if (!MD->isInvalidDecl())
9914        DefineImplicitCopyAssignment(DefaultLoc, MD);
9915      break;
9916    }
9917
9918    case CXXDestructor: {
9919      CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
9920      CheckExplicitlyDefaultedDestructor(DD);
9921      if (!DD->isInvalidDecl())
9922        DefineImplicitDestructor(DefaultLoc, DD);
9923      break;
9924    }
9925
9926    case CXXMoveConstructor: {
9927      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9928      CheckExplicitlyDefaultedMoveConstructor(CD);
9929      if (!CD->isInvalidDecl())
9930        DefineImplicitMoveConstructor(DefaultLoc, CD);
9931      break;
9932    }
9933
9934    case CXXMoveAssignment: {
9935      CheckExplicitlyDefaultedMoveAssignment(MD);
9936      if (!MD->isInvalidDecl())
9937        DefineImplicitMoveAssignment(DefaultLoc, MD);
9938      break;
9939    }
9940
9941    case CXXInvalid:
9942      assert(false && "Invalid special member.");
9943      break;
9944    }
9945  } else {
9946    Diag(DefaultLoc, diag::err_default_special_members);
9947  }
9948}
9949
9950static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
9951  for (Stmt::child_range CI = S->children(); CI; ++CI) {
9952    Stmt *SubStmt = *CI;
9953    if (!SubStmt)
9954      continue;
9955    if (isa<ReturnStmt>(SubStmt))
9956      Self.Diag(SubStmt->getSourceRange().getBegin(),
9957           diag::err_return_in_constructor_handler);
9958    if (!isa<Expr>(SubStmt))
9959      SearchForReturnInStmt(Self, SubStmt);
9960  }
9961}
9962
9963void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
9964  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
9965    CXXCatchStmt *Handler = TryBlock->getHandler(I);
9966    SearchForReturnInStmt(*this, Handler);
9967  }
9968}
9969
9970bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
9971                                             const CXXMethodDecl *Old) {
9972  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
9973  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
9974
9975  if (Context.hasSameType(NewTy, OldTy) ||
9976      NewTy->isDependentType() || OldTy->isDependentType())
9977    return false;
9978
9979  // Check if the return types are covariant
9980  QualType NewClassTy, OldClassTy;
9981
9982  /// Both types must be pointers or references to classes.
9983  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
9984    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
9985      NewClassTy = NewPT->getPointeeType();
9986      OldClassTy = OldPT->getPointeeType();
9987    }
9988  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
9989    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
9990      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
9991        NewClassTy = NewRT->getPointeeType();
9992        OldClassTy = OldRT->getPointeeType();
9993      }
9994    }
9995  }
9996
9997  // The return types aren't either both pointers or references to a class type.
9998  if (NewClassTy.isNull()) {
9999    Diag(New->getLocation(),
10000         diag::err_different_return_type_for_overriding_virtual_function)
10001      << New->getDeclName() << NewTy << OldTy;
10002    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10003
10004    return true;
10005  }
10006
10007  // C++ [class.virtual]p6:
10008  //   If the return type of D::f differs from the return type of B::f, the
10009  //   class type in the return type of D::f shall be complete at the point of
10010  //   declaration of D::f or shall be the class type D.
10011  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10012    if (!RT->isBeingDefined() &&
10013        RequireCompleteType(New->getLocation(), NewClassTy,
10014                            PDiag(diag::err_covariant_return_incomplete)
10015                              << New->getDeclName()))
10016    return true;
10017  }
10018
10019  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
10020    // Check if the new class derives from the old class.
10021    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10022      Diag(New->getLocation(),
10023           diag::err_covariant_return_not_derived)
10024      << New->getDeclName() << NewTy << OldTy;
10025      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10026      return true;
10027    }
10028
10029    // Check if we the conversion from derived to base is valid.
10030    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
10031                    diag::err_covariant_return_inaccessible_base,
10032                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
10033                    // FIXME: Should this point to the return type?
10034                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
10035      // FIXME: this note won't trigger for delayed access control
10036      // diagnostics, and it's impossible to get an undelayed error
10037      // here from access control during the original parse because
10038      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
10039      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10040      return true;
10041    }
10042  }
10043
10044  // The qualifiers of the return types must be the same.
10045  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
10046    Diag(New->getLocation(),
10047         diag::err_covariant_return_type_different_qualifications)
10048    << New->getDeclName() << NewTy << OldTy;
10049    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10050    return true;
10051  };
10052
10053
10054  // The new class type must have the same or less qualifiers as the old type.
10055  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10056    Diag(New->getLocation(),
10057         diag::err_covariant_return_type_class_type_more_qualified)
10058    << New->getDeclName() << NewTy << OldTy;
10059    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10060    return true;
10061  };
10062
10063  return false;
10064}
10065
10066/// \brief Mark the given method pure.
10067///
10068/// \param Method the method to be marked pure.
10069///
10070/// \param InitRange the source range that covers the "0" initializer.
10071bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
10072  SourceLocation EndLoc = InitRange.getEnd();
10073  if (EndLoc.isValid())
10074    Method->setRangeEnd(EndLoc);
10075
10076  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10077    Method->setPure();
10078    return false;
10079  }
10080
10081  if (!Method->isInvalidDecl())
10082    Diag(Method->getLocation(), diag::err_non_virtual_pure)
10083      << Method->getDeclName() << InitRange;
10084  return true;
10085}
10086
10087/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10088/// an initializer for the out-of-line declaration 'Dcl'.  The scope
10089/// is a fresh scope pushed for just this purpose.
10090///
10091/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10092/// static data member of class X, names should be looked up in the scope of
10093/// class X.
10094void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
10095  // If there is no declaration, there was an error parsing it.
10096  if (D == 0 || D->isInvalidDecl()) return;
10097
10098  // We should only get called for declarations with scope specifiers, like:
10099  //   int foo::bar;
10100  assert(D->isOutOfLine());
10101  EnterDeclaratorContext(S, D->getDeclContext());
10102}
10103
10104/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
10105/// initializer for the out-of-line declaration 'D'.
10106void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
10107  // If there is no declaration, there was an error parsing it.
10108  if (D == 0 || D->isInvalidDecl()) return;
10109
10110  assert(D->isOutOfLine());
10111  ExitDeclaratorContext(S);
10112}
10113
10114/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10115/// C++ if/switch/while/for statement.
10116/// e.g: "if (int x = f()) {...}"
10117DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
10118  // C++ 6.4p2:
10119  // The declarator shall not specify a function or an array.
10120  // The type-specifier-seq shall not contain typedef and shall not declare a
10121  // new class or enumeration.
10122  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10123         "Parser allowed 'typedef' as storage class of condition decl.");
10124
10125  Decl *Dcl = ActOnDeclarator(S, D);
10126  if (!Dcl)
10127    return true;
10128
10129  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10130    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
10131      << D.getSourceRange();
10132    return true;
10133  }
10134
10135  return Dcl;
10136}
10137
10138void Sema::LoadExternalVTableUses() {
10139  if (!ExternalSource)
10140    return;
10141
10142  SmallVector<ExternalVTableUse, 4> VTables;
10143  ExternalSource->ReadUsedVTables(VTables);
10144  SmallVector<VTableUse, 4> NewUses;
10145  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10146    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10147      = VTablesUsed.find(VTables[I].Record);
10148    // Even if a definition wasn't required before, it may be required now.
10149    if (Pos != VTablesUsed.end()) {
10150      if (!Pos->second && VTables[I].DefinitionRequired)
10151        Pos->second = true;
10152      continue;
10153    }
10154
10155    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10156    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10157  }
10158
10159  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10160}
10161
10162void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10163                          bool DefinitionRequired) {
10164  // Ignore any vtable uses in unevaluated operands or for classes that do
10165  // not have a vtable.
10166  if (!Class->isDynamicClass() || Class->isDependentContext() ||
10167      CurContext->isDependentContext() ||
10168      ExprEvalContexts.back().Context == Unevaluated)
10169    return;
10170
10171  // Try to insert this class into the map.
10172  LoadExternalVTableUses();
10173  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10174  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10175    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10176  if (!Pos.second) {
10177    // If we already had an entry, check to see if we are promoting this vtable
10178    // to required a definition. If so, we need to reappend to the VTableUses
10179    // list, since we may have already processed the first entry.
10180    if (DefinitionRequired && !Pos.first->second) {
10181      Pos.first->second = true;
10182    } else {
10183      // Otherwise, we can early exit.
10184      return;
10185    }
10186  }
10187
10188  // Local classes need to have their virtual members marked
10189  // immediately. For all other classes, we mark their virtual members
10190  // at the end of the translation unit.
10191  if (Class->isLocalClass())
10192    MarkVirtualMembersReferenced(Loc, Class);
10193  else
10194    VTableUses.push_back(std::make_pair(Class, Loc));
10195}
10196
10197bool Sema::DefineUsedVTables() {
10198  LoadExternalVTableUses();
10199  if (VTableUses.empty())
10200    return false;
10201
10202  // Note: The VTableUses vector could grow as a result of marking
10203  // the members of a class as "used", so we check the size each
10204  // time through the loop and prefer indices (with are stable) to
10205  // iterators (which are not).
10206  bool DefinedAnything = false;
10207  for (unsigned I = 0; I != VTableUses.size(); ++I) {
10208    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
10209    if (!Class)
10210      continue;
10211
10212    SourceLocation Loc = VTableUses[I].second;
10213
10214    // If this class has a key function, but that key function is
10215    // defined in another translation unit, we don't need to emit the
10216    // vtable even though we're using it.
10217    const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
10218    if (KeyFunction && !KeyFunction->hasBody()) {
10219      switch (KeyFunction->getTemplateSpecializationKind()) {
10220      case TSK_Undeclared:
10221      case TSK_ExplicitSpecialization:
10222      case TSK_ExplicitInstantiationDeclaration:
10223        // The key function is in another translation unit.
10224        continue;
10225
10226      case TSK_ExplicitInstantiationDefinition:
10227      case TSK_ImplicitInstantiation:
10228        // We will be instantiating the key function.
10229        break;
10230      }
10231    } else if (!KeyFunction) {
10232      // If we have a class with no key function that is the subject
10233      // of an explicit instantiation declaration, suppress the
10234      // vtable; it will live with the explicit instantiation
10235      // definition.
10236      bool IsExplicitInstantiationDeclaration
10237        = Class->getTemplateSpecializationKind()
10238                                      == TSK_ExplicitInstantiationDeclaration;
10239      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10240                                 REnd = Class->redecls_end();
10241           R != REnd; ++R) {
10242        TemplateSpecializationKind TSK
10243          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10244        if (TSK == TSK_ExplicitInstantiationDeclaration)
10245          IsExplicitInstantiationDeclaration = true;
10246        else if (TSK == TSK_ExplicitInstantiationDefinition) {
10247          IsExplicitInstantiationDeclaration = false;
10248          break;
10249        }
10250      }
10251
10252      if (IsExplicitInstantiationDeclaration)
10253        continue;
10254    }
10255
10256    // Mark all of the virtual members of this class as referenced, so
10257    // that we can build a vtable. Then, tell the AST consumer that a
10258    // vtable for this class is required.
10259    DefinedAnything = true;
10260    MarkVirtualMembersReferenced(Loc, Class);
10261    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10262    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10263
10264    // Optionally warn if we're emitting a weak vtable.
10265    if (Class->getLinkage() == ExternalLinkage &&
10266        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
10267      if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
10268        Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
10269    }
10270  }
10271  VTableUses.clear();
10272
10273  return DefinedAnything;
10274}
10275
10276void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10277                                        const CXXRecordDecl *RD) {
10278  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10279       e = RD->method_end(); i != e; ++i) {
10280    CXXMethodDecl *MD = *i;
10281
10282    // C++ [basic.def.odr]p2:
10283    //   [...] A virtual member function is used if it is not pure. [...]
10284    if (MD->isVirtual() && !MD->isPure())
10285      MarkDeclarationReferenced(Loc, MD);
10286  }
10287
10288  // Only classes that have virtual bases need a VTT.
10289  if (RD->getNumVBases() == 0)
10290    return;
10291
10292  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10293           e = RD->bases_end(); i != e; ++i) {
10294    const CXXRecordDecl *Base =
10295        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
10296    if (Base->getNumVBases() == 0)
10297      continue;
10298    MarkVirtualMembersReferenced(Loc, Base);
10299  }
10300}
10301
10302/// SetIvarInitializers - This routine builds initialization ASTs for the
10303/// Objective-C implementation whose ivars need be initialized.
10304void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10305  if (!getLangOptions().CPlusPlus)
10306    return;
10307  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
10308    SmallVector<ObjCIvarDecl*, 8> ivars;
10309    CollectIvarsToConstructOrDestruct(OID, ivars);
10310    if (ivars.empty())
10311      return;
10312    SmallVector<CXXCtorInitializer*, 32> AllToInit;
10313    for (unsigned i = 0; i < ivars.size(); i++) {
10314      FieldDecl *Field = ivars[i];
10315      if (Field->isInvalidDecl())
10316        continue;
10317
10318      CXXCtorInitializer *Member;
10319      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10320      InitializationKind InitKind =
10321        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10322
10323      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
10324      ExprResult MemberInit =
10325        InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
10326      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
10327      // Note, MemberInit could actually come back empty if no initialization
10328      // is required (e.g., because it would call a trivial default constructor)
10329      if (!MemberInit.get() || MemberInit.isInvalid())
10330        continue;
10331
10332      Member =
10333        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10334                                         SourceLocation(),
10335                                         MemberInit.takeAs<Expr>(),
10336                                         SourceLocation());
10337      AllToInit.push_back(Member);
10338
10339      // Be sure that the destructor is accessible and is marked as referenced.
10340      if (const RecordType *RecordTy
10341                  = Context.getBaseElementType(Field->getType())
10342                                                        ->getAs<RecordType>()) {
10343                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
10344        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
10345          MarkDeclarationReferenced(Field->getLocation(), Destructor);
10346          CheckDestructorAccess(Field->getLocation(), Destructor,
10347                            PDiag(diag::err_access_dtor_ivar)
10348                              << Context.getBaseElementType(Field->getType()));
10349        }
10350      }
10351    }
10352    ObjCImplementation->setIvarInitializers(Context,
10353                                            AllToInit.data(), AllToInit.size());
10354  }
10355}
10356
10357static
10358void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10359                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10360                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10361                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10362                           Sema &S) {
10363  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10364                                                   CE = Current.end();
10365  if (Ctor->isInvalidDecl())
10366    return;
10367
10368  const FunctionDecl *FNTarget = 0;
10369  CXXConstructorDecl *Target;
10370
10371  // We ignore the result here since if we don't have a body, Target will be
10372  // null below.
10373  (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10374  Target
10375= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10376
10377  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10378                     // Avoid dereferencing a null pointer here.
10379                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10380
10381  if (!Current.insert(Canonical))
10382    return;
10383
10384  // We know that beyond here, we aren't chaining into a cycle.
10385  if (!Target || !Target->isDelegatingConstructor() ||
10386      Target->isInvalidDecl() || Valid.count(TCanonical)) {
10387    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10388      Valid.insert(*CI);
10389    Current.clear();
10390  // We've hit a cycle.
10391  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10392             Current.count(TCanonical)) {
10393    // If we haven't diagnosed this cycle yet, do so now.
10394    if (!Invalid.count(TCanonical)) {
10395      S.Diag((*Ctor->init_begin())->getSourceLocation(),
10396             diag::warn_delegating_ctor_cycle)
10397        << Ctor;
10398
10399      // Don't add a note for a function delegating directo to itself.
10400      if (TCanonical != Canonical)
10401        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10402
10403      CXXConstructorDecl *C = Target;
10404      while (C->getCanonicalDecl() != Canonical) {
10405        (void)C->getTargetConstructor()->hasBody(FNTarget);
10406        assert(FNTarget && "Ctor cycle through bodiless function");
10407
10408        C
10409       = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10410        S.Diag(C->getLocation(), diag::note_which_delegates_to);
10411      }
10412    }
10413
10414    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10415      Invalid.insert(*CI);
10416    Current.clear();
10417  } else {
10418    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10419  }
10420}
10421
10422
10423void Sema::CheckDelegatingCtorCycles() {
10424  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10425
10426  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10427                                                   CE = Current.end();
10428
10429  for (DelegatingCtorDeclsType::iterator
10430         I = DelegatingCtorDecls.begin(ExternalSource),
10431         E = DelegatingCtorDecls.end();
10432       I != E; ++I) {
10433   DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
10434  }
10435
10436  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10437    (*CI)->setInvalidDecl();
10438}
10439