SemaDeclCXX.cpp revision 17d35c36fbae764fcd68fa8b31624078a033aabc
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/Sema/ScopeInfo.h"
20#include "clang/AST/ASTConsumer.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/ASTMutationListener.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/CXXInheritance.h"
25#include "clang/AST/DeclVisitor.h"
26#include "clang/AST/EvaluatedExprVisitor.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/RecordLayout.h"
29#include "clang/AST/RecursiveASTVisitor.h"
30#include "clang/AST/StmtVisitor.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/AST/TypeOrdering.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/ParsedTemplate.h"
35#include "clang/Basic/PartialDiagnostic.h"
36#include "clang/Lex/Preprocessor.h"
37#include "llvm/ADT/SmallString.h"
38#include "llvm/ADT/STLExtras.h"
39#include <map>
40#include <set>
41
42using namespace clang;
43
44//===----------------------------------------------------------------------===//
45// CheckDefaultArgumentVisitor
46//===----------------------------------------------------------------------===//
47
48namespace {
49  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
50  /// the default argument of a parameter to determine whether it
51  /// contains any ill-formed subexpressions. For example, this will
52  /// diagnose the use of local variables or parameters within the
53  /// default argument expression.
54  class CheckDefaultArgumentVisitor
55    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
56    Expr *DefaultArg;
57    Sema *S;
58
59  public:
60    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
61      : DefaultArg(defarg), S(s) {}
62
63    bool VisitExpr(Expr *Node);
64    bool VisitDeclRefExpr(DeclRefExpr *DRE);
65    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
66    bool VisitLambdaExpr(LambdaExpr *Lambda);
67  };
68
69  /// VisitExpr - Visit all of the children of this expression.
70  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
71    bool IsInvalid = false;
72    for (Stmt::child_range I = Node->children(); I; ++I)
73      IsInvalid |= Visit(*I);
74    return IsInvalid;
75  }
76
77  /// VisitDeclRefExpr - Visit a reference to a declaration, to
78  /// determine whether this declaration can be used in the default
79  /// argument expression.
80  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
81    NamedDecl *Decl = DRE->getDecl();
82    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
83      // C++ [dcl.fct.default]p9
84      //   Default arguments are evaluated each time the function is
85      //   called. The order of evaluation of function arguments is
86      //   unspecified. Consequently, parameters of a function shall not
87      //   be used in default argument expressions, even if they are not
88      //   evaluated. Parameters of a function declared before a default
89      //   argument expression are in scope and can hide namespace and
90      //   class member names.
91      return S->Diag(DRE->getLocStart(),
92                     diag::err_param_default_argument_references_param)
93         << Param->getDeclName() << DefaultArg->getSourceRange();
94    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
95      // C++ [dcl.fct.default]p7
96      //   Local variables shall not be used in default argument
97      //   expressions.
98      if (VDecl->isLocalVarDecl())
99        return S->Diag(DRE->getLocStart(),
100                       diag::err_param_default_argument_references_local)
101          << VDecl->getDeclName() << DefaultArg->getSourceRange();
102    }
103
104    return false;
105  }
106
107  /// VisitCXXThisExpr - Visit a C++ "this" expression.
108  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
109    // C++ [dcl.fct.default]p8:
110    //   The keyword this shall not be used in a default argument of a
111    //   member function.
112    return S->Diag(ThisE->getLocStart(),
113                   diag::err_param_default_argument_references_this)
114               << ThisE->getSourceRange();
115  }
116
117  bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
118    // C++11 [expr.lambda.prim]p13:
119    //   A lambda-expression appearing in a default argument shall not
120    //   implicitly or explicitly capture any entity.
121    if (Lambda->capture_begin() == Lambda->capture_end())
122      return false;
123
124    return S->Diag(Lambda->getLocStart(),
125                   diag::err_lambda_capture_default_arg);
126  }
127}
128
129void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
130                                                      CXXMethodDecl *Method) {
131  // If we have an MSAny spec already, don't bother.
132  if (!Method || ComputedEST == EST_MSAny)
133    return;
134
135  const FunctionProtoType *Proto
136    = Method->getType()->getAs<FunctionProtoType>();
137  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
138  if (!Proto)
139    return;
140
141  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
142
143  // If this function can throw any exceptions, make a note of that.
144  if (EST == EST_MSAny || EST == EST_None) {
145    ClearExceptions();
146    ComputedEST = EST;
147    return;
148  }
149
150  // FIXME: If the call to this decl is using any of its default arguments, we
151  // need to search them for potentially-throwing calls.
152
153  // If this function has a basic noexcept, it doesn't affect the outcome.
154  if (EST == EST_BasicNoexcept)
155    return;
156
157  // If we have a throw-all spec at this point, ignore the function.
158  if (ComputedEST == EST_None)
159    return;
160
161  // If we're still at noexcept(true) and there's a nothrow() callee,
162  // change to that specification.
163  if (EST == EST_DynamicNone) {
164    if (ComputedEST == EST_BasicNoexcept)
165      ComputedEST = EST_DynamicNone;
166    return;
167  }
168
169  // Check out noexcept specs.
170  if (EST == EST_ComputedNoexcept) {
171    FunctionProtoType::NoexceptResult NR =
172        Proto->getNoexceptSpec(Self->Context);
173    assert(NR != FunctionProtoType::NR_NoNoexcept &&
174           "Must have noexcept result for EST_ComputedNoexcept.");
175    assert(NR != FunctionProtoType::NR_Dependent &&
176           "Should not generate implicit declarations for dependent cases, "
177           "and don't know how to handle them anyway.");
178
179    // noexcept(false) -> no spec on the new function
180    if (NR == FunctionProtoType::NR_Throw) {
181      ClearExceptions();
182      ComputedEST = EST_None;
183    }
184    // noexcept(true) won't change anything either.
185    return;
186  }
187
188  assert(EST == EST_Dynamic && "EST case not considered earlier.");
189  assert(ComputedEST != EST_None &&
190         "Shouldn't collect exceptions when throw-all is guaranteed.");
191  ComputedEST = EST_Dynamic;
192  // Record the exceptions in this function's exception specification.
193  for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
194                                          EEnd = Proto->exception_end();
195       E != EEnd; ++E)
196    if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
197      Exceptions.push_back(*E);
198}
199
200void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
201  if (!E || ComputedEST == EST_MSAny)
202    return;
203
204  // FIXME:
205  //
206  // C++0x [except.spec]p14:
207  //   [An] implicit exception-specification specifies the type-id T if and
208  // only if T is allowed by the exception-specification of a function directly
209  // invoked by f's implicit definition; f shall allow all exceptions if any
210  // function it directly invokes allows all exceptions, and f shall allow no
211  // exceptions if every function it directly invokes allows no exceptions.
212  //
213  // Note in particular that if an implicit exception-specification is generated
214  // for a function containing a throw-expression, that specification can still
215  // be noexcept(true).
216  //
217  // Note also that 'directly invoked' is not defined in the standard, and there
218  // is no indication that we should only consider potentially-evaluated calls.
219  //
220  // Ultimately we should implement the intent of the standard: the exception
221  // specification should be the set of exceptions which can be thrown by the
222  // implicit definition. For now, we assume that any non-nothrow expression can
223  // throw any exception.
224
225  if (Self->canThrow(E))
226    ComputedEST = EST_None;
227}
228
229bool
230Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
231                              SourceLocation EqualLoc) {
232  if (RequireCompleteType(Param->getLocation(), Param->getType(),
233                          diag::err_typecheck_decl_incomplete_type)) {
234    Param->setInvalidDecl();
235    return true;
236  }
237
238  // C++ [dcl.fct.default]p5
239  //   A default argument expression is implicitly converted (clause
240  //   4) to the parameter type. The default argument expression has
241  //   the same semantic constraints as the initializer expression in
242  //   a declaration of a variable of the parameter type, using the
243  //   copy-initialization semantics (8.5).
244  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
245                                                                    Param);
246  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
247                                                           EqualLoc);
248  InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
249  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
250  if (Result.isInvalid())
251    return true;
252  Arg = Result.takeAs<Expr>();
253
254  CheckImplicitConversions(Arg, EqualLoc);
255  Arg = MaybeCreateExprWithCleanups(Arg);
256
257  // Okay: add the default argument to the parameter
258  Param->setDefaultArg(Arg);
259
260  // We have already instantiated this parameter; provide each of the
261  // instantiations with the uninstantiated default argument.
262  UnparsedDefaultArgInstantiationsMap::iterator InstPos
263    = UnparsedDefaultArgInstantiations.find(Param);
264  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
265    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
266      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
267
268    // We're done tracking this parameter's instantiations.
269    UnparsedDefaultArgInstantiations.erase(InstPos);
270  }
271
272  return false;
273}
274
275/// ActOnParamDefaultArgument - Check whether the default argument
276/// provided for a function parameter is well-formed. If so, attach it
277/// to the parameter declaration.
278void
279Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
280                                Expr *DefaultArg) {
281  if (!param || !DefaultArg)
282    return;
283
284  ParmVarDecl *Param = cast<ParmVarDecl>(param);
285  UnparsedDefaultArgLocs.erase(Param);
286
287  // Default arguments are only permitted in C++
288  if (!getLangOpts().CPlusPlus) {
289    Diag(EqualLoc, diag::err_param_default_argument)
290      << DefaultArg->getSourceRange();
291    Param->setInvalidDecl();
292    return;
293  }
294
295  // Check for unexpanded parameter packs.
296  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
297    Param->setInvalidDecl();
298    return;
299  }
300
301  // Check that the default argument is well-formed
302  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
303  if (DefaultArgChecker.Visit(DefaultArg)) {
304    Param->setInvalidDecl();
305    return;
306  }
307
308  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
309}
310
311/// ActOnParamUnparsedDefaultArgument - We've seen a default
312/// argument for a function parameter, but we can't parse it yet
313/// because we're inside a class definition. Note that this default
314/// argument will be parsed later.
315void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
316                                             SourceLocation EqualLoc,
317                                             SourceLocation ArgLoc) {
318  if (!param)
319    return;
320
321  ParmVarDecl *Param = cast<ParmVarDecl>(param);
322  if (Param)
323    Param->setUnparsedDefaultArg();
324
325  UnparsedDefaultArgLocs[Param] = ArgLoc;
326}
327
328/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
329/// the default argument for the parameter param failed.
330void Sema::ActOnParamDefaultArgumentError(Decl *param) {
331  if (!param)
332    return;
333
334  ParmVarDecl *Param = cast<ParmVarDecl>(param);
335
336  Param->setInvalidDecl();
337
338  UnparsedDefaultArgLocs.erase(Param);
339}
340
341/// CheckExtraCXXDefaultArguments - Check for any extra default
342/// arguments in the declarator, which is not a function declaration
343/// or definition and therefore is not permitted to have default
344/// arguments. This routine should be invoked for every declarator
345/// that is not a function declaration or definition.
346void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
347  // C++ [dcl.fct.default]p3
348  //   A default argument expression shall be specified only in the
349  //   parameter-declaration-clause of a function declaration or in a
350  //   template-parameter (14.1). It shall not be specified for a
351  //   parameter pack. If it is specified in a
352  //   parameter-declaration-clause, it shall not occur within a
353  //   declarator or abstract-declarator of a parameter-declaration.
354  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
355    DeclaratorChunk &chunk = D.getTypeObject(i);
356    if (chunk.Kind == DeclaratorChunk::Function) {
357      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
358        ParmVarDecl *Param =
359          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
360        if (Param->hasUnparsedDefaultArg()) {
361          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
362          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
363            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
364          delete Toks;
365          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
366        } else if (Param->getDefaultArg()) {
367          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
368            << Param->getDefaultArg()->getSourceRange();
369          Param->setDefaultArg(0);
370        }
371      }
372    }
373  }
374}
375
376// MergeCXXFunctionDecl - Merge two declarations of the same C++
377// function, once we already know that they have the same
378// type. Subroutine of MergeFunctionDecl. Returns true if there was an
379// error, false otherwise.
380bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
381                                Scope *S) {
382  bool Invalid = false;
383
384  // C++ [dcl.fct.default]p4:
385  //   For non-template functions, default arguments can be added in
386  //   later declarations of a function in the same
387  //   scope. Declarations in different scopes have completely
388  //   distinct sets of default arguments. That is, declarations in
389  //   inner scopes do not acquire default arguments from
390  //   declarations in outer scopes, and vice versa. In a given
391  //   function declaration, all parameters subsequent to a
392  //   parameter with a default argument shall have default
393  //   arguments supplied in this or previous declarations. A
394  //   default argument shall not be redefined by a later
395  //   declaration (not even to the same value).
396  //
397  // C++ [dcl.fct.default]p6:
398  //   Except for member functions of class templates, the default arguments
399  //   in a member function definition that appears outside of the class
400  //   definition are added to the set of default arguments provided by the
401  //   member function declaration in the class definition.
402  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
403    ParmVarDecl *OldParam = Old->getParamDecl(p);
404    ParmVarDecl *NewParam = New->getParamDecl(p);
405
406    bool OldParamHasDfl = OldParam->hasDefaultArg();
407    bool NewParamHasDfl = NewParam->hasDefaultArg();
408
409    NamedDecl *ND = Old;
410    if (S && !isDeclInScope(ND, New->getDeclContext(), S))
411      // Ignore default parameters of old decl if they are not in
412      // the same scope.
413      OldParamHasDfl = false;
414
415    if (OldParamHasDfl && NewParamHasDfl) {
416
417      unsigned DiagDefaultParamID =
418        diag::err_param_default_argument_redefinition;
419
420      // MSVC accepts that default parameters be redefined for member functions
421      // of template class. The new default parameter's value is ignored.
422      Invalid = true;
423      if (getLangOpts().MicrosoftExt) {
424        CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
425        if (MD && MD->getParent()->getDescribedClassTemplate()) {
426          // Merge the old default argument into the new parameter.
427          NewParam->setHasInheritedDefaultArg();
428          if (OldParam->hasUninstantiatedDefaultArg())
429            NewParam->setUninstantiatedDefaultArg(
430                                      OldParam->getUninstantiatedDefaultArg());
431          else
432            NewParam->setDefaultArg(OldParam->getInit());
433          DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
434          Invalid = false;
435        }
436      }
437
438      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
439      // hint here. Alternatively, we could walk the type-source information
440      // for NewParam to find the last source location in the type... but it
441      // isn't worth the effort right now. This is the kind of test case that
442      // is hard to get right:
443      //   int f(int);
444      //   void g(int (*fp)(int) = f);
445      //   void g(int (*fp)(int) = &f);
446      Diag(NewParam->getLocation(), DiagDefaultParamID)
447        << NewParam->getDefaultArgRange();
448
449      // Look for the function declaration where the default argument was
450      // actually written, which may be a declaration prior to Old.
451      for (FunctionDecl *Older = Old->getPreviousDecl();
452           Older; Older = Older->getPreviousDecl()) {
453        if (!Older->getParamDecl(p)->hasDefaultArg())
454          break;
455
456        OldParam = Older->getParamDecl(p);
457      }
458
459      Diag(OldParam->getLocation(), diag::note_previous_definition)
460        << OldParam->getDefaultArgRange();
461    } else if (OldParamHasDfl) {
462      // Merge the old default argument into the new parameter.
463      // It's important to use getInit() here;  getDefaultArg()
464      // strips off any top-level ExprWithCleanups.
465      NewParam->setHasInheritedDefaultArg();
466      if (OldParam->hasUninstantiatedDefaultArg())
467        NewParam->setUninstantiatedDefaultArg(
468                                      OldParam->getUninstantiatedDefaultArg());
469      else
470        NewParam->setDefaultArg(OldParam->getInit());
471    } else if (NewParamHasDfl) {
472      if (New->getDescribedFunctionTemplate()) {
473        // Paragraph 4, quoted above, only applies to non-template functions.
474        Diag(NewParam->getLocation(),
475             diag::err_param_default_argument_template_redecl)
476          << NewParam->getDefaultArgRange();
477        Diag(Old->getLocation(), diag::note_template_prev_declaration)
478          << false;
479      } else if (New->getTemplateSpecializationKind()
480                   != TSK_ImplicitInstantiation &&
481                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
482        // C++ [temp.expr.spec]p21:
483        //   Default function arguments shall not be specified in a declaration
484        //   or a definition for one of the following explicit specializations:
485        //     - the explicit specialization of a function template;
486        //     - the explicit specialization of a member function template;
487        //     - the explicit specialization of a member function of a class
488        //       template where the class template specialization to which the
489        //       member function specialization belongs is implicitly
490        //       instantiated.
491        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
492          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
493          << New->getDeclName()
494          << NewParam->getDefaultArgRange();
495      } else if (New->getDeclContext()->isDependentContext()) {
496        // C++ [dcl.fct.default]p6 (DR217):
497        //   Default arguments for a member function of a class template shall
498        //   be specified on the initial declaration of the member function
499        //   within the class template.
500        //
501        // Reading the tea leaves a bit in DR217 and its reference to DR205
502        // leads me to the conclusion that one cannot add default function
503        // arguments for an out-of-line definition of a member function of a
504        // dependent type.
505        int WhichKind = 2;
506        if (CXXRecordDecl *Record
507              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
508          if (Record->getDescribedClassTemplate())
509            WhichKind = 0;
510          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
511            WhichKind = 1;
512          else
513            WhichKind = 2;
514        }
515
516        Diag(NewParam->getLocation(),
517             diag::err_param_default_argument_member_template_redecl)
518          << WhichKind
519          << NewParam->getDefaultArgRange();
520      } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
521        CXXSpecialMember NewSM = getSpecialMember(Ctor),
522                         OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
523        if (NewSM != OldSM) {
524          Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
525            << NewParam->getDefaultArgRange() << NewSM;
526          Diag(Old->getLocation(), diag::note_previous_declaration_special)
527            << OldSM;
528        }
529      }
530    }
531  }
532
533  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
534  // template has a constexpr specifier then all its declarations shall
535  // contain the constexpr specifier.
536  if (New->isConstexpr() != Old->isConstexpr()) {
537    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
538      << New << New->isConstexpr();
539    Diag(Old->getLocation(), diag::note_previous_declaration);
540    Invalid = true;
541  }
542
543  if (CheckEquivalentExceptionSpec(Old, New))
544    Invalid = true;
545
546  return Invalid;
547}
548
549/// \brief Merge the exception specifications of two variable declarations.
550///
551/// This is called when there's a redeclaration of a VarDecl. The function
552/// checks if the redeclaration might have an exception specification and
553/// validates compatibility and merges the specs if necessary.
554void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
555  // Shortcut if exceptions are disabled.
556  if (!getLangOpts().CXXExceptions)
557    return;
558
559  assert(Context.hasSameType(New->getType(), Old->getType()) &&
560         "Should only be called if types are otherwise the same.");
561
562  QualType NewType = New->getType();
563  QualType OldType = Old->getType();
564
565  // We're only interested in pointers and references to functions, as well
566  // as pointers to member functions.
567  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
568    NewType = R->getPointeeType();
569    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
570  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
571    NewType = P->getPointeeType();
572    OldType = OldType->getAs<PointerType>()->getPointeeType();
573  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
574    NewType = M->getPointeeType();
575    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
576  }
577
578  if (!NewType->isFunctionProtoType())
579    return;
580
581  // There's lots of special cases for functions. For function pointers, system
582  // libraries are hopefully not as broken so that we don't need these
583  // workarounds.
584  if (CheckEquivalentExceptionSpec(
585        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
586        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
587    New->setInvalidDecl();
588  }
589}
590
591/// CheckCXXDefaultArguments - Verify that the default arguments for a
592/// function declaration are well-formed according to C++
593/// [dcl.fct.default].
594void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
595  unsigned NumParams = FD->getNumParams();
596  unsigned p;
597
598  bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
599                  isa<CXXMethodDecl>(FD) &&
600                  cast<CXXMethodDecl>(FD)->getParent()->isLambda();
601
602  // Find first parameter with a default argument
603  for (p = 0; p < NumParams; ++p) {
604    ParmVarDecl *Param = FD->getParamDecl(p);
605    if (Param->hasDefaultArg()) {
606      // C++11 [expr.prim.lambda]p5:
607      //   [...] Default arguments (8.3.6) shall not be specified in the
608      //   parameter-declaration-clause of a lambda-declarator.
609      //
610      // FIXME: Core issue 974 strikes this sentence, we only provide an
611      // extension warning.
612      if (IsLambda)
613        Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
614          << Param->getDefaultArgRange();
615      break;
616    }
617  }
618
619  // C++ [dcl.fct.default]p4:
620  //   In a given function declaration, all parameters
621  //   subsequent to a parameter with a default argument shall
622  //   have default arguments supplied in this or previous
623  //   declarations. A default argument shall not be redefined
624  //   by a later declaration (not even to the same value).
625  unsigned LastMissingDefaultArg = 0;
626  for (; p < NumParams; ++p) {
627    ParmVarDecl *Param = FD->getParamDecl(p);
628    if (!Param->hasDefaultArg()) {
629      if (Param->isInvalidDecl())
630        /* We already complained about this parameter. */;
631      else if (Param->getIdentifier())
632        Diag(Param->getLocation(),
633             diag::err_param_default_argument_missing_name)
634          << Param->getIdentifier();
635      else
636        Diag(Param->getLocation(),
637             diag::err_param_default_argument_missing);
638
639      LastMissingDefaultArg = p;
640    }
641  }
642
643  if (LastMissingDefaultArg > 0) {
644    // Some default arguments were missing. Clear out all of the
645    // default arguments up to (and including) the last missing
646    // default argument, so that we leave the function parameters
647    // in a semantically valid state.
648    for (p = 0; p <= LastMissingDefaultArg; ++p) {
649      ParmVarDecl *Param = FD->getParamDecl(p);
650      if (Param->hasDefaultArg()) {
651        Param->setDefaultArg(0);
652      }
653    }
654  }
655}
656
657// CheckConstexprParameterTypes - Check whether a function's parameter types
658// are all literal types. If so, return true. If not, produce a suitable
659// diagnostic and return false.
660static bool CheckConstexprParameterTypes(Sema &SemaRef,
661                                         const FunctionDecl *FD) {
662  unsigned ArgIndex = 0;
663  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
664  for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
665       e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
666    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
667    SourceLocation ParamLoc = PD->getLocation();
668    if (!(*i)->isDependentType() &&
669        SemaRef.RequireLiteralType(ParamLoc, *i,
670                                   diag::err_constexpr_non_literal_param,
671                                   ArgIndex+1, PD->getSourceRange(),
672                                   isa<CXXConstructorDecl>(FD)))
673      return false;
674  }
675  return true;
676}
677
678/// \brief Get diagnostic %select index for tag kind for
679/// record diagnostic message.
680/// WARNING: Indexes apply to particular diagnostics only!
681///
682/// \returns diagnostic %select index.
683static unsigned getRecordDiagFromTagKind(TagTypeKind Tag)
684{
685  switch (Tag) {
686    case TTK_Struct: return 0;
687    case TTK_Interface: return 1;
688    case TTK_Class:  return 2;
689    default: assert("Invalid tag kind for record diagnostic!");
690  }
691  return -1;
692}
693
694// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
695// the requirements of a constexpr function definition or a constexpr
696// constructor definition. If so, return true. If not, produce appropriate
697// diagnostics and return false.
698//
699// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
700bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
701  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
702  if (MD && MD->isInstance()) {
703    // C++11 [dcl.constexpr]p4:
704    //  The definition of a constexpr constructor shall satisfy the following
705    //  constraints:
706    //  - the class shall not have any virtual base classes;
707    const CXXRecordDecl *RD = MD->getParent();
708    if (RD->getNumVBases()) {
709      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
710        << isa<CXXConstructorDecl>(NewFD)
711        << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
712      for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
713             E = RD->vbases_end(); I != E; ++I)
714        Diag(I->getLocStart(),
715             diag::note_constexpr_virtual_base_here) << I->getSourceRange();
716      return false;
717    }
718  }
719
720  if (!isa<CXXConstructorDecl>(NewFD)) {
721    // C++11 [dcl.constexpr]p3:
722    //  The definition of a constexpr function shall satisfy the following
723    //  constraints:
724    // - it shall not be virtual;
725    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
726    if (Method && Method->isVirtual()) {
727      Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
728
729      // If it's not obvious why this function is virtual, find an overridden
730      // function which uses the 'virtual' keyword.
731      const CXXMethodDecl *WrittenVirtual = Method;
732      while (!WrittenVirtual->isVirtualAsWritten())
733        WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
734      if (WrittenVirtual != Method)
735        Diag(WrittenVirtual->getLocation(),
736             diag::note_overridden_virtual_function);
737      return false;
738    }
739
740    // - its return type shall be a literal type;
741    QualType RT = NewFD->getResultType();
742    if (!RT->isDependentType() &&
743        RequireLiteralType(NewFD->getLocation(), RT,
744                           diag::err_constexpr_non_literal_return))
745      return false;
746  }
747
748  // - each of its parameter types shall be a literal type;
749  if (!CheckConstexprParameterTypes(*this, NewFD))
750    return false;
751
752  return true;
753}
754
755/// Check the given declaration statement is legal within a constexpr function
756/// body. C++0x [dcl.constexpr]p3,p4.
757///
758/// \return true if the body is OK, false if we have diagnosed a problem.
759static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
760                                   DeclStmt *DS) {
761  // C++0x [dcl.constexpr]p3 and p4:
762  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
763  //  contain only
764  for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
765         DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
766    switch ((*DclIt)->getKind()) {
767    case Decl::StaticAssert:
768    case Decl::Using:
769    case Decl::UsingShadow:
770    case Decl::UsingDirective:
771    case Decl::UnresolvedUsingTypename:
772      //   - static_assert-declarations
773      //   - using-declarations,
774      //   - using-directives,
775      continue;
776
777    case Decl::Typedef:
778    case Decl::TypeAlias: {
779      //   - typedef declarations and alias-declarations that do not define
780      //     classes or enumerations,
781      TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
782      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
783        // Don't allow variably-modified types in constexpr functions.
784        TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
785        SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
786          << TL.getSourceRange() << TL.getType()
787          << isa<CXXConstructorDecl>(Dcl);
788        return false;
789      }
790      continue;
791    }
792
793    case Decl::Enum:
794    case Decl::CXXRecord:
795      // As an extension, we allow the declaration (but not the definition) of
796      // classes and enumerations in all declarations, not just in typedef and
797      // alias declarations.
798      if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
799        SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
800          << isa<CXXConstructorDecl>(Dcl);
801        return false;
802      }
803      continue;
804
805    case Decl::Var:
806      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
807        << isa<CXXConstructorDecl>(Dcl);
808      return false;
809
810    default:
811      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
812        << isa<CXXConstructorDecl>(Dcl);
813      return false;
814    }
815  }
816
817  return true;
818}
819
820/// Check that the given field is initialized within a constexpr constructor.
821///
822/// \param Dcl The constexpr constructor being checked.
823/// \param Field The field being checked. This may be a member of an anonymous
824///        struct or union nested within the class being checked.
825/// \param Inits All declarations, including anonymous struct/union members and
826///        indirect members, for which any initialization was provided.
827/// \param Diagnosed Set to true if an error is produced.
828static void CheckConstexprCtorInitializer(Sema &SemaRef,
829                                          const FunctionDecl *Dcl,
830                                          FieldDecl *Field,
831                                          llvm::SmallSet<Decl*, 16> &Inits,
832                                          bool &Diagnosed) {
833  if (Field->isUnnamedBitfield())
834    return;
835
836  if (Field->isAnonymousStructOrUnion() &&
837      Field->getType()->getAsCXXRecordDecl()->isEmpty())
838    return;
839
840  if (!Inits.count(Field)) {
841    if (!Diagnosed) {
842      SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
843      Diagnosed = true;
844    }
845    SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
846  } else if (Field->isAnonymousStructOrUnion()) {
847    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
848    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
849         I != E; ++I)
850      // If an anonymous union contains an anonymous struct of which any member
851      // is initialized, all members must be initialized.
852      if (!RD->isUnion() || Inits.count(*I))
853        CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
854  }
855}
856
857/// Check the body for the given constexpr function declaration only contains
858/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
859///
860/// \return true if the body is OK, false if we have diagnosed a problem.
861bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
862  if (isa<CXXTryStmt>(Body)) {
863    // C++11 [dcl.constexpr]p3:
864    //  The definition of a constexpr function shall satisfy the following
865    //  constraints: [...]
866    // - its function-body shall be = delete, = default, or a
867    //   compound-statement
868    //
869    // C++11 [dcl.constexpr]p4:
870    //  In the definition of a constexpr constructor, [...]
871    // - its function-body shall not be a function-try-block;
872    Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
873      << isa<CXXConstructorDecl>(Dcl);
874    return false;
875  }
876
877  // - its function-body shall be [...] a compound-statement that contains only
878  CompoundStmt *CompBody = cast<CompoundStmt>(Body);
879
880  llvm::SmallVector<SourceLocation, 4> ReturnStmts;
881  for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
882         BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
883    switch ((*BodyIt)->getStmtClass()) {
884    case Stmt::NullStmtClass:
885      //   - null statements,
886      continue;
887
888    case Stmt::DeclStmtClass:
889      //   - static_assert-declarations
890      //   - using-declarations,
891      //   - using-directives,
892      //   - typedef declarations and alias-declarations that do not define
893      //     classes or enumerations,
894      if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
895        return false;
896      continue;
897
898    case Stmt::ReturnStmtClass:
899      //   - and exactly one return statement;
900      if (isa<CXXConstructorDecl>(Dcl))
901        break;
902
903      ReturnStmts.push_back((*BodyIt)->getLocStart());
904      continue;
905
906    default:
907      break;
908    }
909
910    Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
911      << isa<CXXConstructorDecl>(Dcl);
912    return false;
913  }
914
915  if (const CXXConstructorDecl *Constructor
916        = dyn_cast<CXXConstructorDecl>(Dcl)) {
917    const CXXRecordDecl *RD = Constructor->getParent();
918    // DR1359:
919    // - every non-variant non-static data member and base class sub-object
920    //   shall be initialized;
921    // - if the class is a non-empty union, or for each non-empty anonymous
922    //   union member of a non-union class, exactly one non-static data member
923    //   shall be initialized;
924    if (RD->isUnion()) {
925      if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
926        Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
927        return false;
928      }
929    } else if (!Constructor->isDependentContext() &&
930               !Constructor->isDelegatingConstructor()) {
931      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
932
933      // Skip detailed checking if we have enough initializers, and we would
934      // allow at most one initializer per member.
935      bool AnyAnonStructUnionMembers = false;
936      unsigned Fields = 0;
937      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
938           E = RD->field_end(); I != E; ++I, ++Fields) {
939        if (I->isAnonymousStructOrUnion()) {
940          AnyAnonStructUnionMembers = true;
941          break;
942        }
943      }
944      if (AnyAnonStructUnionMembers ||
945          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
946        // Check initialization of non-static data members. Base classes are
947        // always initialized so do not need to be checked. Dependent bases
948        // might not have initializers in the member initializer list.
949        llvm::SmallSet<Decl*, 16> Inits;
950        for (CXXConstructorDecl::init_const_iterator
951               I = Constructor->init_begin(), E = Constructor->init_end();
952             I != E; ++I) {
953          if (FieldDecl *FD = (*I)->getMember())
954            Inits.insert(FD);
955          else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
956            Inits.insert(ID->chain_begin(), ID->chain_end());
957        }
958
959        bool Diagnosed = false;
960        for (CXXRecordDecl::field_iterator I = RD->field_begin(),
961             E = RD->field_end(); I != E; ++I)
962          CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
963        if (Diagnosed)
964          return false;
965      }
966    }
967  } else {
968    if (ReturnStmts.empty()) {
969      Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
970      return false;
971    }
972    if (ReturnStmts.size() > 1) {
973      Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
974      for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
975        Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
976      return false;
977    }
978  }
979
980  // C++11 [dcl.constexpr]p5:
981  //   if no function argument values exist such that the function invocation
982  //   substitution would produce a constant expression, the program is
983  //   ill-formed; no diagnostic required.
984  // C++11 [dcl.constexpr]p3:
985  //   - every constructor call and implicit conversion used in initializing the
986  //     return value shall be one of those allowed in a constant expression.
987  // C++11 [dcl.constexpr]p4:
988  //   - every constructor involved in initializing non-static data members and
989  //     base class sub-objects shall be a constexpr constructor.
990  llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
991  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
992    Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
993      << isa<CXXConstructorDecl>(Dcl);
994    for (size_t I = 0, N = Diags.size(); I != N; ++I)
995      Diag(Diags[I].first, Diags[I].second);
996    return false;
997  }
998
999  return true;
1000}
1001
1002/// isCurrentClassName - Determine whether the identifier II is the
1003/// name of the class type currently being defined. In the case of
1004/// nested classes, this will only return true if II is the name of
1005/// the innermost class.
1006bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1007                              const CXXScopeSpec *SS) {
1008  assert(getLangOpts().CPlusPlus && "No class names in C!");
1009
1010  CXXRecordDecl *CurDecl;
1011  if (SS && SS->isSet() && !SS->isInvalid()) {
1012    DeclContext *DC = computeDeclContext(*SS, true);
1013    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1014  } else
1015    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1016
1017  if (CurDecl && CurDecl->getIdentifier())
1018    return &II == CurDecl->getIdentifier();
1019  else
1020    return false;
1021}
1022
1023/// \brief Check the validity of a C++ base class specifier.
1024///
1025/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1026/// and returns NULL otherwise.
1027CXXBaseSpecifier *
1028Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1029                         SourceRange SpecifierRange,
1030                         bool Virtual, AccessSpecifier Access,
1031                         TypeSourceInfo *TInfo,
1032                         SourceLocation EllipsisLoc) {
1033  QualType BaseType = TInfo->getType();
1034
1035  // C++ [class.union]p1:
1036  //   A union shall not have base classes.
1037  if (Class->isUnion()) {
1038    Diag(Class->getLocation(), diag::err_base_clause_on_union)
1039      << SpecifierRange;
1040    return 0;
1041  }
1042
1043  if (EllipsisLoc.isValid() &&
1044      !TInfo->getType()->containsUnexpandedParameterPack()) {
1045    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1046      << TInfo->getTypeLoc().getSourceRange();
1047    EllipsisLoc = SourceLocation();
1048  }
1049
1050  if (BaseType->isDependentType())
1051    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1052                                          Class->getTagKind() == TTK_Class,
1053                                          Access, TInfo, EllipsisLoc);
1054
1055  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1056
1057  // Base specifiers must be record types.
1058  if (!BaseType->isRecordType()) {
1059    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1060    return 0;
1061  }
1062
1063  // C++ [class.union]p1:
1064  //   A union shall not be used as a base class.
1065  if (BaseType->isUnionType()) {
1066    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1067    return 0;
1068  }
1069
1070  // C++ [class.derived]p2:
1071  //   The class-name in a base-specifier shall not be an incompletely
1072  //   defined class.
1073  if (RequireCompleteType(BaseLoc, BaseType,
1074                          diag::err_incomplete_base_class, SpecifierRange)) {
1075    Class->setInvalidDecl();
1076    return 0;
1077  }
1078
1079  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1080  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1081  assert(BaseDecl && "Record type has no declaration");
1082  BaseDecl = BaseDecl->getDefinition();
1083  assert(BaseDecl && "Base type is not incomplete, but has no definition");
1084  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1085  assert(CXXBaseDecl && "Base type is not a C++ type");
1086
1087  // C++ [class]p3:
1088  //   If a class is marked final and it appears as a base-type-specifier in
1089  //   base-clause, the program is ill-formed.
1090  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1091    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1092      << CXXBaseDecl->getDeclName();
1093    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1094      << CXXBaseDecl->getDeclName();
1095    return 0;
1096  }
1097
1098  if (BaseDecl->isInvalidDecl())
1099    Class->setInvalidDecl();
1100
1101  // Create the base specifier.
1102  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1103                                        Class->getTagKind() == TTK_Class,
1104                                        Access, TInfo, EllipsisLoc);
1105}
1106
1107/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1108/// one entry in the base class list of a class specifier, for
1109/// example:
1110///    class foo : public bar, virtual private baz {
1111/// 'public bar' and 'virtual private baz' are each base-specifiers.
1112BaseResult
1113Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1114                         bool Virtual, AccessSpecifier Access,
1115                         ParsedType basetype, SourceLocation BaseLoc,
1116                         SourceLocation EllipsisLoc) {
1117  if (!classdecl)
1118    return true;
1119
1120  AdjustDeclIfTemplate(classdecl);
1121  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1122  if (!Class)
1123    return true;
1124
1125  TypeSourceInfo *TInfo = 0;
1126  GetTypeFromParser(basetype, &TInfo);
1127
1128  if (EllipsisLoc.isInvalid() &&
1129      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1130                                      UPPC_BaseType))
1131    return true;
1132
1133  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1134                                                      Virtual, Access, TInfo,
1135                                                      EllipsisLoc))
1136    return BaseSpec;
1137  else
1138    Class->setInvalidDecl();
1139
1140  return true;
1141}
1142
1143/// \brief Performs the actual work of attaching the given base class
1144/// specifiers to a C++ class.
1145bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1146                                unsigned NumBases) {
1147 if (NumBases == 0)
1148    return false;
1149
1150  // Used to keep track of which base types we have already seen, so
1151  // that we can properly diagnose redundant direct base types. Note
1152  // that the key is always the unqualified canonical type of the base
1153  // class.
1154  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1155
1156  // Copy non-redundant base specifiers into permanent storage.
1157  unsigned NumGoodBases = 0;
1158  bool Invalid = false;
1159  for (unsigned idx = 0; idx < NumBases; ++idx) {
1160    QualType NewBaseType
1161      = Context.getCanonicalType(Bases[idx]->getType());
1162    NewBaseType = NewBaseType.getLocalUnqualifiedType();
1163
1164    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1165    if (KnownBase) {
1166      // C++ [class.mi]p3:
1167      //   A class shall not be specified as a direct base class of a
1168      //   derived class more than once.
1169      Diag(Bases[idx]->getLocStart(),
1170           diag::err_duplicate_base_class)
1171        << KnownBase->getType()
1172        << Bases[idx]->getSourceRange();
1173
1174      // Delete the duplicate base class specifier; we're going to
1175      // overwrite its pointer later.
1176      Context.Deallocate(Bases[idx]);
1177
1178      Invalid = true;
1179    } else {
1180      // Okay, add this new base class.
1181      KnownBase = Bases[idx];
1182      Bases[NumGoodBases++] = Bases[idx];
1183      if (const RecordType *Record = NewBaseType->getAs<RecordType>())
1184        if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1185          if (RD->hasAttr<WeakAttr>())
1186            Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1187    }
1188  }
1189
1190  // Attach the remaining base class specifiers to the derived class.
1191  Class->setBases(Bases, NumGoodBases);
1192
1193  // Delete the remaining (good) base class specifiers, since their
1194  // data has been copied into the CXXRecordDecl.
1195  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1196    Context.Deallocate(Bases[idx]);
1197
1198  return Invalid;
1199}
1200
1201/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1202/// class, after checking whether there are any duplicate base
1203/// classes.
1204void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1205                               unsigned NumBases) {
1206  if (!ClassDecl || !Bases || !NumBases)
1207    return;
1208
1209  AdjustDeclIfTemplate(ClassDecl);
1210  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1211                       (CXXBaseSpecifier**)(Bases), NumBases);
1212}
1213
1214static CXXRecordDecl *GetClassForType(QualType T) {
1215  if (const RecordType *RT = T->getAs<RecordType>())
1216    return cast<CXXRecordDecl>(RT->getDecl());
1217  else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1218    return ICT->getDecl();
1219  else
1220    return 0;
1221}
1222
1223/// \brief Determine whether the type \p Derived is a C++ class that is
1224/// derived from the type \p Base.
1225bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1226  if (!getLangOpts().CPlusPlus)
1227    return false;
1228
1229  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1230  if (!DerivedRD)
1231    return false;
1232
1233  CXXRecordDecl *BaseRD = GetClassForType(Base);
1234  if (!BaseRD)
1235    return false;
1236
1237  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1238  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1239}
1240
1241/// \brief Determine whether the type \p Derived is a C++ class that is
1242/// derived from the type \p Base.
1243bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1244  if (!getLangOpts().CPlusPlus)
1245    return false;
1246
1247  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1248  if (!DerivedRD)
1249    return false;
1250
1251  CXXRecordDecl *BaseRD = GetClassForType(Base);
1252  if (!BaseRD)
1253    return false;
1254
1255  return DerivedRD->isDerivedFrom(BaseRD, Paths);
1256}
1257
1258void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1259                              CXXCastPath &BasePathArray) {
1260  assert(BasePathArray.empty() && "Base path array must be empty!");
1261  assert(Paths.isRecordingPaths() && "Must record paths!");
1262
1263  const CXXBasePath &Path = Paths.front();
1264
1265  // We first go backward and check if we have a virtual base.
1266  // FIXME: It would be better if CXXBasePath had the base specifier for
1267  // the nearest virtual base.
1268  unsigned Start = 0;
1269  for (unsigned I = Path.size(); I != 0; --I) {
1270    if (Path[I - 1].Base->isVirtual()) {
1271      Start = I - 1;
1272      break;
1273    }
1274  }
1275
1276  // Now add all bases.
1277  for (unsigned I = Start, E = Path.size(); I != E; ++I)
1278    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1279}
1280
1281/// \brief Determine whether the given base path includes a virtual
1282/// base class.
1283bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1284  for (CXXCastPath::const_iterator B = BasePath.begin(),
1285                                BEnd = BasePath.end();
1286       B != BEnd; ++B)
1287    if ((*B)->isVirtual())
1288      return true;
1289
1290  return false;
1291}
1292
1293/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1294/// conversion (where Derived and Base are class types) is
1295/// well-formed, meaning that the conversion is unambiguous (and
1296/// that all of the base classes are accessible). Returns true
1297/// and emits a diagnostic if the code is ill-formed, returns false
1298/// otherwise. Loc is the location where this routine should point to
1299/// if there is an error, and Range is the source range to highlight
1300/// if there is an error.
1301bool
1302Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1303                                   unsigned InaccessibleBaseID,
1304                                   unsigned AmbigiousBaseConvID,
1305                                   SourceLocation Loc, SourceRange Range,
1306                                   DeclarationName Name,
1307                                   CXXCastPath *BasePath) {
1308  // First, determine whether the path from Derived to Base is
1309  // ambiguous. This is slightly more expensive than checking whether
1310  // the Derived to Base conversion exists, because here we need to
1311  // explore multiple paths to determine if there is an ambiguity.
1312  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1313                     /*DetectVirtual=*/false);
1314  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1315  assert(DerivationOkay &&
1316         "Can only be used with a derived-to-base conversion");
1317  (void)DerivationOkay;
1318
1319  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1320    if (InaccessibleBaseID) {
1321      // Check that the base class can be accessed.
1322      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1323                                   InaccessibleBaseID)) {
1324        case AR_inaccessible:
1325          return true;
1326        case AR_accessible:
1327        case AR_dependent:
1328        case AR_delayed:
1329          break;
1330      }
1331    }
1332
1333    // Build a base path if necessary.
1334    if (BasePath)
1335      BuildBasePathArray(Paths, *BasePath);
1336    return false;
1337  }
1338
1339  // We know that the derived-to-base conversion is ambiguous, and
1340  // we're going to produce a diagnostic. Perform the derived-to-base
1341  // search just one more time to compute all of the possible paths so
1342  // that we can print them out. This is more expensive than any of
1343  // the previous derived-to-base checks we've done, but at this point
1344  // performance isn't as much of an issue.
1345  Paths.clear();
1346  Paths.setRecordingPaths(true);
1347  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1348  assert(StillOkay && "Can only be used with a derived-to-base conversion");
1349  (void)StillOkay;
1350
1351  // Build up a textual representation of the ambiguous paths, e.g.,
1352  // D -> B -> A, that will be used to illustrate the ambiguous
1353  // conversions in the diagnostic. We only print one of the paths
1354  // to each base class subobject.
1355  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1356
1357  Diag(Loc, AmbigiousBaseConvID)
1358  << Derived << Base << PathDisplayStr << Range << Name;
1359  return true;
1360}
1361
1362bool
1363Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1364                                   SourceLocation Loc, SourceRange Range,
1365                                   CXXCastPath *BasePath,
1366                                   bool IgnoreAccess) {
1367  return CheckDerivedToBaseConversion(Derived, Base,
1368                                      IgnoreAccess ? 0
1369                                       : diag::err_upcast_to_inaccessible_base,
1370                                      diag::err_ambiguous_derived_to_base_conv,
1371                                      Loc, Range, DeclarationName(),
1372                                      BasePath);
1373}
1374
1375
1376/// @brief Builds a string representing ambiguous paths from a
1377/// specific derived class to different subobjects of the same base
1378/// class.
1379///
1380/// This function builds a string that can be used in error messages
1381/// to show the different paths that one can take through the
1382/// inheritance hierarchy to go from the derived class to different
1383/// subobjects of a base class. The result looks something like this:
1384/// @code
1385/// struct D -> struct B -> struct A
1386/// struct D -> struct C -> struct A
1387/// @endcode
1388std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1389  std::string PathDisplayStr;
1390  std::set<unsigned> DisplayedPaths;
1391  for (CXXBasePaths::paths_iterator Path = Paths.begin();
1392       Path != Paths.end(); ++Path) {
1393    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1394      // We haven't displayed a path to this particular base
1395      // class subobject yet.
1396      PathDisplayStr += "\n    ";
1397      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1398      for (CXXBasePath::const_iterator Element = Path->begin();
1399           Element != Path->end(); ++Element)
1400        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1401    }
1402  }
1403
1404  return PathDisplayStr;
1405}
1406
1407//===----------------------------------------------------------------------===//
1408// C++ class member Handling
1409//===----------------------------------------------------------------------===//
1410
1411/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1412bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1413                                SourceLocation ASLoc,
1414                                SourceLocation ColonLoc,
1415                                AttributeList *Attrs) {
1416  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1417  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1418                                                  ASLoc, ColonLoc);
1419  CurContext->addHiddenDecl(ASDecl);
1420  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1421}
1422
1423/// CheckOverrideControl - Check C++11 override control semantics.
1424void Sema::CheckOverrideControl(Decl *D) {
1425  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1426
1427  // Do we know which functions this declaration might be overriding?
1428  bool OverridesAreKnown = !MD ||
1429      (!MD->getParent()->hasAnyDependentBases() &&
1430       !MD->getType()->isDependentType());
1431
1432  if (!MD || !MD->isVirtual()) {
1433    if (OverridesAreKnown) {
1434      if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1435        Diag(OA->getLocation(),
1436             diag::override_keyword_only_allowed_on_virtual_member_functions)
1437          << "override" << FixItHint::CreateRemoval(OA->getLocation());
1438        D->dropAttr<OverrideAttr>();
1439      }
1440      if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1441        Diag(FA->getLocation(),
1442             diag::override_keyword_only_allowed_on_virtual_member_functions)
1443          << "final" << FixItHint::CreateRemoval(FA->getLocation());
1444        D->dropAttr<FinalAttr>();
1445      }
1446    }
1447    return;
1448  }
1449
1450  if (!OverridesAreKnown)
1451    return;
1452
1453  // C++11 [class.virtual]p5:
1454  //   If a virtual function is marked with the virt-specifier override and
1455  //   does not override a member function of a base class, the program is
1456  //   ill-formed.
1457  bool HasOverriddenMethods =
1458    MD->begin_overridden_methods() != MD->end_overridden_methods();
1459  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1460    Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1461      << MD->getDeclName();
1462}
1463
1464/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1465/// function overrides a virtual member function marked 'final', according to
1466/// C++11 [class.virtual]p4.
1467bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1468                                                  const CXXMethodDecl *Old) {
1469  if (!Old->hasAttr<FinalAttr>())
1470    return false;
1471
1472  Diag(New->getLocation(), diag::err_final_function_overridden)
1473    << New->getDeclName();
1474  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1475  return true;
1476}
1477
1478static bool InitializationHasSideEffects(const FieldDecl &FD) {
1479  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1480  // FIXME: Destruction of ObjC lifetime types has side-effects.
1481  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1482    return !RD->isCompleteDefinition() ||
1483           !RD->hasTrivialDefaultConstructor() ||
1484           !RD->hasTrivialDestructor();
1485  return false;
1486}
1487
1488/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1489/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1490/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1491/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1492/// present (but parsing it has been deferred).
1493Decl *
1494Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1495                               MultiTemplateParamsArg TemplateParameterLists,
1496                               Expr *BW, const VirtSpecifiers &VS,
1497                               InClassInitStyle InitStyle) {
1498  const DeclSpec &DS = D.getDeclSpec();
1499  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1500  DeclarationName Name = NameInfo.getName();
1501  SourceLocation Loc = NameInfo.getLoc();
1502
1503  // For anonymous bitfields, the location should point to the type.
1504  if (Loc.isInvalid())
1505    Loc = D.getLocStart();
1506
1507  Expr *BitWidth = static_cast<Expr*>(BW);
1508
1509  assert(isa<CXXRecordDecl>(CurContext));
1510  assert(!DS.isFriendSpecified());
1511
1512  bool isFunc = D.isDeclarationOfFunction();
1513
1514  // C++ 9.2p6: A member shall not be declared to have automatic storage
1515  // duration (auto, register) or with the extern storage-class-specifier.
1516  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1517  // data members and cannot be applied to names declared const or static,
1518  // and cannot be applied to reference members.
1519  switch (DS.getStorageClassSpec()) {
1520    case DeclSpec::SCS_unspecified:
1521    case DeclSpec::SCS_typedef:
1522    case DeclSpec::SCS_static:
1523      // FALL THROUGH.
1524      break;
1525    case DeclSpec::SCS_mutable:
1526      if (isFunc) {
1527        if (DS.getStorageClassSpecLoc().isValid())
1528          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1529        else
1530          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1531
1532        // FIXME: It would be nicer if the keyword was ignored only for this
1533        // declarator. Otherwise we could get follow-up errors.
1534        D.getMutableDeclSpec().ClearStorageClassSpecs();
1535      }
1536      break;
1537    default:
1538      if (DS.getStorageClassSpecLoc().isValid())
1539        Diag(DS.getStorageClassSpecLoc(),
1540             diag::err_storageclass_invalid_for_member);
1541      else
1542        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1543      D.getMutableDeclSpec().ClearStorageClassSpecs();
1544  }
1545
1546  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1547                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1548                      !isFunc);
1549
1550  Decl *Member;
1551  if (isInstField) {
1552    CXXScopeSpec &SS = D.getCXXScopeSpec();
1553
1554    // Data members must have identifiers for names.
1555    if (!Name.isIdentifier()) {
1556      Diag(Loc, diag::err_bad_variable_name)
1557        << Name;
1558      return 0;
1559    }
1560
1561    IdentifierInfo *II = Name.getAsIdentifierInfo();
1562
1563    // Member field could not be with "template" keyword.
1564    // So TemplateParameterLists should be empty in this case.
1565    if (TemplateParameterLists.size()) {
1566      TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1567      if (TemplateParams->size()) {
1568        // There is no such thing as a member field template.
1569        Diag(D.getIdentifierLoc(), diag::err_template_member)
1570            << II
1571            << SourceRange(TemplateParams->getTemplateLoc(),
1572                TemplateParams->getRAngleLoc());
1573      } else {
1574        // There is an extraneous 'template<>' for this member.
1575        Diag(TemplateParams->getTemplateLoc(),
1576            diag::err_template_member_noparams)
1577            << II
1578            << SourceRange(TemplateParams->getTemplateLoc(),
1579                TemplateParams->getRAngleLoc());
1580      }
1581      return 0;
1582    }
1583
1584    if (SS.isSet() && !SS.isInvalid()) {
1585      // The user provided a superfluous scope specifier inside a class
1586      // definition:
1587      //
1588      // class X {
1589      //   int X::member;
1590      // };
1591      if (DeclContext *DC = computeDeclContext(SS, false))
1592        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1593      else
1594        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1595          << Name << SS.getRange();
1596
1597      SS.clear();
1598    }
1599
1600    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1601                         InitStyle, AS);
1602    assert(Member && "HandleField never returns null");
1603  } else {
1604    assert(InitStyle == ICIS_NoInit);
1605
1606    Member = HandleDeclarator(S, D, TemplateParameterLists);
1607    if (!Member) {
1608      return 0;
1609    }
1610
1611    // Non-instance-fields can't have a bitfield.
1612    if (BitWidth) {
1613      if (Member->isInvalidDecl()) {
1614        // don't emit another diagnostic.
1615      } else if (isa<VarDecl>(Member)) {
1616        // C++ 9.6p3: A bit-field shall not be a static member.
1617        // "static member 'A' cannot be a bit-field"
1618        Diag(Loc, diag::err_static_not_bitfield)
1619          << Name << BitWidth->getSourceRange();
1620      } else if (isa<TypedefDecl>(Member)) {
1621        // "typedef member 'x' cannot be a bit-field"
1622        Diag(Loc, diag::err_typedef_not_bitfield)
1623          << Name << BitWidth->getSourceRange();
1624      } else {
1625        // A function typedef ("typedef int f(); f a;").
1626        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1627        Diag(Loc, diag::err_not_integral_type_bitfield)
1628          << Name << cast<ValueDecl>(Member)->getType()
1629          << BitWidth->getSourceRange();
1630      }
1631
1632      BitWidth = 0;
1633      Member->setInvalidDecl();
1634    }
1635
1636    Member->setAccess(AS);
1637
1638    // If we have declared a member function template, set the access of the
1639    // templated declaration as well.
1640    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1641      FunTmpl->getTemplatedDecl()->setAccess(AS);
1642  }
1643
1644  if (VS.isOverrideSpecified())
1645    Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1646  if (VS.isFinalSpecified())
1647    Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1648
1649  if (VS.getLastLocation().isValid()) {
1650    // Update the end location of a method that has a virt-specifiers.
1651    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1652      MD->setRangeEnd(VS.getLastLocation());
1653  }
1654
1655  CheckOverrideControl(Member);
1656
1657  assert((Name || isInstField) && "No identifier for non-field ?");
1658
1659  if (isInstField) {
1660    FieldDecl *FD = cast<FieldDecl>(Member);
1661    FieldCollector->Add(FD);
1662
1663    if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1664                                 FD->getLocation())
1665          != DiagnosticsEngine::Ignored) {
1666      // Remember all explicit private FieldDecls that have a name, no side
1667      // effects and are not part of a dependent type declaration.
1668      if (!FD->isImplicit() && FD->getDeclName() &&
1669          FD->getAccess() == AS_private &&
1670          !FD->hasAttr<UnusedAttr>() &&
1671          !FD->getParent()->isDependentContext() &&
1672          !InitializationHasSideEffects(*FD))
1673        UnusedPrivateFields.insert(FD);
1674    }
1675  }
1676
1677  return Member;
1678}
1679
1680/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1681/// in-class initializer for a non-static C++ class member, and after
1682/// instantiating an in-class initializer in a class template. Such actions
1683/// are deferred until the class is complete.
1684void
1685Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
1686                                       Expr *InitExpr) {
1687  FieldDecl *FD = cast<FieldDecl>(D);
1688  assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1689         "must set init style when field is created");
1690
1691  if (!InitExpr) {
1692    FD->setInvalidDecl();
1693    FD->removeInClassInitializer();
1694    return;
1695  }
1696
1697  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1698    FD->setInvalidDecl();
1699    FD->removeInClassInitializer();
1700    return;
1701  }
1702
1703  ExprResult Init = InitExpr;
1704  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1705    if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
1706      Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
1707        << /*at end of ctor*/1 << InitExpr->getSourceRange();
1708    }
1709    Expr **Inits = &InitExpr;
1710    unsigned NumInits = 1;
1711    InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1712    InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
1713        ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1714        : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
1715    InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1716    Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
1717    if (Init.isInvalid()) {
1718      FD->setInvalidDecl();
1719      return;
1720    }
1721
1722    CheckImplicitConversions(Init.get(), InitLoc);
1723  }
1724
1725  // C++0x [class.base.init]p7:
1726  //   The initialization of each base and member constitutes a
1727  //   full-expression.
1728  Init = MaybeCreateExprWithCleanups(Init);
1729  if (Init.isInvalid()) {
1730    FD->setInvalidDecl();
1731    return;
1732  }
1733
1734  InitExpr = Init.release();
1735
1736  FD->setInClassInitializer(InitExpr);
1737}
1738
1739/// \brief Find the direct and/or virtual base specifiers that
1740/// correspond to the given base type, for use in base initialization
1741/// within a constructor.
1742static bool FindBaseInitializer(Sema &SemaRef,
1743                                CXXRecordDecl *ClassDecl,
1744                                QualType BaseType,
1745                                const CXXBaseSpecifier *&DirectBaseSpec,
1746                                const CXXBaseSpecifier *&VirtualBaseSpec) {
1747  // First, check for a direct base class.
1748  DirectBaseSpec = 0;
1749  for (CXXRecordDecl::base_class_const_iterator Base
1750         = ClassDecl->bases_begin();
1751       Base != ClassDecl->bases_end(); ++Base) {
1752    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1753      // We found a direct base of this type. That's what we're
1754      // initializing.
1755      DirectBaseSpec = &*Base;
1756      break;
1757    }
1758  }
1759
1760  // Check for a virtual base class.
1761  // FIXME: We might be able to short-circuit this if we know in advance that
1762  // there are no virtual bases.
1763  VirtualBaseSpec = 0;
1764  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1765    // We haven't found a base yet; search the class hierarchy for a
1766    // virtual base class.
1767    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1768                       /*DetectVirtual=*/false);
1769    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1770                              BaseType, Paths)) {
1771      for (CXXBasePaths::paths_iterator Path = Paths.begin();
1772           Path != Paths.end(); ++Path) {
1773        if (Path->back().Base->isVirtual()) {
1774          VirtualBaseSpec = Path->back().Base;
1775          break;
1776        }
1777      }
1778    }
1779  }
1780
1781  return DirectBaseSpec || VirtualBaseSpec;
1782}
1783
1784/// \brief Handle a C++ member initializer using braced-init-list syntax.
1785MemInitResult
1786Sema::ActOnMemInitializer(Decl *ConstructorD,
1787                          Scope *S,
1788                          CXXScopeSpec &SS,
1789                          IdentifierInfo *MemberOrBase,
1790                          ParsedType TemplateTypeTy,
1791                          const DeclSpec &DS,
1792                          SourceLocation IdLoc,
1793                          Expr *InitList,
1794                          SourceLocation EllipsisLoc) {
1795  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1796                             DS, IdLoc, InitList,
1797                             EllipsisLoc);
1798}
1799
1800/// \brief Handle a C++ member initializer using parentheses syntax.
1801MemInitResult
1802Sema::ActOnMemInitializer(Decl *ConstructorD,
1803                          Scope *S,
1804                          CXXScopeSpec &SS,
1805                          IdentifierInfo *MemberOrBase,
1806                          ParsedType TemplateTypeTy,
1807                          const DeclSpec &DS,
1808                          SourceLocation IdLoc,
1809                          SourceLocation LParenLoc,
1810                          Expr **Args, unsigned NumArgs,
1811                          SourceLocation RParenLoc,
1812                          SourceLocation EllipsisLoc) {
1813  Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
1814                                           llvm::makeArrayRef(Args, NumArgs),
1815                                           RParenLoc);
1816  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1817                             DS, IdLoc, List, EllipsisLoc);
1818}
1819
1820namespace {
1821
1822// Callback to only accept typo corrections that can be a valid C++ member
1823// intializer: either a non-static field member or a base class.
1824class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1825 public:
1826  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1827      : ClassDecl(ClassDecl) {}
1828
1829  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1830    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1831      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1832        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1833      else
1834        return isa<TypeDecl>(ND);
1835    }
1836    return false;
1837  }
1838
1839 private:
1840  CXXRecordDecl *ClassDecl;
1841};
1842
1843}
1844
1845/// \brief Handle a C++ member initializer.
1846MemInitResult
1847Sema::BuildMemInitializer(Decl *ConstructorD,
1848                          Scope *S,
1849                          CXXScopeSpec &SS,
1850                          IdentifierInfo *MemberOrBase,
1851                          ParsedType TemplateTypeTy,
1852                          const DeclSpec &DS,
1853                          SourceLocation IdLoc,
1854                          Expr *Init,
1855                          SourceLocation EllipsisLoc) {
1856  if (!ConstructorD)
1857    return true;
1858
1859  AdjustDeclIfTemplate(ConstructorD);
1860
1861  CXXConstructorDecl *Constructor
1862    = dyn_cast<CXXConstructorDecl>(ConstructorD);
1863  if (!Constructor) {
1864    // The user wrote a constructor initializer on a function that is
1865    // not a C++ constructor. Ignore the error for now, because we may
1866    // have more member initializers coming; we'll diagnose it just
1867    // once in ActOnMemInitializers.
1868    return true;
1869  }
1870
1871  CXXRecordDecl *ClassDecl = Constructor->getParent();
1872
1873  // C++ [class.base.init]p2:
1874  //   Names in a mem-initializer-id are looked up in the scope of the
1875  //   constructor's class and, if not found in that scope, are looked
1876  //   up in the scope containing the constructor's definition.
1877  //   [Note: if the constructor's class contains a member with the
1878  //   same name as a direct or virtual base class of the class, a
1879  //   mem-initializer-id naming the member or base class and composed
1880  //   of a single identifier refers to the class member. A
1881  //   mem-initializer-id for the hidden base class may be specified
1882  //   using a qualified name. ]
1883  if (!SS.getScopeRep() && !TemplateTypeTy) {
1884    // Look for a member, first.
1885    DeclContext::lookup_result Result
1886      = ClassDecl->lookup(MemberOrBase);
1887    if (Result.first != Result.second) {
1888      ValueDecl *Member;
1889      if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1890          (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
1891        if (EllipsisLoc.isValid())
1892          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1893            << MemberOrBase
1894            << SourceRange(IdLoc, Init->getSourceRange().getEnd());
1895
1896        return BuildMemberInitializer(Member, Init, IdLoc);
1897      }
1898    }
1899  }
1900  // It didn't name a member, so see if it names a class.
1901  QualType BaseType;
1902  TypeSourceInfo *TInfo = 0;
1903
1904  if (TemplateTypeTy) {
1905    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1906  } else if (DS.getTypeSpecType() == TST_decltype) {
1907    BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
1908  } else {
1909    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1910    LookupParsedName(R, S, &SS);
1911
1912    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1913    if (!TyD) {
1914      if (R.isAmbiguous()) return true;
1915
1916      // We don't want access-control diagnostics here.
1917      R.suppressDiagnostics();
1918
1919      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1920        bool NotUnknownSpecialization = false;
1921        DeclContext *DC = computeDeclContext(SS, false);
1922        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1923          NotUnknownSpecialization = !Record->hasAnyDependentBases();
1924
1925        if (!NotUnknownSpecialization) {
1926          // When the scope specifier can refer to a member of an unknown
1927          // specialization, we take it as a type name.
1928          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1929                                       SS.getWithLocInContext(Context),
1930                                       *MemberOrBase, IdLoc);
1931          if (BaseType.isNull())
1932            return true;
1933
1934          R.clear();
1935          R.setLookupName(MemberOrBase);
1936        }
1937      }
1938
1939      // If no results were found, try to correct typos.
1940      TypoCorrection Corr;
1941      MemInitializerValidatorCCC Validator(ClassDecl);
1942      if (R.empty() && BaseType.isNull() &&
1943          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1944                              Validator, ClassDecl))) {
1945        std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1946        std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
1947        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
1948          // We have found a non-static data member with a similar
1949          // name to what was typed; complain and initialize that
1950          // member.
1951          Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1952            << MemberOrBase << true << CorrectedQuotedStr
1953            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1954          Diag(Member->getLocation(), diag::note_previous_decl)
1955            << CorrectedQuotedStr;
1956
1957          return BuildMemberInitializer(Member, Init, IdLoc);
1958        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
1959          const CXXBaseSpecifier *DirectBaseSpec;
1960          const CXXBaseSpecifier *VirtualBaseSpec;
1961          if (FindBaseInitializer(*this, ClassDecl,
1962                                  Context.getTypeDeclType(Type),
1963                                  DirectBaseSpec, VirtualBaseSpec)) {
1964            // We have found a direct or virtual base class with a
1965            // similar name to what was typed; complain and initialize
1966            // that base class.
1967            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1968              << MemberOrBase << false << CorrectedQuotedStr
1969              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1970
1971            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1972                                                             : VirtualBaseSpec;
1973            Diag(BaseSpec->getLocStart(),
1974                 diag::note_base_class_specified_here)
1975              << BaseSpec->getType()
1976              << BaseSpec->getSourceRange();
1977
1978            TyD = Type;
1979          }
1980        }
1981      }
1982
1983      if (!TyD && BaseType.isNull()) {
1984        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1985          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
1986        return true;
1987      }
1988    }
1989
1990    if (BaseType.isNull()) {
1991      BaseType = Context.getTypeDeclType(TyD);
1992      if (SS.isSet()) {
1993        NestedNameSpecifier *Qualifier =
1994          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1995
1996        // FIXME: preserve source range information
1997        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
1998      }
1999    }
2000  }
2001
2002  if (!TInfo)
2003    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2004
2005  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2006}
2007
2008/// Checks a member initializer expression for cases where reference (or
2009/// pointer) members are bound to by-value parameters (or their addresses).
2010static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2011                                               Expr *Init,
2012                                               SourceLocation IdLoc) {
2013  QualType MemberTy = Member->getType();
2014
2015  // We only handle pointers and references currently.
2016  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2017  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2018    return;
2019
2020  const bool IsPointer = MemberTy->isPointerType();
2021  if (IsPointer) {
2022    if (const UnaryOperator *Op
2023          = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2024      // The only case we're worried about with pointers requires taking the
2025      // address.
2026      if (Op->getOpcode() != UO_AddrOf)
2027        return;
2028
2029      Init = Op->getSubExpr();
2030    } else {
2031      // We only handle address-of expression initializers for pointers.
2032      return;
2033    }
2034  }
2035
2036  if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2037    // Taking the address of a temporary will be diagnosed as a hard error.
2038    if (IsPointer)
2039      return;
2040
2041    S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2042      << Member << Init->getSourceRange();
2043  } else if (const DeclRefExpr *DRE
2044               = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2045    // We only warn when referring to a non-reference parameter declaration.
2046    const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2047    if (!Parameter || Parameter->getType()->isReferenceType())
2048      return;
2049
2050    S.Diag(Init->getExprLoc(),
2051           IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2052                     : diag::warn_bind_ref_member_to_parameter)
2053      << Member << Parameter << Init->getSourceRange();
2054  } else {
2055    // Other initializers are fine.
2056    return;
2057  }
2058
2059  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2060    << (unsigned)IsPointer;
2061}
2062
2063namespace {
2064  class UninitializedFieldVisitor
2065      : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2066    Sema &S;
2067    ValueDecl *VD;
2068  public:
2069    typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2070    UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
2071                                                        S(S), VD(VD) {
2072    }
2073
2074    void HandleExpr(Expr *E) {
2075      if (!E) return;
2076
2077      // Expressions like x(x) sometimes lack the surrounding expressions
2078      // but need to be checked anyways.
2079      HandleValue(E);
2080      Visit(E);
2081    }
2082
2083    void HandleValue(Expr *E) {
2084      E = E->IgnoreParens();
2085
2086      if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2087        if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2088            return;
2089        Expr *Base = E;
2090        while (isa<MemberExpr>(Base)) {
2091          ME = dyn_cast<MemberExpr>(Base);
2092          if (VarDecl *VarD = dyn_cast<VarDecl>(ME->getMemberDecl()))
2093            if (VarD->hasGlobalStorage())
2094              return;
2095          Base = ME->getBase();
2096        }
2097
2098        if (VD == ME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
2099          unsigned diag = VD->getType()->isReferenceType()
2100              ? diag::warn_reference_field_is_uninit
2101              : diag::warn_field_is_uninit;
2102          S.Diag(ME->getExprLoc(), diag);
2103          return;
2104        }
2105      }
2106
2107      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2108        HandleValue(CO->getTrueExpr());
2109        HandleValue(CO->getFalseExpr());
2110        return;
2111      }
2112
2113      if (BinaryConditionalOperator *BCO =
2114              dyn_cast<BinaryConditionalOperator>(E)) {
2115        HandleValue(BCO->getCommon());
2116        HandleValue(BCO->getFalseExpr());
2117        return;
2118      }
2119
2120      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2121        switch (BO->getOpcode()) {
2122        default:
2123          return;
2124        case(BO_PtrMemD):
2125        case(BO_PtrMemI):
2126          HandleValue(BO->getLHS());
2127          return;
2128        case(BO_Comma):
2129          HandleValue(BO->getRHS());
2130          return;
2131        }
2132      }
2133    }
2134
2135    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2136      if (E->getCastKind() == CK_LValueToRValue)
2137        HandleValue(E->getSubExpr());
2138
2139      Inherited::VisitImplicitCastExpr(E);
2140    }
2141
2142    void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2143      Expr *Callee = E->getCallee();
2144      if (isa<MemberExpr>(Callee))
2145        HandleValue(Callee);
2146
2147      Inherited::VisitCXXMemberCallExpr(E);
2148    }
2149  };
2150  static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2151                                                       ValueDecl *VD) {
2152    UninitializedFieldVisitor(S, VD).HandleExpr(E);
2153  }
2154} // namespace
2155
2156MemInitResult
2157Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2158                             SourceLocation IdLoc) {
2159  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2160  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2161  assert((DirectMember || IndirectMember) &&
2162         "Member must be a FieldDecl or IndirectFieldDecl");
2163
2164  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2165    return true;
2166
2167  if (Member->isInvalidDecl())
2168    return true;
2169
2170  // Diagnose value-uses of fields to initialize themselves, e.g.
2171  //   foo(foo)
2172  // where foo is not also a parameter to the constructor.
2173  // TODO: implement -Wuninitialized and fold this into that framework.
2174  Expr **Args;
2175  unsigned NumArgs;
2176  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2177    Args = ParenList->getExprs();
2178    NumArgs = ParenList->getNumExprs();
2179  } else {
2180    InitListExpr *InitList = cast<InitListExpr>(Init);
2181    Args = InitList->getInits();
2182    NumArgs = InitList->getNumInits();
2183  }
2184
2185  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2186        != DiagnosticsEngine::Ignored)
2187    for (unsigned i = 0; i < NumArgs; ++i)
2188      // FIXME: Warn about the case when other fields are used before being
2189      // uninitialized. For example, let this field be the i'th field. When
2190      // initializing the i'th field, throw a warning if any of the >= i'th
2191      // fields are used, as they are not yet initialized.
2192      // Right now we are only handling the case where the i'th field uses
2193      // itself in its initializer.
2194      CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
2195
2196  SourceRange InitRange = Init->getSourceRange();
2197
2198  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2199    // Can't check initialization for a member of dependent type or when
2200    // any of the arguments are type-dependent expressions.
2201    DiscardCleanupsInEvaluationContext();
2202  } else {
2203    bool InitList = false;
2204    if (isa<InitListExpr>(Init)) {
2205      InitList = true;
2206      Args = &Init;
2207      NumArgs = 1;
2208
2209      if (isStdInitializerList(Member->getType(), 0)) {
2210        Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2211            << /*at end of ctor*/1 << InitRange;
2212      }
2213    }
2214
2215    // Initialize the member.
2216    InitializedEntity MemberEntity =
2217      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2218                   : InitializedEntity::InitializeMember(IndirectMember, 0);
2219    InitializationKind Kind =
2220      InitList ? InitializationKind::CreateDirectList(IdLoc)
2221               : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2222                                                  InitRange.getEnd());
2223
2224    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2225    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2226                                            MultiExprArg(Args, NumArgs),
2227                                            0);
2228    if (MemberInit.isInvalid())
2229      return true;
2230
2231    CheckImplicitConversions(MemberInit.get(),
2232                             InitRange.getBegin());
2233
2234    // C++0x [class.base.init]p7:
2235    //   The initialization of each base and member constitutes a
2236    //   full-expression.
2237    MemberInit = MaybeCreateExprWithCleanups(MemberInit);
2238    if (MemberInit.isInvalid())
2239      return true;
2240
2241    // If we are in a dependent context, template instantiation will
2242    // perform this type-checking again. Just save the arguments that we
2243    // received.
2244    // FIXME: This isn't quite ideal, since our ASTs don't capture all
2245    // of the information that we have about the member
2246    // initializer. However, deconstructing the ASTs is a dicey process,
2247    // and this approach is far more likely to get the corner cases right.
2248    if (CurContext->isDependentContext()) {
2249      // The existing Init will do fine.
2250    } else {
2251      Init = MemberInit.get();
2252      CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2253    }
2254  }
2255
2256  if (DirectMember) {
2257    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2258                                            InitRange.getBegin(), Init,
2259                                            InitRange.getEnd());
2260  } else {
2261    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2262                                            InitRange.getBegin(), Init,
2263                                            InitRange.getEnd());
2264  }
2265}
2266
2267MemInitResult
2268Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2269                                 CXXRecordDecl *ClassDecl) {
2270  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2271  if (!LangOpts.CPlusPlus0x)
2272    return Diag(NameLoc, diag::err_delegating_ctor)
2273      << TInfo->getTypeLoc().getLocalSourceRange();
2274  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2275
2276  bool InitList = true;
2277  Expr **Args = &Init;
2278  unsigned NumArgs = 1;
2279  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2280    InitList = false;
2281    Args = ParenList->getExprs();
2282    NumArgs = ParenList->getNumExprs();
2283  }
2284
2285  SourceRange InitRange = Init->getSourceRange();
2286  // Initialize the object.
2287  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2288                                     QualType(ClassDecl->getTypeForDecl(), 0));
2289  InitializationKind Kind =
2290    InitList ? InitializationKind::CreateDirectList(NameLoc)
2291             : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2292                                                InitRange.getEnd());
2293  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2294  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2295                                              MultiExprArg(Args, NumArgs),
2296                                              0);
2297  if (DelegationInit.isInvalid())
2298    return true;
2299
2300  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2301         "Delegating constructor with no target?");
2302
2303  CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
2304
2305  // C++0x [class.base.init]p7:
2306  //   The initialization of each base and member constitutes a
2307  //   full-expression.
2308  DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2309  if (DelegationInit.isInvalid())
2310    return true;
2311
2312  // If we are in a dependent context, template instantiation will
2313  // perform this type-checking again. Just save the arguments that we
2314  // received in a ParenListExpr.
2315  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2316  // of the information that we have about the base
2317  // initializer. However, deconstructing the ASTs is a dicey process,
2318  // and this approach is far more likely to get the corner cases right.
2319  if (CurContext->isDependentContext())
2320    DelegationInit = Owned(Init);
2321
2322  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2323                                          DelegationInit.takeAs<Expr>(),
2324                                          InitRange.getEnd());
2325}
2326
2327MemInitResult
2328Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2329                           Expr *Init, CXXRecordDecl *ClassDecl,
2330                           SourceLocation EllipsisLoc) {
2331  SourceLocation BaseLoc
2332    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2333
2334  if (!BaseType->isDependentType() && !BaseType->isRecordType())
2335    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2336             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2337
2338  // C++ [class.base.init]p2:
2339  //   [...] Unless the mem-initializer-id names a nonstatic data
2340  //   member of the constructor's class or a direct or virtual base
2341  //   of that class, the mem-initializer is ill-formed. A
2342  //   mem-initializer-list can initialize a base class using any
2343  //   name that denotes that base class type.
2344  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2345
2346  SourceRange InitRange = Init->getSourceRange();
2347  if (EllipsisLoc.isValid()) {
2348    // This is a pack expansion.
2349    if (!BaseType->containsUnexpandedParameterPack())  {
2350      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2351        << SourceRange(BaseLoc, InitRange.getEnd());
2352
2353      EllipsisLoc = SourceLocation();
2354    }
2355  } else {
2356    // Check for any unexpanded parameter packs.
2357    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2358      return true;
2359
2360    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2361      return true;
2362  }
2363
2364  // Check for direct and virtual base classes.
2365  const CXXBaseSpecifier *DirectBaseSpec = 0;
2366  const CXXBaseSpecifier *VirtualBaseSpec = 0;
2367  if (!Dependent) {
2368    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2369                                       BaseType))
2370      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2371
2372    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2373                        VirtualBaseSpec);
2374
2375    // C++ [base.class.init]p2:
2376    // Unless the mem-initializer-id names a nonstatic data member of the
2377    // constructor's class or a direct or virtual base of that class, the
2378    // mem-initializer is ill-formed.
2379    if (!DirectBaseSpec && !VirtualBaseSpec) {
2380      // If the class has any dependent bases, then it's possible that
2381      // one of those types will resolve to the same type as
2382      // BaseType. Therefore, just treat this as a dependent base
2383      // class initialization.  FIXME: Should we try to check the
2384      // initialization anyway? It seems odd.
2385      if (ClassDecl->hasAnyDependentBases())
2386        Dependent = true;
2387      else
2388        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2389          << BaseType << Context.getTypeDeclType(ClassDecl)
2390          << BaseTInfo->getTypeLoc().getLocalSourceRange();
2391    }
2392  }
2393
2394  if (Dependent) {
2395    DiscardCleanupsInEvaluationContext();
2396
2397    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2398                                            /*IsVirtual=*/false,
2399                                            InitRange.getBegin(), Init,
2400                                            InitRange.getEnd(), EllipsisLoc);
2401  }
2402
2403  // C++ [base.class.init]p2:
2404  //   If a mem-initializer-id is ambiguous because it designates both
2405  //   a direct non-virtual base class and an inherited virtual base
2406  //   class, the mem-initializer is ill-formed.
2407  if (DirectBaseSpec && VirtualBaseSpec)
2408    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2409      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2410
2411  CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2412  if (!BaseSpec)
2413    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2414
2415  // Initialize the base.
2416  bool InitList = true;
2417  Expr **Args = &Init;
2418  unsigned NumArgs = 1;
2419  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2420    InitList = false;
2421    Args = ParenList->getExprs();
2422    NumArgs = ParenList->getNumExprs();
2423  }
2424
2425  InitializedEntity BaseEntity =
2426    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2427  InitializationKind Kind =
2428    InitList ? InitializationKind::CreateDirectList(BaseLoc)
2429             : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2430                                                InitRange.getEnd());
2431  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2432  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2433                                        MultiExprArg(Args, NumArgs), 0);
2434  if (BaseInit.isInvalid())
2435    return true;
2436
2437  CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
2438
2439  // C++0x [class.base.init]p7:
2440  //   The initialization of each base and member constitutes a
2441  //   full-expression.
2442  BaseInit = MaybeCreateExprWithCleanups(BaseInit);
2443  if (BaseInit.isInvalid())
2444    return true;
2445
2446  // If we are in a dependent context, template instantiation will
2447  // perform this type-checking again. Just save the arguments that we
2448  // received in a ParenListExpr.
2449  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2450  // of the information that we have about the base
2451  // initializer. However, deconstructing the ASTs is a dicey process,
2452  // and this approach is far more likely to get the corner cases right.
2453  if (CurContext->isDependentContext())
2454    BaseInit = Owned(Init);
2455
2456  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2457                                          BaseSpec->isVirtual(),
2458                                          InitRange.getBegin(),
2459                                          BaseInit.takeAs<Expr>(),
2460                                          InitRange.getEnd(), EllipsisLoc);
2461}
2462
2463// Create a static_cast\<T&&>(expr).
2464static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2465  QualType ExprType = E->getType();
2466  QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2467  SourceLocation ExprLoc = E->getLocStart();
2468  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2469      TargetType, ExprLoc);
2470
2471  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2472                                   SourceRange(ExprLoc, ExprLoc),
2473                                   E->getSourceRange()).take();
2474}
2475
2476/// ImplicitInitializerKind - How an implicit base or member initializer should
2477/// initialize its base or member.
2478enum ImplicitInitializerKind {
2479  IIK_Default,
2480  IIK_Copy,
2481  IIK_Move
2482};
2483
2484static bool
2485BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2486                             ImplicitInitializerKind ImplicitInitKind,
2487                             CXXBaseSpecifier *BaseSpec,
2488                             bool IsInheritedVirtualBase,
2489                             CXXCtorInitializer *&CXXBaseInit) {
2490  InitializedEntity InitEntity
2491    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2492                                        IsInheritedVirtualBase);
2493
2494  ExprResult BaseInit;
2495
2496  switch (ImplicitInitKind) {
2497  case IIK_Default: {
2498    InitializationKind InitKind
2499      = InitializationKind::CreateDefault(Constructor->getLocation());
2500    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2501    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2502    break;
2503  }
2504
2505  case IIK_Move:
2506  case IIK_Copy: {
2507    bool Moving = ImplicitInitKind == IIK_Move;
2508    ParmVarDecl *Param = Constructor->getParamDecl(0);
2509    QualType ParamType = Param->getType().getNonReferenceType();
2510
2511    Expr *CopyCtorArg =
2512      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2513                          SourceLocation(), Param, false,
2514                          Constructor->getLocation(), ParamType,
2515                          VK_LValue, 0);
2516
2517    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2518
2519    // Cast to the base class to avoid ambiguities.
2520    QualType ArgTy =
2521      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2522                                       ParamType.getQualifiers());
2523
2524    if (Moving) {
2525      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2526    }
2527
2528    CXXCastPath BasePath;
2529    BasePath.push_back(BaseSpec);
2530    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2531                                            CK_UncheckedDerivedToBase,
2532                                            Moving ? VK_XValue : VK_LValue,
2533                                            &BasePath).take();
2534
2535    InitializationKind InitKind
2536      = InitializationKind::CreateDirect(Constructor->getLocation(),
2537                                         SourceLocation(), SourceLocation());
2538    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2539                                   &CopyCtorArg, 1);
2540    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2541                               MultiExprArg(&CopyCtorArg, 1));
2542    break;
2543  }
2544  }
2545
2546  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2547  if (BaseInit.isInvalid())
2548    return true;
2549
2550  CXXBaseInit =
2551    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2552               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2553                                                        SourceLocation()),
2554                                             BaseSpec->isVirtual(),
2555                                             SourceLocation(),
2556                                             BaseInit.takeAs<Expr>(),
2557                                             SourceLocation(),
2558                                             SourceLocation());
2559
2560  return false;
2561}
2562
2563static bool RefersToRValueRef(Expr *MemRef) {
2564  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2565  return Referenced->getType()->isRValueReferenceType();
2566}
2567
2568static bool
2569BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2570                               ImplicitInitializerKind ImplicitInitKind,
2571                               FieldDecl *Field, IndirectFieldDecl *Indirect,
2572                               CXXCtorInitializer *&CXXMemberInit) {
2573  if (Field->isInvalidDecl())
2574    return true;
2575
2576  SourceLocation Loc = Constructor->getLocation();
2577
2578  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2579    bool Moving = ImplicitInitKind == IIK_Move;
2580    ParmVarDecl *Param = Constructor->getParamDecl(0);
2581    QualType ParamType = Param->getType().getNonReferenceType();
2582
2583    // Suppress copying zero-width bitfields.
2584    if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2585      return false;
2586
2587    Expr *MemberExprBase =
2588      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2589                          SourceLocation(), Param, false,
2590                          Loc, ParamType, VK_LValue, 0);
2591
2592    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2593
2594    if (Moving) {
2595      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2596    }
2597
2598    // Build a reference to this field within the parameter.
2599    CXXScopeSpec SS;
2600    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2601                              Sema::LookupMemberName);
2602    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2603                                  : cast<ValueDecl>(Field), AS_public);
2604    MemberLookup.resolveKind();
2605    ExprResult CtorArg
2606      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2607                                         ParamType, Loc,
2608                                         /*IsArrow=*/false,
2609                                         SS,
2610                                         /*TemplateKWLoc=*/SourceLocation(),
2611                                         /*FirstQualifierInScope=*/0,
2612                                         MemberLookup,
2613                                         /*TemplateArgs=*/0);
2614    if (CtorArg.isInvalid())
2615      return true;
2616
2617    // C++11 [class.copy]p15:
2618    //   - if a member m has rvalue reference type T&&, it is direct-initialized
2619    //     with static_cast<T&&>(x.m);
2620    if (RefersToRValueRef(CtorArg.get())) {
2621      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2622    }
2623
2624    // When the field we are copying is an array, create index variables for
2625    // each dimension of the array. We use these index variables to subscript
2626    // the source array, and other clients (e.g., CodeGen) will perform the
2627    // necessary iteration with these index variables.
2628    SmallVector<VarDecl *, 4> IndexVariables;
2629    QualType BaseType = Field->getType();
2630    QualType SizeType = SemaRef.Context.getSizeType();
2631    bool InitializingArray = false;
2632    while (const ConstantArrayType *Array
2633                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2634      InitializingArray = true;
2635      // Create the iteration variable for this array index.
2636      IdentifierInfo *IterationVarName = 0;
2637      {
2638        SmallString<8> Str;
2639        llvm::raw_svector_ostream OS(Str);
2640        OS << "__i" << IndexVariables.size();
2641        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2642      }
2643      VarDecl *IterationVar
2644        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2645                          IterationVarName, SizeType,
2646                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2647                          SC_None, SC_None);
2648      IndexVariables.push_back(IterationVar);
2649
2650      // Create a reference to the iteration variable.
2651      ExprResult IterationVarRef
2652        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
2653      assert(!IterationVarRef.isInvalid() &&
2654             "Reference to invented variable cannot fail!");
2655      IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2656      assert(!IterationVarRef.isInvalid() &&
2657             "Conversion of invented variable cannot fail!");
2658
2659      // Subscript the array with this iteration variable.
2660      CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
2661                                                        IterationVarRef.take(),
2662                                                        Loc);
2663      if (CtorArg.isInvalid())
2664        return true;
2665
2666      BaseType = Array->getElementType();
2667    }
2668
2669    // The array subscript expression is an lvalue, which is wrong for moving.
2670    if (Moving && InitializingArray)
2671      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2672
2673    // Construct the entity that we will be initializing. For an array, this
2674    // will be first element in the array, which may require several levels
2675    // of array-subscript entities.
2676    SmallVector<InitializedEntity, 4> Entities;
2677    Entities.reserve(1 + IndexVariables.size());
2678    if (Indirect)
2679      Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2680    else
2681      Entities.push_back(InitializedEntity::InitializeMember(Field));
2682    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2683      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2684                                                              0,
2685                                                              Entities.back()));
2686
2687    // Direct-initialize to use the copy constructor.
2688    InitializationKind InitKind =
2689      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2690
2691    Expr *CtorArgE = CtorArg.takeAs<Expr>();
2692    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2693                                   &CtorArgE, 1);
2694
2695    ExprResult MemberInit
2696      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2697                        MultiExprArg(&CtorArgE, 1));
2698    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2699    if (MemberInit.isInvalid())
2700      return true;
2701
2702    if (Indirect) {
2703      assert(IndexVariables.size() == 0 &&
2704             "Indirect field improperly initialized");
2705      CXXMemberInit
2706        = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2707                                                   Loc, Loc,
2708                                                   MemberInit.takeAs<Expr>(),
2709                                                   Loc);
2710    } else
2711      CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2712                                                 Loc, MemberInit.takeAs<Expr>(),
2713                                                 Loc,
2714                                                 IndexVariables.data(),
2715                                                 IndexVariables.size());
2716    return false;
2717  }
2718
2719  assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2720
2721  QualType FieldBaseElementType =
2722    SemaRef.Context.getBaseElementType(Field->getType());
2723
2724  if (FieldBaseElementType->isRecordType()) {
2725    InitializedEntity InitEntity
2726      = Indirect? InitializedEntity::InitializeMember(Indirect)
2727                : InitializedEntity::InitializeMember(Field);
2728    InitializationKind InitKind =
2729      InitializationKind::CreateDefault(Loc);
2730
2731    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2732    ExprResult MemberInit =
2733      InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2734
2735    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2736    if (MemberInit.isInvalid())
2737      return true;
2738
2739    if (Indirect)
2740      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2741                                                               Indirect, Loc,
2742                                                               Loc,
2743                                                               MemberInit.get(),
2744                                                               Loc);
2745    else
2746      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2747                                                               Field, Loc, Loc,
2748                                                               MemberInit.get(),
2749                                                               Loc);
2750    return false;
2751  }
2752
2753  if (!Field->getParent()->isUnion()) {
2754    if (FieldBaseElementType->isReferenceType()) {
2755      SemaRef.Diag(Constructor->getLocation(),
2756                   diag::err_uninitialized_member_in_ctor)
2757      << (int)Constructor->isImplicit()
2758      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2759      << 0 << Field->getDeclName();
2760      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2761      return true;
2762    }
2763
2764    if (FieldBaseElementType.isConstQualified()) {
2765      SemaRef.Diag(Constructor->getLocation(),
2766                   diag::err_uninitialized_member_in_ctor)
2767      << (int)Constructor->isImplicit()
2768      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2769      << 1 << Field->getDeclName();
2770      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2771      return true;
2772    }
2773  }
2774
2775  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2776      FieldBaseElementType->isObjCRetainableType() &&
2777      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2778      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2779    // ARC:
2780    //   Default-initialize Objective-C pointers to NULL.
2781    CXXMemberInit
2782      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2783                                                 Loc, Loc,
2784                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2785                                                 Loc);
2786    return false;
2787  }
2788
2789  // Nothing to initialize.
2790  CXXMemberInit = 0;
2791  return false;
2792}
2793
2794namespace {
2795struct BaseAndFieldInfo {
2796  Sema &S;
2797  CXXConstructorDecl *Ctor;
2798  bool AnyErrorsInInits;
2799  ImplicitInitializerKind IIK;
2800  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2801  SmallVector<CXXCtorInitializer*, 8> AllToInit;
2802
2803  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2804    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2805    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2806    if (Generated && Ctor->isCopyConstructor())
2807      IIK = IIK_Copy;
2808    else if (Generated && Ctor->isMoveConstructor())
2809      IIK = IIK_Move;
2810    else
2811      IIK = IIK_Default;
2812  }
2813
2814  bool isImplicitCopyOrMove() const {
2815    switch (IIK) {
2816    case IIK_Copy:
2817    case IIK_Move:
2818      return true;
2819
2820    case IIK_Default:
2821      return false;
2822    }
2823
2824    llvm_unreachable("Invalid ImplicitInitializerKind!");
2825  }
2826
2827  bool addFieldInitializer(CXXCtorInitializer *Init) {
2828    AllToInit.push_back(Init);
2829
2830    // Check whether this initializer makes the field "used".
2831    if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2832      S.UnusedPrivateFields.remove(Init->getAnyMember());
2833
2834    return false;
2835  }
2836};
2837}
2838
2839/// \brief Determine whether the given indirect field declaration is somewhere
2840/// within an anonymous union.
2841static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2842  for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2843                                      CEnd = F->chain_end();
2844       C != CEnd; ++C)
2845    if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2846      if (Record->isUnion())
2847        return true;
2848
2849  return false;
2850}
2851
2852/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2853/// array type.
2854static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2855  if (T->isIncompleteArrayType())
2856    return true;
2857
2858  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2859    if (!ArrayT->getSize())
2860      return true;
2861
2862    T = ArrayT->getElementType();
2863  }
2864
2865  return false;
2866}
2867
2868static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
2869                                    FieldDecl *Field,
2870                                    IndirectFieldDecl *Indirect = 0) {
2871
2872  // Overwhelmingly common case: we have a direct initializer for this field.
2873  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
2874    return Info.addFieldInitializer(Init);
2875
2876  // C++11 [class.base.init]p8: if the entity is a non-static data member that
2877  // has a brace-or-equal-initializer, the entity is initialized as specified
2878  // in [dcl.init].
2879  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
2880    CXXCtorInitializer *Init;
2881    if (Indirect)
2882      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2883                                                      SourceLocation(),
2884                                                      SourceLocation(), 0,
2885                                                      SourceLocation());
2886    else
2887      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2888                                                      SourceLocation(),
2889                                                      SourceLocation(), 0,
2890                                                      SourceLocation());
2891    return Info.addFieldInitializer(Init);
2892  }
2893
2894  // Don't build an implicit initializer for union members if none was
2895  // explicitly specified.
2896  if (Field->getParent()->isUnion() ||
2897      (Indirect && isWithinAnonymousUnion(Indirect)))
2898    return false;
2899
2900  // Don't initialize incomplete or zero-length arrays.
2901  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2902    return false;
2903
2904  // Don't try to build an implicit initializer if there were semantic
2905  // errors in any of the initializers (and therefore we might be
2906  // missing some that the user actually wrote).
2907  if (Info.AnyErrorsInInits || Field->isInvalidDecl())
2908    return false;
2909
2910  CXXCtorInitializer *Init = 0;
2911  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2912                                     Indirect, Init))
2913    return true;
2914
2915  if (!Init)
2916    return false;
2917
2918  return Info.addFieldInitializer(Init);
2919}
2920
2921bool
2922Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2923                               CXXCtorInitializer *Initializer) {
2924  assert(Initializer->isDelegatingInitializer());
2925  Constructor->setNumCtorInitializers(1);
2926  CXXCtorInitializer **initializer =
2927    new (Context) CXXCtorInitializer*[1];
2928  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2929  Constructor->setCtorInitializers(initializer);
2930
2931  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2932    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
2933    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2934  }
2935
2936  DelegatingCtorDecls.push_back(Constructor);
2937
2938  return false;
2939}
2940
2941bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2942                               CXXCtorInitializer **Initializers,
2943                               unsigned NumInitializers,
2944                               bool AnyErrors) {
2945  if (Constructor->isDependentContext()) {
2946    // Just store the initializers as written, they will be checked during
2947    // instantiation.
2948    if (NumInitializers > 0) {
2949      Constructor->setNumCtorInitializers(NumInitializers);
2950      CXXCtorInitializer **baseOrMemberInitializers =
2951        new (Context) CXXCtorInitializer*[NumInitializers];
2952      memcpy(baseOrMemberInitializers, Initializers,
2953             NumInitializers * sizeof(CXXCtorInitializer*));
2954      Constructor->setCtorInitializers(baseOrMemberInitializers);
2955    }
2956
2957    return false;
2958  }
2959
2960  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
2961
2962  // We need to build the initializer AST according to order of construction
2963  // and not what user specified in the Initializers list.
2964  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
2965  if (!ClassDecl)
2966    return true;
2967
2968  bool HadError = false;
2969
2970  for (unsigned i = 0; i < NumInitializers; i++) {
2971    CXXCtorInitializer *Member = Initializers[i];
2972
2973    if (Member->isBaseInitializer())
2974      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
2975    else
2976      Info.AllBaseFields[Member->getAnyMember()] = Member;
2977  }
2978
2979  // Keep track of the direct virtual bases.
2980  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2981  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2982       E = ClassDecl->bases_end(); I != E; ++I) {
2983    if (I->isVirtual())
2984      DirectVBases.insert(I);
2985  }
2986
2987  // Push virtual bases before others.
2988  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2989       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2990
2991    if (CXXCtorInitializer *Value
2992        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2993      Info.AllToInit.push_back(Value);
2994    } else if (!AnyErrors) {
2995      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
2996      CXXCtorInitializer *CXXBaseInit;
2997      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2998                                       VBase, IsInheritedVirtualBase,
2999                                       CXXBaseInit)) {
3000        HadError = true;
3001        continue;
3002      }
3003
3004      Info.AllToInit.push_back(CXXBaseInit);
3005    }
3006  }
3007
3008  // Non-virtual bases.
3009  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3010       E = ClassDecl->bases_end(); Base != E; ++Base) {
3011    // Virtuals are in the virtual base list and already constructed.
3012    if (Base->isVirtual())
3013      continue;
3014
3015    if (CXXCtorInitializer *Value
3016          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3017      Info.AllToInit.push_back(Value);
3018    } else if (!AnyErrors) {
3019      CXXCtorInitializer *CXXBaseInit;
3020      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3021                                       Base, /*IsInheritedVirtualBase=*/false,
3022                                       CXXBaseInit)) {
3023        HadError = true;
3024        continue;
3025      }
3026
3027      Info.AllToInit.push_back(CXXBaseInit);
3028    }
3029  }
3030
3031  // Fields.
3032  for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3033                               MemEnd = ClassDecl->decls_end();
3034       Mem != MemEnd; ++Mem) {
3035    if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3036      // C++ [class.bit]p2:
3037      //   A declaration for a bit-field that omits the identifier declares an
3038      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3039      //   initialized.
3040      if (F->isUnnamedBitfield())
3041        continue;
3042
3043      // If we're not generating the implicit copy/move constructor, then we'll
3044      // handle anonymous struct/union fields based on their individual
3045      // indirect fields.
3046      if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3047        continue;
3048
3049      if (CollectFieldInitializer(*this, Info, F))
3050        HadError = true;
3051      continue;
3052    }
3053
3054    // Beyond this point, we only consider default initialization.
3055    if (Info.IIK != IIK_Default)
3056      continue;
3057
3058    if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3059      if (F->getType()->isIncompleteArrayType()) {
3060        assert(ClassDecl->hasFlexibleArrayMember() &&
3061               "Incomplete array type is not valid");
3062        continue;
3063      }
3064
3065      // Initialize each field of an anonymous struct individually.
3066      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3067        HadError = true;
3068
3069      continue;
3070    }
3071  }
3072
3073  NumInitializers = Info.AllToInit.size();
3074  if (NumInitializers > 0) {
3075    Constructor->setNumCtorInitializers(NumInitializers);
3076    CXXCtorInitializer **baseOrMemberInitializers =
3077      new (Context) CXXCtorInitializer*[NumInitializers];
3078    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3079           NumInitializers * sizeof(CXXCtorInitializer*));
3080    Constructor->setCtorInitializers(baseOrMemberInitializers);
3081
3082    // Constructors implicitly reference the base and member
3083    // destructors.
3084    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3085                                           Constructor->getParent());
3086  }
3087
3088  return HadError;
3089}
3090
3091static void *GetKeyForTopLevelField(FieldDecl *Field) {
3092  // For anonymous unions, use the class declaration as the key.
3093  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3094    if (RT->getDecl()->isAnonymousStructOrUnion())
3095      return static_cast<void *>(RT->getDecl());
3096  }
3097  return static_cast<void *>(Field);
3098}
3099
3100static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3101  return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3102}
3103
3104static void *GetKeyForMember(ASTContext &Context,
3105                             CXXCtorInitializer *Member) {
3106  if (!Member->isAnyMemberInitializer())
3107    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3108
3109  // For fields injected into the class via declaration of an anonymous union,
3110  // use its anonymous union class declaration as the unique key.
3111  FieldDecl *Field = Member->getAnyMember();
3112
3113  // If the field is a member of an anonymous struct or union, our key
3114  // is the anonymous record decl that's a direct child of the class.
3115  RecordDecl *RD = Field->getParent();
3116  if (RD->isAnonymousStructOrUnion()) {
3117    while (true) {
3118      RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3119      if (Parent->isAnonymousStructOrUnion())
3120        RD = Parent;
3121      else
3122        break;
3123    }
3124
3125    return static_cast<void *>(RD);
3126  }
3127
3128  return static_cast<void *>(Field);
3129}
3130
3131static void
3132DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
3133                                  const CXXConstructorDecl *Constructor,
3134                                  CXXCtorInitializer **Inits,
3135                                  unsigned NumInits) {
3136  if (Constructor->getDeclContext()->isDependentContext())
3137    return;
3138
3139  // Don't check initializers order unless the warning is enabled at the
3140  // location of at least one initializer.
3141  bool ShouldCheckOrder = false;
3142  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3143    CXXCtorInitializer *Init = Inits[InitIndex];
3144    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3145                                         Init->getSourceLocation())
3146          != DiagnosticsEngine::Ignored) {
3147      ShouldCheckOrder = true;
3148      break;
3149    }
3150  }
3151  if (!ShouldCheckOrder)
3152    return;
3153
3154  // Build the list of bases and members in the order that they'll
3155  // actually be initialized.  The explicit initializers should be in
3156  // this same order but may be missing things.
3157  SmallVector<const void*, 32> IdealInitKeys;
3158
3159  const CXXRecordDecl *ClassDecl = Constructor->getParent();
3160
3161  // 1. Virtual bases.
3162  for (CXXRecordDecl::base_class_const_iterator VBase =
3163       ClassDecl->vbases_begin(),
3164       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3165    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3166
3167  // 2. Non-virtual bases.
3168  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3169       E = ClassDecl->bases_end(); Base != E; ++Base) {
3170    if (Base->isVirtual())
3171      continue;
3172    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3173  }
3174
3175  // 3. Direct fields.
3176  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3177       E = ClassDecl->field_end(); Field != E; ++Field) {
3178    if (Field->isUnnamedBitfield())
3179      continue;
3180
3181    IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
3182  }
3183
3184  unsigned NumIdealInits = IdealInitKeys.size();
3185  unsigned IdealIndex = 0;
3186
3187  CXXCtorInitializer *PrevInit = 0;
3188  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3189    CXXCtorInitializer *Init = Inits[InitIndex];
3190    void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3191
3192    // Scan forward to try to find this initializer in the idealized
3193    // initializers list.
3194    for (; IdealIndex != NumIdealInits; ++IdealIndex)
3195      if (InitKey == IdealInitKeys[IdealIndex])
3196        break;
3197
3198    // If we didn't find this initializer, it must be because we
3199    // scanned past it on a previous iteration.  That can only
3200    // happen if we're out of order;  emit a warning.
3201    if (IdealIndex == NumIdealInits && PrevInit) {
3202      Sema::SemaDiagnosticBuilder D =
3203        SemaRef.Diag(PrevInit->getSourceLocation(),
3204                     diag::warn_initializer_out_of_order);
3205
3206      if (PrevInit->isAnyMemberInitializer())
3207        D << 0 << PrevInit->getAnyMember()->getDeclName();
3208      else
3209        D << 1 << PrevInit->getTypeSourceInfo()->getType();
3210
3211      if (Init->isAnyMemberInitializer())
3212        D << 0 << Init->getAnyMember()->getDeclName();
3213      else
3214        D << 1 << Init->getTypeSourceInfo()->getType();
3215
3216      // Move back to the initializer's location in the ideal list.
3217      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3218        if (InitKey == IdealInitKeys[IdealIndex])
3219          break;
3220
3221      assert(IdealIndex != NumIdealInits &&
3222             "initializer not found in initializer list");
3223    }
3224
3225    PrevInit = Init;
3226  }
3227}
3228
3229namespace {
3230bool CheckRedundantInit(Sema &S,
3231                        CXXCtorInitializer *Init,
3232                        CXXCtorInitializer *&PrevInit) {
3233  if (!PrevInit) {
3234    PrevInit = Init;
3235    return false;
3236  }
3237
3238  if (FieldDecl *Field = Init->getMember())
3239    S.Diag(Init->getSourceLocation(),
3240           diag::err_multiple_mem_initialization)
3241      << Field->getDeclName()
3242      << Init->getSourceRange();
3243  else {
3244    const Type *BaseClass = Init->getBaseClass();
3245    assert(BaseClass && "neither field nor base");
3246    S.Diag(Init->getSourceLocation(),
3247           diag::err_multiple_base_initialization)
3248      << QualType(BaseClass, 0)
3249      << Init->getSourceRange();
3250  }
3251  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3252    << 0 << PrevInit->getSourceRange();
3253
3254  return true;
3255}
3256
3257typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3258typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3259
3260bool CheckRedundantUnionInit(Sema &S,
3261                             CXXCtorInitializer *Init,
3262                             RedundantUnionMap &Unions) {
3263  FieldDecl *Field = Init->getAnyMember();
3264  RecordDecl *Parent = Field->getParent();
3265  NamedDecl *Child = Field;
3266
3267  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3268    if (Parent->isUnion()) {
3269      UnionEntry &En = Unions[Parent];
3270      if (En.first && En.first != Child) {
3271        S.Diag(Init->getSourceLocation(),
3272               diag::err_multiple_mem_union_initialization)
3273          << Field->getDeclName()
3274          << Init->getSourceRange();
3275        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3276          << 0 << En.second->getSourceRange();
3277        return true;
3278      }
3279      if (!En.first) {
3280        En.first = Child;
3281        En.second = Init;
3282      }
3283      if (!Parent->isAnonymousStructOrUnion())
3284        return false;
3285    }
3286
3287    Child = Parent;
3288    Parent = cast<RecordDecl>(Parent->getDeclContext());
3289  }
3290
3291  return false;
3292}
3293}
3294
3295/// ActOnMemInitializers - Handle the member initializers for a constructor.
3296void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3297                                SourceLocation ColonLoc,
3298                                CXXCtorInitializer **meminits,
3299                                unsigned NumMemInits,
3300                                bool AnyErrors) {
3301  if (!ConstructorDecl)
3302    return;
3303
3304  AdjustDeclIfTemplate(ConstructorDecl);
3305
3306  CXXConstructorDecl *Constructor
3307    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3308
3309  if (!Constructor) {
3310    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3311    return;
3312  }
3313
3314  CXXCtorInitializer **MemInits =
3315    reinterpret_cast<CXXCtorInitializer **>(meminits);
3316
3317  // Mapping for the duplicate initializers check.
3318  // For member initializers, this is keyed with a FieldDecl*.
3319  // For base initializers, this is keyed with a Type*.
3320  llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3321
3322  // Mapping for the inconsistent anonymous-union initializers check.
3323  RedundantUnionMap MemberUnions;
3324
3325  bool HadError = false;
3326  for (unsigned i = 0; i < NumMemInits; i++) {
3327    CXXCtorInitializer *Init = MemInits[i];
3328
3329    // Set the source order index.
3330    Init->setSourceOrder(i);
3331
3332    if (Init->isAnyMemberInitializer()) {
3333      FieldDecl *Field = Init->getAnyMember();
3334      if (CheckRedundantInit(*this, Init, Members[Field]) ||
3335          CheckRedundantUnionInit(*this, Init, MemberUnions))
3336        HadError = true;
3337    } else if (Init->isBaseInitializer()) {
3338      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3339      if (CheckRedundantInit(*this, Init, Members[Key]))
3340        HadError = true;
3341    } else {
3342      assert(Init->isDelegatingInitializer());
3343      // This must be the only initializer
3344      if (i != 0 || NumMemInits > 1) {
3345        Diag(MemInits[0]->getSourceLocation(),
3346             diag::err_delegating_initializer_alone)
3347          << MemInits[0]->getSourceRange();
3348        HadError = true;
3349        // We will treat this as being the only initializer.
3350      }
3351      SetDelegatingInitializer(Constructor, MemInits[i]);
3352      // Return immediately as the initializer is set.
3353      return;
3354    }
3355  }
3356
3357  if (HadError)
3358    return;
3359
3360  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
3361
3362  SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
3363}
3364
3365void
3366Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3367                                             CXXRecordDecl *ClassDecl) {
3368  // Ignore dependent contexts. Also ignore unions, since their members never
3369  // have destructors implicitly called.
3370  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3371    return;
3372
3373  // FIXME: all the access-control diagnostics are positioned on the
3374  // field/base declaration.  That's probably good; that said, the
3375  // user might reasonably want to know why the destructor is being
3376  // emitted, and we currently don't say.
3377
3378  // Non-static data members.
3379  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3380       E = ClassDecl->field_end(); I != E; ++I) {
3381    FieldDecl *Field = *I;
3382    if (Field->isInvalidDecl())
3383      continue;
3384
3385    // Don't destroy incomplete or zero-length arrays.
3386    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3387      continue;
3388
3389    QualType FieldType = Context.getBaseElementType(Field->getType());
3390
3391    const RecordType* RT = FieldType->getAs<RecordType>();
3392    if (!RT)
3393      continue;
3394
3395    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3396    if (FieldClassDecl->isInvalidDecl())
3397      continue;
3398    if (FieldClassDecl->hasIrrelevantDestructor())
3399      continue;
3400    // The destructor for an implicit anonymous union member is never invoked.
3401    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3402      continue;
3403
3404    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3405    assert(Dtor && "No dtor found for FieldClassDecl!");
3406    CheckDestructorAccess(Field->getLocation(), Dtor,
3407                          PDiag(diag::err_access_dtor_field)
3408                            << Field->getDeclName()
3409                            << FieldType);
3410
3411    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3412    DiagnoseUseOfDecl(Dtor, Location);
3413  }
3414
3415  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3416
3417  // Bases.
3418  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3419       E = ClassDecl->bases_end(); Base != E; ++Base) {
3420    // Bases are always records in a well-formed non-dependent class.
3421    const RecordType *RT = Base->getType()->getAs<RecordType>();
3422
3423    // Remember direct virtual bases.
3424    if (Base->isVirtual())
3425      DirectVirtualBases.insert(RT);
3426
3427    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3428    // If our base class is invalid, we probably can't get its dtor anyway.
3429    if (BaseClassDecl->isInvalidDecl())
3430      continue;
3431    if (BaseClassDecl->hasIrrelevantDestructor())
3432      continue;
3433
3434    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3435    assert(Dtor && "No dtor found for BaseClassDecl!");
3436
3437    // FIXME: caret should be on the start of the class name
3438    CheckDestructorAccess(Base->getLocStart(), Dtor,
3439                          PDiag(diag::err_access_dtor_base)
3440                            << Base->getType()
3441                            << Base->getSourceRange(),
3442                          Context.getTypeDeclType(ClassDecl));
3443
3444    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3445    DiagnoseUseOfDecl(Dtor, Location);
3446  }
3447
3448  // Virtual bases.
3449  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3450       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3451
3452    // Bases are always records in a well-formed non-dependent class.
3453    const RecordType *RT = VBase->getType()->castAs<RecordType>();
3454
3455    // Ignore direct virtual bases.
3456    if (DirectVirtualBases.count(RT))
3457      continue;
3458
3459    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3460    // If our base class is invalid, we probably can't get its dtor anyway.
3461    if (BaseClassDecl->isInvalidDecl())
3462      continue;
3463    if (BaseClassDecl->hasIrrelevantDestructor())
3464      continue;
3465
3466    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3467    assert(Dtor && "No dtor found for BaseClassDecl!");
3468    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3469                          PDiag(diag::err_access_dtor_vbase)
3470                            << VBase->getType(),
3471                          Context.getTypeDeclType(ClassDecl));
3472
3473    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3474    DiagnoseUseOfDecl(Dtor, Location);
3475  }
3476}
3477
3478void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3479  if (!CDtorDecl)
3480    return;
3481
3482  if (CXXConstructorDecl *Constructor
3483      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3484    SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
3485}
3486
3487bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3488                                  unsigned DiagID, AbstractDiagSelID SelID) {
3489  class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3490    unsigned DiagID;
3491    AbstractDiagSelID SelID;
3492
3493  public:
3494    NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3495      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3496
3497    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3498      if (Suppressed) return;
3499      if (SelID == -1)
3500        S.Diag(Loc, DiagID) << T;
3501      else
3502        S.Diag(Loc, DiagID) << SelID << T;
3503    }
3504  } Diagnoser(DiagID, SelID);
3505
3506  return RequireNonAbstractType(Loc, T, Diagnoser);
3507}
3508
3509bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3510                                  TypeDiagnoser &Diagnoser) {
3511  if (!getLangOpts().CPlusPlus)
3512    return false;
3513
3514  if (const ArrayType *AT = Context.getAsArrayType(T))
3515    return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3516
3517  if (const PointerType *PT = T->getAs<PointerType>()) {
3518    // Find the innermost pointer type.
3519    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3520      PT = T;
3521
3522    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3523      return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3524  }
3525
3526  const RecordType *RT = T->getAs<RecordType>();
3527  if (!RT)
3528    return false;
3529
3530  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3531
3532  // We can't answer whether something is abstract until it has a
3533  // definition.  If it's currently being defined, we'll walk back
3534  // over all the declarations when we have a full definition.
3535  const CXXRecordDecl *Def = RD->getDefinition();
3536  if (!Def || Def->isBeingDefined())
3537    return false;
3538
3539  if (!RD->isAbstract())
3540    return false;
3541
3542  Diagnoser.diagnose(*this, Loc, T);
3543  DiagnoseAbstractType(RD);
3544
3545  return true;
3546}
3547
3548void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3549  // Check if we've already emitted the list of pure virtual functions
3550  // for this class.
3551  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3552    return;
3553
3554  CXXFinalOverriderMap FinalOverriders;
3555  RD->getFinalOverriders(FinalOverriders);
3556
3557  // Keep a set of seen pure methods so we won't diagnose the same method
3558  // more than once.
3559  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3560
3561  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3562                                   MEnd = FinalOverriders.end();
3563       M != MEnd;
3564       ++M) {
3565    for (OverridingMethods::iterator SO = M->second.begin(),
3566                                  SOEnd = M->second.end();
3567         SO != SOEnd; ++SO) {
3568      // C++ [class.abstract]p4:
3569      //   A class is abstract if it contains or inherits at least one
3570      //   pure virtual function for which the final overrider is pure
3571      //   virtual.
3572
3573      //
3574      if (SO->second.size() != 1)
3575        continue;
3576
3577      if (!SO->second.front().Method->isPure())
3578        continue;
3579
3580      if (!SeenPureMethods.insert(SO->second.front().Method))
3581        continue;
3582
3583      Diag(SO->second.front().Method->getLocation(),
3584           diag::note_pure_virtual_function)
3585        << SO->second.front().Method->getDeclName() << RD->getDeclName();
3586    }
3587  }
3588
3589  if (!PureVirtualClassDiagSet)
3590    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3591  PureVirtualClassDiagSet->insert(RD);
3592}
3593
3594namespace {
3595struct AbstractUsageInfo {
3596  Sema &S;
3597  CXXRecordDecl *Record;
3598  CanQualType AbstractType;
3599  bool Invalid;
3600
3601  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3602    : S(S), Record(Record),
3603      AbstractType(S.Context.getCanonicalType(
3604                   S.Context.getTypeDeclType(Record))),
3605      Invalid(false) {}
3606
3607  void DiagnoseAbstractType() {
3608    if (Invalid) return;
3609    S.DiagnoseAbstractType(Record);
3610    Invalid = true;
3611  }
3612
3613  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3614};
3615
3616struct CheckAbstractUsage {
3617  AbstractUsageInfo &Info;
3618  const NamedDecl *Ctx;
3619
3620  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3621    : Info(Info), Ctx(Ctx) {}
3622
3623  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3624    switch (TL.getTypeLocClass()) {
3625#define ABSTRACT_TYPELOC(CLASS, PARENT)
3626#define TYPELOC(CLASS, PARENT) \
3627    case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3628#include "clang/AST/TypeLocNodes.def"
3629    }
3630  }
3631
3632  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3633    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3634    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3635      if (!TL.getArg(I))
3636        continue;
3637
3638      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3639      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3640    }
3641  }
3642
3643  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3644    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3645  }
3646
3647  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3648    // Visit the type parameters from a permissive context.
3649    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3650      TemplateArgumentLoc TAL = TL.getArgLoc(I);
3651      if (TAL.getArgument().getKind() == TemplateArgument::Type)
3652        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3653          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3654      // TODO: other template argument types?
3655    }
3656  }
3657
3658  // Visit pointee types from a permissive context.
3659#define CheckPolymorphic(Type) \
3660  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3661    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3662  }
3663  CheckPolymorphic(PointerTypeLoc)
3664  CheckPolymorphic(ReferenceTypeLoc)
3665  CheckPolymorphic(MemberPointerTypeLoc)
3666  CheckPolymorphic(BlockPointerTypeLoc)
3667  CheckPolymorphic(AtomicTypeLoc)
3668
3669  /// Handle all the types we haven't given a more specific
3670  /// implementation for above.
3671  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3672    // Every other kind of type that we haven't called out already
3673    // that has an inner type is either (1) sugar or (2) contains that
3674    // inner type in some way as a subobject.
3675    if (TypeLoc Next = TL.getNextTypeLoc())
3676      return Visit(Next, Sel);
3677
3678    // If there's no inner type and we're in a permissive context,
3679    // don't diagnose.
3680    if (Sel == Sema::AbstractNone) return;
3681
3682    // Check whether the type matches the abstract type.
3683    QualType T = TL.getType();
3684    if (T->isArrayType()) {
3685      Sel = Sema::AbstractArrayType;
3686      T = Info.S.Context.getBaseElementType(T);
3687    }
3688    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3689    if (CT != Info.AbstractType) return;
3690
3691    // It matched; do some magic.
3692    if (Sel == Sema::AbstractArrayType) {
3693      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3694        << T << TL.getSourceRange();
3695    } else {
3696      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3697        << Sel << T << TL.getSourceRange();
3698    }
3699    Info.DiagnoseAbstractType();
3700  }
3701};
3702
3703void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3704                                  Sema::AbstractDiagSelID Sel) {
3705  CheckAbstractUsage(*this, D).Visit(TL, Sel);
3706}
3707
3708}
3709
3710/// Check for invalid uses of an abstract type in a method declaration.
3711static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3712                                    CXXMethodDecl *MD) {
3713  // No need to do the check on definitions, which require that
3714  // the return/param types be complete.
3715  if (MD->doesThisDeclarationHaveABody())
3716    return;
3717
3718  // For safety's sake, just ignore it if we don't have type source
3719  // information.  This should never happen for non-implicit methods,
3720  // but...
3721  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3722    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3723}
3724
3725/// Check for invalid uses of an abstract type within a class definition.
3726static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3727                                    CXXRecordDecl *RD) {
3728  for (CXXRecordDecl::decl_iterator
3729         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3730    Decl *D = *I;
3731    if (D->isImplicit()) continue;
3732
3733    // Methods and method templates.
3734    if (isa<CXXMethodDecl>(D)) {
3735      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3736    } else if (isa<FunctionTemplateDecl>(D)) {
3737      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3738      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3739
3740    // Fields and static variables.
3741    } else if (isa<FieldDecl>(D)) {
3742      FieldDecl *FD = cast<FieldDecl>(D);
3743      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3744        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3745    } else if (isa<VarDecl>(D)) {
3746      VarDecl *VD = cast<VarDecl>(D);
3747      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3748        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3749
3750    // Nested classes and class templates.
3751    } else if (isa<CXXRecordDecl>(D)) {
3752      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3753    } else if (isa<ClassTemplateDecl>(D)) {
3754      CheckAbstractClassUsage(Info,
3755                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3756    }
3757  }
3758}
3759
3760/// \brief Perform semantic checks on a class definition that has been
3761/// completing, introducing implicitly-declared members, checking for
3762/// abstract types, etc.
3763void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3764  if (!Record)
3765    return;
3766
3767  if (Record->isAbstract() && !Record->isInvalidDecl()) {
3768    AbstractUsageInfo Info(*this, Record);
3769    CheckAbstractClassUsage(Info, Record);
3770  }
3771
3772  // If this is not an aggregate type and has no user-declared constructor,
3773  // complain about any non-static data members of reference or const scalar
3774  // type, since they will never get initializers.
3775  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3776      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3777      !Record->isLambda()) {
3778    bool Complained = false;
3779    for (RecordDecl::field_iterator F = Record->field_begin(),
3780                                 FEnd = Record->field_end();
3781         F != FEnd; ++F) {
3782      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
3783        continue;
3784
3785      if (F->getType()->isReferenceType() ||
3786          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3787        if (!Complained) {
3788          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3789            << Record->getTagKind() << Record;
3790          Complained = true;
3791        }
3792
3793        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3794          << F->getType()->isReferenceType()
3795          << F->getDeclName();
3796      }
3797    }
3798  }
3799
3800  if (Record->isDynamicClass() && !Record->isDependentType())
3801    DynamicClasses.push_back(Record);
3802
3803  if (Record->getIdentifier()) {
3804    // C++ [class.mem]p13:
3805    //   If T is the name of a class, then each of the following shall have a
3806    //   name different from T:
3807    //     - every member of every anonymous union that is a member of class T.
3808    //
3809    // C++ [class.mem]p14:
3810    //   In addition, if class T has a user-declared constructor (12.1), every
3811    //   non-static data member of class T shall have a name different from T.
3812    for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3813         R.first != R.second; ++R.first) {
3814      NamedDecl *D = *R.first;
3815      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3816          isa<IndirectFieldDecl>(D)) {
3817        Diag(D->getLocation(), diag::err_member_name_of_class)
3818          << D->getDeclName();
3819        break;
3820      }
3821    }
3822  }
3823
3824  // Warn if the class has virtual methods but non-virtual public destructor.
3825  if (Record->isPolymorphic() && !Record->isDependentType()) {
3826    CXXDestructorDecl *dtor = Record->getDestructor();
3827    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3828      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3829           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3830  }
3831
3832  // See if a method overloads virtual methods in a base
3833  /// class without overriding any.
3834  if (!Record->isDependentType()) {
3835    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3836                                     MEnd = Record->method_end();
3837         M != MEnd; ++M) {
3838      if (!M->isStatic())
3839        DiagnoseHiddenVirtualMethods(Record, *M);
3840    }
3841  }
3842
3843  // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3844  // function that is not a constructor declares that member function to be
3845  // const. [...] The class of which that function is a member shall be
3846  // a literal type.
3847  //
3848  // If the class has virtual bases, any constexpr members will already have
3849  // been diagnosed by the checks performed on the member declaration, so
3850  // suppress this (less useful) diagnostic.
3851  if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3852      !Record->isLiteral() && !Record->getNumVBases()) {
3853    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3854                                     MEnd = Record->method_end();
3855         M != MEnd; ++M) {
3856      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
3857        switch (Record->getTemplateSpecializationKind()) {
3858        case TSK_ImplicitInstantiation:
3859        case TSK_ExplicitInstantiationDeclaration:
3860        case TSK_ExplicitInstantiationDefinition:
3861          // If a template instantiates to a non-literal type, but its members
3862          // instantiate to constexpr functions, the template is technically
3863          // ill-formed, but we allow it for sanity.
3864          continue;
3865
3866        case TSK_Undeclared:
3867        case TSK_ExplicitSpecialization:
3868          RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
3869                             diag::err_constexpr_method_non_literal);
3870          break;
3871        }
3872
3873        // Only produce one error per class.
3874        break;
3875      }
3876    }
3877  }
3878
3879  // Declare inherited constructors. We do this eagerly here because:
3880  // - The standard requires an eager diagnostic for conflicting inherited
3881  //   constructors from different classes.
3882  // - The lazy declaration of the other implicit constructors is so as to not
3883  //   waste space and performance on classes that are not meant to be
3884  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
3885  //   have inherited constructors.
3886  DeclareInheritedConstructors(Record);
3887}
3888
3889void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3890  for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3891                                      ME = Record->method_end();
3892       MI != ME; ++MI)
3893    if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
3894      CheckExplicitlyDefaultedSpecialMember(*MI);
3895}
3896
3897/// Is the special member function which would be selected to perform the
3898/// specified operation on the specified class type a constexpr constructor?
3899static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3900                                     Sema::CXXSpecialMember CSM,
3901                                     bool ConstArg) {
3902  Sema::SpecialMemberOverloadResult *SMOR =
3903      S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
3904                            false, false, false, false);
3905  if (!SMOR || !SMOR->getMethod())
3906    // A constructor we wouldn't select can't be "involved in initializing"
3907    // anything.
3908    return true;
3909  return SMOR->getMethod()->isConstexpr();
3910}
3911
3912/// Determine whether the specified special member function would be constexpr
3913/// if it were implicitly defined.
3914static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3915                                              Sema::CXXSpecialMember CSM,
3916                                              bool ConstArg) {
3917  if (!S.getLangOpts().CPlusPlus0x)
3918    return false;
3919
3920  // C++11 [dcl.constexpr]p4:
3921  // In the definition of a constexpr constructor [...]
3922  switch (CSM) {
3923  case Sema::CXXDefaultConstructor:
3924    // Since default constructor lookup is essentially trivial (and cannot
3925    // involve, for instance, template instantiation), we compute whether a
3926    // defaulted default constructor is constexpr directly within CXXRecordDecl.
3927    //
3928    // This is important for performance; we need to know whether the default
3929    // constructor is constexpr to determine whether the type is a literal type.
3930    return ClassDecl->defaultedDefaultConstructorIsConstexpr();
3931
3932  case Sema::CXXCopyConstructor:
3933  case Sema::CXXMoveConstructor:
3934    // For copy or move constructors, we need to perform overload resolution.
3935    break;
3936
3937  case Sema::CXXCopyAssignment:
3938  case Sema::CXXMoveAssignment:
3939  case Sema::CXXDestructor:
3940  case Sema::CXXInvalid:
3941    return false;
3942  }
3943
3944  //   -- if the class is a non-empty union, or for each non-empty anonymous
3945  //      union member of a non-union class, exactly one non-static data member
3946  //      shall be initialized; [DR1359]
3947  //
3948  // If we squint, this is guaranteed, since exactly one non-static data member
3949  // will be initialized (if the constructor isn't deleted), we just don't know
3950  // which one.
3951  if (ClassDecl->isUnion())
3952    return true;
3953
3954  //   -- the class shall not have any virtual base classes;
3955  if (ClassDecl->getNumVBases())
3956    return false;
3957
3958  //   -- every constructor involved in initializing [...] base class
3959  //      sub-objects shall be a constexpr constructor;
3960  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
3961                                       BEnd = ClassDecl->bases_end();
3962       B != BEnd; ++B) {
3963    const RecordType *BaseType = B->getType()->getAs<RecordType>();
3964    if (!BaseType) continue;
3965
3966    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
3967    if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
3968      return false;
3969  }
3970
3971  //   -- every constructor involved in initializing non-static data members
3972  //      [...] shall be a constexpr constructor;
3973  //   -- every non-static data member and base class sub-object shall be
3974  //      initialized
3975  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
3976                               FEnd = ClassDecl->field_end();
3977       F != FEnd; ++F) {
3978    if (F->isInvalidDecl())
3979      continue;
3980    if (const RecordType *RecordTy =
3981            S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
3982      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
3983      if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
3984        return false;
3985    }
3986  }
3987
3988  // All OK, it's constexpr!
3989  return true;
3990}
3991
3992static Sema::ImplicitExceptionSpecification
3993computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
3994  switch (S.getSpecialMember(MD)) {
3995  case Sema::CXXDefaultConstructor:
3996    return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
3997  case Sema::CXXCopyConstructor:
3998    return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
3999  case Sema::CXXCopyAssignment:
4000    return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4001  case Sema::CXXMoveConstructor:
4002    return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4003  case Sema::CXXMoveAssignment:
4004    return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4005  case Sema::CXXDestructor:
4006    return S.ComputeDefaultedDtorExceptionSpec(MD);
4007  case Sema::CXXInvalid:
4008    break;
4009  }
4010  llvm_unreachable("only special members have implicit exception specs");
4011}
4012
4013static void
4014updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4015                    const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4016  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4017  ExceptSpec.getEPI(EPI);
4018  const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4019    S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4020                              FPT->getNumArgs(), EPI));
4021  FD->setType(QualType(NewFPT, 0));
4022}
4023
4024void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4025  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4026  if (FPT->getExceptionSpecType() != EST_Unevaluated)
4027    return;
4028
4029  // Evaluate the exception specification.
4030  ImplicitExceptionSpecification ExceptSpec =
4031      computeImplicitExceptionSpec(*this, Loc, MD);
4032
4033  // Update the type of the special member to use it.
4034  updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4035
4036  // A user-provided destructor can be defined outside the class. When that
4037  // happens, be sure to update the exception specification on both
4038  // declarations.
4039  const FunctionProtoType *CanonicalFPT =
4040    MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4041  if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4042    updateExceptionSpec(*this, MD->getCanonicalDecl(),
4043                        CanonicalFPT, ExceptSpec);
4044}
4045
4046static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4047static bool isImplicitCopyAssignmentArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4048
4049void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4050  CXXRecordDecl *RD = MD->getParent();
4051  CXXSpecialMember CSM = getSpecialMember(MD);
4052
4053  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4054         "not an explicitly-defaulted special member");
4055
4056  // Whether this was the first-declared instance of the constructor.
4057  // This affects whether we implicitly add an exception spec and constexpr.
4058  bool First = MD == MD->getCanonicalDecl();
4059
4060  bool HadError = false;
4061
4062  // C++11 [dcl.fct.def.default]p1:
4063  //   A function that is explicitly defaulted shall
4064  //     -- be a special member function (checked elsewhere),
4065  //     -- have the same type (except for ref-qualifiers, and except that a
4066  //        copy operation can take a non-const reference) as an implicit
4067  //        declaration, and
4068  //     -- not have default arguments.
4069  unsigned ExpectedParams = 1;
4070  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4071    ExpectedParams = 0;
4072  if (MD->getNumParams() != ExpectedParams) {
4073    // This also checks for default arguments: a copy or move constructor with a
4074    // default argument is classified as a default constructor, and assignment
4075    // operations and destructors can't have default arguments.
4076    Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4077      << CSM << MD->getSourceRange();
4078    HadError = true;
4079  }
4080
4081  const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4082
4083  // Compute argument constness, constexpr, and triviality.
4084  bool CanHaveConstParam = false;
4085  bool Trivial;
4086  switch (CSM) {
4087  case CXXDefaultConstructor:
4088    Trivial = RD->hasTrivialDefaultConstructor();
4089    break;
4090  case CXXCopyConstructor:
4091    CanHaveConstParam = isImplicitCopyCtorArgConst(*this, RD);
4092    Trivial = RD->hasTrivialCopyConstructor();
4093    break;
4094  case CXXCopyAssignment:
4095    CanHaveConstParam = isImplicitCopyAssignmentArgConst(*this, RD);
4096    Trivial = RD->hasTrivialCopyAssignment();
4097    break;
4098  case CXXMoveConstructor:
4099    Trivial = RD->hasTrivialMoveConstructor();
4100    break;
4101  case CXXMoveAssignment:
4102    Trivial = RD->hasTrivialMoveAssignment();
4103    break;
4104  case CXXDestructor:
4105    Trivial = RD->hasTrivialDestructor();
4106    break;
4107  case CXXInvalid:
4108    llvm_unreachable("non-special member explicitly defaulted!");
4109  }
4110
4111  QualType ReturnType = Context.VoidTy;
4112  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4113    // Check for return type matching.
4114    ReturnType = Type->getResultType();
4115    QualType ExpectedReturnType =
4116        Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4117    if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4118      Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4119        << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4120      HadError = true;
4121    }
4122
4123    // A defaulted special member cannot have cv-qualifiers.
4124    if (Type->getTypeQuals()) {
4125      Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4126        << (CSM == CXXMoveAssignment);
4127      HadError = true;
4128    }
4129  }
4130
4131  // Check for parameter type matching.
4132  QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4133  bool HasConstParam = false;
4134  if (ExpectedParams && ArgType->isReferenceType()) {
4135    // Argument must be reference to possibly-const T.
4136    QualType ReferentType = ArgType->getPointeeType();
4137    HasConstParam = ReferentType.isConstQualified();
4138
4139    if (ReferentType.isVolatileQualified()) {
4140      Diag(MD->getLocation(),
4141           diag::err_defaulted_special_member_volatile_param) << CSM;
4142      HadError = true;
4143    }
4144
4145    if (HasConstParam && !CanHaveConstParam) {
4146      if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4147        Diag(MD->getLocation(),
4148             diag::err_defaulted_special_member_copy_const_param)
4149          << (CSM == CXXCopyAssignment);
4150        // FIXME: Explain why this special member can't be const.
4151      } else {
4152        Diag(MD->getLocation(),
4153             diag::err_defaulted_special_member_move_const_param)
4154          << (CSM == CXXMoveAssignment);
4155      }
4156      HadError = true;
4157    }
4158
4159    // If a function is explicitly defaulted on its first declaration, it shall
4160    // have the same parameter type as if it had been implicitly declared.
4161    // (Presumably this is to prevent it from being trivial?)
4162    if (!HasConstParam && CanHaveConstParam && First)
4163      Diag(MD->getLocation(),
4164           diag::err_defaulted_special_member_copy_non_const_param)
4165        << (CSM == CXXCopyAssignment);
4166  } else if (ExpectedParams) {
4167    // A copy assignment operator can take its argument by value, but a
4168    // defaulted one cannot.
4169    assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4170    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4171    HadError = true;
4172  }
4173
4174  // Rebuild the type with the implicit exception specification added, if we
4175  // are going to need it.
4176  const FunctionProtoType *ImplicitType = 0;
4177  if (First || Type->hasExceptionSpec()) {
4178    FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4179    computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4180    ImplicitType = cast<FunctionProtoType>(
4181      Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
4182  }
4183
4184  // C++11 [dcl.fct.def.default]p2:
4185  //   An explicitly-defaulted function may be declared constexpr only if it
4186  //   would have been implicitly declared as constexpr,
4187  // Do not apply this rule to members of class templates, since core issue 1358
4188  // makes such functions always instantiate to constexpr functions. For
4189  // non-constructors, this is checked elsewhere.
4190  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4191                                                     HasConstParam);
4192  if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4193      MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4194    Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4195    // FIXME: Explain why the constructor can't be constexpr.
4196    HadError = true;
4197  }
4198  //   and may have an explicit exception-specification only if it is compatible
4199  //   with the exception-specification on the implicit declaration.
4200  if (Type->hasExceptionSpec() &&
4201      CheckEquivalentExceptionSpec(
4202        PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
4203        PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
4204    HadError = true;
4205
4206  //   If a function is explicitly defaulted on its first declaration,
4207  if (First) {
4208    //  -- it is implicitly considered to be constexpr if the implicit
4209    //     definition would be,
4210    MD->setConstexpr(Constexpr);
4211
4212    //  -- it is implicitly considered to have the same exception-specification
4213    //     as if it had been implicitly declared,
4214    MD->setType(QualType(ImplicitType, 0));
4215
4216    // Such a function is also trivial if the implicitly-declared function
4217    // would have been.
4218    MD->setTrivial(Trivial);
4219  }
4220
4221  if (ShouldDeleteSpecialMember(MD, CSM)) {
4222    if (First) {
4223      MD->setDeletedAsWritten();
4224    } else {
4225      // C++11 [dcl.fct.def.default]p4:
4226      //   [For a] user-provided explicitly-defaulted function [...] if such a
4227      //   function is implicitly defined as deleted, the program is ill-formed.
4228      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4229      HadError = true;
4230    }
4231  }
4232
4233  if (HadError)
4234    MD->setInvalidDecl();
4235}
4236
4237namespace {
4238struct SpecialMemberDeletionInfo {
4239  Sema &S;
4240  CXXMethodDecl *MD;
4241  Sema::CXXSpecialMember CSM;
4242  bool Diagnose;
4243
4244  // Properties of the special member, computed for convenience.
4245  bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4246  SourceLocation Loc;
4247
4248  bool AllFieldsAreConst;
4249
4250  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4251                            Sema::CXXSpecialMember CSM, bool Diagnose)
4252    : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4253      IsConstructor(false), IsAssignment(false), IsMove(false),
4254      ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4255      AllFieldsAreConst(true) {
4256    switch (CSM) {
4257      case Sema::CXXDefaultConstructor:
4258      case Sema::CXXCopyConstructor:
4259        IsConstructor = true;
4260        break;
4261      case Sema::CXXMoveConstructor:
4262        IsConstructor = true;
4263        IsMove = true;
4264        break;
4265      case Sema::CXXCopyAssignment:
4266        IsAssignment = true;
4267        break;
4268      case Sema::CXXMoveAssignment:
4269        IsAssignment = true;
4270        IsMove = true;
4271        break;
4272      case Sema::CXXDestructor:
4273        break;
4274      case Sema::CXXInvalid:
4275        llvm_unreachable("invalid special member kind");
4276    }
4277
4278    if (MD->getNumParams()) {
4279      ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4280      VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4281    }
4282  }
4283
4284  bool inUnion() const { return MD->getParent()->isUnion(); }
4285
4286  /// Look up the corresponding special member in the given class.
4287  Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4288                                              unsigned Quals) {
4289    unsigned TQ = MD->getTypeQualifiers();
4290    // cv-qualifiers on class members don't affect default ctor / dtor calls.
4291    if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4292      Quals = 0;
4293    return S.LookupSpecialMember(Class, CSM,
4294                                 ConstArg || (Quals & Qualifiers::Const),
4295                                 VolatileArg || (Quals & Qualifiers::Volatile),
4296                                 MD->getRefQualifier() == RQ_RValue,
4297                                 TQ & Qualifiers::Const,
4298                                 TQ & Qualifiers::Volatile);
4299  }
4300
4301  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4302
4303  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4304  bool shouldDeleteForField(FieldDecl *FD);
4305  bool shouldDeleteForAllConstMembers();
4306
4307  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4308                                     unsigned Quals);
4309  bool shouldDeleteForSubobjectCall(Subobject Subobj,
4310                                    Sema::SpecialMemberOverloadResult *SMOR,
4311                                    bool IsDtorCallInCtor);
4312
4313  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4314};
4315}
4316
4317/// Is the given special member inaccessible when used on the given
4318/// sub-object.
4319bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4320                                             CXXMethodDecl *target) {
4321  /// If we're operating on a base class, the object type is the
4322  /// type of this special member.
4323  QualType objectTy;
4324  AccessSpecifier access = target->getAccess();;
4325  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4326    objectTy = S.Context.getTypeDeclType(MD->getParent());
4327    access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4328
4329  // If we're operating on a field, the object type is the type of the field.
4330  } else {
4331    objectTy = S.Context.getTypeDeclType(target->getParent());
4332  }
4333
4334  return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4335}
4336
4337/// Check whether we should delete a special member due to the implicit
4338/// definition containing a call to a special member of a subobject.
4339bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4340    Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4341    bool IsDtorCallInCtor) {
4342  CXXMethodDecl *Decl = SMOR->getMethod();
4343  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4344
4345  int DiagKind = -1;
4346
4347  if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4348    DiagKind = !Decl ? 0 : 1;
4349  else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4350    DiagKind = 2;
4351  else if (!isAccessible(Subobj, Decl))
4352    DiagKind = 3;
4353  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4354           !Decl->isTrivial()) {
4355    // A member of a union must have a trivial corresponding special member.
4356    // As a weird special case, a destructor call from a union's constructor
4357    // must be accessible and non-deleted, but need not be trivial. Such a
4358    // destructor is never actually called, but is semantically checked as
4359    // if it were.
4360    DiagKind = 4;
4361  }
4362
4363  if (DiagKind == -1)
4364    return false;
4365
4366  if (Diagnose) {
4367    if (Field) {
4368      S.Diag(Field->getLocation(),
4369             diag::note_deleted_special_member_class_subobject)
4370        << CSM << MD->getParent() << /*IsField*/true
4371        << Field << DiagKind << IsDtorCallInCtor;
4372    } else {
4373      CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4374      S.Diag(Base->getLocStart(),
4375             diag::note_deleted_special_member_class_subobject)
4376        << CSM << MD->getParent() << /*IsField*/false
4377        << Base->getType() << DiagKind << IsDtorCallInCtor;
4378    }
4379
4380    if (DiagKind == 1)
4381      S.NoteDeletedFunction(Decl);
4382    // FIXME: Explain inaccessibility if DiagKind == 3.
4383  }
4384
4385  return true;
4386}
4387
4388/// Check whether we should delete a special member function due to having a
4389/// direct or virtual base class or non-static data member of class type M.
4390bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4391    CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
4392  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4393
4394  // C++11 [class.ctor]p5:
4395  // -- any direct or virtual base class, or non-static data member with no
4396  //    brace-or-equal-initializer, has class type M (or array thereof) and
4397  //    either M has no default constructor or overload resolution as applied
4398  //    to M's default constructor results in an ambiguity or in a function
4399  //    that is deleted or inaccessible
4400  // C++11 [class.copy]p11, C++11 [class.copy]p23:
4401  // -- a direct or virtual base class B that cannot be copied/moved because
4402  //    overload resolution, as applied to B's corresponding special member,
4403  //    results in an ambiguity or a function that is deleted or inaccessible
4404  //    from the defaulted special member
4405  // C++11 [class.dtor]p5:
4406  // -- any direct or virtual base class [...] has a type with a destructor
4407  //    that is deleted or inaccessible
4408  if (!(CSM == Sema::CXXDefaultConstructor &&
4409        Field && Field->hasInClassInitializer()) &&
4410      shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
4411    return true;
4412
4413  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4414  // -- any direct or virtual base class or non-static data member has a
4415  //    type with a destructor that is deleted or inaccessible
4416  if (IsConstructor) {
4417    Sema::SpecialMemberOverloadResult *SMOR =
4418        S.LookupSpecialMember(Class, Sema::CXXDestructor,
4419                              false, false, false, false, false);
4420    if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4421      return true;
4422  }
4423
4424  return false;
4425}
4426
4427/// Check whether we should delete a special member function due to the class
4428/// having a particular direct or virtual base class.
4429bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4430  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4431  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
4432}
4433
4434/// Check whether we should delete a special member function due to the class
4435/// having a particular non-static data member.
4436bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4437  QualType FieldType = S.Context.getBaseElementType(FD->getType());
4438  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4439
4440  if (CSM == Sema::CXXDefaultConstructor) {
4441    // For a default constructor, all references must be initialized in-class
4442    // and, if a union, it must have a non-const member.
4443    if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4444      if (Diagnose)
4445        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4446          << MD->getParent() << FD << FieldType << /*Reference*/0;
4447      return true;
4448    }
4449    // C++11 [class.ctor]p5: any non-variant non-static data member of
4450    // const-qualified type (or array thereof) with no
4451    // brace-or-equal-initializer does not have a user-provided default
4452    // constructor.
4453    if (!inUnion() && FieldType.isConstQualified() &&
4454        !FD->hasInClassInitializer() &&
4455        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4456      if (Diagnose)
4457        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4458          << MD->getParent() << FD << FD->getType() << /*Const*/1;
4459      return true;
4460    }
4461
4462    if (inUnion() && !FieldType.isConstQualified())
4463      AllFieldsAreConst = false;
4464  } else if (CSM == Sema::CXXCopyConstructor) {
4465    // For a copy constructor, data members must not be of rvalue reference
4466    // type.
4467    if (FieldType->isRValueReferenceType()) {
4468      if (Diagnose)
4469        S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4470          << MD->getParent() << FD << FieldType;
4471      return true;
4472    }
4473  } else if (IsAssignment) {
4474    // For an assignment operator, data members must not be of reference type.
4475    if (FieldType->isReferenceType()) {
4476      if (Diagnose)
4477        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4478          << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4479      return true;
4480    }
4481    if (!FieldRecord && FieldType.isConstQualified()) {
4482      // C++11 [class.copy]p23:
4483      // -- a non-static data member of const non-class type (or array thereof)
4484      if (Diagnose)
4485        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4486          << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
4487      return true;
4488    }
4489  }
4490
4491  if (FieldRecord) {
4492    // Some additional restrictions exist on the variant members.
4493    if (!inUnion() && FieldRecord->isUnion() &&
4494        FieldRecord->isAnonymousStructOrUnion()) {
4495      bool AllVariantFieldsAreConst = true;
4496
4497      // FIXME: Handle anonymous unions declared within anonymous unions.
4498      for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4499                                         UE = FieldRecord->field_end();
4500           UI != UE; ++UI) {
4501        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4502
4503        if (!UnionFieldType.isConstQualified())
4504          AllVariantFieldsAreConst = false;
4505
4506        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4507        if (UnionFieldRecord &&
4508            shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4509                                          UnionFieldType.getCVRQualifiers()))
4510          return true;
4511      }
4512
4513      // At least one member in each anonymous union must be non-const
4514      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4515          FieldRecord->field_begin() != FieldRecord->field_end()) {
4516        if (Diagnose)
4517          S.Diag(FieldRecord->getLocation(),
4518                 diag::note_deleted_default_ctor_all_const)
4519            << MD->getParent() << /*anonymous union*/1;
4520        return true;
4521      }
4522
4523      // Don't check the implicit member of the anonymous union type.
4524      // This is technically non-conformant, but sanity demands it.
4525      return false;
4526    }
4527
4528    if (shouldDeleteForClassSubobject(FieldRecord, FD,
4529                                      FieldType.getCVRQualifiers()))
4530      return true;
4531  }
4532
4533  return false;
4534}
4535
4536/// C++11 [class.ctor] p5:
4537///   A defaulted default constructor for a class X is defined as deleted if
4538/// X is a union and all of its variant members are of const-qualified type.
4539bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4540  // This is a silly definition, because it gives an empty union a deleted
4541  // default constructor. Don't do that.
4542  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4543      (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4544    if (Diagnose)
4545      S.Diag(MD->getParent()->getLocation(),
4546             diag::note_deleted_default_ctor_all_const)
4547        << MD->getParent() << /*not anonymous union*/0;
4548    return true;
4549  }
4550  return false;
4551}
4552
4553/// Determine whether a defaulted special member function should be defined as
4554/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4555/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
4556bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4557                                     bool Diagnose) {
4558  if (MD->isInvalidDecl())
4559    return false;
4560  CXXRecordDecl *RD = MD->getParent();
4561  assert(!RD->isDependentType() && "do deletion after instantiation");
4562  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4563    return false;
4564
4565  // C++11 [expr.lambda.prim]p19:
4566  //   The closure type associated with a lambda-expression has a
4567  //   deleted (8.4.3) default constructor and a deleted copy
4568  //   assignment operator.
4569  if (RD->isLambda() &&
4570      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4571    if (Diagnose)
4572      Diag(RD->getLocation(), diag::note_lambda_decl);
4573    return true;
4574  }
4575
4576  // For an anonymous struct or union, the copy and assignment special members
4577  // will never be used, so skip the check. For an anonymous union declared at
4578  // namespace scope, the constructor and destructor are used.
4579  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4580      RD->isAnonymousStructOrUnion())
4581    return false;
4582
4583  // C++11 [class.copy]p7, p18:
4584  //   If the class definition declares a move constructor or move assignment
4585  //   operator, an implicitly declared copy constructor or copy assignment
4586  //   operator is defined as deleted.
4587  if (MD->isImplicit() &&
4588      (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4589    CXXMethodDecl *UserDeclaredMove = 0;
4590
4591    // In Microsoft mode, a user-declared move only causes the deletion of the
4592    // corresponding copy operation, not both copy operations.
4593    if (RD->hasUserDeclaredMoveConstructor() &&
4594        (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4595      if (!Diagnose) return true;
4596      UserDeclaredMove = RD->getMoveConstructor();
4597      assert(UserDeclaredMove);
4598    } else if (RD->hasUserDeclaredMoveAssignment() &&
4599               (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4600      if (!Diagnose) return true;
4601      UserDeclaredMove = RD->getMoveAssignmentOperator();
4602      assert(UserDeclaredMove);
4603    }
4604
4605    if (UserDeclaredMove) {
4606      Diag(UserDeclaredMove->getLocation(),
4607           diag::note_deleted_copy_user_declared_move)
4608        << (CSM == CXXCopyAssignment) << RD
4609        << UserDeclaredMove->isMoveAssignmentOperator();
4610      return true;
4611    }
4612  }
4613
4614  // Do access control from the special member function
4615  ContextRAII MethodContext(*this, MD);
4616
4617  // C++11 [class.dtor]p5:
4618  // -- for a virtual destructor, lookup of the non-array deallocation function
4619  //    results in an ambiguity or in a function that is deleted or inaccessible
4620  if (CSM == CXXDestructor && MD->isVirtual()) {
4621    FunctionDecl *OperatorDelete = 0;
4622    DeclarationName Name =
4623      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4624    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
4625                                 OperatorDelete, false)) {
4626      if (Diagnose)
4627        Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
4628      return true;
4629    }
4630  }
4631
4632  SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
4633
4634  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4635                                          BE = RD->bases_end(); BI != BE; ++BI)
4636    if (!BI->isVirtual() &&
4637        SMI.shouldDeleteForBase(BI))
4638      return true;
4639
4640  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4641                                          BE = RD->vbases_end(); BI != BE; ++BI)
4642    if (SMI.shouldDeleteForBase(BI))
4643      return true;
4644
4645  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4646                                     FE = RD->field_end(); FI != FE; ++FI)
4647    if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4648        SMI.shouldDeleteForField(*FI))
4649      return true;
4650
4651  if (SMI.shouldDeleteForAllConstMembers())
4652    return true;
4653
4654  return false;
4655}
4656
4657/// \brief Data used with FindHiddenVirtualMethod
4658namespace {
4659  struct FindHiddenVirtualMethodData {
4660    Sema *S;
4661    CXXMethodDecl *Method;
4662    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4663    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4664  };
4665}
4666
4667/// \brief Member lookup function that determines whether a given C++
4668/// method overloads virtual methods in a base class without overriding any,
4669/// to be used with CXXRecordDecl::lookupInBases().
4670static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4671                                    CXXBasePath &Path,
4672                                    void *UserData) {
4673  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4674
4675  FindHiddenVirtualMethodData &Data
4676    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4677
4678  DeclarationName Name = Data.Method->getDeclName();
4679  assert(Name.getNameKind() == DeclarationName::Identifier);
4680
4681  bool foundSameNameMethod = false;
4682  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4683  for (Path.Decls = BaseRecord->lookup(Name);
4684       Path.Decls.first != Path.Decls.second;
4685       ++Path.Decls.first) {
4686    NamedDecl *D = *Path.Decls.first;
4687    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4688      MD = MD->getCanonicalDecl();
4689      foundSameNameMethod = true;
4690      // Interested only in hidden virtual methods.
4691      if (!MD->isVirtual())
4692        continue;
4693      // If the method we are checking overrides a method from its base
4694      // don't warn about the other overloaded methods.
4695      if (!Data.S->IsOverload(Data.Method, MD, false))
4696        return true;
4697      // Collect the overload only if its hidden.
4698      if (!Data.OverridenAndUsingBaseMethods.count(MD))
4699        overloadedMethods.push_back(MD);
4700    }
4701  }
4702
4703  if (foundSameNameMethod)
4704    Data.OverloadedMethods.append(overloadedMethods.begin(),
4705                                   overloadedMethods.end());
4706  return foundSameNameMethod;
4707}
4708
4709/// \brief See if a method overloads virtual methods in a base class without
4710/// overriding any.
4711void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4712  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4713                               MD->getLocation()) == DiagnosticsEngine::Ignored)
4714    return;
4715  if (!MD->getDeclName().isIdentifier())
4716    return;
4717
4718  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4719                     /*bool RecordPaths=*/false,
4720                     /*bool DetectVirtual=*/false);
4721  FindHiddenVirtualMethodData Data;
4722  Data.Method = MD;
4723  Data.S = this;
4724
4725  // Keep the base methods that were overriden or introduced in the subclass
4726  // by 'using' in a set. A base method not in this set is hidden.
4727  for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4728       res.first != res.second; ++res.first) {
4729    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4730      for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4731                                          E = MD->end_overridden_methods();
4732           I != E; ++I)
4733        Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
4734    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4735      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
4736        Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
4737  }
4738
4739  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4740      !Data.OverloadedMethods.empty()) {
4741    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4742      << MD << (Data.OverloadedMethods.size() > 1);
4743
4744    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4745      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4746      Diag(overloadedMD->getLocation(),
4747           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4748    }
4749  }
4750}
4751
4752void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4753                                             Decl *TagDecl,
4754                                             SourceLocation LBrac,
4755                                             SourceLocation RBrac,
4756                                             AttributeList *AttrList) {
4757  if (!TagDecl)
4758    return;
4759
4760  AdjustDeclIfTemplate(TagDecl);
4761
4762  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4763    if (l->getKind() != AttributeList::AT_Visibility)
4764      continue;
4765    l->setInvalid();
4766    Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
4767      l->getName();
4768  }
4769
4770  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
4771              // strict aliasing violation!
4772              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
4773              FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
4774
4775  CheckCompletedCXXClass(
4776                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
4777}
4778
4779/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4780/// special functions, such as the default constructor, copy
4781/// constructor, or destructor, to the given C++ class (C++
4782/// [special]p1).  This routine can only be executed just before the
4783/// definition of the class is complete.
4784void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
4785  if (!ClassDecl->hasUserDeclaredConstructor())
4786    ++ASTContext::NumImplicitDefaultConstructors;
4787
4788  if (!ClassDecl->hasUserDeclaredCopyConstructor())
4789    ++ASTContext::NumImplicitCopyConstructors;
4790
4791  if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
4792    ++ASTContext::NumImplicitMoveConstructors;
4793
4794  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4795    ++ASTContext::NumImplicitCopyAssignmentOperators;
4796
4797    // If we have a dynamic class, then the copy assignment operator may be
4798    // virtual, so we have to declare it immediately. This ensures that, e.g.,
4799    // it shows up in the right place in the vtable and that we diagnose
4800    // problems with the implicit exception specification.
4801    if (ClassDecl->isDynamicClass())
4802      DeclareImplicitCopyAssignment(ClassDecl);
4803  }
4804
4805  if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
4806    ++ASTContext::NumImplicitMoveAssignmentOperators;
4807
4808    // Likewise for the move assignment operator.
4809    if (ClassDecl->isDynamicClass())
4810      DeclareImplicitMoveAssignment(ClassDecl);
4811  }
4812
4813  if (!ClassDecl->hasUserDeclaredDestructor()) {
4814    ++ASTContext::NumImplicitDestructors;
4815
4816    // If we have a dynamic class, then the destructor may be virtual, so we
4817    // have to declare the destructor immediately. This ensures that, e.g., it
4818    // shows up in the right place in the vtable and that we diagnose problems
4819    // with the implicit exception specification.
4820    if (ClassDecl->isDynamicClass())
4821      DeclareImplicitDestructor(ClassDecl);
4822  }
4823}
4824
4825void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4826  if (!D)
4827    return;
4828
4829  int NumParamList = D->getNumTemplateParameterLists();
4830  for (int i = 0; i < NumParamList; i++) {
4831    TemplateParameterList* Params = D->getTemplateParameterList(i);
4832    for (TemplateParameterList::iterator Param = Params->begin(),
4833                                      ParamEnd = Params->end();
4834          Param != ParamEnd; ++Param) {
4835      NamedDecl *Named = cast<NamedDecl>(*Param);
4836      if (Named->getDeclName()) {
4837        S->AddDecl(Named);
4838        IdResolver.AddDecl(Named);
4839      }
4840    }
4841  }
4842}
4843
4844void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
4845  if (!D)
4846    return;
4847
4848  TemplateParameterList *Params = 0;
4849  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4850    Params = Template->getTemplateParameters();
4851  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4852           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4853    Params = PartialSpec->getTemplateParameters();
4854  else
4855    return;
4856
4857  for (TemplateParameterList::iterator Param = Params->begin(),
4858                                    ParamEnd = Params->end();
4859       Param != ParamEnd; ++Param) {
4860    NamedDecl *Named = cast<NamedDecl>(*Param);
4861    if (Named->getDeclName()) {
4862      S->AddDecl(Named);
4863      IdResolver.AddDecl(Named);
4864    }
4865  }
4866}
4867
4868void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4869  if (!RecordD) return;
4870  AdjustDeclIfTemplate(RecordD);
4871  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
4872  PushDeclContext(S, Record);
4873}
4874
4875void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4876  if (!RecordD) return;
4877  PopDeclContext();
4878}
4879
4880/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4881/// parsing a top-level (non-nested) C++ class, and we are now
4882/// parsing those parts of the given Method declaration that could
4883/// not be parsed earlier (C++ [class.mem]p2), such as default
4884/// arguments. This action should enter the scope of the given
4885/// Method declaration as if we had just parsed the qualified method
4886/// name. However, it should not bring the parameters into scope;
4887/// that will be performed by ActOnDelayedCXXMethodParameter.
4888void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4889}
4890
4891/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4892/// C++ method declaration. We're (re-)introducing the given
4893/// function parameter into scope for use in parsing later parts of
4894/// the method declaration. For example, we could see an
4895/// ActOnParamDefaultArgument event for this parameter.
4896void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
4897  if (!ParamD)
4898    return;
4899
4900  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
4901
4902  // If this parameter has an unparsed default argument, clear it out
4903  // to make way for the parsed default argument.
4904  if (Param->hasUnparsedDefaultArg())
4905    Param->setDefaultArg(0);
4906
4907  S->AddDecl(Param);
4908  if (Param->getDeclName())
4909    IdResolver.AddDecl(Param);
4910}
4911
4912/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4913/// processing the delayed method declaration for Method. The method
4914/// declaration is now considered finished. There may be a separate
4915/// ActOnStartOfFunctionDef action later (not necessarily
4916/// immediately!) for this method, if it was also defined inside the
4917/// class body.
4918void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4919  if (!MethodD)
4920    return;
4921
4922  AdjustDeclIfTemplate(MethodD);
4923
4924  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
4925
4926  // Now that we have our default arguments, check the constructor
4927  // again. It could produce additional diagnostics or affect whether
4928  // the class has implicitly-declared destructors, among other
4929  // things.
4930  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4931    CheckConstructor(Constructor);
4932
4933  // Check the default arguments, which we may have added.
4934  if (!Method->isInvalidDecl())
4935    CheckCXXDefaultArguments(Method);
4936}
4937
4938/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
4939/// the well-formedness of the constructor declarator @p D with type @p
4940/// R. If there are any errors in the declarator, this routine will
4941/// emit diagnostics and set the invalid bit to true.  In any case, the type
4942/// will be updated to reflect a well-formed type for the constructor and
4943/// returned.
4944QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
4945                                          StorageClass &SC) {
4946  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4947
4948  // C++ [class.ctor]p3:
4949  //   A constructor shall not be virtual (10.3) or static (9.4). A
4950  //   constructor can be invoked for a const, volatile or const
4951  //   volatile object. A constructor shall not be declared const,
4952  //   volatile, or const volatile (9.3.2).
4953  if (isVirtual) {
4954    if (!D.isInvalidType())
4955      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4956        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4957        << SourceRange(D.getIdentifierLoc());
4958    D.setInvalidType();
4959  }
4960  if (SC == SC_Static) {
4961    if (!D.isInvalidType())
4962      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4963        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4964        << SourceRange(D.getIdentifierLoc());
4965    D.setInvalidType();
4966    SC = SC_None;
4967  }
4968
4969  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4970  if (FTI.TypeQuals != 0) {
4971    if (FTI.TypeQuals & Qualifiers::Const)
4972      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4973        << "const" << SourceRange(D.getIdentifierLoc());
4974    if (FTI.TypeQuals & Qualifiers::Volatile)
4975      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4976        << "volatile" << SourceRange(D.getIdentifierLoc());
4977    if (FTI.TypeQuals & Qualifiers::Restrict)
4978      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4979        << "restrict" << SourceRange(D.getIdentifierLoc());
4980    D.setInvalidType();
4981  }
4982
4983  // C++0x [class.ctor]p4:
4984  //   A constructor shall not be declared with a ref-qualifier.
4985  if (FTI.hasRefQualifier()) {
4986    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4987      << FTI.RefQualifierIsLValueRef
4988      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4989    D.setInvalidType();
4990  }
4991
4992  // Rebuild the function type "R" without any type qualifiers (in
4993  // case any of the errors above fired) and with "void" as the
4994  // return type, since constructors don't have return types.
4995  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4996  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4997    return R;
4998
4999  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5000  EPI.TypeQuals = 0;
5001  EPI.RefQualifier = RQ_None;
5002
5003  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
5004                                 Proto->getNumArgs(), EPI);
5005}
5006
5007/// CheckConstructor - Checks a fully-formed constructor for
5008/// well-formedness, issuing any diagnostics required. Returns true if
5009/// the constructor declarator is invalid.
5010void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5011  CXXRecordDecl *ClassDecl
5012    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5013  if (!ClassDecl)
5014    return Constructor->setInvalidDecl();
5015
5016  // C++ [class.copy]p3:
5017  //   A declaration of a constructor for a class X is ill-formed if
5018  //   its first parameter is of type (optionally cv-qualified) X and
5019  //   either there are no other parameters or else all other
5020  //   parameters have default arguments.
5021  if (!Constructor->isInvalidDecl() &&
5022      ((Constructor->getNumParams() == 1) ||
5023       (Constructor->getNumParams() > 1 &&
5024        Constructor->getParamDecl(1)->hasDefaultArg())) &&
5025      Constructor->getTemplateSpecializationKind()
5026                                              != TSK_ImplicitInstantiation) {
5027    QualType ParamType = Constructor->getParamDecl(0)->getType();
5028    QualType ClassTy = Context.getTagDeclType(ClassDecl);
5029    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5030      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5031      const char *ConstRef
5032        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5033                                                        : " const &";
5034      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5035        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5036
5037      // FIXME: Rather that making the constructor invalid, we should endeavor
5038      // to fix the type.
5039      Constructor->setInvalidDecl();
5040    }
5041  }
5042}
5043
5044/// CheckDestructor - Checks a fully-formed destructor definition for
5045/// well-formedness, issuing any diagnostics required.  Returns true
5046/// on error.
5047bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5048  CXXRecordDecl *RD = Destructor->getParent();
5049
5050  if (Destructor->isVirtual()) {
5051    SourceLocation Loc;
5052
5053    if (!Destructor->isImplicit())
5054      Loc = Destructor->getLocation();
5055    else
5056      Loc = RD->getLocation();
5057
5058    // If we have a virtual destructor, look up the deallocation function
5059    FunctionDecl *OperatorDelete = 0;
5060    DeclarationName Name =
5061    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5062    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5063      return true;
5064
5065    MarkFunctionReferenced(Loc, OperatorDelete);
5066
5067    Destructor->setOperatorDelete(OperatorDelete);
5068  }
5069
5070  return false;
5071}
5072
5073static inline bool
5074FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5075  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5076          FTI.ArgInfo[0].Param &&
5077          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5078}
5079
5080/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5081/// the well-formednes of the destructor declarator @p D with type @p
5082/// R. If there are any errors in the declarator, this routine will
5083/// emit diagnostics and set the declarator to invalid.  Even if this happens,
5084/// will be updated to reflect a well-formed type for the destructor and
5085/// returned.
5086QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5087                                         StorageClass& SC) {
5088  // C++ [class.dtor]p1:
5089  //   [...] A typedef-name that names a class is a class-name
5090  //   (7.1.3); however, a typedef-name that names a class shall not
5091  //   be used as the identifier in the declarator for a destructor
5092  //   declaration.
5093  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5094  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5095    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5096      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5097  else if (const TemplateSpecializationType *TST =
5098             DeclaratorType->getAs<TemplateSpecializationType>())
5099    if (TST->isTypeAlias())
5100      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5101        << DeclaratorType << 1;
5102
5103  // C++ [class.dtor]p2:
5104  //   A destructor is used to destroy objects of its class type. A
5105  //   destructor takes no parameters, and no return type can be
5106  //   specified for it (not even void). The address of a destructor
5107  //   shall not be taken. A destructor shall not be static. A
5108  //   destructor can be invoked for a const, volatile or const
5109  //   volatile object. A destructor shall not be declared const,
5110  //   volatile or const volatile (9.3.2).
5111  if (SC == SC_Static) {
5112    if (!D.isInvalidType())
5113      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5114        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5115        << SourceRange(D.getIdentifierLoc())
5116        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5117
5118    SC = SC_None;
5119  }
5120  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5121    // Destructors don't have return types, but the parser will
5122    // happily parse something like:
5123    //
5124    //   class X {
5125    //     float ~X();
5126    //   };
5127    //
5128    // The return type will be eliminated later.
5129    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5130      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5131      << SourceRange(D.getIdentifierLoc());
5132  }
5133
5134  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5135  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5136    if (FTI.TypeQuals & Qualifiers::Const)
5137      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5138        << "const" << SourceRange(D.getIdentifierLoc());
5139    if (FTI.TypeQuals & Qualifiers::Volatile)
5140      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5141        << "volatile" << SourceRange(D.getIdentifierLoc());
5142    if (FTI.TypeQuals & Qualifiers::Restrict)
5143      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5144        << "restrict" << SourceRange(D.getIdentifierLoc());
5145    D.setInvalidType();
5146  }
5147
5148  // C++0x [class.dtor]p2:
5149  //   A destructor shall not be declared with a ref-qualifier.
5150  if (FTI.hasRefQualifier()) {
5151    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5152      << FTI.RefQualifierIsLValueRef
5153      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5154    D.setInvalidType();
5155  }
5156
5157  // Make sure we don't have any parameters.
5158  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5159    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5160
5161    // Delete the parameters.
5162    FTI.freeArgs();
5163    D.setInvalidType();
5164  }
5165
5166  // Make sure the destructor isn't variadic.
5167  if (FTI.isVariadic) {
5168    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5169    D.setInvalidType();
5170  }
5171
5172  // Rebuild the function type "R" without any type qualifiers or
5173  // parameters (in case any of the errors above fired) and with
5174  // "void" as the return type, since destructors don't have return
5175  // types.
5176  if (!D.isInvalidType())
5177    return R;
5178
5179  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5180  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5181  EPI.Variadic = false;
5182  EPI.TypeQuals = 0;
5183  EPI.RefQualifier = RQ_None;
5184  return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
5185}
5186
5187/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5188/// well-formednes of the conversion function declarator @p D with
5189/// type @p R. If there are any errors in the declarator, this routine
5190/// will emit diagnostics and return true. Otherwise, it will return
5191/// false. Either way, the type @p R will be updated to reflect a
5192/// well-formed type for the conversion operator.
5193void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
5194                                     StorageClass& SC) {
5195  // C++ [class.conv.fct]p1:
5196  //   Neither parameter types nor return type can be specified. The
5197  //   type of a conversion function (8.3.5) is "function taking no
5198  //   parameter returning conversion-type-id."
5199  if (SC == SC_Static) {
5200    if (!D.isInvalidType())
5201      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5202        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5203        << SourceRange(D.getIdentifierLoc());
5204    D.setInvalidType();
5205    SC = SC_None;
5206  }
5207
5208  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5209
5210  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5211    // Conversion functions don't have return types, but the parser will
5212    // happily parse something like:
5213    //
5214    //   class X {
5215    //     float operator bool();
5216    //   };
5217    //
5218    // The return type will be changed later anyway.
5219    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5220      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5221      << SourceRange(D.getIdentifierLoc());
5222    D.setInvalidType();
5223  }
5224
5225  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5226
5227  // Make sure we don't have any parameters.
5228  if (Proto->getNumArgs() > 0) {
5229    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5230
5231    // Delete the parameters.
5232    D.getFunctionTypeInfo().freeArgs();
5233    D.setInvalidType();
5234  } else if (Proto->isVariadic()) {
5235    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
5236    D.setInvalidType();
5237  }
5238
5239  // Diagnose "&operator bool()" and other such nonsense.  This
5240  // is actually a gcc extension which we don't support.
5241  if (Proto->getResultType() != ConvType) {
5242    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5243      << Proto->getResultType();
5244    D.setInvalidType();
5245    ConvType = Proto->getResultType();
5246  }
5247
5248  // C++ [class.conv.fct]p4:
5249  //   The conversion-type-id shall not represent a function type nor
5250  //   an array type.
5251  if (ConvType->isArrayType()) {
5252    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5253    ConvType = Context.getPointerType(ConvType);
5254    D.setInvalidType();
5255  } else if (ConvType->isFunctionType()) {
5256    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5257    ConvType = Context.getPointerType(ConvType);
5258    D.setInvalidType();
5259  }
5260
5261  // Rebuild the function type "R" without any parameters (in case any
5262  // of the errors above fired) and with the conversion type as the
5263  // return type.
5264  if (D.isInvalidType())
5265    R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
5266
5267  // C++0x explicit conversion operators.
5268  if (D.getDeclSpec().isExplicitSpecified())
5269    Diag(D.getDeclSpec().getExplicitSpecLoc(),
5270         getLangOpts().CPlusPlus0x ?
5271           diag::warn_cxx98_compat_explicit_conversion_functions :
5272           diag::ext_explicit_conversion_functions)
5273      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
5274}
5275
5276/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5277/// the declaration of the given C++ conversion function. This routine
5278/// is responsible for recording the conversion function in the C++
5279/// class, if possible.
5280Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
5281  assert(Conversion && "Expected to receive a conversion function declaration");
5282
5283  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
5284
5285  // Make sure we aren't redeclaring the conversion function.
5286  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
5287
5288  // C++ [class.conv.fct]p1:
5289  //   [...] A conversion function is never used to convert a
5290  //   (possibly cv-qualified) object to the (possibly cv-qualified)
5291  //   same object type (or a reference to it), to a (possibly
5292  //   cv-qualified) base class of that type (or a reference to it),
5293  //   or to (possibly cv-qualified) void.
5294  // FIXME: Suppress this warning if the conversion function ends up being a
5295  // virtual function that overrides a virtual function in a base class.
5296  QualType ClassType
5297    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5298  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
5299    ConvType = ConvTypeRef->getPointeeType();
5300  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5301      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5302    /* Suppress diagnostics for instantiations. */;
5303  else if (ConvType->isRecordType()) {
5304    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5305    if (ConvType == ClassType)
5306      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
5307        << ClassType;
5308    else if (IsDerivedFrom(ClassType, ConvType))
5309      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
5310        <<  ClassType << ConvType;
5311  } else if (ConvType->isVoidType()) {
5312    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
5313      << ClassType << ConvType;
5314  }
5315
5316  if (FunctionTemplateDecl *ConversionTemplate
5317                                = Conversion->getDescribedFunctionTemplate())
5318    return ConversionTemplate;
5319
5320  return Conversion;
5321}
5322
5323//===----------------------------------------------------------------------===//
5324// Namespace Handling
5325//===----------------------------------------------------------------------===//
5326
5327
5328
5329/// ActOnStartNamespaceDef - This is called at the start of a namespace
5330/// definition.
5331Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
5332                                   SourceLocation InlineLoc,
5333                                   SourceLocation NamespaceLoc,
5334                                   SourceLocation IdentLoc,
5335                                   IdentifierInfo *II,
5336                                   SourceLocation LBrace,
5337                                   AttributeList *AttrList) {
5338  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5339  // For anonymous namespace, take the location of the left brace.
5340  SourceLocation Loc = II ? IdentLoc : LBrace;
5341  bool IsInline = InlineLoc.isValid();
5342  bool IsInvalid = false;
5343  bool IsStd = false;
5344  bool AddToKnown = false;
5345  Scope *DeclRegionScope = NamespcScope->getParent();
5346
5347  NamespaceDecl *PrevNS = 0;
5348  if (II) {
5349    // C++ [namespace.def]p2:
5350    //   The identifier in an original-namespace-definition shall not
5351    //   have been previously defined in the declarative region in
5352    //   which the original-namespace-definition appears. The
5353    //   identifier in an original-namespace-definition is the name of
5354    //   the namespace. Subsequently in that declarative region, it is
5355    //   treated as an original-namespace-name.
5356    //
5357    // Since namespace names are unique in their scope, and we don't
5358    // look through using directives, just look for any ordinary names.
5359
5360    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5361    Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5362    Decl::IDNS_Namespace;
5363    NamedDecl *PrevDecl = 0;
5364    for (DeclContext::lookup_result R
5365         = CurContext->getRedeclContext()->lookup(II);
5366         R.first != R.second; ++R.first) {
5367      if ((*R.first)->getIdentifierNamespace() & IDNS) {
5368        PrevDecl = *R.first;
5369        break;
5370      }
5371    }
5372
5373    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5374
5375    if (PrevNS) {
5376      // This is an extended namespace definition.
5377      if (IsInline != PrevNS->isInline()) {
5378        // inline-ness must match
5379        if (PrevNS->isInline()) {
5380          // The user probably just forgot the 'inline', so suggest that it
5381          // be added back.
5382          Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5383            << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5384        } else {
5385          Diag(Loc, diag::err_inline_namespace_mismatch)
5386            << IsInline;
5387        }
5388        Diag(PrevNS->getLocation(), diag::note_previous_definition);
5389
5390        IsInline = PrevNS->isInline();
5391      }
5392    } else if (PrevDecl) {
5393      // This is an invalid name redefinition.
5394      Diag(Loc, diag::err_redefinition_different_kind)
5395        << II;
5396      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5397      IsInvalid = true;
5398      // Continue on to push Namespc as current DeclContext and return it.
5399    } else if (II->isStr("std") &&
5400               CurContext->getRedeclContext()->isTranslationUnit()) {
5401      // This is the first "real" definition of the namespace "std", so update
5402      // our cache of the "std" namespace to point at this definition.
5403      PrevNS = getStdNamespace();
5404      IsStd = true;
5405      AddToKnown = !IsInline;
5406    } else {
5407      // We've seen this namespace for the first time.
5408      AddToKnown = !IsInline;
5409    }
5410  } else {
5411    // Anonymous namespaces.
5412
5413    // Determine whether the parent already has an anonymous namespace.
5414    DeclContext *Parent = CurContext->getRedeclContext();
5415    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5416      PrevNS = TU->getAnonymousNamespace();
5417    } else {
5418      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5419      PrevNS = ND->getAnonymousNamespace();
5420    }
5421
5422    if (PrevNS && IsInline != PrevNS->isInline()) {
5423      // inline-ness must match
5424      Diag(Loc, diag::err_inline_namespace_mismatch)
5425        << IsInline;
5426      Diag(PrevNS->getLocation(), diag::note_previous_definition);
5427
5428      // Recover by ignoring the new namespace's inline status.
5429      IsInline = PrevNS->isInline();
5430    }
5431  }
5432
5433  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5434                                                 StartLoc, Loc, II, PrevNS);
5435  if (IsInvalid)
5436    Namespc->setInvalidDecl();
5437
5438  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5439
5440  // FIXME: Should we be merging attributes?
5441  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5442    PushNamespaceVisibilityAttr(Attr, Loc);
5443
5444  if (IsStd)
5445    StdNamespace = Namespc;
5446  if (AddToKnown)
5447    KnownNamespaces[Namespc] = false;
5448
5449  if (II) {
5450    PushOnScopeChains(Namespc, DeclRegionScope);
5451  } else {
5452    // Link the anonymous namespace into its parent.
5453    DeclContext *Parent = CurContext->getRedeclContext();
5454    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5455      TU->setAnonymousNamespace(Namespc);
5456    } else {
5457      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
5458    }
5459
5460    CurContext->addDecl(Namespc);
5461
5462    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
5463    //   behaves as if it were replaced by
5464    //     namespace unique { /* empty body */ }
5465    //     using namespace unique;
5466    //     namespace unique { namespace-body }
5467    //   where all occurrences of 'unique' in a translation unit are
5468    //   replaced by the same identifier and this identifier differs
5469    //   from all other identifiers in the entire program.
5470
5471    // We just create the namespace with an empty name and then add an
5472    // implicit using declaration, just like the standard suggests.
5473    //
5474    // CodeGen enforces the "universally unique" aspect by giving all
5475    // declarations semantically contained within an anonymous
5476    // namespace internal linkage.
5477
5478    if (!PrevNS) {
5479      UsingDirectiveDecl* UD
5480        = UsingDirectiveDecl::Create(Context, CurContext,
5481                                     /* 'using' */ LBrace,
5482                                     /* 'namespace' */ SourceLocation(),
5483                                     /* qualifier */ NestedNameSpecifierLoc(),
5484                                     /* identifier */ SourceLocation(),
5485                                     Namespc,
5486                                     /* Ancestor */ CurContext);
5487      UD->setImplicit();
5488      CurContext->addDecl(UD);
5489    }
5490  }
5491
5492  ActOnDocumentableDecl(Namespc);
5493
5494  // Although we could have an invalid decl (i.e. the namespace name is a
5495  // redefinition), push it as current DeclContext and try to continue parsing.
5496  // FIXME: We should be able to push Namespc here, so that the each DeclContext
5497  // for the namespace has the declarations that showed up in that particular
5498  // namespace definition.
5499  PushDeclContext(NamespcScope, Namespc);
5500  return Namespc;
5501}
5502
5503/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5504/// is a namespace alias, returns the namespace it points to.
5505static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5506  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5507    return AD->getNamespace();
5508  return dyn_cast_or_null<NamespaceDecl>(D);
5509}
5510
5511/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5512/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5513void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
5514  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5515  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
5516  Namespc->setRBraceLoc(RBrace);
5517  PopDeclContext();
5518  if (Namespc->hasAttr<VisibilityAttr>())
5519    PopPragmaVisibility(true, RBrace);
5520}
5521
5522CXXRecordDecl *Sema::getStdBadAlloc() const {
5523  return cast_or_null<CXXRecordDecl>(
5524                                  StdBadAlloc.get(Context.getExternalSource()));
5525}
5526
5527NamespaceDecl *Sema::getStdNamespace() const {
5528  return cast_or_null<NamespaceDecl>(
5529                                 StdNamespace.get(Context.getExternalSource()));
5530}
5531
5532/// \brief Retrieve the special "std" namespace, which may require us to
5533/// implicitly define the namespace.
5534NamespaceDecl *Sema::getOrCreateStdNamespace() {
5535  if (!StdNamespace) {
5536    // The "std" namespace has not yet been defined, so build one implicitly.
5537    StdNamespace = NamespaceDecl::Create(Context,
5538                                         Context.getTranslationUnitDecl(),
5539                                         /*Inline=*/false,
5540                                         SourceLocation(), SourceLocation(),
5541                                         &PP.getIdentifierTable().get("std"),
5542                                         /*PrevDecl=*/0);
5543    getStdNamespace()->setImplicit(true);
5544  }
5545
5546  return getStdNamespace();
5547}
5548
5549bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5550  assert(getLangOpts().CPlusPlus &&
5551         "Looking for std::initializer_list outside of C++.");
5552
5553  // We're looking for implicit instantiations of
5554  // template <typename E> class std::initializer_list.
5555
5556  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5557    return false;
5558
5559  ClassTemplateDecl *Template = 0;
5560  const TemplateArgument *Arguments = 0;
5561
5562  if (const RecordType *RT = Ty->getAs<RecordType>()) {
5563
5564    ClassTemplateSpecializationDecl *Specialization =
5565        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5566    if (!Specialization)
5567      return false;
5568
5569    Template = Specialization->getSpecializedTemplate();
5570    Arguments = Specialization->getTemplateArgs().data();
5571  } else if (const TemplateSpecializationType *TST =
5572                 Ty->getAs<TemplateSpecializationType>()) {
5573    Template = dyn_cast_or_null<ClassTemplateDecl>(
5574        TST->getTemplateName().getAsTemplateDecl());
5575    Arguments = TST->getArgs();
5576  }
5577  if (!Template)
5578    return false;
5579
5580  if (!StdInitializerList) {
5581    // Haven't recognized std::initializer_list yet, maybe this is it.
5582    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5583    if (TemplateClass->getIdentifier() !=
5584            &PP.getIdentifierTable().get("initializer_list") ||
5585        !getStdNamespace()->InEnclosingNamespaceSetOf(
5586            TemplateClass->getDeclContext()))
5587      return false;
5588    // This is a template called std::initializer_list, but is it the right
5589    // template?
5590    TemplateParameterList *Params = Template->getTemplateParameters();
5591    if (Params->getMinRequiredArguments() != 1)
5592      return false;
5593    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5594      return false;
5595
5596    // It's the right template.
5597    StdInitializerList = Template;
5598  }
5599
5600  if (Template != StdInitializerList)
5601    return false;
5602
5603  // This is an instance of std::initializer_list. Find the argument type.
5604  if (Element)
5605    *Element = Arguments[0].getAsType();
5606  return true;
5607}
5608
5609static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5610  NamespaceDecl *Std = S.getStdNamespace();
5611  if (!Std) {
5612    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5613    return 0;
5614  }
5615
5616  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5617                      Loc, Sema::LookupOrdinaryName);
5618  if (!S.LookupQualifiedName(Result, Std)) {
5619    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5620    return 0;
5621  }
5622  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5623  if (!Template) {
5624    Result.suppressDiagnostics();
5625    // We found something weird. Complain about the first thing we found.
5626    NamedDecl *Found = *Result.begin();
5627    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5628    return 0;
5629  }
5630
5631  // We found some template called std::initializer_list. Now verify that it's
5632  // correct.
5633  TemplateParameterList *Params = Template->getTemplateParameters();
5634  if (Params->getMinRequiredArguments() != 1 ||
5635      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5636    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5637    return 0;
5638  }
5639
5640  return Template;
5641}
5642
5643QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5644  if (!StdInitializerList) {
5645    StdInitializerList = LookupStdInitializerList(*this, Loc);
5646    if (!StdInitializerList)
5647      return QualType();
5648  }
5649
5650  TemplateArgumentListInfo Args(Loc, Loc);
5651  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5652                                       Context.getTrivialTypeSourceInfo(Element,
5653                                                                        Loc)));
5654  return Context.getCanonicalType(
5655      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5656}
5657
5658bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5659  // C++ [dcl.init.list]p2:
5660  //   A constructor is an initializer-list constructor if its first parameter
5661  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
5662  //   std::initializer_list<E> for some type E, and either there are no other
5663  //   parameters or else all other parameters have default arguments.
5664  if (Ctor->getNumParams() < 1 ||
5665      (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5666    return false;
5667
5668  QualType ArgType = Ctor->getParamDecl(0)->getType();
5669  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5670    ArgType = RT->getPointeeType().getUnqualifiedType();
5671
5672  return isStdInitializerList(ArgType, 0);
5673}
5674
5675/// \brief Determine whether a using statement is in a context where it will be
5676/// apply in all contexts.
5677static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5678  switch (CurContext->getDeclKind()) {
5679    case Decl::TranslationUnit:
5680      return true;
5681    case Decl::LinkageSpec:
5682      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5683    default:
5684      return false;
5685  }
5686}
5687
5688namespace {
5689
5690// Callback to only accept typo corrections that are namespaces.
5691class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5692 public:
5693  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5694    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5695      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5696    }
5697    return false;
5698  }
5699};
5700
5701}
5702
5703static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5704                                       CXXScopeSpec &SS,
5705                                       SourceLocation IdentLoc,
5706                                       IdentifierInfo *Ident) {
5707  NamespaceValidatorCCC Validator;
5708  R.clear();
5709  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5710                                               R.getLookupKind(), Sc, &SS,
5711                                               Validator)) {
5712    std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5713    std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
5714    if (DeclContext *DC = S.computeDeclContext(SS, false))
5715      S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5716        << Ident << DC << CorrectedQuotedStr << SS.getRange()
5717        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5718    else
5719      S.Diag(IdentLoc, diag::err_using_directive_suggest)
5720        << Ident << CorrectedQuotedStr
5721        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5722
5723    S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5724         diag::note_namespace_defined_here) << CorrectedQuotedStr;
5725
5726    R.addDecl(Corrected.getCorrectionDecl());
5727    return true;
5728  }
5729  return false;
5730}
5731
5732Decl *Sema::ActOnUsingDirective(Scope *S,
5733                                          SourceLocation UsingLoc,
5734                                          SourceLocation NamespcLoc,
5735                                          CXXScopeSpec &SS,
5736                                          SourceLocation IdentLoc,
5737                                          IdentifierInfo *NamespcName,
5738                                          AttributeList *AttrList) {
5739  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5740  assert(NamespcName && "Invalid NamespcName.");
5741  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
5742
5743  // This can only happen along a recovery path.
5744  while (S->getFlags() & Scope::TemplateParamScope)
5745    S = S->getParent();
5746  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5747
5748  UsingDirectiveDecl *UDir = 0;
5749  NestedNameSpecifier *Qualifier = 0;
5750  if (SS.isSet())
5751    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5752
5753  // Lookup namespace name.
5754  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5755  LookupParsedName(R, S, &SS);
5756  if (R.isAmbiguous())
5757    return 0;
5758
5759  if (R.empty()) {
5760    R.clear();
5761    // Allow "using namespace std;" or "using namespace ::std;" even if
5762    // "std" hasn't been defined yet, for GCC compatibility.
5763    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5764        NamespcName->isStr("std")) {
5765      Diag(IdentLoc, diag::ext_using_undefined_std);
5766      R.addDecl(getOrCreateStdNamespace());
5767      R.resolveKind();
5768    }
5769    // Otherwise, attempt typo correction.
5770    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
5771  }
5772
5773  if (!R.empty()) {
5774    NamedDecl *Named = R.getFoundDecl();
5775    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5776        && "expected namespace decl");
5777    // C++ [namespace.udir]p1:
5778    //   A using-directive specifies that the names in the nominated
5779    //   namespace can be used in the scope in which the
5780    //   using-directive appears after the using-directive. During
5781    //   unqualified name lookup (3.4.1), the names appear as if they
5782    //   were declared in the nearest enclosing namespace which
5783    //   contains both the using-directive and the nominated
5784    //   namespace. [Note: in this context, "contains" means "contains
5785    //   directly or indirectly". ]
5786
5787    // Find enclosing context containing both using-directive and
5788    // nominated namespace.
5789    NamespaceDecl *NS = getNamespaceDecl(Named);
5790    DeclContext *CommonAncestor = cast<DeclContext>(NS);
5791    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5792      CommonAncestor = CommonAncestor->getParent();
5793
5794    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
5795                                      SS.getWithLocInContext(Context),
5796                                      IdentLoc, Named, CommonAncestor);
5797
5798    if (IsUsingDirectiveInToplevelContext(CurContext) &&
5799        !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
5800      Diag(IdentLoc, diag::warn_using_directive_in_header);
5801    }
5802
5803    PushUsingDirective(S, UDir);
5804  } else {
5805    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
5806  }
5807
5808  // FIXME: We ignore attributes for now.
5809  return UDir;
5810}
5811
5812void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5813  // If the scope has an associated entity and the using directive is at
5814  // namespace or translation unit scope, add the UsingDirectiveDecl into
5815  // its lookup structure so qualified name lookup can find it.
5816  DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5817  if (Ctx && !Ctx->isFunctionOrMethod())
5818    Ctx->addDecl(UDir);
5819  else
5820    // Otherwise, it is at block sope. The using-directives will affect lookup
5821    // only to the end of the scope.
5822    S->PushUsingDirective(UDir);
5823}
5824
5825
5826Decl *Sema::ActOnUsingDeclaration(Scope *S,
5827                                  AccessSpecifier AS,
5828                                  bool HasUsingKeyword,
5829                                  SourceLocation UsingLoc,
5830                                  CXXScopeSpec &SS,
5831                                  UnqualifiedId &Name,
5832                                  AttributeList *AttrList,
5833                                  bool IsTypeName,
5834                                  SourceLocation TypenameLoc) {
5835  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5836
5837  switch (Name.getKind()) {
5838  case UnqualifiedId::IK_ImplicitSelfParam:
5839  case UnqualifiedId::IK_Identifier:
5840  case UnqualifiedId::IK_OperatorFunctionId:
5841  case UnqualifiedId::IK_LiteralOperatorId:
5842  case UnqualifiedId::IK_ConversionFunctionId:
5843    break;
5844
5845  case UnqualifiedId::IK_ConstructorName:
5846  case UnqualifiedId::IK_ConstructorTemplateId:
5847    // C++11 inheriting constructors.
5848    Diag(Name.getLocStart(),
5849         getLangOpts().CPlusPlus0x ?
5850           // FIXME: Produce warn_cxx98_compat_using_decl_constructor
5851           //        instead once inheriting constructors work.
5852           diag::err_using_decl_constructor_unsupported :
5853           diag::err_using_decl_constructor)
5854      << SS.getRange();
5855
5856    if (getLangOpts().CPlusPlus0x) break;
5857
5858    return 0;
5859
5860  case UnqualifiedId::IK_DestructorName:
5861    Diag(Name.getLocStart(), diag::err_using_decl_destructor)
5862      << SS.getRange();
5863    return 0;
5864
5865  case UnqualifiedId::IK_TemplateId:
5866    Diag(Name.getLocStart(), diag::err_using_decl_template_id)
5867      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
5868    return 0;
5869  }
5870
5871  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5872  DeclarationName TargetName = TargetNameInfo.getName();
5873  if (!TargetName)
5874    return 0;
5875
5876  // Warn about using declarations.
5877  // TODO: store that the declaration was written without 'using' and
5878  // talk about access decls instead of using decls in the
5879  // diagnostics.
5880  if (!HasUsingKeyword) {
5881    UsingLoc = Name.getLocStart();
5882
5883    Diag(UsingLoc, diag::warn_access_decl_deprecated)
5884      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
5885  }
5886
5887  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5888      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5889    return 0;
5890
5891  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
5892                                        TargetNameInfo, AttrList,
5893                                        /* IsInstantiation */ false,
5894                                        IsTypeName, TypenameLoc);
5895  if (UD)
5896    PushOnScopeChains(UD, S, /*AddToContext*/ false);
5897
5898  return UD;
5899}
5900
5901/// \brief Determine whether a using declaration considers the given
5902/// declarations as "equivalent", e.g., if they are redeclarations of
5903/// the same entity or are both typedefs of the same type.
5904static bool
5905IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5906                         bool &SuppressRedeclaration) {
5907  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5908    SuppressRedeclaration = false;
5909    return true;
5910  }
5911
5912  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5913    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
5914      SuppressRedeclaration = true;
5915      return Context.hasSameType(TD1->getUnderlyingType(),
5916                                 TD2->getUnderlyingType());
5917    }
5918
5919  return false;
5920}
5921
5922
5923/// Determines whether to create a using shadow decl for a particular
5924/// decl, given the set of decls existing prior to this using lookup.
5925bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5926                                const LookupResult &Previous) {
5927  // Diagnose finding a decl which is not from a base class of the
5928  // current class.  We do this now because there are cases where this
5929  // function will silently decide not to build a shadow decl, which
5930  // will pre-empt further diagnostics.
5931  //
5932  // We don't need to do this in C++0x because we do the check once on
5933  // the qualifier.
5934  //
5935  // FIXME: diagnose the following if we care enough:
5936  //   struct A { int foo; };
5937  //   struct B : A { using A::foo; };
5938  //   template <class T> struct C : A {};
5939  //   template <class T> struct D : C<T> { using B::foo; } // <---
5940  // This is invalid (during instantiation) in C++03 because B::foo
5941  // resolves to the using decl in B, which is not a base class of D<T>.
5942  // We can't diagnose it immediately because C<T> is an unknown
5943  // specialization.  The UsingShadowDecl in D<T> then points directly
5944  // to A::foo, which will look well-formed when we instantiate.
5945  // The right solution is to not collapse the shadow-decl chain.
5946  if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
5947    DeclContext *OrigDC = Orig->getDeclContext();
5948
5949    // Handle enums and anonymous structs.
5950    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5951    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5952    while (OrigRec->isAnonymousStructOrUnion())
5953      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5954
5955    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5956      if (OrigDC == CurContext) {
5957        Diag(Using->getLocation(),
5958             diag::err_using_decl_nested_name_specifier_is_current_class)
5959          << Using->getQualifierLoc().getSourceRange();
5960        Diag(Orig->getLocation(), diag::note_using_decl_target);
5961        return true;
5962      }
5963
5964      Diag(Using->getQualifierLoc().getBeginLoc(),
5965           diag::err_using_decl_nested_name_specifier_is_not_base_class)
5966        << Using->getQualifier()
5967        << cast<CXXRecordDecl>(CurContext)
5968        << Using->getQualifierLoc().getSourceRange();
5969      Diag(Orig->getLocation(), diag::note_using_decl_target);
5970      return true;
5971    }
5972  }
5973
5974  if (Previous.empty()) return false;
5975
5976  NamedDecl *Target = Orig;
5977  if (isa<UsingShadowDecl>(Target))
5978    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5979
5980  // If the target happens to be one of the previous declarations, we
5981  // don't have a conflict.
5982  //
5983  // FIXME: but we might be increasing its access, in which case we
5984  // should redeclare it.
5985  NamedDecl *NonTag = 0, *Tag = 0;
5986  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5987         I != E; ++I) {
5988    NamedDecl *D = (*I)->getUnderlyingDecl();
5989    bool Result;
5990    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5991      return Result;
5992
5993    (isa<TagDecl>(D) ? Tag : NonTag) = D;
5994  }
5995
5996  if (Target->isFunctionOrFunctionTemplate()) {
5997    FunctionDecl *FD;
5998    if (isa<FunctionTemplateDecl>(Target))
5999      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6000    else
6001      FD = cast<FunctionDecl>(Target);
6002
6003    NamedDecl *OldDecl = 0;
6004    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6005    case Ovl_Overload:
6006      return false;
6007
6008    case Ovl_NonFunction:
6009      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6010      break;
6011
6012    // We found a decl with the exact signature.
6013    case Ovl_Match:
6014      // If we're in a record, we want to hide the target, so we
6015      // return true (without a diagnostic) to tell the caller not to
6016      // build a shadow decl.
6017      if (CurContext->isRecord())
6018        return true;
6019
6020      // If we're not in a record, this is an error.
6021      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6022      break;
6023    }
6024
6025    Diag(Target->getLocation(), diag::note_using_decl_target);
6026    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6027    return true;
6028  }
6029
6030  // Target is not a function.
6031
6032  if (isa<TagDecl>(Target)) {
6033    // No conflict between a tag and a non-tag.
6034    if (!Tag) return false;
6035
6036    Diag(Using->getLocation(), diag::err_using_decl_conflict);
6037    Diag(Target->getLocation(), diag::note_using_decl_target);
6038    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6039    return true;
6040  }
6041
6042  // No conflict between a tag and a non-tag.
6043  if (!NonTag) return false;
6044
6045  Diag(Using->getLocation(), diag::err_using_decl_conflict);
6046  Diag(Target->getLocation(), diag::note_using_decl_target);
6047  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6048  return true;
6049}
6050
6051/// Builds a shadow declaration corresponding to a 'using' declaration.
6052UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6053                                            UsingDecl *UD,
6054                                            NamedDecl *Orig) {
6055
6056  // If we resolved to another shadow declaration, just coalesce them.
6057  NamedDecl *Target = Orig;
6058  if (isa<UsingShadowDecl>(Target)) {
6059    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6060    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6061  }
6062
6063  UsingShadowDecl *Shadow
6064    = UsingShadowDecl::Create(Context, CurContext,
6065                              UD->getLocation(), UD, Target);
6066  UD->addShadowDecl(Shadow);
6067
6068  Shadow->setAccess(UD->getAccess());
6069  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6070    Shadow->setInvalidDecl();
6071
6072  if (S)
6073    PushOnScopeChains(Shadow, S);
6074  else
6075    CurContext->addDecl(Shadow);
6076
6077
6078  return Shadow;
6079}
6080
6081/// Hides a using shadow declaration.  This is required by the current
6082/// using-decl implementation when a resolvable using declaration in a
6083/// class is followed by a declaration which would hide or override
6084/// one or more of the using decl's targets; for example:
6085///
6086///   struct Base { void foo(int); };
6087///   struct Derived : Base {
6088///     using Base::foo;
6089///     void foo(int);
6090///   };
6091///
6092/// The governing language is C++03 [namespace.udecl]p12:
6093///
6094///   When a using-declaration brings names from a base class into a
6095///   derived class scope, member functions in the derived class
6096///   override and/or hide member functions with the same name and
6097///   parameter types in a base class (rather than conflicting).
6098///
6099/// There are two ways to implement this:
6100///   (1) optimistically create shadow decls when they're not hidden
6101///       by existing declarations, or
6102///   (2) don't create any shadow decls (or at least don't make them
6103///       visible) until we've fully parsed/instantiated the class.
6104/// The problem with (1) is that we might have to retroactively remove
6105/// a shadow decl, which requires several O(n) operations because the
6106/// decl structures are (very reasonably) not designed for removal.
6107/// (2) avoids this but is very fiddly and phase-dependent.
6108void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6109  if (Shadow->getDeclName().getNameKind() ==
6110        DeclarationName::CXXConversionFunctionName)
6111    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6112
6113  // Remove it from the DeclContext...
6114  Shadow->getDeclContext()->removeDecl(Shadow);
6115
6116  // ...and the scope, if applicable...
6117  if (S) {
6118    S->RemoveDecl(Shadow);
6119    IdResolver.RemoveDecl(Shadow);
6120  }
6121
6122  // ...and the using decl.
6123  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6124
6125  // TODO: complain somehow if Shadow was used.  It shouldn't
6126  // be possible for this to happen, because...?
6127}
6128
6129/// Builds a using declaration.
6130///
6131/// \param IsInstantiation - Whether this call arises from an
6132///   instantiation of an unresolved using declaration.  We treat
6133///   the lookup differently for these declarations.
6134NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6135                                       SourceLocation UsingLoc,
6136                                       CXXScopeSpec &SS,
6137                                       const DeclarationNameInfo &NameInfo,
6138                                       AttributeList *AttrList,
6139                                       bool IsInstantiation,
6140                                       bool IsTypeName,
6141                                       SourceLocation TypenameLoc) {
6142  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6143  SourceLocation IdentLoc = NameInfo.getLoc();
6144  assert(IdentLoc.isValid() && "Invalid TargetName location.");
6145
6146  // FIXME: We ignore attributes for now.
6147
6148  if (SS.isEmpty()) {
6149    Diag(IdentLoc, diag::err_using_requires_qualname);
6150    return 0;
6151  }
6152
6153  // Do the redeclaration lookup in the current scope.
6154  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
6155                        ForRedeclaration);
6156  Previous.setHideTags(false);
6157  if (S) {
6158    LookupName(Previous, S);
6159
6160    // It is really dumb that we have to do this.
6161    LookupResult::Filter F = Previous.makeFilter();
6162    while (F.hasNext()) {
6163      NamedDecl *D = F.next();
6164      if (!isDeclInScope(D, CurContext, S))
6165        F.erase();
6166    }
6167    F.done();
6168  } else {
6169    assert(IsInstantiation && "no scope in non-instantiation");
6170    assert(CurContext->isRecord() && "scope not record in instantiation");
6171    LookupQualifiedName(Previous, CurContext);
6172  }
6173
6174  // Check for invalid redeclarations.
6175  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6176    return 0;
6177
6178  // Check for bad qualifiers.
6179  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6180    return 0;
6181
6182  DeclContext *LookupContext = computeDeclContext(SS);
6183  NamedDecl *D;
6184  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6185  if (!LookupContext) {
6186    if (IsTypeName) {
6187      // FIXME: not all declaration name kinds are legal here
6188      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6189                                              UsingLoc, TypenameLoc,
6190                                              QualifierLoc,
6191                                              IdentLoc, NameInfo.getName());
6192    } else {
6193      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6194                                           QualifierLoc, NameInfo);
6195    }
6196  } else {
6197    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6198                          NameInfo, IsTypeName);
6199  }
6200  D->setAccess(AS);
6201  CurContext->addDecl(D);
6202
6203  if (!LookupContext) return D;
6204  UsingDecl *UD = cast<UsingDecl>(D);
6205
6206  if (RequireCompleteDeclContext(SS, LookupContext)) {
6207    UD->setInvalidDecl();
6208    return UD;
6209  }
6210
6211  // The normal rules do not apply to inheriting constructor declarations.
6212  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
6213    if (CheckInheritingConstructorUsingDecl(UD))
6214      UD->setInvalidDecl();
6215    return UD;
6216  }
6217
6218  // Otherwise, look up the target name.
6219
6220  LookupResult R(*this, NameInfo, LookupOrdinaryName);
6221
6222  // Unlike most lookups, we don't always want to hide tag
6223  // declarations: tag names are visible through the using declaration
6224  // even if hidden by ordinary names, *except* in a dependent context
6225  // where it's important for the sanity of two-phase lookup.
6226  if (!IsInstantiation)
6227    R.setHideTags(false);
6228
6229  // For the purposes of this lookup, we have a base object type
6230  // equal to that of the current context.
6231  if (CurContext->isRecord()) {
6232    R.setBaseObjectType(
6233                   Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6234  }
6235
6236  LookupQualifiedName(R, LookupContext);
6237
6238  if (R.empty()) {
6239    Diag(IdentLoc, diag::err_no_member)
6240      << NameInfo.getName() << LookupContext << SS.getRange();
6241    UD->setInvalidDecl();
6242    return UD;
6243  }
6244
6245  if (R.isAmbiguous()) {
6246    UD->setInvalidDecl();
6247    return UD;
6248  }
6249
6250  if (IsTypeName) {
6251    // If we asked for a typename and got a non-type decl, error out.
6252    if (!R.getAsSingle<TypeDecl>()) {
6253      Diag(IdentLoc, diag::err_using_typename_non_type);
6254      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6255        Diag((*I)->getUnderlyingDecl()->getLocation(),
6256             diag::note_using_decl_target);
6257      UD->setInvalidDecl();
6258      return UD;
6259    }
6260  } else {
6261    // If we asked for a non-typename and we got a type, error out,
6262    // but only if this is an instantiation of an unresolved using
6263    // decl.  Otherwise just silently find the type name.
6264    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
6265      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6266      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
6267      UD->setInvalidDecl();
6268      return UD;
6269    }
6270  }
6271
6272  // C++0x N2914 [namespace.udecl]p6:
6273  // A using-declaration shall not name a namespace.
6274  if (R.getAsSingle<NamespaceDecl>()) {
6275    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6276      << SS.getRange();
6277    UD->setInvalidDecl();
6278    return UD;
6279  }
6280
6281  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6282    if (!CheckUsingShadowDecl(UD, *I, Previous))
6283      BuildUsingShadowDecl(S, UD, *I);
6284  }
6285
6286  return UD;
6287}
6288
6289/// Additional checks for a using declaration referring to a constructor name.
6290bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6291  assert(!UD->isTypeName() && "expecting a constructor name");
6292
6293  const Type *SourceType = UD->getQualifier()->getAsType();
6294  assert(SourceType &&
6295         "Using decl naming constructor doesn't have type in scope spec.");
6296  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6297
6298  // Check whether the named type is a direct base class.
6299  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6300  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6301  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6302       BaseIt != BaseE; ++BaseIt) {
6303    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6304    if (CanonicalSourceType == BaseType)
6305      break;
6306    if (BaseIt->getType()->isDependentType())
6307      break;
6308  }
6309
6310  if (BaseIt == BaseE) {
6311    // Did not find SourceType in the bases.
6312    Diag(UD->getUsingLocation(),
6313         diag::err_using_decl_constructor_not_in_direct_base)
6314      << UD->getNameInfo().getSourceRange()
6315      << QualType(SourceType, 0) << TargetClass;
6316    return true;
6317  }
6318
6319  if (!CurContext->isDependentContext())
6320    BaseIt->setInheritConstructors();
6321
6322  return false;
6323}
6324
6325/// Checks that the given using declaration is not an invalid
6326/// redeclaration.  Note that this is checking only for the using decl
6327/// itself, not for any ill-formedness among the UsingShadowDecls.
6328bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6329                                       bool isTypeName,
6330                                       const CXXScopeSpec &SS,
6331                                       SourceLocation NameLoc,
6332                                       const LookupResult &Prev) {
6333  // C++03 [namespace.udecl]p8:
6334  // C++0x [namespace.udecl]p10:
6335  //   A using-declaration is a declaration and can therefore be used
6336  //   repeatedly where (and only where) multiple declarations are
6337  //   allowed.
6338  //
6339  // That's in non-member contexts.
6340  if (!CurContext->getRedeclContext()->isRecord())
6341    return false;
6342
6343  NestedNameSpecifier *Qual
6344    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6345
6346  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6347    NamedDecl *D = *I;
6348
6349    bool DTypename;
6350    NestedNameSpecifier *DQual;
6351    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6352      DTypename = UD->isTypeName();
6353      DQual = UD->getQualifier();
6354    } else if (UnresolvedUsingValueDecl *UD
6355                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6356      DTypename = false;
6357      DQual = UD->getQualifier();
6358    } else if (UnresolvedUsingTypenameDecl *UD
6359                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6360      DTypename = true;
6361      DQual = UD->getQualifier();
6362    } else continue;
6363
6364    // using decls differ if one says 'typename' and the other doesn't.
6365    // FIXME: non-dependent using decls?
6366    if (isTypeName != DTypename) continue;
6367
6368    // using decls differ if they name different scopes (but note that
6369    // template instantiation can cause this check to trigger when it
6370    // didn't before instantiation).
6371    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6372        Context.getCanonicalNestedNameSpecifier(DQual))
6373      continue;
6374
6375    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
6376    Diag(D->getLocation(), diag::note_using_decl) << 1;
6377    return true;
6378  }
6379
6380  return false;
6381}
6382
6383
6384/// Checks that the given nested-name qualifier used in a using decl
6385/// in the current context is appropriately related to the current
6386/// scope.  If an error is found, diagnoses it and returns true.
6387bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6388                                   const CXXScopeSpec &SS,
6389                                   SourceLocation NameLoc) {
6390  DeclContext *NamedContext = computeDeclContext(SS);
6391
6392  if (!CurContext->isRecord()) {
6393    // C++03 [namespace.udecl]p3:
6394    // C++0x [namespace.udecl]p8:
6395    //   A using-declaration for a class member shall be a member-declaration.
6396
6397    // If we weren't able to compute a valid scope, it must be a
6398    // dependent class scope.
6399    if (!NamedContext || NamedContext->isRecord()) {
6400      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6401        << SS.getRange();
6402      return true;
6403    }
6404
6405    // Otherwise, everything is known to be fine.
6406    return false;
6407  }
6408
6409  // The current scope is a record.
6410
6411  // If the named context is dependent, we can't decide much.
6412  if (!NamedContext) {
6413    // FIXME: in C++0x, we can diagnose if we can prove that the
6414    // nested-name-specifier does not refer to a base class, which is
6415    // still possible in some cases.
6416
6417    // Otherwise we have to conservatively report that things might be
6418    // okay.
6419    return false;
6420  }
6421
6422  if (!NamedContext->isRecord()) {
6423    // Ideally this would point at the last name in the specifier,
6424    // but we don't have that level of source info.
6425    Diag(SS.getRange().getBegin(),
6426         diag::err_using_decl_nested_name_specifier_is_not_class)
6427      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6428    return true;
6429  }
6430
6431  if (!NamedContext->isDependentContext() &&
6432      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6433    return true;
6434
6435  if (getLangOpts().CPlusPlus0x) {
6436    // C++0x [namespace.udecl]p3:
6437    //   In a using-declaration used as a member-declaration, the
6438    //   nested-name-specifier shall name a base class of the class
6439    //   being defined.
6440
6441    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6442                                 cast<CXXRecordDecl>(NamedContext))) {
6443      if (CurContext == NamedContext) {
6444        Diag(NameLoc,
6445             diag::err_using_decl_nested_name_specifier_is_current_class)
6446          << SS.getRange();
6447        return true;
6448      }
6449
6450      Diag(SS.getRange().getBegin(),
6451           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6452        << (NestedNameSpecifier*) SS.getScopeRep()
6453        << cast<CXXRecordDecl>(CurContext)
6454        << SS.getRange();
6455      return true;
6456    }
6457
6458    return false;
6459  }
6460
6461  // C++03 [namespace.udecl]p4:
6462  //   A using-declaration used as a member-declaration shall refer
6463  //   to a member of a base class of the class being defined [etc.].
6464
6465  // Salient point: SS doesn't have to name a base class as long as
6466  // lookup only finds members from base classes.  Therefore we can
6467  // diagnose here only if we can prove that that can't happen,
6468  // i.e. if the class hierarchies provably don't intersect.
6469
6470  // TODO: it would be nice if "definitely valid" results were cached
6471  // in the UsingDecl and UsingShadowDecl so that these checks didn't
6472  // need to be repeated.
6473
6474  struct UserData {
6475    llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
6476
6477    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6478      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6479      Data->Bases.insert(Base);
6480      return true;
6481    }
6482
6483    bool hasDependentBases(const CXXRecordDecl *Class) {
6484      return !Class->forallBases(collect, this);
6485    }
6486
6487    /// Returns true if the base is dependent or is one of the
6488    /// accumulated base classes.
6489    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6490      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6491      return !Data->Bases.count(Base);
6492    }
6493
6494    bool mightShareBases(const CXXRecordDecl *Class) {
6495      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6496    }
6497  };
6498
6499  UserData Data;
6500
6501  // Returns false if we find a dependent base.
6502  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6503    return false;
6504
6505  // Returns false if the class has a dependent base or if it or one
6506  // of its bases is present in the base set of the current context.
6507  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6508    return false;
6509
6510  Diag(SS.getRange().getBegin(),
6511       diag::err_using_decl_nested_name_specifier_is_not_base_class)
6512    << (NestedNameSpecifier*) SS.getScopeRep()
6513    << cast<CXXRecordDecl>(CurContext)
6514    << SS.getRange();
6515
6516  return true;
6517}
6518
6519Decl *Sema::ActOnAliasDeclaration(Scope *S,
6520                                  AccessSpecifier AS,
6521                                  MultiTemplateParamsArg TemplateParamLists,
6522                                  SourceLocation UsingLoc,
6523                                  UnqualifiedId &Name,
6524                                  TypeResult Type) {
6525  // Skip up to the relevant declaration scope.
6526  while (S->getFlags() & Scope::TemplateParamScope)
6527    S = S->getParent();
6528  assert((S->getFlags() & Scope::DeclScope) &&
6529         "got alias-declaration outside of declaration scope");
6530
6531  if (Type.isInvalid())
6532    return 0;
6533
6534  bool Invalid = false;
6535  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6536  TypeSourceInfo *TInfo = 0;
6537  GetTypeFromParser(Type.get(), &TInfo);
6538
6539  if (DiagnoseClassNameShadow(CurContext, NameInfo))
6540    return 0;
6541
6542  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
6543                                      UPPC_DeclarationType)) {
6544    Invalid = true;
6545    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6546                                             TInfo->getTypeLoc().getBeginLoc());
6547  }
6548
6549  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6550  LookupName(Previous, S);
6551
6552  // Warn about shadowing the name of a template parameter.
6553  if (Previous.isSingleResult() &&
6554      Previous.getFoundDecl()->isTemplateParameter()) {
6555    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
6556    Previous.clear();
6557  }
6558
6559  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6560         "name in alias declaration must be an identifier");
6561  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6562                                               Name.StartLocation,
6563                                               Name.Identifier, TInfo);
6564
6565  NewTD->setAccess(AS);
6566
6567  if (Invalid)
6568    NewTD->setInvalidDecl();
6569
6570  CheckTypedefForVariablyModifiedType(S, NewTD);
6571  Invalid |= NewTD->isInvalidDecl();
6572
6573  bool Redeclaration = false;
6574
6575  NamedDecl *NewND;
6576  if (TemplateParamLists.size()) {
6577    TypeAliasTemplateDecl *OldDecl = 0;
6578    TemplateParameterList *OldTemplateParams = 0;
6579
6580    if (TemplateParamLists.size() != 1) {
6581      Diag(UsingLoc, diag::err_alias_template_extra_headers)
6582        << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
6583         TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
6584    }
6585    TemplateParameterList *TemplateParams = TemplateParamLists[0];
6586
6587    // Only consider previous declarations in the same scope.
6588    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6589                         /*ExplicitInstantiationOrSpecialization*/false);
6590    if (!Previous.empty()) {
6591      Redeclaration = true;
6592
6593      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6594      if (!OldDecl && !Invalid) {
6595        Diag(UsingLoc, diag::err_redefinition_different_kind)
6596          << Name.Identifier;
6597
6598        NamedDecl *OldD = Previous.getRepresentativeDecl();
6599        if (OldD->getLocation().isValid())
6600          Diag(OldD->getLocation(), diag::note_previous_definition);
6601
6602        Invalid = true;
6603      }
6604
6605      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6606        if (TemplateParameterListsAreEqual(TemplateParams,
6607                                           OldDecl->getTemplateParameters(),
6608                                           /*Complain=*/true,
6609                                           TPL_TemplateMatch))
6610          OldTemplateParams = OldDecl->getTemplateParameters();
6611        else
6612          Invalid = true;
6613
6614        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6615        if (!Invalid &&
6616            !Context.hasSameType(OldTD->getUnderlyingType(),
6617                                 NewTD->getUnderlyingType())) {
6618          // FIXME: The C++0x standard does not clearly say this is ill-formed,
6619          // but we can't reasonably accept it.
6620          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6621            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6622          if (OldTD->getLocation().isValid())
6623            Diag(OldTD->getLocation(), diag::note_previous_definition);
6624          Invalid = true;
6625        }
6626      }
6627    }
6628
6629    // Merge any previous default template arguments into our parameters,
6630    // and check the parameter list.
6631    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6632                                   TPC_TypeAliasTemplate))
6633      return 0;
6634
6635    TypeAliasTemplateDecl *NewDecl =
6636      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6637                                    Name.Identifier, TemplateParams,
6638                                    NewTD);
6639
6640    NewDecl->setAccess(AS);
6641
6642    if (Invalid)
6643      NewDecl->setInvalidDecl();
6644    else if (OldDecl)
6645      NewDecl->setPreviousDeclaration(OldDecl);
6646
6647    NewND = NewDecl;
6648  } else {
6649    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6650    NewND = NewTD;
6651  }
6652
6653  if (!Redeclaration)
6654    PushOnScopeChains(NewND, S);
6655
6656  ActOnDocumentableDecl(NewND);
6657  return NewND;
6658}
6659
6660Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
6661                                             SourceLocation NamespaceLoc,
6662                                             SourceLocation AliasLoc,
6663                                             IdentifierInfo *Alias,
6664                                             CXXScopeSpec &SS,
6665                                             SourceLocation IdentLoc,
6666                                             IdentifierInfo *Ident) {
6667
6668  // Lookup the namespace name.
6669  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6670  LookupParsedName(R, S, &SS);
6671
6672  // Check if we have a previous declaration with the same name.
6673  NamedDecl *PrevDecl
6674    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6675                       ForRedeclaration);
6676  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6677    PrevDecl = 0;
6678
6679  if (PrevDecl) {
6680    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
6681      // We already have an alias with the same name that points to the same
6682      // namespace, so don't create a new one.
6683      // FIXME: At some point, we'll want to create the (redundant)
6684      // declaration to maintain better source information.
6685      if (!R.isAmbiguous() && !R.empty() &&
6686          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
6687        return 0;
6688    }
6689
6690    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6691      diag::err_redefinition_different_kind;
6692    Diag(AliasLoc, DiagID) << Alias;
6693    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6694    return 0;
6695  }
6696
6697  if (R.isAmbiguous())
6698    return 0;
6699
6700  if (R.empty()) {
6701    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
6702      Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6703      return 0;
6704    }
6705  }
6706
6707  NamespaceAliasDecl *AliasDecl =
6708    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
6709                               Alias, SS.getWithLocInContext(Context),
6710                               IdentLoc, R.getFoundDecl());
6711
6712  PushOnScopeChains(AliasDecl, S);
6713  return AliasDecl;
6714}
6715
6716namespace {
6717  /// \brief Scoped object used to handle the state changes required in Sema
6718  /// to implicitly define the body of a C++ member function;
6719  class ImplicitlyDefinedFunctionScope {
6720    Sema &S;
6721    Sema::ContextRAII SavedContext;
6722
6723  public:
6724    ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
6725      : S(S), SavedContext(S, Method)
6726    {
6727      S.PushFunctionScope();
6728      S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6729    }
6730
6731    ~ImplicitlyDefinedFunctionScope() {
6732      S.PopExpressionEvaluationContext();
6733      S.PopFunctionScopeInfo();
6734    }
6735  };
6736}
6737
6738Sema::ImplicitExceptionSpecification
6739Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
6740                                               CXXMethodDecl *MD) {
6741  CXXRecordDecl *ClassDecl = MD->getParent();
6742
6743  // C++ [except.spec]p14:
6744  //   An implicitly declared special member function (Clause 12) shall have an
6745  //   exception-specification. [...]
6746  ImplicitExceptionSpecification ExceptSpec(*this);
6747  if (ClassDecl->isInvalidDecl())
6748    return ExceptSpec;
6749
6750  // Direct base-class constructors.
6751  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6752                                       BEnd = ClassDecl->bases_end();
6753       B != BEnd; ++B) {
6754    if (B->isVirtual()) // Handled below.
6755      continue;
6756
6757    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6758      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6759      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6760      // If this is a deleted function, add it anyway. This might be conformant
6761      // with the standard. This might not. I'm not sure. It might not matter.
6762      if (Constructor)
6763        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
6764    }
6765  }
6766
6767  // Virtual base-class constructors.
6768  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6769                                       BEnd = ClassDecl->vbases_end();
6770       B != BEnd; ++B) {
6771    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6772      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6773      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6774      // If this is a deleted function, add it anyway. This might be conformant
6775      // with the standard. This might not. I'm not sure. It might not matter.
6776      if (Constructor)
6777        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
6778    }
6779  }
6780
6781  // Field constructors.
6782  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6783                               FEnd = ClassDecl->field_end();
6784       F != FEnd; ++F) {
6785    if (F->hasInClassInitializer()) {
6786      if (Expr *E = F->getInClassInitializer())
6787        ExceptSpec.CalledExpr(E);
6788      else if (!F->isInvalidDecl())
6789        // DR1351:
6790        //   If the brace-or-equal-initializer of a non-static data member
6791        //   invokes a defaulted default constructor of its class or of an
6792        //   enclosing class in a potentially evaluated subexpression, the
6793        //   program is ill-formed.
6794        //
6795        // This resolution is unworkable: the exception specification of the
6796        // default constructor can be needed in an unevaluated context, in
6797        // particular, in the operand of a noexcept-expression, and we can be
6798        // unable to compute an exception specification for an enclosed class.
6799        //
6800        // We do not allow an in-class initializer to require the evaluation
6801        // of the exception specification for any in-class initializer whose
6802        // definition is not lexically complete.
6803        Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
6804    } else if (const RecordType *RecordTy
6805              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
6806      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6807      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6808      // If this is a deleted function, add it anyway. This might be conformant
6809      // with the standard. This might not. I'm not sure. It might not matter.
6810      // In particular, the problem is that this function never gets called. It
6811      // might just be ill-formed because this function attempts to refer to
6812      // a deleted function here.
6813      if (Constructor)
6814        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
6815    }
6816  }
6817
6818  return ExceptSpec;
6819}
6820
6821CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6822                                                     CXXRecordDecl *ClassDecl) {
6823  // C++ [class.ctor]p5:
6824  //   A default constructor for a class X is a constructor of class X
6825  //   that can be called without an argument. If there is no
6826  //   user-declared constructor for class X, a default constructor is
6827  //   implicitly declared. An implicitly-declared default constructor
6828  //   is an inline public member of its class.
6829  assert(!ClassDecl->hasUserDeclaredConstructor() &&
6830         "Should not build implicit default constructor!");
6831
6832  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
6833                                                     CXXDefaultConstructor,
6834                                                     false);
6835
6836  // Create the actual constructor declaration.
6837  CanQualType ClassType
6838    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6839  SourceLocation ClassLoc = ClassDecl->getLocation();
6840  DeclarationName Name
6841    = Context.DeclarationNames.getCXXConstructorName(ClassType);
6842  DeclarationNameInfo NameInfo(Name, ClassLoc);
6843  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6844      Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
6845      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
6846      Constexpr);
6847  DefaultCon->setAccess(AS_public);
6848  DefaultCon->setDefaulted();
6849  DefaultCon->setImplicit();
6850  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
6851
6852  // Build an exception specification pointing back at this constructor.
6853  FunctionProtoType::ExtProtoInfo EPI;
6854  EPI.ExceptionSpecType = EST_Unevaluated;
6855  EPI.ExceptionSpecDecl = DefaultCon;
6856  DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6857
6858  // Note that we have declared this constructor.
6859  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6860
6861  if (Scope *S = getScopeForContext(ClassDecl))
6862    PushOnScopeChains(DefaultCon, S, false);
6863  ClassDecl->addDecl(DefaultCon);
6864
6865  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
6866    DefaultCon->setDeletedAsWritten();
6867
6868  return DefaultCon;
6869}
6870
6871void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6872                                            CXXConstructorDecl *Constructor) {
6873  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6874          !Constructor->doesThisDeclarationHaveABody() &&
6875          !Constructor->isDeleted()) &&
6876    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
6877
6878  CXXRecordDecl *ClassDecl = Constructor->getParent();
6879  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
6880
6881  ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
6882  DiagnosticErrorTrap Trap(Diags);
6883  if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
6884      Trap.hasErrorOccurred()) {
6885    Diag(CurrentLocation, diag::note_member_synthesized_at)
6886      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
6887    Constructor->setInvalidDecl();
6888    return;
6889  }
6890
6891  SourceLocation Loc = Constructor->getLocation();
6892  Constructor->setBody(new (Context) CompoundStmt(Loc));
6893
6894  Constructor->setUsed();
6895  MarkVTableUsed(CurrentLocation, ClassDecl);
6896
6897  if (ASTMutationListener *L = getASTMutationListener()) {
6898    L->CompletedImplicitDefinition(Constructor);
6899  }
6900}
6901
6902void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6903  if (!D) return;
6904  AdjustDeclIfTemplate(D);
6905
6906  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6907
6908  if (!ClassDecl->isDependentType())
6909    CheckExplicitlyDefaultedMethods(ClassDecl);
6910}
6911
6912void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6913  // We start with an initial pass over the base classes to collect those that
6914  // inherit constructors from. If there are none, we can forgo all further
6915  // processing.
6916  typedef SmallVector<const RecordType *, 4> BasesVector;
6917  BasesVector BasesToInheritFrom;
6918  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6919                                          BaseE = ClassDecl->bases_end();
6920         BaseIt != BaseE; ++BaseIt) {
6921    if (BaseIt->getInheritConstructors()) {
6922      QualType Base = BaseIt->getType();
6923      if (Base->isDependentType()) {
6924        // If we inherit constructors from anything that is dependent, just
6925        // abort processing altogether. We'll get another chance for the
6926        // instantiations.
6927        return;
6928      }
6929      BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6930    }
6931  }
6932  if (BasesToInheritFrom.empty())
6933    return;
6934
6935  // Now collect the constructors that we already have in the current class.
6936  // Those take precedence over inherited constructors.
6937  // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6938  //   unless there is a user-declared constructor with the same signature in
6939  //   the class where the using-declaration appears.
6940  llvm::SmallSet<const Type *, 8> ExistingConstructors;
6941  for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6942                                    CtorE = ClassDecl->ctor_end();
6943       CtorIt != CtorE; ++CtorIt) {
6944    ExistingConstructors.insert(
6945        Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6946  }
6947
6948  DeclarationName CreatedCtorName =
6949      Context.DeclarationNames.getCXXConstructorName(
6950          ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6951
6952  // Now comes the true work.
6953  // First, we keep a map from constructor types to the base that introduced
6954  // them. Needed for finding conflicting constructors. We also keep the
6955  // actually inserted declarations in there, for pretty diagnostics.
6956  typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6957  typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6958  ConstructorToSourceMap InheritedConstructors;
6959  for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6960                             BaseE = BasesToInheritFrom.end();
6961       BaseIt != BaseE; ++BaseIt) {
6962    const RecordType *Base = *BaseIt;
6963    CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6964    CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6965    for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6966                                      CtorE = BaseDecl->ctor_end();
6967         CtorIt != CtorE; ++CtorIt) {
6968      // Find the using declaration for inheriting this base's constructors.
6969      // FIXME: Don't perform name lookup just to obtain a source location!
6970      DeclarationName Name =
6971          Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6972      LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
6973      LookupQualifiedName(Result, CurContext);
6974      UsingDecl *UD = Result.getAsSingle<UsingDecl>();
6975      SourceLocation UsingLoc = UD ? UD->getLocation() :
6976                                     ClassDecl->getLocation();
6977
6978      // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6979      //   from the class X named in the using-declaration consists of actual
6980      //   constructors and notional constructors that result from the
6981      //   transformation of defaulted parameters as follows:
6982      //   - all non-template default constructors of X, and
6983      //   - for each non-template constructor of X that has at least one
6984      //     parameter with a default argument, the set of constructors that
6985      //     results from omitting any ellipsis parameter specification and
6986      //     successively omitting parameters with a default argument from the
6987      //     end of the parameter-type-list.
6988      CXXConstructorDecl *BaseCtor = *CtorIt;
6989      bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6990      const FunctionProtoType *BaseCtorType =
6991          BaseCtor->getType()->getAs<FunctionProtoType>();
6992
6993      for (unsigned params = BaseCtor->getMinRequiredArguments(),
6994                    maxParams = BaseCtor->getNumParams();
6995           params <= maxParams; ++params) {
6996        // Skip default constructors. They're never inherited.
6997        if (params == 0)
6998          continue;
6999        // Skip copy and move constructors for the same reason.
7000        if (CanBeCopyOrMove && params == 1)
7001          continue;
7002
7003        // Build up a function type for this particular constructor.
7004        // FIXME: The working paper does not consider that the exception spec
7005        // for the inheriting constructor might be larger than that of the
7006        // source. This code doesn't yet, either. When it does, this code will
7007        // need to be delayed until after exception specifications and in-class
7008        // member initializers are attached.
7009        const Type *NewCtorType;
7010        if (params == maxParams)
7011          NewCtorType = BaseCtorType;
7012        else {
7013          SmallVector<QualType, 16> Args;
7014          for (unsigned i = 0; i < params; ++i) {
7015            Args.push_back(BaseCtorType->getArgType(i));
7016          }
7017          FunctionProtoType::ExtProtoInfo ExtInfo =
7018              BaseCtorType->getExtProtoInfo();
7019          ExtInfo.Variadic = false;
7020          NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7021                                                Args.data(), params, ExtInfo)
7022                       .getTypePtr();
7023        }
7024        const Type *CanonicalNewCtorType =
7025            Context.getCanonicalType(NewCtorType);
7026
7027        // Now that we have the type, first check if the class already has a
7028        // constructor with this signature.
7029        if (ExistingConstructors.count(CanonicalNewCtorType))
7030          continue;
7031
7032        // Then we check if we have already declared an inherited constructor
7033        // with this signature.
7034        std::pair<ConstructorToSourceMap::iterator, bool> result =
7035            InheritedConstructors.insert(std::make_pair(
7036                CanonicalNewCtorType,
7037                std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7038        if (!result.second) {
7039          // Already in the map. If it came from a different class, that's an
7040          // error. Not if it's from the same.
7041          CanQualType PreviousBase = result.first->second.first;
7042          if (CanonicalBase != PreviousBase) {
7043            const CXXConstructorDecl *PrevCtor = result.first->second.second;
7044            const CXXConstructorDecl *PrevBaseCtor =
7045                PrevCtor->getInheritedConstructor();
7046            assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7047
7048            Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7049            Diag(BaseCtor->getLocation(),
7050                 diag::note_using_decl_constructor_conflict_current_ctor);
7051            Diag(PrevBaseCtor->getLocation(),
7052                 diag::note_using_decl_constructor_conflict_previous_ctor);
7053            Diag(PrevCtor->getLocation(),
7054                 diag::note_using_decl_constructor_conflict_previous_using);
7055          }
7056          continue;
7057        }
7058
7059        // OK, we're there, now add the constructor.
7060        // C++0x [class.inhctor]p8: [...] that would be performed by a
7061        //   user-written inline constructor [...]
7062        DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7063        CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
7064            Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7065            /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
7066            /*ImplicitlyDeclared=*/true,
7067            // FIXME: Due to a defect in the standard, we treat inherited
7068            // constructors as constexpr even if that makes them ill-formed.
7069            /*Constexpr=*/BaseCtor->isConstexpr());
7070        NewCtor->setAccess(BaseCtor->getAccess());
7071
7072        // Build up the parameter decls and add them.
7073        SmallVector<ParmVarDecl *, 16> ParamDecls;
7074        for (unsigned i = 0; i < params; ++i) {
7075          ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7076                                                   UsingLoc, UsingLoc,
7077                                                   /*IdentifierInfo=*/0,
7078                                                   BaseCtorType->getArgType(i),
7079                                                   /*TInfo=*/0, SC_None,
7080                                                   SC_None, /*DefaultArg=*/0));
7081        }
7082        NewCtor->setParams(ParamDecls);
7083        NewCtor->setInheritedConstructor(BaseCtor);
7084
7085        ClassDecl->addDecl(NewCtor);
7086        result.first->second.second = NewCtor;
7087      }
7088    }
7089  }
7090}
7091
7092Sema::ImplicitExceptionSpecification
7093Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7094  CXXRecordDecl *ClassDecl = MD->getParent();
7095
7096  // C++ [except.spec]p14:
7097  //   An implicitly declared special member function (Clause 12) shall have
7098  //   an exception-specification.
7099  ImplicitExceptionSpecification ExceptSpec(*this);
7100  if (ClassDecl->isInvalidDecl())
7101    return ExceptSpec;
7102
7103  // Direct base-class destructors.
7104  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7105                                       BEnd = ClassDecl->bases_end();
7106       B != BEnd; ++B) {
7107    if (B->isVirtual()) // Handled below.
7108      continue;
7109
7110    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7111      ExceptSpec.CalledDecl(B->getLocStart(),
7112                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7113  }
7114
7115  // Virtual base-class destructors.
7116  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7117                                       BEnd = ClassDecl->vbases_end();
7118       B != BEnd; ++B) {
7119    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7120      ExceptSpec.CalledDecl(B->getLocStart(),
7121                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7122  }
7123
7124  // Field destructors.
7125  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7126                               FEnd = ClassDecl->field_end();
7127       F != FEnd; ++F) {
7128    if (const RecordType *RecordTy
7129        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7130      ExceptSpec.CalledDecl(F->getLocation(),
7131                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
7132  }
7133
7134  return ExceptSpec;
7135}
7136
7137CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7138  // C++ [class.dtor]p2:
7139  //   If a class has no user-declared destructor, a destructor is
7140  //   declared implicitly. An implicitly-declared destructor is an
7141  //   inline public member of its class.
7142
7143  // Create the actual destructor declaration.
7144  CanQualType ClassType
7145    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7146  SourceLocation ClassLoc = ClassDecl->getLocation();
7147  DeclarationName Name
7148    = Context.DeclarationNames.getCXXDestructorName(ClassType);
7149  DeclarationNameInfo NameInfo(Name, ClassLoc);
7150  CXXDestructorDecl *Destructor
7151      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7152                                  QualType(), 0, /*isInline=*/true,
7153                                  /*isImplicitlyDeclared=*/true);
7154  Destructor->setAccess(AS_public);
7155  Destructor->setDefaulted();
7156  Destructor->setImplicit();
7157  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7158
7159  // Build an exception specification pointing back at this destructor.
7160  FunctionProtoType::ExtProtoInfo EPI;
7161  EPI.ExceptionSpecType = EST_Unevaluated;
7162  EPI.ExceptionSpecDecl = Destructor;
7163  Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7164
7165  // Note that we have declared this destructor.
7166  ++ASTContext::NumImplicitDestructorsDeclared;
7167
7168  // Introduce this destructor into its scope.
7169  if (Scope *S = getScopeForContext(ClassDecl))
7170    PushOnScopeChains(Destructor, S, false);
7171  ClassDecl->addDecl(Destructor);
7172
7173  AddOverriddenMethods(ClassDecl, Destructor);
7174
7175  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7176    Destructor->setDeletedAsWritten();
7177
7178  return Destructor;
7179}
7180
7181void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
7182                                    CXXDestructorDecl *Destructor) {
7183  assert((Destructor->isDefaulted() &&
7184          !Destructor->doesThisDeclarationHaveABody() &&
7185          !Destructor->isDeleted()) &&
7186         "DefineImplicitDestructor - call it for implicit default dtor");
7187  CXXRecordDecl *ClassDecl = Destructor->getParent();
7188  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
7189
7190  if (Destructor->isInvalidDecl())
7191    return;
7192
7193  ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
7194
7195  DiagnosticErrorTrap Trap(Diags);
7196  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7197                                         Destructor->getParent());
7198
7199  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
7200    Diag(CurrentLocation, diag::note_member_synthesized_at)
7201      << CXXDestructor << Context.getTagDeclType(ClassDecl);
7202
7203    Destructor->setInvalidDecl();
7204    return;
7205  }
7206
7207  SourceLocation Loc = Destructor->getLocation();
7208  Destructor->setBody(new (Context) CompoundStmt(Loc));
7209  Destructor->setImplicitlyDefined(true);
7210  Destructor->setUsed();
7211  MarkVTableUsed(CurrentLocation, ClassDecl);
7212
7213  if (ASTMutationListener *L = getASTMutationListener()) {
7214    L->CompletedImplicitDefinition(Destructor);
7215  }
7216}
7217
7218/// \brief Perform any semantic analysis which needs to be delayed until all
7219/// pending class member declarations have been parsed.
7220void Sema::ActOnFinishCXXMemberDecls() {
7221  // Perform any deferred checking of exception specifications for virtual
7222  // destructors.
7223  for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7224       i != e; ++i) {
7225    const CXXDestructorDecl *Dtor =
7226        DelayedDestructorExceptionSpecChecks[i].first;
7227    assert(!Dtor->getParent()->isDependentType() &&
7228           "Should not ever add destructors of templates into the list.");
7229    CheckOverridingFunctionExceptionSpec(Dtor,
7230        DelayedDestructorExceptionSpecChecks[i].second);
7231  }
7232  DelayedDestructorExceptionSpecChecks.clear();
7233}
7234
7235void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7236                                         CXXDestructorDecl *Destructor) {
7237  assert(getLangOpts().CPlusPlus0x &&
7238         "adjusting dtor exception specs was introduced in c++11");
7239
7240  // C++11 [class.dtor]p3:
7241  //   A declaration of a destructor that does not have an exception-
7242  //   specification is implicitly considered to have the same exception-
7243  //   specification as an implicit declaration.
7244  const FunctionProtoType *DtorType = Destructor->getType()->
7245                                        getAs<FunctionProtoType>();
7246  if (DtorType->hasExceptionSpec())
7247    return;
7248
7249  // Replace the destructor's type, building off the existing one. Fortunately,
7250  // the only thing of interest in the destructor type is its extended info.
7251  // The return and arguments are fixed.
7252  FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7253  EPI.ExceptionSpecType = EST_Unevaluated;
7254  EPI.ExceptionSpecDecl = Destructor;
7255  Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7256
7257  // FIXME: If the destructor has a body that could throw, and the newly created
7258  // spec doesn't allow exceptions, we should emit a warning, because this
7259  // change in behavior can break conforming C++03 programs at runtime.
7260  // However, we don't have a body or an exception specification yet, so it
7261  // needs to be done somewhere else.
7262}
7263
7264/// \brief Builds a statement that copies/moves the given entity from \p From to
7265/// \c To.
7266///
7267/// This routine is used to copy/move the members of a class with an
7268/// implicitly-declared copy/move assignment operator. When the entities being
7269/// copied are arrays, this routine builds for loops to copy them.
7270///
7271/// \param S The Sema object used for type-checking.
7272///
7273/// \param Loc The location where the implicit copy/move is being generated.
7274///
7275/// \param T The type of the expressions being copied/moved. Both expressions
7276/// must have this type.
7277///
7278/// \param To The expression we are copying/moving to.
7279///
7280/// \param From The expression we are copying/moving from.
7281///
7282/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
7283/// Otherwise, it's a non-static member subobject.
7284///
7285/// \param Copying Whether we're copying or moving.
7286///
7287/// \param Depth Internal parameter recording the depth of the recursion.
7288///
7289/// \returns A statement or a loop that copies the expressions.
7290static StmtResult
7291BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
7292                      Expr *To, Expr *From,
7293                      bool CopyingBaseSubobject, bool Copying,
7294                      unsigned Depth = 0) {
7295  // C++0x [class.copy]p28:
7296  //   Each subobject is assigned in the manner appropriate to its type:
7297  //
7298  //     - if the subobject is of class type, as if by a call to operator= with
7299  //       the subobject as the object expression and the corresponding
7300  //       subobject of x as a single function argument (as if by explicit
7301  //       qualification; that is, ignoring any possible virtual overriding
7302  //       functions in more derived classes);
7303  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7304    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7305
7306    // Look for operator=.
7307    DeclarationName Name
7308      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7309    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7310    S.LookupQualifiedName(OpLookup, ClassDecl, false);
7311
7312    // Filter out any result that isn't a copy/move-assignment operator.
7313    LookupResult::Filter F = OpLookup.makeFilter();
7314    while (F.hasNext()) {
7315      NamedDecl *D = F.next();
7316      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
7317        if (Method->isCopyAssignmentOperator() ||
7318            (!Copying && Method->isMoveAssignmentOperator()))
7319          continue;
7320
7321      F.erase();
7322    }
7323    F.done();
7324
7325    // Suppress the protected check (C++ [class.protected]) for each of the
7326    // assignment operators we found. This strange dance is required when
7327    // we're assigning via a base classes's copy-assignment operator. To
7328    // ensure that we're getting the right base class subobject (without
7329    // ambiguities), we need to cast "this" to that subobject type; to
7330    // ensure that we don't go through the virtual call mechanism, we need
7331    // to qualify the operator= name with the base class (see below). However,
7332    // this means that if the base class has a protected copy assignment
7333    // operator, the protected member access check will fail. So, we
7334    // rewrite "protected" access to "public" access in this case, since we
7335    // know by construction that we're calling from a derived class.
7336    if (CopyingBaseSubobject) {
7337      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7338           L != LEnd; ++L) {
7339        if (L.getAccess() == AS_protected)
7340          L.setAccess(AS_public);
7341      }
7342    }
7343
7344    // Create the nested-name-specifier that will be used to qualify the
7345    // reference to operator=; this is required to suppress the virtual
7346    // call mechanism.
7347    CXXScopeSpec SS;
7348    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
7349    SS.MakeTrivial(S.Context,
7350                   NestedNameSpecifier::Create(S.Context, 0, false,
7351                                               CanonicalT),
7352                   Loc);
7353
7354    // Create the reference to operator=.
7355    ExprResult OpEqualRef
7356      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
7357                                   /*TemplateKWLoc=*/SourceLocation(),
7358                                   /*FirstQualifierInScope=*/0,
7359                                   OpLookup,
7360                                   /*TemplateArgs=*/0,
7361                                   /*SuppressQualifierCheck=*/true);
7362    if (OpEqualRef.isInvalid())
7363      return StmtError();
7364
7365    // Build the call to the assignment operator.
7366
7367    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
7368                                                  OpEqualRef.takeAs<Expr>(),
7369                                                  Loc, &From, 1, Loc);
7370    if (Call.isInvalid())
7371      return StmtError();
7372
7373    return S.Owned(Call.takeAs<Stmt>());
7374  }
7375
7376  //     - if the subobject is of scalar type, the built-in assignment
7377  //       operator is used.
7378  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7379  if (!ArrayTy) {
7380    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
7381    if (Assignment.isInvalid())
7382      return StmtError();
7383
7384    return S.Owned(Assignment.takeAs<Stmt>());
7385  }
7386
7387  //     - if the subobject is an array, each element is assigned, in the
7388  //       manner appropriate to the element type;
7389
7390  // Construct a loop over the array bounds, e.g.,
7391  //
7392  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7393  //
7394  // that will copy each of the array elements.
7395  QualType SizeType = S.Context.getSizeType();
7396
7397  // Create the iteration variable.
7398  IdentifierInfo *IterationVarName = 0;
7399  {
7400    SmallString<8> Str;
7401    llvm::raw_svector_ostream OS(Str);
7402    OS << "__i" << Depth;
7403    IterationVarName = &S.Context.Idents.get(OS.str());
7404  }
7405  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
7406                                          IterationVarName, SizeType,
7407                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
7408                                          SC_None, SC_None);
7409
7410  // Initialize the iteration variable to zero.
7411  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
7412  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
7413
7414  // Create a reference to the iteration variable; we'll use this several
7415  // times throughout.
7416  Expr *IterationVarRef
7417    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
7418  assert(IterationVarRef && "Reference to invented variable cannot fail!");
7419  Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7420  assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7421
7422  // Create the DeclStmt that holds the iteration variable.
7423  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7424
7425  // Create the comparison against the array bound.
7426  llvm::APInt Upper
7427    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
7428  Expr *Comparison
7429    = new (S.Context) BinaryOperator(IterationVarRefRVal,
7430                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7431                                     BO_NE, S.Context.BoolTy,
7432                                     VK_RValue, OK_Ordinary, Loc);
7433
7434  // Create the pre-increment of the iteration variable.
7435  Expr *Increment
7436    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7437                                    VK_LValue, OK_Ordinary, Loc);
7438
7439  // Subscript the "from" and "to" expressions with the iteration variable.
7440  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7441                                                         IterationVarRefRVal,
7442                                                         Loc));
7443  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7444                                                       IterationVarRefRVal,
7445                                                       Loc));
7446  if (!Copying) // Cast to rvalue
7447    From = CastForMoving(S, From);
7448
7449  // Build the copy/move for an individual element of the array.
7450  StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7451                                          To, From, CopyingBaseSubobject,
7452                                          Copying, Depth + 1);
7453  if (Copy.isInvalid())
7454    return StmtError();
7455
7456  // Construct the loop that copies all elements of this array.
7457  return S.ActOnForStmt(Loc, Loc, InitStmt,
7458                        S.MakeFullExpr(Comparison),
7459                        0, S.MakeFullExpr(Increment),
7460                        Loc, Copy.take());
7461}
7462
7463/// Determine whether an implicit copy assignment operator for ClassDecl has a
7464/// const argument.
7465/// FIXME: It ought to be possible to store this on the record.
7466static bool isImplicitCopyAssignmentArgConst(Sema &S,
7467                                             CXXRecordDecl *ClassDecl) {
7468  if (ClassDecl->isInvalidDecl())
7469    return true;
7470
7471  // C++ [class.copy]p10:
7472  //   If the class definition does not explicitly declare a copy
7473  //   assignment operator, one is declared implicitly.
7474  //   The implicitly-defined copy assignment operator for a class X
7475  //   will have the form
7476  //
7477  //       X& X::operator=(const X&)
7478  //
7479  //   if
7480  //       -- each direct base class B of X has a copy assignment operator
7481  //          whose parameter is of type const B&, const volatile B& or B,
7482  //          and
7483  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7484                                       BaseEnd = ClassDecl->bases_end();
7485       Base != BaseEnd; ++Base) {
7486    // We'll handle this below
7487    if (S.getLangOpts().CPlusPlus0x && Base->isVirtual())
7488      continue;
7489
7490    assert(!Base->getType()->isDependentType() &&
7491           "Cannot generate implicit members for class with dependent bases.");
7492    CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7493    if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0))
7494      return false;
7495  }
7496
7497  // In C++11, the above citation has "or virtual" added
7498  if (S.getLangOpts().CPlusPlus0x) {
7499    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7500                                         BaseEnd = ClassDecl->vbases_end();
7501         Base != BaseEnd; ++Base) {
7502      assert(!Base->getType()->isDependentType() &&
7503             "Cannot generate implicit members for class with dependent bases.");
7504      CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7505      if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7506                                     false, 0))
7507        return false;
7508    }
7509  }
7510
7511  //       -- for all the nonstatic data members of X that are of a class
7512  //          type M (or array thereof), each such class type has a copy
7513  //          assignment operator whose parameter is of type const M&,
7514  //          const volatile M& or M.
7515  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7516                                  FieldEnd = ClassDecl->field_end();
7517       Field != FieldEnd; ++Field) {
7518    QualType FieldType = S.Context.getBaseElementType(Field->getType());
7519    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl())
7520      if (!S.LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const,
7521                                     false, 0))
7522        return false;
7523  }
7524
7525  //   Otherwise, the implicitly declared copy assignment operator will
7526  //   have the form
7527  //
7528  //       X& X::operator=(X&)
7529
7530  return true;
7531}
7532
7533Sema::ImplicitExceptionSpecification
7534Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
7535  CXXRecordDecl *ClassDecl = MD->getParent();
7536
7537  ImplicitExceptionSpecification ExceptSpec(*this);
7538  if (ClassDecl->isInvalidDecl())
7539    return ExceptSpec;
7540
7541  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
7542  assert(T->getNumArgs() == 1 && "not a copy assignment op");
7543  unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
7544
7545  // C++ [except.spec]p14:
7546  //   An implicitly declared special member function (Clause 12) shall have an
7547  //   exception-specification. [...]
7548
7549  // It is unspecified whether or not an implicit copy assignment operator
7550  // attempts to deduplicate calls to assignment operators of virtual bases are
7551  // made. As such, this exception specification is effectively unspecified.
7552  // Based on a similar decision made for constness in C++0x, we're erring on
7553  // the side of assuming such calls to be made regardless of whether they
7554  // actually happen.
7555  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7556                                       BaseEnd = ClassDecl->bases_end();
7557       Base != BaseEnd; ++Base) {
7558    if (Base->isVirtual())
7559      continue;
7560
7561    CXXRecordDecl *BaseClassDecl
7562      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7563    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7564                                                            ArgQuals, false, 0))
7565      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
7566  }
7567
7568  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7569                                       BaseEnd = ClassDecl->vbases_end();
7570       Base != BaseEnd; ++Base) {
7571    CXXRecordDecl *BaseClassDecl
7572      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7573    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7574                                                            ArgQuals, false, 0))
7575      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
7576  }
7577
7578  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7579                                  FieldEnd = ClassDecl->field_end();
7580       Field != FieldEnd;
7581       ++Field) {
7582    QualType FieldType = Context.getBaseElementType(Field->getType());
7583    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7584      if (CXXMethodDecl *CopyAssign =
7585          LookupCopyingAssignment(FieldClassDecl,
7586                                  ArgQuals | FieldType.getCVRQualifiers(),
7587                                  false, 0))
7588        ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
7589    }
7590  }
7591
7592  return ExceptSpec;
7593}
7594
7595CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7596  // Note: The following rules are largely analoguous to the copy
7597  // constructor rules. Note that virtual bases are not taken into account
7598  // for determining the argument type of the operator. Note also that
7599  // operators taking an object instead of a reference are allowed.
7600
7601  QualType ArgType = Context.getTypeDeclType(ClassDecl);
7602  QualType RetType = Context.getLValueReferenceType(ArgType);
7603  if (isImplicitCopyAssignmentArgConst(*this, ClassDecl))
7604    ArgType = ArgType.withConst();
7605  ArgType = Context.getLValueReferenceType(ArgType);
7606
7607  //   An implicitly-declared copy assignment operator is an inline public
7608  //   member of its class.
7609  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7610  SourceLocation ClassLoc = ClassDecl->getLocation();
7611  DeclarationNameInfo NameInfo(Name, ClassLoc);
7612  CXXMethodDecl *CopyAssignment
7613    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
7614                            /*TInfo=*/0, /*isStatic=*/false,
7615                            /*StorageClassAsWritten=*/SC_None,
7616                            /*isInline=*/true, /*isConstexpr=*/false,
7617                            SourceLocation());
7618  CopyAssignment->setAccess(AS_public);
7619  CopyAssignment->setDefaulted();
7620  CopyAssignment->setImplicit();
7621  CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
7622
7623  // Build an exception specification pointing back at this member.
7624  FunctionProtoType::ExtProtoInfo EPI;
7625  EPI.ExceptionSpecType = EST_Unevaluated;
7626  EPI.ExceptionSpecDecl = CopyAssignment;
7627  CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
7628
7629  // Add the parameter to the operator.
7630  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
7631                                               ClassLoc, ClassLoc, /*Id=*/0,
7632                                               ArgType, /*TInfo=*/0,
7633                                               SC_None,
7634                                               SC_None, 0);
7635  CopyAssignment->setParams(FromParam);
7636
7637  // Note that we have added this copy-assignment operator.
7638  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
7639
7640  if (Scope *S = getScopeForContext(ClassDecl))
7641    PushOnScopeChains(CopyAssignment, S, false);
7642  ClassDecl->addDecl(CopyAssignment);
7643
7644  // C++0x [class.copy]p19:
7645  //   ....  If the class definition does not explicitly declare a copy
7646  //   assignment operator, there is no user-declared move constructor, and
7647  //   there is no user-declared move assignment operator, a copy assignment
7648  //   operator is implicitly declared as defaulted.
7649  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
7650    CopyAssignment->setDeletedAsWritten();
7651
7652  AddOverriddenMethods(ClassDecl, CopyAssignment);
7653  return CopyAssignment;
7654}
7655
7656void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7657                                        CXXMethodDecl *CopyAssignOperator) {
7658  assert((CopyAssignOperator->isDefaulted() &&
7659          CopyAssignOperator->isOverloadedOperator() &&
7660          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
7661          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7662          !CopyAssignOperator->isDeleted()) &&
7663         "DefineImplicitCopyAssignment called for wrong function");
7664
7665  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7666
7667  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7668    CopyAssignOperator->setInvalidDecl();
7669    return;
7670  }
7671
7672  CopyAssignOperator->setUsed();
7673
7674  ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
7675  DiagnosticErrorTrap Trap(Diags);
7676
7677  // C++0x [class.copy]p30:
7678  //   The implicitly-defined or explicitly-defaulted copy assignment operator
7679  //   for a non-union class X performs memberwise copy assignment of its
7680  //   subobjects. The direct base classes of X are assigned first, in the
7681  //   order of their declaration in the base-specifier-list, and then the
7682  //   immediate non-static data members of X are assigned, in the order in
7683  //   which they were declared in the class definition.
7684
7685  // The statements that form the synthesized function body.
7686  SmallVector<Stmt*, 8> Statements;
7687
7688  // The parameter for the "other" object, which we are copying from.
7689  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7690  Qualifiers OtherQuals = Other->getType().getQualifiers();
7691  QualType OtherRefType = Other->getType();
7692  if (const LValueReferenceType *OtherRef
7693                                = OtherRefType->getAs<LValueReferenceType>()) {
7694    OtherRefType = OtherRef->getPointeeType();
7695    OtherQuals = OtherRefType.getQualifiers();
7696  }
7697
7698  // Our location for everything implicitly-generated.
7699  SourceLocation Loc = CopyAssignOperator->getLocation();
7700
7701  // Construct a reference to the "other" object. We'll be using this
7702  // throughout the generated ASTs.
7703  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7704  assert(OtherRef && "Reference to parameter cannot fail!");
7705
7706  // Construct the "this" pointer. We'll be using this throughout the generated
7707  // ASTs.
7708  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7709  assert(This && "Reference to this cannot fail!");
7710
7711  // Assign base classes.
7712  bool Invalid = false;
7713  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7714       E = ClassDecl->bases_end(); Base != E; ++Base) {
7715    // Form the assignment:
7716    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7717    QualType BaseType = Base->getType().getUnqualifiedType();
7718    if (!BaseType->isRecordType()) {
7719      Invalid = true;
7720      continue;
7721    }
7722
7723    CXXCastPath BasePath;
7724    BasePath.push_back(Base);
7725
7726    // Construct the "from" expression, which is an implicit cast to the
7727    // appropriately-qualified base type.
7728    Expr *From = OtherRef;
7729    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7730                             CK_UncheckedDerivedToBase,
7731                             VK_LValue, &BasePath).take();
7732
7733    // Dereference "this".
7734    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7735
7736    // Implicitly cast "this" to the appropriately-qualified base type.
7737    To = ImpCastExprToType(To.take(),
7738                           Context.getCVRQualifiedType(BaseType,
7739                                     CopyAssignOperator->getTypeQualifiers()),
7740                           CK_UncheckedDerivedToBase,
7741                           VK_LValue, &BasePath);
7742
7743    // Build the copy.
7744    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
7745                                            To.get(), From,
7746                                            /*CopyingBaseSubobject=*/true,
7747                                            /*Copying=*/true);
7748    if (Copy.isInvalid()) {
7749      Diag(CurrentLocation, diag::note_member_synthesized_at)
7750        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7751      CopyAssignOperator->setInvalidDecl();
7752      return;
7753    }
7754
7755    // Success! Record the copy.
7756    Statements.push_back(Copy.takeAs<Expr>());
7757  }
7758
7759  // \brief Reference to the __builtin_memcpy function.
7760  Expr *BuiltinMemCpyRef = 0;
7761  // \brief Reference to the __builtin_objc_memmove_collectable function.
7762  Expr *CollectableMemCpyRef = 0;
7763
7764  // Assign non-static members.
7765  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7766                                  FieldEnd = ClassDecl->field_end();
7767       Field != FieldEnd; ++Field) {
7768    if (Field->isUnnamedBitfield())
7769      continue;
7770
7771    // Check for members of reference type; we can't copy those.
7772    if (Field->getType()->isReferenceType()) {
7773      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7774        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7775      Diag(Field->getLocation(), diag::note_declared_at);
7776      Diag(CurrentLocation, diag::note_member_synthesized_at)
7777        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7778      Invalid = true;
7779      continue;
7780    }
7781
7782    // Check for members of const-qualified, non-class type.
7783    QualType BaseType = Context.getBaseElementType(Field->getType());
7784    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7785      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7786        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7787      Diag(Field->getLocation(), diag::note_declared_at);
7788      Diag(CurrentLocation, diag::note_member_synthesized_at)
7789        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7790      Invalid = true;
7791      continue;
7792    }
7793
7794    // Suppress assigning zero-width bitfields.
7795    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7796      continue;
7797
7798    QualType FieldType = Field->getType().getNonReferenceType();
7799    if (FieldType->isIncompleteArrayType()) {
7800      assert(ClassDecl->hasFlexibleArrayMember() &&
7801             "Incomplete array type is not valid");
7802      continue;
7803    }
7804
7805    // Build references to the field in the object we're copying from and to.
7806    CXXScopeSpec SS; // Intentionally empty
7807    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7808                              LookupMemberName);
7809    MemberLookup.addDecl(*Field);
7810    MemberLookup.resolveKind();
7811    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7812                                               Loc, /*IsArrow=*/false,
7813                                               SS, SourceLocation(), 0,
7814                                               MemberLookup, 0);
7815    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7816                                             Loc, /*IsArrow=*/true,
7817                                             SS, SourceLocation(), 0,
7818                                             MemberLookup, 0);
7819    assert(!From.isInvalid() && "Implicit field reference cannot fail");
7820    assert(!To.isInvalid() && "Implicit field reference cannot fail");
7821
7822    // If the field should be copied with __builtin_memcpy rather than via
7823    // explicit assignments, do so. This optimization only applies for arrays
7824    // of scalars and arrays of class type with trivial copy-assignment
7825    // operators.
7826    if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7827        && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
7828      // Compute the size of the memory buffer to be copied.
7829      QualType SizeType = Context.getSizeType();
7830      llvm::APInt Size(Context.getTypeSize(SizeType),
7831                       Context.getTypeSizeInChars(BaseType).getQuantity());
7832      for (const ConstantArrayType *Array
7833              = Context.getAsConstantArrayType(FieldType);
7834           Array;
7835           Array = Context.getAsConstantArrayType(Array->getElementType())) {
7836        llvm::APInt ArraySize
7837          = Array->getSize().zextOrTrunc(Size.getBitWidth());
7838        Size *= ArraySize;
7839      }
7840
7841      // Take the address of the field references for "from" and "to".
7842      From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7843      To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
7844
7845      bool NeedsCollectableMemCpy =
7846          (BaseType->isRecordType() &&
7847           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7848
7849      if (NeedsCollectableMemCpy) {
7850        if (!CollectableMemCpyRef) {
7851          // Create a reference to the __builtin_objc_memmove_collectable function.
7852          LookupResult R(*this,
7853                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
7854                         Loc, LookupOrdinaryName);
7855          LookupName(R, TUScope, true);
7856
7857          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7858          if (!CollectableMemCpy) {
7859            // Something went horribly wrong earlier, and we will have
7860            // complained about it.
7861            Invalid = true;
7862            continue;
7863          }
7864
7865          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7866                                                  Context.BuiltinFnTy,
7867                                                  VK_RValue, Loc, 0).take();
7868          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7869        }
7870      }
7871      // Create a reference to the __builtin_memcpy builtin function.
7872      else if (!BuiltinMemCpyRef) {
7873        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7874                       LookupOrdinaryName);
7875        LookupName(R, TUScope, true);
7876
7877        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7878        if (!BuiltinMemCpy) {
7879          // Something went horribly wrong earlier, and we will have complained
7880          // about it.
7881          Invalid = true;
7882          continue;
7883        }
7884
7885        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7886                                            Context.BuiltinFnTy,
7887                                            VK_RValue, Loc, 0).take();
7888        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7889      }
7890
7891      SmallVector<Expr*, 8> CallArgs;
7892      CallArgs.push_back(To.takeAs<Expr>());
7893      CallArgs.push_back(From.takeAs<Expr>());
7894      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
7895      ExprResult Call = ExprError();
7896      if (NeedsCollectableMemCpy)
7897        Call = ActOnCallExpr(/*Scope=*/0,
7898                             CollectableMemCpyRef,
7899                             Loc, CallArgs,
7900                             Loc);
7901      else
7902        Call = ActOnCallExpr(/*Scope=*/0,
7903                             BuiltinMemCpyRef,
7904                             Loc, CallArgs,
7905                             Loc);
7906
7907      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7908      Statements.push_back(Call.takeAs<Expr>());
7909      continue;
7910    }
7911
7912    // Build the copy of this field.
7913    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
7914                                            To.get(), From.get(),
7915                                            /*CopyingBaseSubobject=*/false,
7916                                            /*Copying=*/true);
7917    if (Copy.isInvalid()) {
7918      Diag(CurrentLocation, diag::note_member_synthesized_at)
7919        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7920      CopyAssignOperator->setInvalidDecl();
7921      return;
7922    }
7923
7924    // Success! Record the copy.
7925    Statements.push_back(Copy.takeAs<Stmt>());
7926  }
7927
7928  if (!Invalid) {
7929    // Add a "return *this;"
7930    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7931
7932    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
7933    if (Return.isInvalid())
7934      Invalid = true;
7935    else {
7936      Statements.push_back(Return.takeAs<Stmt>());
7937
7938      if (Trap.hasErrorOccurred()) {
7939        Diag(CurrentLocation, diag::note_member_synthesized_at)
7940          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7941        Invalid = true;
7942      }
7943    }
7944  }
7945
7946  if (Invalid) {
7947    CopyAssignOperator->setInvalidDecl();
7948    return;
7949  }
7950
7951  StmtResult Body;
7952  {
7953    CompoundScopeRAII CompoundScope(*this);
7954    Body = ActOnCompoundStmt(Loc, Loc, Statements,
7955                             /*isStmtExpr=*/false);
7956    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7957  }
7958  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
7959
7960  if (ASTMutationListener *L = getASTMutationListener()) {
7961    L->CompletedImplicitDefinition(CopyAssignOperator);
7962  }
7963}
7964
7965Sema::ImplicitExceptionSpecification
7966Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
7967  CXXRecordDecl *ClassDecl = MD->getParent();
7968
7969  ImplicitExceptionSpecification ExceptSpec(*this);
7970  if (ClassDecl->isInvalidDecl())
7971    return ExceptSpec;
7972
7973  // C++0x [except.spec]p14:
7974  //   An implicitly declared special member function (Clause 12) shall have an
7975  //   exception-specification. [...]
7976
7977  // It is unspecified whether or not an implicit move assignment operator
7978  // attempts to deduplicate calls to assignment operators of virtual bases are
7979  // made. As such, this exception specification is effectively unspecified.
7980  // Based on a similar decision made for constness in C++0x, we're erring on
7981  // the side of assuming such calls to be made regardless of whether they
7982  // actually happen.
7983  // Note that a move constructor is not implicitly declared when there are
7984  // virtual bases, but it can still be user-declared and explicitly defaulted.
7985  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7986                                       BaseEnd = ClassDecl->bases_end();
7987       Base != BaseEnd; ++Base) {
7988    if (Base->isVirtual())
7989      continue;
7990
7991    CXXRecordDecl *BaseClassDecl
7992      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7993    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7994                                                           0, false, 0))
7995      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
7996  }
7997
7998  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7999                                       BaseEnd = ClassDecl->vbases_end();
8000       Base != BaseEnd; ++Base) {
8001    CXXRecordDecl *BaseClassDecl
8002      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8003    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8004                                                           0, false, 0))
8005      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8006  }
8007
8008  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8009                                  FieldEnd = ClassDecl->field_end();
8010       Field != FieldEnd;
8011       ++Field) {
8012    QualType FieldType = Context.getBaseElementType(Field->getType());
8013    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8014      if (CXXMethodDecl *MoveAssign =
8015              LookupMovingAssignment(FieldClassDecl,
8016                                     FieldType.getCVRQualifiers(),
8017                                     false, 0))
8018        ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
8019    }
8020  }
8021
8022  return ExceptSpec;
8023}
8024
8025/// Determine whether the class type has any direct or indirect virtual base
8026/// classes which have a non-trivial move assignment operator.
8027static bool
8028hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8029  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8030                                          BaseEnd = ClassDecl->vbases_end();
8031       Base != BaseEnd; ++Base) {
8032    CXXRecordDecl *BaseClass =
8033        cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8034
8035    // Try to declare the move assignment. If it would be deleted, then the
8036    // class does not have a non-trivial move assignment.
8037    if (BaseClass->needsImplicitMoveAssignment())
8038      S.DeclareImplicitMoveAssignment(BaseClass);
8039
8040    // If the class has both a trivial move assignment and a non-trivial move
8041    // assignment, hasTrivialMoveAssignment() is false.
8042    if (BaseClass->hasDeclaredMoveAssignment() &&
8043        !BaseClass->hasTrivialMoveAssignment())
8044      return true;
8045  }
8046
8047  return false;
8048}
8049
8050/// Determine whether the given type either has a move constructor or is
8051/// trivially copyable.
8052static bool
8053hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8054  Type = S.Context.getBaseElementType(Type);
8055
8056  // FIXME: Technically, non-trivially-copyable non-class types, such as
8057  // reference types, are supposed to return false here, but that appears
8058  // to be a standard defect.
8059  CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
8060  if (!ClassDecl || !ClassDecl->getDefinition())
8061    return true;
8062
8063  if (Type.isTriviallyCopyableType(S.Context))
8064    return true;
8065
8066  if (IsConstructor) {
8067    if (ClassDecl->needsImplicitMoveConstructor())
8068      S.DeclareImplicitMoveConstructor(ClassDecl);
8069    return ClassDecl->hasDeclaredMoveConstructor();
8070  }
8071
8072  if (ClassDecl->needsImplicitMoveAssignment())
8073    S.DeclareImplicitMoveAssignment(ClassDecl);
8074  return ClassDecl->hasDeclaredMoveAssignment();
8075}
8076
8077/// Determine whether all non-static data members and direct or virtual bases
8078/// of class \p ClassDecl have either a move operation, or are trivially
8079/// copyable.
8080static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8081                                            bool IsConstructor) {
8082  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8083                                          BaseEnd = ClassDecl->bases_end();
8084       Base != BaseEnd; ++Base) {
8085    if (Base->isVirtual())
8086      continue;
8087
8088    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8089      return false;
8090  }
8091
8092  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8093                                          BaseEnd = ClassDecl->vbases_end();
8094       Base != BaseEnd; ++Base) {
8095    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8096      return false;
8097  }
8098
8099  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8100                                     FieldEnd = ClassDecl->field_end();
8101       Field != FieldEnd; ++Field) {
8102    if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
8103      return false;
8104  }
8105
8106  return true;
8107}
8108
8109CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8110  // C++11 [class.copy]p20:
8111  //   If the definition of a class X does not explicitly declare a move
8112  //   assignment operator, one will be implicitly declared as defaulted
8113  //   if and only if:
8114  //
8115  //   - [first 4 bullets]
8116  assert(ClassDecl->needsImplicitMoveAssignment());
8117
8118  // [Checked after we build the declaration]
8119  //   - the move assignment operator would not be implicitly defined as
8120  //     deleted,
8121
8122  // [DR1402]:
8123  //   - X has no direct or indirect virtual base class with a non-trivial
8124  //     move assignment operator, and
8125  //   - each of X's non-static data members and direct or virtual base classes
8126  //     has a type that either has a move assignment operator or is trivially
8127  //     copyable.
8128  if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8129      !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8130    ClassDecl->setFailedImplicitMoveAssignment();
8131    return 0;
8132  }
8133
8134  // Note: The following rules are largely analoguous to the move
8135  // constructor rules.
8136
8137  QualType ArgType = Context.getTypeDeclType(ClassDecl);
8138  QualType RetType = Context.getLValueReferenceType(ArgType);
8139  ArgType = Context.getRValueReferenceType(ArgType);
8140
8141  //   An implicitly-declared move assignment operator is an inline public
8142  //   member of its class.
8143  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8144  SourceLocation ClassLoc = ClassDecl->getLocation();
8145  DeclarationNameInfo NameInfo(Name, ClassLoc);
8146  CXXMethodDecl *MoveAssignment
8147    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8148                            /*TInfo=*/0, /*isStatic=*/false,
8149                            /*StorageClassAsWritten=*/SC_None,
8150                            /*isInline=*/true,
8151                            /*isConstexpr=*/false,
8152                            SourceLocation());
8153  MoveAssignment->setAccess(AS_public);
8154  MoveAssignment->setDefaulted();
8155  MoveAssignment->setImplicit();
8156  MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8157
8158  // Build an exception specification pointing back at this member.
8159  FunctionProtoType::ExtProtoInfo EPI;
8160  EPI.ExceptionSpecType = EST_Unevaluated;
8161  EPI.ExceptionSpecDecl = MoveAssignment;
8162  MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8163
8164  // Add the parameter to the operator.
8165  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8166                                               ClassLoc, ClassLoc, /*Id=*/0,
8167                                               ArgType, /*TInfo=*/0,
8168                                               SC_None,
8169                                               SC_None, 0);
8170  MoveAssignment->setParams(FromParam);
8171
8172  // Note that we have added this copy-assignment operator.
8173  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8174
8175  // C++0x [class.copy]p9:
8176  //   If the definition of a class X does not explicitly declare a move
8177  //   assignment operator, one will be implicitly declared as defaulted if and
8178  //   only if:
8179  //   [...]
8180  //   - the move assignment operator would not be implicitly defined as
8181  //     deleted.
8182  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
8183    // Cache this result so that we don't try to generate this over and over
8184    // on every lookup, leaking memory and wasting time.
8185    ClassDecl->setFailedImplicitMoveAssignment();
8186    return 0;
8187  }
8188
8189  if (Scope *S = getScopeForContext(ClassDecl))
8190    PushOnScopeChains(MoveAssignment, S, false);
8191  ClassDecl->addDecl(MoveAssignment);
8192
8193  AddOverriddenMethods(ClassDecl, MoveAssignment);
8194  return MoveAssignment;
8195}
8196
8197void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8198                                        CXXMethodDecl *MoveAssignOperator) {
8199  assert((MoveAssignOperator->isDefaulted() &&
8200          MoveAssignOperator->isOverloadedOperator() &&
8201          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8202          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8203          !MoveAssignOperator->isDeleted()) &&
8204         "DefineImplicitMoveAssignment called for wrong function");
8205
8206  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8207
8208  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8209    MoveAssignOperator->setInvalidDecl();
8210    return;
8211  }
8212
8213  MoveAssignOperator->setUsed();
8214
8215  ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8216  DiagnosticErrorTrap Trap(Diags);
8217
8218  // C++0x [class.copy]p28:
8219  //   The implicitly-defined or move assignment operator for a non-union class
8220  //   X performs memberwise move assignment of its subobjects. The direct base
8221  //   classes of X are assigned first, in the order of their declaration in the
8222  //   base-specifier-list, and then the immediate non-static data members of X
8223  //   are assigned, in the order in which they were declared in the class
8224  //   definition.
8225
8226  // The statements that form the synthesized function body.
8227  SmallVector<Stmt*, 8> Statements;
8228
8229  // The parameter for the "other" object, which we are move from.
8230  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8231  QualType OtherRefType = Other->getType()->
8232      getAs<RValueReferenceType>()->getPointeeType();
8233  assert(OtherRefType.getQualifiers() == 0 &&
8234         "Bad argument type of defaulted move assignment");
8235
8236  // Our location for everything implicitly-generated.
8237  SourceLocation Loc = MoveAssignOperator->getLocation();
8238
8239  // Construct a reference to the "other" object. We'll be using this
8240  // throughout the generated ASTs.
8241  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8242  assert(OtherRef && "Reference to parameter cannot fail!");
8243  // Cast to rvalue.
8244  OtherRef = CastForMoving(*this, OtherRef);
8245
8246  // Construct the "this" pointer. We'll be using this throughout the generated
8247  // ASTs.
8248  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8249  assert(This && "Reference to this cannot fail!");
8250
8251  // Assign base classes.
8252  bool Invalid = false;
8253  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8254       E = ClassDecl->bases_end(); Base != E; ++Base) {
8255    // Form the assignment:
8256    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8257    QualType BaseType = Base->getType().getUnqualifiedType();
8258    if (!BaseType->isRecordType()) {
8259      Invalid = true;
8260      continue;
8261    }
8262
8263    CXXCastPath BasePath;
8264    BasePath.push_back(Base);
8265
8266    // Construct the "from" expression, which is an implicit cast to the
8267    // appropriately-qualified base type.
8268    Expr *From = OtherRef;
8269    From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
8270                             VK_XValue, &BasePath).take();
8271
8272    // Dereference "this".
8273    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8274
8275    // Implicitly cast "this" to the appropriately-qualified base type.
8276    To = ImpCastExprToType(To.take(),
8277                           Context.getCVRQualifiedType(BaseType,
8278                                     MoveAssignOperator->getTypeQualifiers()),
8279                           CK_UncheckedDerivedToBase,
8280                           VK_LValue, &BasePath);
8281
8282    // Build the move.
8283    StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8284                                            To.get(), From,
8285                                            /*CopyingBaseSubobject=*/true,
8286                                            /*Copying=*/false);
8287    if (Move.isInvalid()) {
8288      Diag(CurrentLocation, diag::note_member_synthesized_at)
8289        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8290      MoveAssignOperator->setInvalidDecl();
8291      return;
8292    }
8293
8294    // Success! Record the move.
8295    Statements.push_back(Move.takeAs<Expr>());
8296  }
8297
8298  // \brief Reference to the __builtin_memcpy function.
8299  Expr *BuiltinMemCpyRef = 0;
8300  // \brief Reference to the __builtin_objc_memmove_collectable function.
8301  Expr *CollectableMemCpyRef = 0;
8302
8303  // Assign non-static members.
8304  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8305                                  FieldEnd = ClassDecl->field_end();
8306       Field != FieldEnd; ++Field) {
8307    if (Field->isUnnamedBitfield())
8308      continue;
8309
8310    // Check for members of reference type; we can't move those.
8311    if (Field->getType()->isReferenceType()) {
8312      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8313        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8314      Diag(Field->getLocation(), diag::note_declared_at);
8315      Diag(CurrentLocation, diag::note_member_synthesized_at)
8316        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8317      Invalid = true;
8318      continue;
8319    }
8320
8321    // Check for members of const-qualified, non-class type.
8322    QualType BaseType = Context.getBaseElementType(Field->getType());
8323    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8324      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8325        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8326      Diag(Field->getLocation(), diag::note_declared_at);
8327      Diag(CurrentLocation, diag::note_member_synthesized_at)
8328        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8329      Invalid = true;
8330      continue;
8331    }
8332
8333    // Suppress assigning zero-width bitfields.
8334    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8335      continue;
8336
8337    QualType FieldType = Field->getType().getNonReferenceType();
8338    if (FieldType->isIncompleteArrayType()) {
8339      assert(ClassDecl->hasFlexibleArrayMember() &&
8340             "Incomplete array type is not valid");
8341      continue;
8342    }
8343
8344    // Build references to the field in the object we're copying from and to.
8345    CXXScopeSpec SS; // Intentionally empty
8346    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8347                              LookupMemberName);
8348    MemberLookup.addDecl(*Field);
8349    MemberLookup.resolveKind();
8350    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8351                                               Loc, /*IsArrow=*/false,
8352                                               SS, SourceLocation(), 0,
8353                                               MemberLookup, 0);
8354    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8355                                             Loc, /*IsArrow=*/true,
8356                                             SS, SourceLocation(), 0,
8357                                             MemberLookup, 0);
8358    assert(!From.isInvalid() && "Implicit field reference cannot fail");
8359    assert(!To.isInvalid() && "Implicit field reference cannot fail");
8360
8361    assert(!From.get()->isLValue() && // could be xvalue or prvalue
8362        "Member reference with rvalue base must be rvalue except for reference "
8363        "members, which aren't allowed for move assignment.");
8364
8365    // If the field should be copied with __builtin_memcpy rather than via
8366    // explicit assignments, do so. This optimization only applies for arrays
8367    // of scalars and arrays of class type with trivial move-assignment
8368    // operators.
8369    if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8370        && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8371      // Compute the size of the memory buffer to be copied.
8372      QualType SizeType = Context.getSizeType();
8373      llvm::APInt Size(Context.getTypeSize(SizeType),
8374                       Context.getTypeSizeInChars(BaseType).getQuantity());
8375      for (const ConstantArrayType *Array
8376              = Context.getAsConstantArrayType(FieldType);
8377           Array;
8378           Array = Context.getAsConstantArrayType(Array->getElementType())) {
8379        llvm::APInt ArraySize
8380          = Array->getSize().zextOrTrunc(Size.getBitWidth());
8381        Size *= ArraySize;
8382      }
8383
8384      // Take the address of the field references for "from" and "to". We
8385      // directly construct UnaryOperators here because semantic analysis
8386      // does not permit us to take the address of an xvalue.
8387      From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8388                             Context.getPointerType(From.get()->getType()),
8389                             VK_RValue, OK_Ordinary, Loc);
8390      To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8391                           Context.getPointerType(To.get()->getType()),
8392                           VK_RValue, OK_Ordinary, Loc);
8393
8394      bool NeedsCollectableMemCpy =
8395          (BaseType->isRecordType() &&
8396           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8397
8398      if (NeedsCollectableMemCpy) {
8399        if (!CollectableMemCpyRef) {
8400          // Create a reference to the __builtin_objc_memmove_collectable function.
8401          LookupResult R(*this,
8402                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
8403                         Loc, LookupOrdinaryName);
8404          LookupName(R, TUScope, true);
8405
8406          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8407          if (!CollectableMemCpy) {
8408            // Something went horribly wrong earlier, and we will have
8409            // complained about it.
8410            Invalid = true;
8411            continue;
8412          }
8413
8414          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8415                                                  Context.BuiltinFnTy,
8416                                                  VK_RValue, Loc, 0).take();
8417          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8418        }
8419      }
8420      // Create a reference to the __builtin_memcpy builtin function.
8421      else if (!BuiltinMemCpyRef) {
8422        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8423                       LookupOrdinaryName);
8424        LookupName(R, TUScope, true);
8425
8426        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8427        if (!BuiltinMemCpy) {
8428          // Something went horribly wrong earlier, and we will have complained
8429          // about it.
8430          Invalid = true;
8431          continue;
8432        }
8433
8434        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8435                                            Context.BuiltinFnTy,
8436                                            VK_RValue, Loc, 0).take();
8437        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8438      }
8439
8440      SmallVector<Expr*, 8> CallArgs;
8441      CallArgs.push_back(To.takeAs<Expr>());
8442      CallArgs.push_back(From.takeAs<Expr>());
8443      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8444      ExprResult Call = ExprError();
8445      if (NeedsCollectableMemCpy)
8446        Call = ActOnCallExpr(/*Scope=*/0,
8447                             CollectableMemCpyRef,
8448                             Loc, CallArgs,
8449                             Loc);
8450      else
8451        Call = ActOnCallExpr(/*Scope=*/0,
8452                             BuiltinMemCpyRef,
8453                             Loc, CallArgs,
8454                             Loc);
8455
8456      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8457      Statements.push_back(Call.takeAs<Expr>());
8458      continue;
8459    }
8460
8461    // Build the move of this field.
8462    StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8463                                            To.get(), From.get(),
8464                                            /*CopyingBaseSubobject=*/false,
8465                                            /*Copying=*/false);
8466    if (Move.isInvalid()) {
8467      Diag(CurrentLocation, diag::note_member_synthesized_at)
8468        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8469      MoveAssignOperator->setInvalidDecl();
8470      return;
8471    }
8472
8473    // Success! Record the copy.
8474    Statements.push_back(Move.takeAs<Stmt>());
8475  }
8476
8477  if (!Invalid) {
8478    // Add a "return *this;"
8479    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8480
8481    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8482    if (Return.isInvalid())
8483      Invalid = true;
8484    else {
8485      Statements.push_back(Return.takeAs<Stmt>());
8486
8487      if (Trap.hasErrorOccurred()) {
8488        Diag(CurrentLocation, diag::note_member_synthesized_at)
8489          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8490        Invalid = true;
8491      }
8492    }
8493  }
8494
8495  if (Invalid) {
8496    MoveAssignOperator->setInvalidDecl();
8497    return;
8498  }
8499
8500  StmtResult Body;
8501  {
8502    CompoundScopeRAII CompoundScope(*this);
8503    Body = ActOnCompoundStmt(Loc, Loc, Statements,
8504                             /*isStmtExpr=*/false);
8505    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8506  }
8507  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8508
8509  if (ASTMutationListener *L = getASTMutationListener()) {
8510    L->CompletedImplicitDefinition(MoveAssignOperator);
8511  }
8512}
8513
8514/// Determine whether an implicit copy constructor for ClassDecl has a const
8515/// argument.
8516/// FIXME: It ought to be possible to store this on the record.
8517static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl) {
8518  if (ClassDecl->isInvalidDecl())
8519    return true;
8520
8521  // C++ [class.copy]p5:
8522  //   The implicitly-declared copy constructor for a class X will
8523  //   have the form
8524  //
8525  //       X::X(const X&)
8526  //
8527  //   if
8528  //     -- each direct or virtual base class B of X has a copy
8529  //        constructor whose first parameter is of type const B& or
8530  //        const volatile B&, and
8531  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8532                                       BaseEnd = ClassDecl->bases_end();
8533       Base != BaseEnd; ++Base) {
8534    // Virtual bases are handled below.
8535    if (Base->isVirtual())
8536      continue;
8537
8538    CXXRecordDecl *BaseClassDecl
8539      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8540    // FIXME: This lookup is wrong. If the copy ctor for a member or base is
8541    // ambiguous, we should still produce a constructor with a const-qualified
8542    // parameter.
8543    if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8544      return false;
8545  }
8546
8547  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8548                                       BaseEnd = ClassDecl->vbases_end();
8549       Base != BaseEnd; ++Base) {
8550    CXXRecordDecl *BaseClassDecl
8551      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8552    if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8553      return false;
8554  }
8555
8556  //     -- for all the nonstatic data members of X that are of a
8557  //        class type M (or array thereof), each such class type
8558  //        has a copy constructor whose first parameter is of type
8559  //        const M& or const volatile M&.
8560  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8561                                  FieldEnd = ClassDecl->field_end();
8562       Field != FieldEnd; ++Field) {
8563    QualType FieldType = S.Context.getBaseElementType(Field->getType());
8564    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8565      if (!S.LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const))
8566        return false;
8567    }
8568  }
8569
8570  //   Otherwise, the implicitly declared copy constructor will have
8571  //   the form
8572  //
8573  //       X::X(X&)
8574
8575  return true;
8576}
8577
8578Sema::ImplicitExceptionSpecification
8579Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
8580  CXXRecordDecl *ClassDecl = MD->getParent();
8581
8582  ImplicitExceptionSpecification ExceptSpec(*this);
8583  if (ClassDecl->isInvalidDecl())
8584    return ExceptSpec;
8585
8586  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8587  assert(T->getNumArgs() >= 1 && "not a copy ctor");
8588  unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8589
8590  // C++ [except.spec]p14:
8591  //   An implicitly declared special member function (Clause 12) shall have an
8592  //   exception-specification. [...]
8593  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8594                                       BaseEnd = ClassDecl->bases_end();
8595       Base != BaseEnd;
8596       ++Base) {
8597    // Virtual bases are handled below.
8598    if (Base->isVirtual())
8599      continue;
8600
8601    CXXRecordDecl *BaseClassDecl
8602      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8603    if (CXXConstructorDecl *CopyConstructor =
8604          LookupCopyingConstructor(BaseClassDecl, Quals))
8605      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
8606  }
8607  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8608                                       BaseEnd = ClassDecl->vbases_end();
8609       Base != BaseEnd;
8610       ++Base) {
8611    CXXRecordDecl *BaseClassDecl
8612      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8613    if (CXXConstructorDecl *CopyConstructor =
8614          LookupCopyingConstructor(BaseClassDecl, Quals))
8615      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
8616  }
8617  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8618                                  FieldEnd = ClassDecl->field_end();
8619       Field != FieldEnd;
8620       ++Field) {
8621    QualType FieldType = Context.getBaseElementType(Field->getType());
8622    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8623      if (CXXConstructorDecl *CopyConstructor =
8624              LookupCopyingConstructor(FieldClassDecl,
8625                                       Quals | FieldType.getCVRQualifiers()))
8626      ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
8627    }
8628  }
8629
8630  return ExceptSpec;
8631}
8632
8633CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8634                                                    CXXRecordDecl *ClassDecl) {
8635  // C++ [class.copy]p4:
8636  //   If the class definition does not explicitly declare a copy
8637  //   constructor, one is declared implicitly.
8638
8639  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8640  QualType ArgType = ClassType;
8641  bool Const = isImplicitCopyCtorArgConst(*this, ClassDecl);
8642  if (Const)
8643    ArgType = ArgType.withConst();
8644  ArgType = Context.getLValueReferenceType(ArgType);
8645
8646  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8647                                                     CXXCopyConstructor,
8648                                                     Const);
8649
8650  DeclarationName Name
8651    = Context.DeclarationNames.getCXXConstructorName(
8652                                           Context.getCanonicalType(ClassType));
8653  SourceLocation ClassLoc = ClassDecl->getLocation();
8654  DeclarationNameInfo NameInfo(Name, ClassLoc);
8655
8656  //   An implicitly-declared copy constructor is an inline public
8657  //   member of its class.
8658  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8659      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
8660      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8661      Constexpr);
8662  CopyConstructor->setAccess(AS_public);
8663  CopyConstructor->setDefaulted();
8664  CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8665
8666  // Build an exception specification pointing back at this member.
8667  FunctionProtoType::ExtProtoInfo EPI;
8668  EPI.ExceptionSpecType = EST_Unevaluated;
8669  EPI.ExceptionSpecDecl = CopyConstructor;
8670  CopyConstructor->setType(
8671      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8672
8673  // Note that we have declared this constructor.
8674  ++ASTContext::NumImplicitCopyConstructorsDeclared;
8675
8676  // Add the parameter to the constructor.
8677  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
8678                                               ClassLoc, ClassLoc,
8679                                               /*IdentifierInfo=*/0,
8680                                               ArgType, /*TInfo=*/0,
8681                                               SC_None,
8682                                               SC_None, 0);
8683  CopyConstructor->setParams(FromParam);
8684
8685  if (Scope *S = getScopeForContext(ClassDecl))
8686    PushOnScopeChains(CopyConstructor, S, false);
8687  ClassDecl->addDecl(CopyConstructor);
8688
8689  // C++11 [class.copy]p8:
8690  //   ... If the class definition does not explicitly declare a copy
8691  //   constructor, there is no user-declared move constructor, and there is no
8692  //   user-declared move assignment operator, a copy constructor is implicitly
8693  //   declared as defaulted.
8694  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
8695    CopyConstructor->setDeletedAsWritten();
8696
8697  return CopyConstructor;
8698}
8699
8700void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
8701                                   CXXConstructorDecl *CopyConstructor) {
8702  assert((CopyConstructor->isDefaulted() &&
8703          CopyConstructor->isCopyConstructor() &&
8704          !CopyConstructor->doesThisDeclarationHaveABody() &&
8705          !CopyConstructor->isDeleted()) &&
8706         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
8707
8708  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
8709  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
8710
8711  ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
8712  DiagnosticErrorTrap Trap(Diags);
8713
8714  if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
8715      Trap.hasErrorOccurred()) {
8716    Diag(CurrentLocation, diag::note_member_synthesized_at)
8717      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
8718    CopyConstructor->setInvalidDecl();
8719  }  else {
8720    Sema::CompoundScopeRAII CompoundScope(*this);
8721    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8722                                               CopyConstructor->getLocation(),
8723                                               MultiStmtArg(),
8724                                               /*isStmtExpr=*/false)
8725                                                              .takeAs<Stmt>());
8726    CopyConstructor->setImplicitlyDefined(true);
8727  }
8728
8729  CopyConstructor->setUsed();
8730  if (ASTMutationListener *L = getASTMutationListener()) {
8731    L->CompletedImplicitDefinition(CopyConstructor);
8732  }
8733}
8734
8735Sema::ImplicitExceptionSpecification
8736Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
8737  CXXRecordDecl *ClassDecl = MD->getParent();
8738
8739  // C++ [except.spec]p14:
8740  //   An implicitly declared special member function (Clause 12) shall have an
8741  //   exception-specification. [...]
8742  ImplicitExceptionSpecification ExceptSpec(*this);
8743  if (ClassDecl->isInvalidDecl())
8744    return ExceptSpec;
8745
8746  // Direct base-class constructors.
8747  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8748                                       BEnd = ClassDecl->bases_end();
8749       B != BEnd; ++B) {
8750    if (B->isVirtual()) // Handled below.
8751      continue;
8752
8753    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8754      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8755      CXXConstructorDecl *Constructor =
8756          LookupMovingConstructor(BaseClassDecl, 0);
8757      // If this is a deleted function, add it anyway. This might be conformant
8758      // with the standard. This might not. I'm not sure. It might not matter.
8759      if (Constructor)
8760        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8761    }
8762  }
8763
8764  // Virtual base-class constructors.
8765  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8766                                       BEnd = ClassDecl->vbases_end();
8767       B != BEnd; ++B) {
8768    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8769      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8770      CXXConstructorDecl *Constructor =
8771          LookupMovingConstructor(BaseClassDecl, 0);
8772      // If this is a deleted function, add it anyway. This might be conformant
8773      // with the standard. This might not. I'm not sure. It might not matter.
8774      if (Constructor)
8775        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8776    }
8777  }
8778
8779  // Field constructors.
8780  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8781                               FEnd = ClassDecl->field_end();
8782       F != FEnd; ++F) {
8783    QualType FieldType = Context.getBaseElementType(F->getType());
8784    if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
8785      CXXConstructorDecl *Constructor =
8786          LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
8787      // If this is a deleted function, add it anyway. This might be conformant
8788      // with the standard. This might not. I'm not sure. It might not matter.
8789      // In particular, the problem is that this function never gets called. It
8790      // might just be ill-formed because this function attempts to refer to
8791      // a deleted function here.
8792      if (Constructor)
8793        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8794    }
8795  }
8796
8797  return ExceptSpec;
8798}
8799
8800CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8801                                                    CXXRecordDecl *ClassDecl) {
8802  // C++11 [class.copy]p9:
8803  //   If the definition of a class X does not explicitly declare a move
8804  //   constructor, one will be implicitly declared as defaulted if and only if:
8805  //
8806  //   - [first 4 bullets]
8807  assert(ClassDecl->needsImplicitMoveConstructor());
8808
8809  // [Checked after we build the declaration]
8810  //   - the move assignment operator would not be implicitly defined as
8811  //     deleted,
8812
8813  // [DR1402]:
8814  //   - each of X's non-static data members and direct or virtual base classes
8815  //     has a type that either has a move constructor or is trivially copyable.
8816  if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8817    ClassDecl->setFailedImplicitMoveConstructor();
8818    return 0;
8819  }
8820
8821  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8822  QualType ArgType = Context.getRValueReferenceType(ClassType);
8823
8824  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8825                                                     CXXMoveConstructor,
8826                                                     false);
8827
8828  DeclarationName Name
8829    = Context.DeclarationNames.getCXXConstructorName(
8830                                           Context.getCanonicalType(ClassType));
8831  SourceLocation ClassLoc = ClassDecl->getLocation();
8832  DeclarationNameInfo NameInfo(Name, ClassLoc);
8833
8834  // C++0x [class.copy]p11:
8835  //   An implicitly-declared copy/move constructor is an inline public
8836  //   member of its class.
8837  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8838      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
8839      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8840      Constexpr);
8841  MoveConstructor->setAccess(AS_public);
8842  MoveConstructor->setDefaulted();
8843  MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8844
8845  // Build an exception specification pointing back at this member.
8846  FunctionProtoType::ExtProtoInfo EPI;
8847  EPI.ExceptionSpecType = EST_Unevaluated;
8848  EPI.ExceptionSpecDecl = MoveConstructor;
8849  MoveConstructor->setType(
8850      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8851
8852  // Add the parameter to the constructor.
8853  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8854                                               ClassLoc, ClassLoc,
8855                                               /*IdentifierInfo=*/0,
8856                                               ArgType, /*TInfo=*/0,
8857                                               SC_None,
8858                                               SC_None, 0);
8859  MoveConstructor->setParams(FromParam);
8860
8861  // C++0x [class.copy]p9:
8862  //   If the definition of a class X does not explicitly declare a move
8863  //   constructor, one will be implicitly declared as defaulted if and only if:
8864  //   [...]
8865  //   - the move constructor would not be implicitly defined as deleted.
8866  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
8867    // Cache this result so that we don't try to generate this over and over
8868    // on every lookup, leaking memory and wasting time.
8869    ClassDecl->setFailedImplicitMoveConstructor();
8870    return 0;
8871  }
8872
8873  // Note that we have declared this constructor.
8874  ++ASTContext::NumImplicitMoveConstructorsDeclared;
8875
8876  if (Scope *S = getScopeForContext(ClassDecl))
8877    PushOnScopeChains(MoveConstructor, S, false);
8878  ClassDecl->addDecl(MoveConstructor);
8879
8880  return MoveConstructor;
8881}
8882
8883void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8884                                   CXXConstructorDecl *MoveConstructor) {
8885  assert((MoveConstructor->isDefaulted() &&
8886          MoveConstructor->isMoveConstructor() &&
8887          !MoveConstructor->doesThisDeclarationHaveABody() &&
8888          !MoveConstructor->isDeleted()) &&
8889         "DefineImplicitMoveConstructor - call it for implicit move ctor");
8890
8891  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8892  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8893
8894  ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8895  DiagnosticErrorTrap Trap(Diags);
8896
8897  if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8898      Trap.hasErrorOccurred()) {
8899    Diag(CurrentLocation, diag::note_member_synthesized_at)
8900      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8901    MoveConstructor->setInvalidDecl();
8902  }  else {
8903    Sema::CompoundScopeRAII CompoundScope(*this);
8904    MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8905                                               MoveConstructor->getLocation(),
8906                                               MultiStmtArg(),
8907                                               /*isStmtExpr=*/false)
8908                                                              .takeAs<Stmt>());
8909    MoveConstructor->setImplicitlyDefined(true);
8910  }
8911
8912  MoveConstructor->setUsed();
8913
8914  if (ASTMutationListener *L = getASTMutationListener()) {
8915    L->CompletedImplicitDefinition(MoveConstructor);
8916  }
8917}
8918
8919bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8920  return FD->isDeleted() &&
8921         (FD->isDefaulted() || FD->isImplicit()) &&
8922         isa<CXXMethodDecl>(FD);
8923}
8924
8925/// \brief Mark the call operator of the given lambda closure type as "used".
8926static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8927  CXXMethodDecl *CallOperator
8928    = cast<CXXMethodDecl>(
8929        *Lambda->lookup(
8930          S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
8931  CallOperator->setReferenced();
8932  CallOperator->setUsed();
8933}
8934
8935void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8936       SourceLocation CurrentLocation,
8937       CXXConversionDecl *Conv)
8938{
8939  CXXRecordDecl *Lambda = Conv->getParent();
8940
8941  // Make sure that the lambda call operator is marked used.
8942  markLambdaCallOperatorUsed(*this, Lambda);
8943
8944  Conv->setUsed();
8945
8946  ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8947  DiagnosticErrorTrap Trap(Diags);
8948
8949  // Return the address of the __invoke function.
8950  DeclarationName InvokeName = &Context.Idents.get("__invoke");
8951  CXXMethodDecl *Invoke
8952    = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8953  Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8954                                       VK_LValue, Conv->getLocation()).take();
8955  assert(FunctionRef && "Can't refer to __invoke function?");
8956  Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8957  Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8958                                           Conv->getLocation(),
8959                                           Conv->getLocation()));
8960
8961  // Fill in the __invoke function with a dummy implementation. IR generation
8962  // will fill in the actual details.
8963  Invoke->setUsed();
8964  Invoke->setReferenced();
8965  Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
8966
8967  if (ASTMutationListener *L = getASTMutationListener()) {
8968    L->CompletedImplicitDefinition(Conv);
8969    L->CompletedImplicitDefinition(Invoke);
8970  }
8971}
8972
8973void Sema::DefineImplicitLambdaToBlockPointerConversion(
8974       SourceLocation CurrentLocation,
8975       CXXConversionDecl *Conv)
8976{
8977  Conv->setUsed();
8978
8979  ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8980  DiagnosticErrorTrap Trap(Diags);
8981
8982  // Copy-initialize the lambda object as needed to capture it.
8983  Expr *This = ActOnCXXThis(CurrentLocation).take();
8984  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
8985
8986  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8987                                                        Conv->getLocation(),
8988                                                        Conv, DerefThis);
8989
8990  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8991  // behavior.  Note that only the general conversion function does this
8992  // (since it's unusable otherwise); in the case where we inline the
8993  // block literal, it has block literal lifetime semantics.
8994  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
8995    BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
8996                                          CK_CopyAndAutoreleaseBlockObject,
8997                                          BuildBlock.get(), 0, VK_RValue);
8998
8999  if (BuildBlock.isInvalid()) {
9000    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9001    Conv->setInvalidDecl();
9002    return;
9003  }
9004
9005  // Create the return statement that returns the block from the conversion
9006  // function.
9007  StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
9008  if (Return.isInvalid()) {
9009    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9010    Conv->setInvalidDecl();
9011    return;
9012  }
9013
9014  // Set the body of the conversion function.
9015  Stmt *ReturnS = Return.take();
9016  Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9017                                           Conv->getLocation(),
9018                                           Conv->getLocation()));
9019
9020  // We're done; notify the mutation listener, if any.
9021  if (ASTMutationListener *L = getASTMutationListener()) {
9022    L->CompletedImplicitDefinition(Conv);
9023  }
9024}
9025
9026/// \brief Determine whether the given list arguments contains exactly one
9027/// "real" (non-default) argument.
9028static bool hasOneRealArgument(MultiExprArg Args) {
9029  switch (Args.size()) {
9030  case 0:
9031    return false;
9032
9033  default:
9034    if (!Args[1]->isDefaultArgument())
9035      return false;
9036
9037    // fall through
9038  case 1:
9039    return !Args[0]->isDefaultArgument();
9040  }
9041
9042  return false;
9043}
9044
9045ExprResult
9046Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9047                            CXXConstructorDecl *Constructor,
9048                            MultiExprArg ExprArgs,
9049                            bool HadMultipleCandidates,
9050                            bool RequiresZeroInit,
9051                            unsigned ConstructKind,
9052                            SourceRange ParenRange) {
9053  bool Elidable = false;
9054
9055  // C++0x [class.copy]p34:
9056  //   When certain criteria are met, an implementation is allowed to
9057  //   omit the copy/move construction of a class object, even if the
9058  //   copy/move constructor and/or destructor for the object have
9059  //   side effects. [...]
9060  //     - when a temporary class object that has not been bound to a
9061  //       reference (12.2) would be copied/moved to a class object
9062  //       with the same cv-unqualified type, the copy/move operation
9063  //       can be omitted by constructing the temporary object
9064  //       directly into the target of the omitted copy/move
9065  if (ConstructKind == CXXConstructExpr::CK_Complete &&
9066      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
9067    Expr *SubExpr = ExprArgs[0];
9068    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
9069  }
9070
9071  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
9072                               Elidable, ExprArgs, HadMultipleCandidates,
9073                               RequiresZeroInit, ConstructKind, ParenRange);
9074}
9075
9076/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9077/// including handling of its default argument expressions.
9078ExprResult
9079Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9080                            CXXConstructorDecl *Constructor, bool Elidable,
9081                            MultiExprArg ExprArgs,
9082                            bool HadMultipleCandidates,
9083                            bool RequiresZeroInit,
9084                            unsigned ConstructKind,
9085                            SourceRange ParenRange) {
9086  MarkFunctionReferenced(ConstructLoc, Constructor);
9087  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
9088                                        Constructor, Elidable, ExprArgs,
9089                                        HadMultipleCandidates, /*FIXME*/false,
9090                                        RequiresZeroInit,
9091              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9092                                        ParenRange));
9093}
9094
9095bool Sema::InitializeVarWithConstructor(VarDecl *VD,
9096                                        CXXConstructorDecl *Constructor,
9097                                        MultiExprArg Exprs,
9098                                        bool HadMultipleCandidates) {
9099  // FIXME: Provide the correct paren SourceRange when available.
9100  ExprResult TempResult =
9101    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
9102                          Exprs, HadMultipleCandidates, false,
9103                          CXXConstructExpr::CK_Complete, SourceRange());
9104  if (TempResult.isInvalid())
9105    return true;
9106
9107  Expr *Temp = TempResult.takeAs<Expr>();
9108  CheckImplicitConversions(Temp, VD->getLocation());
9109  MarkFunctionReferenced(VD->getLocation(), Constructor);
9110  Temp = MaybeCreateExprWithCleanups(Temp);
9111  VD->setInit(Temp);
9112
9113  return false;
9114}
9115
9116void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
9117  if (VD->isInvalidDecl()) return;
9118
9119  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
9120  if (ClassDecl->isInvalidDecl()) return;
9121  if (ClassDecl->hasIrrelevantDestructor()) return;
9122  if (ClassDecl->isDependentContext()) return;
9123
9124  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9125  MarkFunctionReferenced(VD->getLocation(), Destructor);
9126  CheckDestructorAccess(VD->getLocation(), Destructor,
9127                        PDiag(diag::err_access_dtor_var)
9128                        << VD->getDeclName()
9129                        << VD->getType());
9130  DiagnoseUseOfDecl(Destructor, VD->getLocation());
9131
9132  if (!VD->hasGlobalStorage()) return;
9133
9134  // Emit warning for non-trivial dtor in global scope (a real global,
9135  // class-static, function-static).
9136  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9137
9138  // TODO: this should be re-enabled for static locals by !CXAAtExit
9139  if (!VD->isStaticLocal())
9140    Diag(VD->getLocation(), diag::warn_global_destructor);
9141}
9142
9143/// \brief Given a constructor and the set of arguments provided for the
9144/// constructor, convert the arguments and add any required default arguments
9145/// to form a proper call to this constructor.
9146///
9147/// \returns true if an error occurred, false otherwise.
9148bool
9149Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9150                              MultiExprArg ArgsPtr,
9151                              SourceLocation Loc,
9152                              SmallVectorImpl<Expr*> &ConvertedArgs,
9153                              bool AllowExplicit) {
9154  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9155  unsigned NumArgs = ArgsPtr.size();
9156  Expr **Args = ArgsPtr.data();
9157
9158  const FunctionProtoType *Proto
9159    = Constructor->getType()->getAs<FunctionProtoType>();
9160  assert(Proto && "Constructor without a prototype?");
9161  unsigned NumArgsInProto = Proto->getNumArgs();
9162
9163  // If too few arguments are available, we'll fill in the rest with defaults.
9164  if (NumArgs < NumArgsInProto)
9165    ConvertedArgs.reserve(NumArgsInProto);
9166  else
9167    ConvertedArgs.reserve(NumArgs);
9168
9169  VariadicCallType CallType =
9170    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
9171  SmallVector<Expr *, 8> AllArgs;
9172  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9173                                        Proto, 0, Args, NumArgs, AllArgs,
9174                                        CallType, AllowExplicit);
9175  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
9176
9177  DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9178
9179  CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9180                       Proto, Loc);
9181
9182  return Invalid;
9183}
9184
9185static inline bool
9186CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9187                                       const FunctionDecl *FnDecl) {
9188  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
9189  if (isa<NamespaceDecl>(DC)) {
9190    return SemaRef.Diag(FnDecl->getLocation(),
9191                        diag::err_operator_new_delete_declared_in_namespace)
9192      << FnDecl->getDeclName();
9193  }
9194
9195  if (isa<TranslationUnitDecl>(DC) &&
9196      FnDecl->getStorageClass() == SC_Static) {
9197    return SemaRef.Diag(FnDecl->getLocation(),
9198                        diag::err_operator_new_delete_declared_static)
9199      << FnDecl->getDeclName();
9200  }
9201
9202  return false;
9203}
9204
9205static inline bool
9206CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9207                            CanQualType ExpectedResultType,
9208                            CanQualType ExpectedFirstParamType,
9209                            unsigned DependentParamTypeDiag,
9210                            unsigned InvalidParamTypeDiag) {
9211  QualType ResultType =
9212    FnDecl->getType()->getAs<FunctionType>()->getResultType();
9213
9214  // Check that the result type is not dependent.
9215  if (ResultType->isDependentType())
9216    return SemaRef.Diag(FnDecl->getLocation(),
9217                        diag::err_operator_new_delete_dependent_result_type)
9218    << FnDecl->getDeclName() << ExpectedResultType;
9219
9220  // Check that the result type is what we expect.
9221  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9222    return SemaRef.Diag(FnDecl->getLocation(),
9223                        diag::err_operator_new_delete_invalid_result_type)
9224    << FnDecl->getDeclName() << ExpectedResultType;
9225
9226  // A function template must have at least 2 parameters.
9227  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9228    return SemaRef.Diag(FnDecl->getLocation(),
9229                      diag::err_operator_new_delete_template_too_few_parameters)
9230        << FnDecl->getDeclName();
9231
9232  // The function decl must have at least 1 parameter.
9233  if (FnDecl->getNumParams() == 0)
9234    return SemaRef.Diag(FnDecl->getLocation(),
9235                        diag::err_operator_new_delete_too_few_parameters)
9236      << FnDecl->getDeclName();
9237
9238  // Check the first parameter type is not dependent.
9239  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9240  if (FirstParamType->isDependentType())
9241    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9242      << FnDecl->getDeclName() << ExpectedFirstParamType;
9243
9244  // Check that the first parameter type is what we expect.
9245  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
9246      ExpectedFirstParamType)
9247    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9248    << FnDecl->getDeclName() << ExpectedFirstParamType;
9249
9250  return false;
9251}
9252
9253static bool
9254CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9255  // C++ [basic.stc.dynamic.allocation]p1:
9256  //   A program is ill-formed if an allocation function is declared in a
9257  //   namespace scope other than global scope or declared static in global
9258  //   scope.
9259  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9260    return true;
9261
9262  CanQualType SizeTy =
9263    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9264
9265  // C++ [basic.stc.dynamic.allocation]p1:
9266  //  The return type shall be void*. The first parameter shall have type
9267  //  std::size_t.
9268  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9269                                  SizeTy,
9270                                  diag::err_operator_new_dependent_param_type,
9271                                  diag::err_operator_new_param_type))
9272    return true;
9273
9274  // C++ [basic.stc.dynamic.allocation]p1:
9275  //  The first parameter shall not have an associated default argument.
9276  if (FnDecl->getParamDecl(0)->hasDefaultArg())
9277    return SemaRef.Diag(FnDecl->getLocation(),
9278                        diag::err_operator_new_default_arg)
9279      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9280
9281  return false;
9282}
9283
9284static bool
9285CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9286  // C++ [basic.stc.dynamic.deallocation]p1:
9287  //   A program is ill-formed if deallocation functions are declared in a
9288  //   namespace scope other than global scope or declared static in global
9289  //   scope.
9290  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9291    return true;
9292
9293  // C++ [basic.stc.dynamic.deallocation]p2:
9294  //   Each deallocation function shall return void and its first parameter
9295  //   shall be void*.
9296  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9297                                  SemaRef.Context.VoidPtrTy,
9298                                 diag::err_operator_delete_dependent_param_type,
9299                                 diag::err_operator_delete_param_type))
9300    return true;
9301
9302  return false;
9303}
9304
9305/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9306/// of this overloaded operator is well-formed. If so, returns false;
9307/// otherwise, emits appropriate diagnostics and returns true.
9308bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
9309  assert(FnDecl && FnDecl->isOverloadedOperator() &&
9310         "Expected an overloaded operator declaration");
9311
9312  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9313
9314  // C++ [over.oper]p5:
9315  //   The allocation and deallocation functions, operator new,
9316  //   operator new[], operator delete and operator delete[], are
9317  //   described completely in 3.7.3. The attributes and restrictions
9318  //   found in the rest of this subclause do not apply to them unless
9319  //   explicitly stated in 3.7.3.
9320  if (Op == OO_Delete || Op == OO_Array_Delete)
9321    return CheckOperatorDeleteDeclaration(*this, FnDecl);
9322
9323  if (Op == OO_New || Op == OO_Array_New)
9324    return CheckOperatorNewDeclaration(*this, FnDecl);
9325
9326  // C++ [over.oper]p6:
9327  //   An operator function shall either be a non-static member
9328  //   function or be a non-member function and have at least one
9329  //   parameter whose type is a class, a reference to a class, an
9330  //   enumeration, or a reference to an enumeration.
9331  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9332    if (MethodDecl->isStatic())
9333      return Diag(FnDecl->getLocation(),
9334                  diag::err_operator_overload_static) << FnDecl->getDeclName();
9335  } else {
9336    bool ClassOrEnumParam = false;
9337    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9338                                   ParamEnd = FnDecl->param_end();
9339         Param != ParamEnd; ++Param) {
9340      QualType ParamType = (*Param)->getType().getNonReferenceType();
9341      if (ParamType->isDependentType() || ParamType->isRecordType() ||
9342          ParamType->isEnumeralType()) {
9343        ClassOrEnumParam = true;
9344        break;
9345      }
9346    }
9347
9348    if (!ClassOrEnumParam)
9349      return Diag(FnDecl->getLocation(),
9350                  diag::err_operator_overload_needs_class_or_enum)
9351        << FnDecl->getDeclName();
9352  }
9353
9354  // C++ [over.oper]p8:
9355  //   An operator function cannot have default arguments (8.3.6),
9356  //   except where explicitly stated below.
9357  //
9358  // Only the function-call operator allows default arguments
9359  // (C++ [over.call]p1).
9360  if (Op != OO_Call) {
9361    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9362         Param != FnDecl->param_end(); ++Param) {
9363      if ((*Param)->hasDefaultArg())
9364        return Diag((*Param)->getLocation(),
9365                    diag::err_operator_overload_default_arg)
9366          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
9367    }
9368  }
9369
9370  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9371    { false, false, false }
9372#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9373    , { Unary, Binary, MemberOnly }
9374#include "clang/Basic/OperatorKinds.def"
9375  };
9376
9377  bool CanBeUnaryOperator = OperatorUses[Op][0];
9378  bool CanBeBinaryOperator = OperatorUses[Op][1];
9379  bool MustBeMemberOperator = OperatorUses[Op][2];
9380
9381  // C++ [over.oper]p8:
9382  //   [...] Operator functions cannot have more or fewer parameters
9383  //   than the number required for the corresponding operator, as
9384  //   described in the rest of this subclause.
9385  unsigned NumParams = FnDecl->getNumParams()
9386                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
9387  if (Op != OO_Call &&
9388      ((NumParams == 1 && !CanBeUnaryOperator) ||
9389       (NumParams == 2 && !CanBeBinaryOperator) ||
9390       (NumParams < 1) || (NumParams > 2))) {
9391    // We have the wrong number of parameters.
9392    unsigned ErrorKind;
9393    if (CanBeUnaryOperator && CanBeBinaryOperator) {
9394      ErrorKind = 2;  // 2 -> unary or binary.
9395    } else if (CanBeUnaryOperator) {
9396      ErrorKind = 0;  // 0 -> unary
9397    } else {
9398      assert(CanBeBinaryOperator &&
9399             "All non-call overloaded operators are unary or binary!");
9400      ErrorKind = 1;  // 1 -> binary
9401    }
9402
9403    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
9404      << FnDecl->getDeclName() << NumParams << ErrorKind;
9405  }
9406
9407  // Overloaded operators other than operator() cannot be variadic.
9408  if (Op != OO_Call &&
9409      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
9410    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
9411      << FnDecl->getDeclName();
9412  }
9413
9414  // Some operators must be non-static member functions.
9415  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9416    return Diag(FnDecl->getLocation(),
9417                diag::err_operator_overload_must_be_member)
9418      << FnDecl->getDeclName();
9419  }
9420
9421  // C++ [over.inc]p1:
9422  //   The user-defined function called operator++ implements the
9423  //   prefix and postfix ++ operator. If this function is a member
9424  //   function with no parameters, or a non-member function with one
9425  //   parameter of class or enumeration type, it defines the prefix
9426  //   increment operator ++ for objects of that type. If the function
9427  //   is a member function with one parameter (which shall be of type
9428  //   int) or a non-member function with two parameters (the second
9429  //   of which shall be of type int), it defines the postfix
9430  //   increment operator ++ for objects of that type.
9431  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9432    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9433    bool ParamIsInt = false;
9434    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
9435      ParamIsInt = BT->getKind() == BuiltinType::Int;
9436
9437    if (!ParamIsInt)
9438      return Diag(LastParam->getLocation(),
9439                  diag::err_operator_overload_post_incdec_must_be_int)
9440        << LastParam->getType() << (Op == OO_MinusMinus);
9441  }
9442
9443  return false;
9444}
9445
9446/// CheckLiteralOperatorDeclaration - Check whether the declaration
9447/// of this literal operator function is well-formed. If so, returns
9448/// false; otherwise, emits appropriate diagnostics and returns true.
9449bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9450  if (isa<CXXMethodDecl>(FnDecl)) {
9451    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9452      << FnDecl->getDeclName();
9453    return true;
9454  }
9455
9456  if (FnDecl->isExternC()) {
9457    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9458    return true;
9459  }
9460
9461  bool Valid = false;
9462
9463  // This might be the definition of a literal operator template.
9464  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9465  // This might be a specialization of a literal operator template.
9466  if (!TpDecl)
9467    TpDecl = FnDecl->getPrimaryTemplate();
9468
9469  // template <char...> type operator "" name() is the only valid template
9470  // signature, and the only valid signature with no parameters.
9471  if (TpDecl) {
9472    if (FnDecl->param_size() == 0) {
9473      // Must have only one template parameter
9474      TemplateParameterList *Params = TpDecl->getTemplateParameters();
9475      if (Params->size() == 1) {
9476        NonTypeTemplateParmDecl *PmDecl =
9477          dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
9478
9479        // The template parameter must be a char parameter pack.
9480        if (PmDecl && PmDecl->isTemplateParameterPack() &&
9481            Context.hasSameType(PmDecl->getType(), Context.CharTy))
9482          Valid = true;
9483      }
9484    }
9485  } else if (FnDecl->param_size()) {
9486    // Check the first parameter
9487    FunctionDecl::param_iterator Param = FnDecl->param_begin();
9488
9489    QualType T = (*Param)->getType().getUnqualifiedType();
9490
9491    // unsigned long long int, long double, and any character type are allowed
9492    // as the only parameters.
9493    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9494        Context.hasSameType(T, Context.LongDoubleTy) ||
9495        Context.hasSameType(T, Context.CharTy) ||
9496        Context.hasSameType(T, Context.WCharTy) ||
9497        Context.hasSameType(T, Context.Char16Ty) ||
9498        Context.hasSameType(T, Context.Char32Ty)) {
9499      if (++Param == FnDecl->param_end())
9500        Valid = true;
9501      goto FinishedParams;
9502    }
9503
9504    // Otherwise it must be a pointer to const; let's strip those qualifiers.
9505    const PointerType *PT = T->getAs<PointerType>();
9506    if (!PT)
9507      goto FinishedParams;
9508    T = PT->getPointeeType();
9509    if (!T.isConstQualified() || T.isVolatileQualified())
9510      goto FinishedParams;
9511    T = T.getUnqualifiedType();
9512
9513    // Move on to the second parameter;
9514    ++Param;
9515
9516    // If there is no second parameter, the first must be a const char *
9517    if (Param == FnDecl->param_end()) {
9518      if (Context.hasSameType(T, Context.CharTy))
9519        Valid = true;
9520      goto FinishedParams;
9521    }
9522
9523    // const char *, const wchar_t*, const char16_t*, and const char32_t*
9524    // are allowed as the first parameter to a two-parameter function
9525    if (!(Context.hasSameType(T, Context.CharTy) ||
9526          Context.hasSameType(T, Context.WCharTy) ||
9527          Context.hasSameType(T, Context.Char16Ty) ||
9528          Context.hasSameType(T, Context.Char32Ty)))
9529      goto FinishedParams;
9530
9531    // The second and final parameter must be an std::size_t
9532    T = (*Param)->getType().getUnqualifiedType();
9533    if (Context.hasSameType(T, Context.getSizeType()) &&
9534        ++Param == FnDecl->param_end())
9535      Valid = true;
9536  }
9537
9538  // FIXME: This diagnostic is absolutely terrible.
9539FinishedParams:
9540  if (!Valid) {
9541    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9542      << FnDecl->getDeclName();
9543    return true;
9544  }
9545
9546  // A parameter-declaration-clause containing a default argument is not
9547  // equivalent to any of the permitted forms.
9548  for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9549                                    ParamEnd = FnDecl->param_end();
9550       Param != ParamEnd; ++Param) {
9551    if ((*Param)->hasDefaultArg()) {
9552      Diag((*Param)->getDefaultArgRange().getBegin(),
9553           diag::err_literal_operator_default_argument)
9554        << (*Param)->getDefaultArgRange();
9555      break;
9556    }
9557  }
9558
9559  StringRef LiteralName
9560    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9561  if (LiteralName[0] != '_') {
9562    // C++11 [usrlit.suffix]p1:
9563    //   Literal suffix identifiers that do not start with an underscore
9564    //   are reserved for future standardization.
9565    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9566  }
9567
9568  return false;
9569}
9570
9571/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9572/// linkage specification, including the language and (if present)
9573/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9574/// the location of the language string literal, which is provided
9575/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9576/// the '{' brace. Otherwise, this linkage specification does not
9577/// have any braces.
9578Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9579                                           SourceLocation LangLoc,
9580                                           StringRef Lang,
9581                                           SourceLocation LBraceLoc) {
9582  LinkageSpecDecl::LanguageIDs Language;
9583  if (Lang == "\"C\"")
9584    Language = LinkageSpecDecl::lang_c;
9585  else if (Lang == "\"C++\"")
9586    Language = LinkageSpecDecl::lang_cxx;
9587  else {
9588    Diag(LangLoc, diag::err_bad_language);
9589    return 0;
9590  }
9591
9592  // FIXME: Add all the various semantics of linkage specifications
9593
9594  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
9595                                               ExternLoc, LangLoc, Language);
9596  CurContext->addDecl(D);
9597  PushDeclContext(S, D);
9598  return D;
9599}
9600
9601/// ActOnFinishLinkageSpecification - Complete the definition of
9602/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9603/// valid, it's the position of the closing '}' brace in a linkage
9604/// specification that uses braces.
9605Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
9606                                            Decl *LinkageSpec,
9607                                            SourceLocation RBraceLoc) {
9608  if (LinkageSpec) {
9609    if (RBraceLoc.isValid()) {
9610      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9611      LSDecl->setRBraceLoc(RBraceLoc);
9612    }
9613    PopDeclContext();
9614  }
9615  return LinkageSpec;
9616}
9617
9618/// \brief Perform semantic analysis for the variable declaration that
9619/// occurs within a C++ catch clause, returning the newly-created
9620/// variable.
9621VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
9622                                         TypeSourceInfo *TInfo,
9623                                         SourceLocation StartLoc,
9624                                         SourceLocation Loc,
9625                                         IdentifierInfo *Name) {
9626  bool Invalid = false;
9627  QualType ExDeclType = TInfo->getType();
9628
9629  // Arrays and functions decay.
9630  if (ExDeclType->isArrayType())
9631    ExDeclType = Context.getArrayDecayedType(ExDeclType);
9632  else if (ExDeclType->isFunctionType())
9633    ExDeclType = Context.getPointerType(ExDeclType);
9634
9635  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9636  // The exception-declaration shall not denote a pointer or reference to an
9637  // incomplete type, other than [cv] void*.
9638  // N2844 forbids rvalue references.
9639  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
9640    Diag(Loc, diag::err_catch_rvalue_ref);
9641    Invalid = true;
9642  }
9643
9644  QualType BaseType = ExDeclType;
9645  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
9646  unsigned DK = diag::err_catch_incomplete;
9647  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
9648    BaseType = Ptr->getPointeeType();
9649    Mode = 1;
9650    DK = diag::err_catch_incomplete_ptr;
9651  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
9652    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
9653    BaseType = Ref->getPointeeType();
9654    Mode = 2;
9655    DK = diag::err_catch_incomplete_ref;
9656  }
9657  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
9658      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
9659    Invalid = true;
9660
9661  if (!Invalid && !ExDeclType->isDependentType() &&
9662      RequireNonAbstractType(Loc, ExDeclType,
9663                             diag::err_abstract_type_in_decl,
9664                             AbstractVariableType))
9665    Invalid = true;
9666
9667  // Only the non-fragile NeXT runtime currently supports C++ catches
9668  // of ObjC types, and no runtime supports catching ObjC types by value.
9669  if (!Invalid && getLangOpts().ObjC1) {
9670    QualType T = ExDeclType;
9671    if (const ReferenceType *RT = T->getAs<ReferenceType>())
9672      T = RT->getPointeeType();
9673
9674    if (T->isObjCObjectType()) {
9675      Diag(Loc, diag::err_objc_object_catch);
9676      Invalid = true;
9677    } else if (T->isObjCObjectPointerType()) {
9678      // FIXME: should this be a test for macosx-fragile specifically?
9679      if (getLangOpts().ObjCRuntime.isFragile())
9680        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
9681    }
9682  }
9683
9684  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9685                                    ExDeclType, TInfo, SC_None, SC_None);
9686  ExDecl->setExceptionVariable(true);
9687
9688  // In ARC, infer 'retaining' for variables of retainable type.
9689  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9690    Invalid = true;
9691
9692  if (!Invalid && !ExDeclType->isDependentType()) {
9693    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
9694      // C++ [except.handle]p16:
9695      //   The object declared in an exception-declaration or, if the
9696      //   exception-declaration does not specify a name, a temporary (12.2) is
9697      //   copy-initialized (8.5) from the exception object. [...]
9698      //   The object is destroyed when the handler exits, after the destruction
9699      //   of any automatic objects initialized within the handler.
9700      //
9701      // We just pretend to initialize the object with itself, then make sure
9702      // it can be destroyed later.
9703      QualType initType = ExDeclType;
9704
9705      InitializedEntity entity =
9706        InitializedEntity::InitializeVariable(ExDecl);
9707      InitializationKind initKind =
9708        InitializationKind::CreateCopy(Loc, SourceLocation());
9709
9710      Expr *opaqueValue =
9711        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9712      InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9713      ExprResult result = sequence.Perform(*this, entity, initKind,
9714                                           MultiExprArg(&opaqueValue, 1));
9715      if (result.isInvalid())
9716        Invalid = true;
9717      else {
9718        // If the constructor used was non-trivial, set this as the
9719        // "initializer".
9720        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9721        if (!construct->getConstructor()->isTrivial()) {
9722          Expr *init = MaybeCreateExprWithCleanups(construct);
9723          ExDecl->setInit(init);
9724        }
9725
9726        // And make sure it's destructable.
9727        FinalizeVarWithDestructor(ExDecl, recordType);
9728      }
9729    }
9730  }
9731
9732  if (Invalid)
9733    ExDecl->setInvalidDecl();
9734
9735  return ExDecl;
9736}
9737
9738/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9739/// handler.
9740Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
9741  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9742  bool Invalid = D.isInvalidType();
9743
9744  // Check for unexpanded parameter packs.
9745  if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9746                                               UPPC_ExceptionType)) {
9747    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9748                                             D.getIdentifierLoc());
9749    Invalid = true;
9750  }
9751
9752  IdentifierInfo *II = D.getIdentifier();
9753  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
9754                                             LookupOrdinaryName,
9755                                             ForRedeclaration)) {
9756    // The scope should be freshly made just for us. There is just no way
9757    // it contains any previous declaration.
9758    assert(!S->isDeclScope(PrevDecl));
9759    if (PrevDecl->isTemplateParameter()) {
9760      // Maybe we will complain about the shadowed template parameter.
9761      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9762      PrevDecl = 0;
9763    }
9764  }
9765
9766  if (D.getCXXScopeSpec().isSet() && !Invalid) {
9767    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9768      << D.getCXXScopeSpec().getRange();
9769    Invalid = true;
9770  }
9771
9772  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
9773                                              D.getLocStart(),
9774                                              D.getIdentifierLoc(),
9775                                              D.getIdentifier());
9776  if (Invalid)
9777    ExDecl->setInvalidDecl();
9778
9779  // Add the exception declaration into this scope.
9780  if (II)
9781    PushOnScopeChains(ExDecl, S);
9782  else
9783    CurContext->addDecl(ExDecl);
9784
9785  ProcessDeclAttributes(S, ExDecl, D);
9786  return ExDecl;
9787}
9788
9789Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9790                                         Expr *AssertExpr,
9791                                         Expr *AssertMessageExpr,
9792                                         SourceLocation RParenLoc) {
9793  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
9794
9795  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9796    return 0;
9797
9798  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
9799                                      AssertMessage, RParenLoc, false);
9800}
9801
9802Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9803                                         Expr *AssertExpr,
9804                                         StringLiteral *AssertMessage,
9805                                         SourceLocation RParenLoc,
9806                                         bool Failed) {
9807  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
9808      !Failed) {
9809    // In a static_assert-declaration, the constant-expression shall be a
9810    // constant expression that can be contextually converted to bool.
9811    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9812    if (Converted.isInvalid())
9813      Failed = true;
9814
9815    llvm::APSInt Cond;
9816    if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
9817          diag::err_static_assert_expression_is_not_constant,
9818          /*AllowFold=*/false).isInvalid())
9819      Failed = true;
9820
9821    if (!Failed && !Cond) {
9822      llvm::SmallString<256> MsgBuffer;
9823      llvm::raw_svector_ostream Msg(MsgBuffer);
9824      AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
9825      Diag(StaticAssertLoc, diag::err_static_assert_failed)
9826        << Msg.str() << AssertExpr->getSourceRange();
9827      Failed = true;
9828    }
9829  }
9830
9831  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9832                                        AssertExpr, AssertMessage, RParenLoc,
9833                                        Failed);
9834
9835  CurContext->addDecl(Decl);
9836  return Decl;
9837}
9838
9839/// \brief Perform semantic analysis of the given friend type declaration.
9840///
9841/// \returns A friend declaration that.
9842FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9843                                      SourceLocation FriendLoc,
9844                                      TypeSourceInfo *TSInfo) {
9845  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9846
9847  QualType T = TSInfo->getType();
9848  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
9849
9850  // C++03 [class.friend]p2:
9851  //   An elaborated-type-specifier shall be used in a friend declaration
9852  //   for a class.*
9853  //
9854  //   * The class-key of the elaborated-type-specifier is required.
9855  if (!ActiveTemplateInstantiations.empty()) {
9856    // Do not complain about the form of friend template types during
9857    // template instantiation; we will already have complained when the
9858    // template was declared.
9859  } else if (!T->isElaboratedTypeSpecifier()) {
9860    // If we evaluated the type to a record type, suggest putting
9861    // a tag in front.
9862    if (const RecordType *RT = T->getAs<RecordType>()) {
9863      RecordDecl *RD = RT->getDecl();
9864
9865      std::string InsertionText = std::string(" ") + RD->getKindName();
9866
9867      Diag(TypeRange.getBegin(),
9868           getLangOpts().CPlusPlus0x ?
9869             diag::warn_cxx98_compat_unelaborated_friend_type :
9870             diag::ext_unelaborated_friend_type)
9871        << (unsigned) RD->getTagKind()
9872        << T
9873        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9874                                      InsertionText);
9875    } else {
9876      Diag(FriendLoc,
9877           getLangOpts().CPlusPlus0x ?
9878             diag::warn_cxx98_compat_nonclass_type_friend :
9879             diag::ext_nonclass_type_friend)
9880        << T
9881        << SourceRange(FriendLoc, TypeRange.getEnd());
9882    }
9883  } else if (T->getAs<EnumType>()) {
9884    Diag(FriendLoc,
9885         getLangOpts().CPlusPlus0x ?
9886           diag::warn_cxx98_compat_enum_friend :
9887           diag::ext_enum_friend)
9888      << T
9889      << SourceRange(FriendLoc, TypeRange.getEnd());
9890  }
9891
9892  // C++0x [class.friend]p3:
9893  //   If the type specifier in a friend declaration designates a (possibly
9894  //   cv-qualified) class type, that class is declared as a friend; otherwise,
9895  //   the friend declaration is ignored.
9896
9897  // FIXME: C++0x has some syntactic restrictions on friend type declarations
9898  // in [class.friend]p3 that we do not implement.
9899
9900  return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
9901}
9902
9903/// Handle a friend tag declaration where the scope specifier was
9904/// templated.
9905Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9906                                    unsigned TagSpec, SourceLocation TagLoc,
9907                                    CXXScopeSpec &SS,
9908                                    IdentifierInfo *Name, SourceLocation NameLoc,
9909                                    AttributeList *Attr,
9910                                    MultiTemplateParamsArg TempParamLists) {
9911  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9912
9913  bool isExplicitSpecialization = false;
9914  bool Invalid = false;
9915
9916  if (TemplateParameterList *TemplateParams
9917        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
9918                                                  TempParamLists.data(),
9919                                                  TempParamLists.size(),
9920                                                  /*friend*/ true,
9921                                                  isExplicitSpecialization,
9922                                                  Invalid)) {
9923    if (TemplateParams->size() > 0) {
9924      // This is a declaration of a class template.
9925      if (Invalid)
9926        return 0;
9927
9928      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9929                                SS, Name, NameLoc, Attr,
9930                                TemplateParams, AS_public,
9931                                /*ModulePrivateLoc=*/SourceLocation(),
9932                                TempParamLists.size() - 1,
9933                                TempParamLists.data()).take();
9934    } else {
9935      // The "template<>" header is extraneous.
9936      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9937        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9938      isExplicitSpecialization = true;
9939    }
9940  }
9941
9942  if (Invalid) return 0;
9943
9944  bool isAllExplicitSpecializations = true;
9945  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
9946    if (TempParamLists[I]->size()) {
9947      isAllExplicitSpecializations = false;
9948      break;
9949    }
9950  }
9951
9952  // FIXME: don't ignore attributes.
9953
9954  // If it's explicit specializations all the way down, just forget
9955  // about the template header and build an appropriate non-templated
9956  // friend.  TODO: for source fidelity, remember the headers.
9957  if (isAllExplicitSpecializations) {
9958    if (SS.isEmpty()) {
9959      bool Owned = false;
9960      bool IsDependent = false;
9961      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9962                      Attr, AS_public,
9963                      /*ModulePrivateLoc=*/SourceLocation(),
9964                      MultiTemplateParamsArg(), Owned, IsDependent,
9965                      /*ScopedEnumKWLoc=*/SourceLocation(),
9966                      /*ScopedEnumUsesClassTag=*/false,
9967                      /*UnderlyingType=*/TypeResult());
9968    }
9969
9970    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9971    ElaboratedTypeKeyword Keyword
9972      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9973    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
9974                                   *Name, NameLoc);
9975    if (T.isNull())
9976      return 0;
9977
9978    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9979    if (isa<DependentNameType>(T)) {
9980      DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9981      TL.setElaboratedKeywordLoc(TagLoc);
9982      TL.setQualifierLoc(QualifierLoc);
9983      TL.setNameLoc(NameLoc);
9984    } else {
9985      ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9986      TL.setElaboratedKeywordLoc(TagLoc);
9987      TL.setQualifierLoc(QualifierLoc);
9988      cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9989    }
9990
9991    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9992                                            TSI, FriendLoc);
9993    Friend->setAccess(AS_public);
9994    CurContext->addDecl(Friend);
9995    return Friend;
9996  }
9997
9998  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9999
10000
10001
10002  // Handle the case of a templated-scope friend class.  e.g.
10003  //   template <class T> class A<T>::B;
10004  // FIXME: we don't support these right now.
10005  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10006  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10007  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10008  DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10009  TL.setElaboratedKeywordLoc(TagLoc);
10010  TL.setQualifierLoc(SS.getWithLocInContext(Context));
10011  TL.setNameLoc(NameLoc);
10012
10013  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10014                                          TSI, FriendLoc);
10015  Friend->setAccess(AS_public);
10016  Friend->setUnsupportedFriend(true);
10017  CurContext->addDecl(Friend);
10018  return Friend;
10019}
10020
10021
10022/// Handle a friend type declaration.  This works in tandem with
10023/// ActOnTag.
10024///
10025/// Notes on friend class templates:
10026///
10027/// We generally treat friend class declarations as if they were
10028/// declaring a class.  So, for example, the elaborated type specifier
10029/// in a friend declaration is required to obey the restrictions of a
10030/// class-head (i.e. no typedefs in the scope chain), template
10031/// parameters are required to match up with simple template-ids, &c.
10032/// However, unlike when declaring a template specialization, it's
10033/// okay to refer to a template specialization without an empty
10034/// template parameter declaration, e.g.
10035///   friend class A<T>::B<unsigned>;
10036/// We permit this as a special case; if there are any template
10037/// parameters present at all, require proper matching, i.e.
10038///   template <> template \<class T> friend class A<int>::B;
10039Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
10040                                MultiTemplateParamsArg TempParams) {
10041  SourceLocation Loc = DS.getLocStart();
10042
10043  assert(DS.isFriendSpecified());
10044  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10045
10046  // Try to convert the decl specifier to a type.  This works for
10047  // friend templates because ActOnTag never produces a ClassTemplateDecl
10048  // for a TUK_Friend.
10049  Declarator TheDeclarator(DS, Declarator::MemberContext);
10050  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10051  QualType T = TSI->getType();
10052  if (TheDeclarator.isInvalidType())
10053    return 0;
10054
10055  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10056    return 0;
10057
10058  // This is definitely an error in C++98.  It's probably meant to
10059  // be forbidden in C++0x, too, but the specification is just
10060  // poorly written.
10061  //
10062  // The problem is with declarations like the following:
10063  //   template <T> friend A<T>::foo;
10064  // where deciding whether a class C is a friend or not now hinges
10065  // on whether there exists an instantiation of A that causes
10066  // 'foo' to equal C.  There are restrictions on class-heads
10067  // (which we declare (by fiat) elaborated friend declarations to
10068  // be) that makes this tractable.
10069  //
10070  // FIXME: handle "template <> friend class A<T>;", which
10071  // is possibly well-formed?  Who even knows?
10072  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
10073    Diag(Loc, diag::err_tagless_friend_type_template)
10074      << DS.getSourceRange();
10075    return 0;
10076  }
10077
10078  // C++98 [class.friend]p1: A friend of a class is a function
10079  //   or class that is not a member of the class . . .
10080  // This is fixed in DR77, which just barely didn't make the C++03
10081  // deadline.  It's also a very silly restriction that seriously
10082  // affects inner classes and which nobody else seems to implement;
10083  // thus we never diagnose it, not even in -pedantic.
10084  //
10085  // But note that we could warn about it: it's always useless to
10086  // friend one of your own members (it's not, however, worthless to
10087  // friend a member of an arbitrary specialization of your template).
10088
10089  Decl *D;
10090  if (unsigned NumTempParamLists = TempParams.size())
10091    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
10092                                   NumTempParamLists,
10093                                   TempParams.data(),
10094                                   TSI,
10095                                   DS.getFriendSpecLoc());
10096  else
10097    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
10098
10099  if (!D)
10100    return 0;
10101
10102  D->setAccess(AS_public);
10103  CurContext->addDecl(D);
10104
10105  return D;
10106}
10107
10108Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10109                                    MultiTemplateParamsArg TemplateParams) {
10110  const DeclSpec &DS = D.getDeclSpec();
10111
10112  assert(DS.isFriendSpecified());
10113  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10114
10115  SourceLocation Loc = D.getIdentifierLoc();
10116  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10117
10118  // C++ [class.friend]p1
10119  //   A friend of a class is a function or class....
10120  // Note that this sees through typedefs, which is intended.
10121  // It *doesn't* see through dependent types, which is correct
10122  // according to [temp.arg.type]p3:
10123  //   If a declaration acquires a function type through a
10124  //   type dependent on a template-parameter and this causes
10125  //   a declaration that does not use the syntactic form of a
10126  //   function declarator to have a function type, the program
10127  //   is ill-formed.
10128  if (!TInfo->getType()->isFunctionType()) {
10129    Diag(Loc, diag::err_unexpected_friend);
10130
10131    // It might be worthwhile to try to recover by creating an
10132    // appropriate declaration.
10133    return 0;
10134  }
10135
10136  // C++ [namespace.memdef]p3
10137  //  - If a friend declaration in a non-local class first declares a
10138  //    class or function, the friend class or function is a member
10139  //    of the innermost enclosing namespace.
10140  //  - The name of the friend is not found by simple name lookup
10141  //    until a matching declaration is provided in that namespace
10142  //    scope (either before or after the class declaration granting
10143  //    friendship).
10144  //  - If a friend function is called, its name may be found by the
10145  //    name lookup that considers functions from namespaces and
10146  //    classes associated with the types of the function arguments.
10147  //  - When looking for a prior declaration of a class or a function
10148  //    declared as a friend, scopes outside the innermost enclosing
10149  //    namespace scope are not considered.
10150
10151  CXXScopeSpec &SS = D.getCXXScopeSpec();
10152  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10153  DeclarationName Name = NameInfo.getName();
10154  assert(Name);
10155
10156  // Check for unexpanded parameter packs.
10157  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10158      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10159      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10160    return 0;
10161
10162  // The context we found the declaration in, or in which we should
10163  // create the declaration.
10164  DeclContext *DC;
10165  Scope *DCScope = S;
10166  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10167                        ForRedeclaration);
10168
10169  // FIXME: there are different rules in local classes
10170
10171  // There are four cases here.
10172  //   - There's no scope specifier, in which case we just go to the
10173  //     appropriate scope and look for a function or function template
10174  //     there as appropriate.
10175  // Recover from invalid scope qualifiers as if they just weren't there.
10176  if (SS.isInvalid() || !SS.isSet()) {
10177    // C++0x [namespace.memdef]p3:
10178    //   If the name in a friend declaration is neither qualified nor
10179    //   a template-id and the declaration is a function or an
10180    //   elaborated-type-specifier, the lookup to determine whether
10181    //   the entity has been previously declared shall not consider
10182    //   any scopes outside the innermost enclosing namespace.
10183    // C++0x [class.friend]p11:
10184    //   If a friend declaration appears in a local class and the name
10185    //   specified is an unqualified name, a prior declaration is
10186    //   looked up without considering scopes that are outside the
10187    //   innermost enclosing non-class scope. For a friend function
10188    //   declaration, if there is no prior declaration, the program is
10189    //   ill-formed.
10190    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
10191    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
10192
10193    // Find the appropriate context according to the above.
10194    DC = CurContext;
10195    while (true) {
10196      // Skip class contexts.  If someone can cite chapter and verse
10197      // for this behavior, that would be nice --- it's what GCC and
10198      // EDG do, and it seems like a reasonable intent, but the spec
10199      // really only says that checks for unqualified existing
10200      // declarations should stop at the nearest enclosing namespace,
10201      // not that they should only consider the nearest enclosing
10202      // namespace.
10203      while (DC->isRecord() || DC->isTransparentContext())
10204        DC = DC->getParent();
10205
10206      LookupQualifiedName(Previous, DC);
10207
10208      // TODO: decide what we think about using declarations.
10209      if (isLocal || !Previous.empty())
10210        break;
10211
10212      if (isTemplateId) {
10213        if (isa<TranslationUnitDecl>(DC)) break;
10214      } else {
10215        if (DC->isFileContext()) break;
10216      }
10217      DC = DC->getParent();
10218    }
10219
10220    // C++ [class.friend]p1: A friend of a class is a function or
10221    //   class that is not a member of the class . . .
10222    // C++11 changes this for both friend types and functions.
10223    // Most C++ 98 compilers do seem to give an error here, so
10224    // we do, too.
10225    if (!Previous.empty() && DC->Equals(CurContext))
10226      Diag(DS.getFriendSpecLoc(),
10227           getLangOpts().CPlusPlus0x ?
10228             diag::warn_cxx98_compat_friend_is_member :
10229             diag::err_friend_is_member);
10230
10231    DCScope = getScopeForDeclContext(S, DC);
10232
10233    // C++ [class.friend]p6:
10234    //   A function can be defined in a friend declaration of a class if and
10235    //   only if the class is a non-local class (9.8), the function name is
10236    //   unqualified, and the function has namespace scope.
10237    if (isLocal && D.isFunctionDefinition()) {
10238      Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10239    }
10240
10241  //   - There's a non-dependent scope specifier, in which case we
10242  //     compute it and do a previous lookup there for a function
10243  //     or function template.
10244  } else if (!SS.getScopeRep()->isDependent()) {
10245    DC = computeDeclContext(SS);
10246    if (!DC) return 0;
10247
10248    if (RequireCompleteDeclContext(SS, DC)) return 0;
10249
10250    LookupQualifiedName(Previous, DC);
10251
10252    // Ignore things found implicitly in the wrong scope.
10253    // TODO: better diagnostics for this case.  Suggesting the right
10254    // qualified scope would be nice...
10255    LookupResult::Filter F = Previous.makeFilter();
10256    while (F.hasNext()) {
10257      NamedDecl *D = F.next();
10258      if (!DC->InEnclosingNamespaceSetOf(
10259              D->getDeclContext()->getRedeclContext()))
10260        F.erase();
10261    }
10262    F.done();
10263
10264    if (Previous.empty()) {
10265      D.setInvalidType();
10266      Diag(Loc, diag::err_qualified_friend_not_found)
10267          << Name << TInfo->getType();
10268      return 0;
10269    }
10270
10271    // C++ [class.friend]p1: A friend of a class is a function or
10272    //   class that is not a member of the class . . .
10273    if (DC->Equals(CurContext))
10274      Diag(DS.getFriendSpecLoc(),
10275           getLangOpts().CPlusPlus0x ?
10276             diag::warn_cxx98_compat_friend_is_member :
10277             diag::err_friend_is_member);
10278
10279    if (D.isFunctionDefinition()) {
10280      // C++ [class.friend]p6:
10281      //   A function can be defined in a friend declaration of a class if and
10282      //   only if the class is a non-local class (9.8), the function name is
10283      //   unqualified, and the function has namespace scope.
10284      SemaDiagnosticBuilder DB
10285        = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10286
10287      DB << SS.getScopeRep();
10288      if (DC->isFileContext())
10289        DB << FixItHint::CreateRemoval(SS.getRange());
10290      SS.clear();
10291    }
10292
10293  //   - There's a scope specifier that does not match any template
10294  //     parameter lists, in which case we use some arbitrary context,
10295  //     create a method or method template, and wait for instantiation.
10296  //   - There's a scope specifier that does match some template
10297  //     parameter lists, which we don't handle right now.
10298  } else {
10299    if (D.isFunctionDefinition()) {
10300      // C++ [class.friend]p6:
10301      //   A function can be defined in a friend declaration of a class if and
10302      //   only if the class is a non-local class (9.8), the function name is
10303      //   unqualified, and the function has namespace scope.
10304      Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10305        << SS.getScopeRep();
10306    }
10307
10308    DC = CurContext;
10309    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
10310  }
10311
10312  if (!DC->isRecord()) {
10313    // This implies that it has to be an operator or function.
10314    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10315        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10316        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
10317      Diag(Loc, diag::err_introducing_special_friend) <<
10318        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10319         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
10320      return 0;
10321    }
10322  }
10323
10324  // FIXME: This is an egregious hack to cope with cases where the scope stack
10325  // does not contain the declaration context, i.e., in an out-of-line
10326  // definition of a class.
10327  Scope FakeDCScope(S, Scope::DeclScope, Diags);
10328  if (!DCScope) {
10329    FakeDCScope.setEntity(DC);
10330    DCScope = &FakeDCScope;
10331  }
10332
10333  bool AddToScope = true;
10334  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10335                                          TemplateParams, AddToScope);
10336  if (!ND) return 0;
10337
10338  assert(ND->getDeclContext() == DC);
10339  assert(ND->getLexicalDeclContext() == CurContext);
10340
10341  // Add the function declaration to the appropriate lookup tables,
10342  // adjusting the redeclarations list as necessary.  We don't
10343  // want to do this yet if the friending class is dependent.
10344  //
10345  // Also update the scope-based lookup if the target context's
10346  // lookup context is in lexical scope.
10347  if (!CurContext->isDependentContext()) {
10348    DC = DC->getRedeclContext();
10349    DC->makeDeclVisibleInContext(ND);
10350    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10351      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
10352  }
10353
10354  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
10355                                       D.getIdentifierLoc(), ND,
10356                                       DS.getFriendSpecLoc());
10357  FrD->setAccess(AS_public);
10358  CurContext->addDecl(FrD);
10359
10360  if (ND->isInvalidDecl()) {
10361    FrD->setInvalidDecl();
10362  } else {
10363    if (DC->isRecord()) CheckFriendAccess(ND);
10364
10365    FunctionDecl *FD;
10366    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10367      FD = FTD->getTemplatedDecl();
10368    else
10369      FD = cast<FunctionDecl>(ND);
10370
10371    // Mark templated-scope function declarations as unsupported.
10372    if (FD->getNumTemplateParameterLists())
10373      FrD->setUnsupportedFriend(true);
10374  }
10375
10376  return ND;
10377}
10378
10379void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10380  AdjustDeclIfTemplate(Dcl);
10381
10382  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10383  if (!Fn) {
10384    Diag(DelLoc, diag::err_deleted_non_function);
10385    return;
10386  }
10387  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
10388    // Don't consider the implicit declaration we generate for explicit
10389    // specializations. FIXME: Do not generate these implicit declarations.
10390    if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10391        || Prev->getPreviousDecl()) && !Prev->isDefined()) {
10392      Diag(DelLoc, diag::err_deleted_decl_not_first);
10393      Diag(Prev->getLocation(), diag::note_previous_declaration);
10394    }
10395    // If the declaration wasn't the first, we delete the function anyway for
10396    // recovery.
10397  }
10398  Fn->setDeletedAsWritten();
10399
10400  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10401  if (!MD)
10402    return;
10403
10404  // A deleted special member function is trivial if the corresponding
10405  // implicitly-declared function would have been.
10406  switch (getSpecialMember(MD)) {
10407  case CXXInvalid:
10408    break;
10409  case CXXDefaultConstructor:
10410    MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10411    break;
10412  case CXXCopyConstructor:
10413    MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10414    break;
10415  case CXXMoveConstructor:
10416    MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10417    break;
10418  case CXXCopyAssignment:
10419    MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10420    break;
10421  case CXXMoveAssignment:
10422    MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10423    break;
10424  case CXXDestructor:
10425    MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10426    break;
10427  }
10428}
10429
10430void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10431  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10432
10433  if (MD) {
10434    if (MD->getParent()->isDependentType()) {
10435      MD->setDefaulted();
10436      MD->setExplicitlyDefaulted();
10437      return;
10438    }
10439
10440    CXXSpecialMember Member = getSpecialMember(MD);
10441    if (Member == CXXInvalid) {
10442      Diag(DefaultLoc, diag::err_default_special_members);
10443      return;
10444    }
10445
10446    MD->setDefaulted();
10447    MD->setExplicitlyDefaulted();
10448
10449    // If this definition appears within the record, do the checking when
10450    // the record is complete.
10451    const FunctionDecl *Primary = MD;
10452    if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
10453      // Find the uninstantiated declaration that actually had the '= default'
10454      // on it.
10455      Pattern->isDefined(Primary);
10456
10457    if (Primary == Primary->getCanonicalDecl())
10458      return;
10459
10460    CheckExplicitlyDefaultedSpecialMember(MD);
10461
10462    switch (Member) {
10463    case CXXDefaultConstructor: {
10464      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10465      if (!CD->isInvalidDecl())
10466        DefineImplicitDefaultConstructor(DefaultLoc, CD);
10467      break;
10468    }
10469
10470    case CXXCopyConstructor: {
10471      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10472      if (!CD->isInvalidDecl())
10473        DefineImplicitCopyConstructor(DefaultLoc, CD);
10474      break;
10475    }
10476
10477    case CXXCopyAssignment: {
10478      if (!MD->isInvalidDecl())
10479        DefineImplicitCopyAssignment(DefaultLoc, MD);
10480      break;
10481    }
10482
10483    case CXXDestructor: {
10484      CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10485      if (!DD->isInvalidDecl())
10486        DefineImplicitDestructor(DefaultLoc, DD);
10487      break;
10488    }
10489
10490    case CXXMoveConstructor: {
10491      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10492      if (!CD->isInvalidDecl())
10493        DefineImplicitMoveConstructor(DefaultLoc, CD);
10494      break;
10495    }
10496
10497    case CXXMoveAssignment: {
10498      if (!MD->isInvalidDecl())
10499        DefineImplicitMoveAssignment(DefaultLoc, MD);
10500      break;
10501    }
10502
10503    case CXXInvalid:
10504      llvm_unreachable("Invalid special member.");
10505    }
10506  } else {
10507    Diag(DefaultLoc, diag::err_default_special_members);
10508  }
10509}
10510
10511static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
10512  for (Stmt::child_range CI = S->children(); CI; ++CI) {
10513    Stmt *SubStmt = *CI;
10514    if (!SubStmt)
10515      continue;
10516    if (isa<ReturnStmt>(SubStmt))
10517      Self.Diag(SubStmt->getLocStart(),
10518           diag::err_return_in_constructor_handler);
10519    if (!isa<Expr>(SubStmt))
10520      SearchForReturnInStmt(Self, SubStmt);
10521  }
10522}
10523
10524void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10525  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10526    CXXCatchStmt *Handler = TryBlock->getHandler(I);
10527    SearchForReturnInStmt(*this, Handler);
10528  }
10529}
10530
10531bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
10532                                             const CXXMethodDecl *Old) {
10533  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10534  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
10535
10536  if (Context.hasSameType(NewTy, OldTy) ||
10537      NewTy->isDependentType() || OldTy->isDependentType())
10538    return false;
10539
10540  // Check if the return types are covariant
10541  QualType NewClassTy, OldClassTy;
10542
10543  /// Both types must be pointers or references to classes.
10544  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10545    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
10546      NewClassTy = NewPT->getPointeeType();
10547      OldClassTy = OldPT->getPointeeType();
10548    }
10549  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10550    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10551      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10552        NewClassTy = NewRT->getPointeeType();
10553        OldClassTy = OldRT->getPointeeType();
10554      }
10555    }
10556  }
10557
10558  // The return types aren't either both pointers or references to a class type.
10559  if (NewClassTy.isNull()) {
10560    Diag(New->getLocation(),
10561         diag::err_different_return_type_for_overriding_virtual_function)
10562      << New->getDeclName() << NewTy << OldTy;
10563    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10564
10565    return true;
10566  }
10567
10568  // C++ [class.virtual]p6:
10569  //   If the return type of D::f differs from the return type of B::f, the
10570  //   class type in the return type of D::f shall be complete at the point of
10571  //   declaration of D::f or shall be the class type D.
10572  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10573    if (!RT->isBeingDefined() &&
10574        RequireCompleteType(New->getLocation(), NewClassTy,
10575                            diag::err_covariant_return_incomplete,
10576                            New->getDeclName()))
10577    return true;
10578  }
10579
10580  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
10581    // Check if the new class derives from the old class.
10582    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10583      Diag(New->getLocation(),
10584           diag::err_covariant_return_not_derived)
10585      << New->getDeclName() << NewTy << OldTy;
10586      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10587      return true;
10588    }
10589
10590    // Check if we the conversion from derived to base is valid.
10591    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
10592                    diag::err_covariant_return_inaccessible_base,
10593                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
10594                    // FIXME: Should this point to the return type?
10595                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
10596      // FIXME: this note won't trigger for delayed access control
10597      // diagnostics, and it's impossible to get an undelayed error
10598      // here from access control during the original parse because
10599      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
10600      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10601      return true;
10602    }
10603  }
10604
10605  // The qualifiers of the return types must be the same.
10606  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
10607    Diag(New->getLocation(),
10608         diag::err_covariant_return_type_different_qualifications)
10609    << New->getDeclName() << NewTy << OldTy;
10610    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10611    return true;
10612  };
10613
10614
10615  // The new class type must have the same or less qualifiers as the old type.
10616  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10617    Diag(New->getLocation(),
10618         diag::err_covariant_return_type_class_type_more_qualified)
10619    << New->getDeclName() << NewTy << OldTy;
10620    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10621    return true;
10622  };
10623
10624  return false;
10625}
10626
10627/// \brief Mark the given method pure.
10628///
10629/// \param Method the method to be marked pure.
10630///
10631/// \param InitRange the source range that covers the "0" initializer.
10632bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
10633  SourceLocation EndLoc = InitRange.getEnd();
10634  if (EndLoc.isValid())
10635    Method->setRangeEnd(EndLoc);
10636
10637  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10638    Method->setPure();
10639    return false;
10640  }
10641
10642  if (!Method->isInvalidDecl())
10643    Diag(Method->getLocation(), diag::err_non_virtual_pure)
10644      << Method->getDeclName() << InitRange;
10645  return true;
10646}
10647
10648/// \brief Determine whether the given declaration is a static data member.
10649static bool isStaticDataMember(Decl *D) {
10650  VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10651  if (!Var)
10652    return false;
10653
10654  return Var->isStaticDataMember();
10655}
10656/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10657/// an initializer for the out-of-line declaration 'Dcl'.  The scope
10658/// is a fresh scope pushed for just this purpose.
10659///
10660/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10661/// static data member of class X, names should be looked up in the scope of
10662/// class X.
10663void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
10664  // If there is no declaration, there was an error parsing it.
10665  if (D == 0 || D->isInvalidDecl()) return;
10666
10667  // We should only get called for declarations with scope specifiers, like:
10668  //   int foo::bar;
10669  assert(D->isOutOfLine());
10670  EnterDeclaratorContext(S, D->getDeclContext());
10671
10672  // If we are parsing the initializer for a static data member, push a
10673  // new expression evaluation context that is associated with this static
10674  // data member.
10675  if (isStaticDataMember(D))
10676    PushExpressionEvaluationContext(PotentiallyEvaluated, D);
10677}
10678
10679/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
10680/// initializer for the out-of-line declaration 'D'.
10681void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
10682  // If there is no declaration, there was an error parsing it.
10683  if (D == 0 || D->isInvalidDecl()) return;
10684
10685  if (isStaticDataMember(D))
10686    PopExpressionEvaluationContext();
10687
10688  assert(D->isOutOfLine());
10689  ExitDeclaratorContext(S);
10690}
10691
10692/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10693/// C++ if/switch/while/for statement.
10694/// e.g: "if (int x = f()) {...}"
10695DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
10696  // C++ 6.4p2:
10697  // The declarator shall not specify a function or an array.
10698  // The type-specifier-seq shall not contain typedef and shall not declare a
10699  // new class or enumeration.
10700  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10701         "Parser allowed 'typedef' as storage class of condition decl.");
10702
10703  Decl *Dcl = ActOnDeclarator(S, D);
10704  if (!Dcl)
10705    return true;
10706
10707  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10708    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
10709      << D.getSourceRange();
10710    return true;
10711  }
10712
10713  return Dcl;
10714}
10715
10716void Sema::LoadExternalVTableUses() {
10717  if (!ExternalSource)
10718    return;
10719
10720  SmallVector<ExternalVTableUse, 4> VTables;
10721  ExternalSource->ReadUsedVTables(VTables);
10722  SmallVector<VTableUse, 4> NewUses;
10723  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10724    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10725      = VTablesUsed.find(VTables[I].Record);
10726    // Even if a definition wasn't required before, it may be required now.
10727    if (Pos != VTablesUsed.end()) {
10728      if (!Pos->second && VTables[I].DefinitionRequired)
10729        Pos->second = true;
10730      continue;
10731    }
10732
10733    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10734    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10735  }
10736
10737  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10738}
10739
10740void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10741                          bool DefinitionRequired) {
10742  // Ignore any vtable uses in unevaluated operands or for classes that do
10743  // not have a vtable.
10744  if (!Class->isDynamicClass() || Class->isDependentContext() ||
10745      CurContext->isDependentContext() ||
10746      ExprEvalContexts.back().Context == Unevaluated)
10747    return;
10748
10749  // Try to insert this class into the map.
10750  LoadExternalVTableUses();
10751  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10752  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10753    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10754  if (!Pos.second) {
10755    // If we already had an entry, check to see if we are promoting this vtable
10756    // to required a definition. If so, we need to reappend to the VTableUses
10757    // list, since we may have already processed the first entry.
10758    if (DefinitionRequired && !Pos.first->second) {
10759      Pos.first->second = true;
10760    } else {
10761      // Otherwise, we can early exit.
10762      return;
10763    }
10764  }
10765
10766  // Local classes need to have their virtual members marked
10767  // immediately. For all other classes, we mark their virtual members
10768  // at the end of the translation unit.
10769  if (Class->isLocalClass())
10770    MarkVirtualMembersReferenced(Loc, Class);
10771  else
10772    VTableUses.push_back(std::make_pair(Class, Loc));
10773}
10774
10775bool Sema::DefineUsedVTables() {
10776  LoadExternalVTableUses();
10777  if (VTableUses.empty())
10778    return false;
10779
10780  // Note: The VTableUses vector could grow as a result of marking
10781  // the members of a class as "used", so we check the size each
10782  // time through the loop and prefer indices (which are stable) to
10783  // iterators (which are not).
10784  bool DefinedAnything = false;
10785  for (unsigned I = 0; I != VTableUses.size(); ++I) {
10786    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
10787    if (!Class)
10788      continue;
10789
10790    SourceLocation Loc = VTableUses[I].second;
10791
10792    bool DefineVTable = true;
10793
10794    // If this class has a key function, but that key function is
10795    // defined in another translation unit, we don't need to emit the
10796    // vtable even though we're using it.
10797    const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
10798    if (KeyFunction && !KeyFunction->hasBody()) {
10799      switch (KeyFunction->getTemplateSpecializationKind()) {
10800      case TSK_Undeclared:
10801      case TSK_ExplicitSpecialization:
10802      case TSK_ExplicitInstantiationDeclaration:
10803        // The key function is in another translation unit.
10804        DefineVTable = false;
10805        break;
10806
10807      case TSK_ExplicitInstantiationDefinition:
10808      case TSK_ImplicitInstantiation:
10809        // We will be instantiating the key function.
10810        break;
10811      }
10812    } else if (!KeyFunction) {
10813      // If we have a class with no key function that is the subject
10814      // of an explicit instantiation declaration, suppress the
10815      // vtable; it will live with the explicit instantiation
10816      // definition.
10817      bool IsExplicitInstantiationDeclaration
10818        = Class->getTemplateSpecializationKind()
10819                                      == TSK_ExplicitInstantiationDeclaration;
10820      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10821                                 REnd = Class->redecls_end();
10822           R != REnd; ++R) {
10823        TemplateSpecializationKind TSK
10824          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10825        if (TSK == TSK_ExplicitInstantiationDeclaration)
10826          IsExplicitInstantiationDeclaration = true;
10827        else if (TSK == TSK_ExplicitInstantiationDefinition) {
10828          IsExplicitInstantiationDeclaration = false;
10829          break;
10830        }
10831      }
10832
10833      if (IsExplicitInstantiationDeclaration)
10834        DefineVTable = false;
10835    }
10836
10837    // The exception specifications for all virtual members may be needed even
10838    // if we are not providing an authoritative form of the vtable in this TU.
10839    // We may choose to emit it available_externally anyway.
10840    if (!DefineVTable) {
10841      MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
10842      continue;
10843    }
10844
10845    // Mark all of the virtual members of this class as referenced, so
10846    // that we can build a vtable. Then, tell the AST consumer that a
10847    // vtable for this class is required.
10848    DefinedAnything = true;
10849    MarkVirtualMembersReferenced(Loc, Class);
10850    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10851    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10852
10853    // Optionally warn if we're emitting a weak vtable.
10854    if (Class->getLinkage() == ExternalLinkage &&
10855        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
10856      const FunctionDecl *KeyFunctionDef = 0;
10857      if (!KeyFunction ||
10858          (KeyFunction->hasBody(KeyFunctionDef) &&
10859           KeyFunctionDef->isInlined()))
10860        Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10861             TSK_ExplicitInstantiationDefinition
10862             ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10863          << Class;
10864    }
10865  }
10866  VTableUses.clear();
10867
10868  return DefinedAnything;
10869}
10870
10871void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
10872                                                 const CXXRecordDecl *RD) {
10873  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
10874                                      E = RD->method_end(); I != E; ++I)
10875    if ((*I)->isVirtual() && !(*I)->isPure())
10876      ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
10877}
10878
10879void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10880                                        const CXXRecordDecl *RD) {
10881  // Mark all functions which will appear in RD's vtable as used.
10882  CXXFinalOverriderMap FinalOverriders;
10883  RD->getFinalOverriders(FinalOverriders);
10884  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
10885                                            E = FinalOverriders.end();
10886       I != E; ++I) {
10887    for (OverridingMethods::const_iterator OI = I->second.begin(),
10888                                           OE = I->second.end();
10889         OI != OE; ++OI) {
10890      assert(OI->second.size() > 0 && "no final overrider");
10891      CXXMethodDecl *Overrider = OI->second.front().Method;
10892
10893      // C++ [basic.def.odr]p2:
10894      //   [...] A virtual member function is used if it is not pure. [...]
10895      if (!Overrider->isPure())
10896        MarkFunctionReferenced(Loc, Overrider);
10897    }
10898  }
10899
10900  // Only classes that have virtual bases need a VTT.
10901  if (RD->getNumVBases() == 0)
10902    return;
10903
10904  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10905           e = RD->bases_end(); i != e; ++i) {
10906    const CXXRecordDecl *Base =
10907        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
10908    if (Base->getNumVBases() == 0)
10909      continue;
10910    MarkVirtualMembersReferenced(Loc, Base);
10911  }
10912}
10913
10914/// SetIvarInitializers - This routine builds initialization ASTs for the
10915/// Objective-C implementation whose ivars need be initialized.
10916void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10917  if (!getLangOpts().CPlusPlus)
10918    return;
10919  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
10920    SmallVector<ObjCIvarDecl*, 8> ivars;
10921    CollectIvarsToConstructOrDestruct(OID, ivars);
10922    if (ivars.empty())
10923      return;
10924    SmallVector<CXXCtorInitializer*, 32> AllToInit;
10925    for (unsigned i = 0; i < ivars.size(); i++) {
10926      FieldDecl *Field = ivars[i];
10927      if (Field->isInvalidDecl())
10928        continue;
10929
10930      CXXCtorInitializer *Member;
10931      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10932      InitializationKind InitKind =
10933        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10934
10935      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
10936      ExprResult MemberInit =
10937        InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
10938      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
10939      // Note, MemberInit could actually come back empty if no initialization
10940      // is required (e.g., because it would call a trivial default constructor)
10941      if (!MemberInit.get() || MemberInit.isInvalid())
10942        continue;
10943
10944      Member =
10945        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10946                                         SourceLocation(),
10947                                         MemberInit.takeAs<Expr>(),
10948                                         SourceLocation());
10949      AllToInit.push_back(Member);
10950
10951      // Be sure that the destructor is accessible and is marked as referenced.
10952      if (const RecordType *RecordTy
10953                  = Context.getBaseElementType(Field->getType())
10954                                                        ->getAs<RecordType>()) {
10955                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
10956        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
10957          MarkFunctionReferenced(Field->getLocation(), Destructor);
10958          CheckDestructorAccess(Field->getLocation(), Destructor,
10959                            PDiag(diag::err_access_dtor_ivar)
10960                              << Context.getBaseElementType(Field->getType()));
10961        }
10962      }
10963    }
10964    ObjCImplementation->setIvarInitializers(Context,
10965                                            AllToInit.data(), AllToInit.size());
10966  }
10967}
10968
10969static
10970void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10971                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10972                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10973                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10974                           Sema &S) {
10975  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10976                                                   CE = Current.end();
10977  if (Ctor->isInvalidDecl())
10978    return;
10979
10980  CXXConstructorDecl *Target = Ctor->getTargetConstructor();
10981
10982  // Target may not be determinable yet, for instance if this is a dependent
10983  // call in an uninstantiated template.
10984  if (Target) {
10985    const FunctionDecl *FNTarget = 0;
10986    (void)Target->hasBody(FNTarget);
10987    Target = const_cast<CXXConstructorDecl*>(
10988      cast_or_null<CXXConstructorDecl>(FNTarget));
10989  }
10990
10991  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10992                     // Avoid dereferencing a null pointer here.
10993                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10994
10995  if (!Current.insert(Canonical))
10996    return;
10997
10998  // We know that beyond here, we aren't chaining into a cycle.
10999  if (!Target || !Target->isDelegatingConstructor() ||
11000      Target->isInvalidDecl() || Valid.count(TCanonical)) {
11001    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11002      Valid.insert(*CI);
11003    Current.clear();
11004  // We've hit a cycle.
11005  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11006             Current.count(TCanonical)) {
11007    // If we haven't diagnosed this cycle yet, do so now.
11008    if (!Invalid.count(TCanonical)) {
11009      S.Diag((*Ctor->init_begin())->getSourceLocation(),
11010             diag::warn_delegating_ctor_cycle)
11011        << Ctor;
11012
11013      // Don't add a note for a function delegating directly to itself.
11014      if (TCanonical != Canonical)
11015        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11016
11017      CXXConstructorDecl *C = Target;
11018      while (C->getCanonicalDecl() != Canonical) {
11019        const FunctionDecl *FNTarget = 0;
11020        (void)C->getTargetConstructor()->hasBody(FNTarget);
11021        assert(FNTarget && "Ctor cycle through bodiless function");
11022
11023        C = const_cast<CXXConstructorDecl*>(
11024          cast<CXXConstructorDecl>(FNTarget));
11025        S.Diag(C->getLocation(), diag::note_which_delegates_to);
11026      }
11027    }
11028
11029    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11030      Invalid.insert(*CI);
11031    Current.clear();
11032  } else {
11033    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11034  }
11035}
11036
11037
11038void Sema::CheckDelegatingCtorCycles() {
11039  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11040
11041  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11042                                                   CE = Current.end();
11043
11044  for (DelegatingCtorDeclsType::iterator
11045         I = DelegatingCtorDecls.begin(ExternalSource),
11046         E = DelegatingCtorDecls.end();
11047       I != E; ++I)
11048    DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
11049
11050  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11051    (*CI)->setInvalidDecl();
11052}
11053
11054namespace {
11055  /// \brief AST visitor that finds references to the 'this' expression.
11056  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11057    Sema &S;
11058
11059  public:
11060    explicit FindCXXThisExpr(Sema &S) : S(S) { }
11061
11062    bool VisitCXXThisExpr(CXXThisExpr *E) {
11063      S.Diag(E->getLocation(), diag::err_this_static_member_func)
11064        << E->isImplicit();
11065      return false;
11066    }
11067  };
11068}
11069
11070bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11071  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11072  if (!TSInfo)
11073    return false;
11074
11075  TypeLoc TL = TSInfo->getTypeLoc();
11076  FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11077  if (!ProtoTL)
11078    return false;
11079
11080  // C++11 [expr.prim.general]p3:
11081  //   [The expression this] shall not appear before the optional
11082  //   cv-qualifier-seq and it shall not appear within the declaration of a
11083  //   static member function (although its type and value category are defined
11084  //   within a static member function as they are within a non-static member
11085  //   function). [ Note: this is because declaration matching does not occur
11086  //  until the complete declarator is known. - end note ]
11087  const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11088  FindCXXThisExpr Finder(*this);
11089
11090  // If the return type came after the cv-qualifier-seq, check it now.
11091  if (Proto->hasTrailingReturn() &&
11092      !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11093    return true;
11094
11095  // Check the exception specification.
11096  if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11097    return true;
11098
11099  return checkThisInStaticMemberFunctionAttributes(Method);
11100}
11101
11102bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11103  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11104  if (!TSInfo)
11105    return false;
11106
11107  TypeLoc TL = TSInfo->getTypeLoc();
11108  FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11109  if (!ProtoTL)
11110    return false;
11111
11112  const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11113  FindCXXThisExpr Finder(*this);
11114
11115  switch (Proto->getExceptionSpecType()) {
11116  case EST_Uninstantiated:
11117  case EST_Unevaluated:
11118  case EST_BasicNoexcept:
11119  case EST_DynamicNone:
11120  case EST_MSAny:
11121  case EST_None:
11122    break;
11123
11124  case EST_ComputedNoexcept:
11125    if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11126      return true;
11127
11128  case EST_Dynamic:
11129    for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
11130         EEnd = Proto->exception_end();
11131         E != EEnd; ++E) {
11132      if (!Finder.TraverseType(*E))
11133        return true;
11134    }
11135    break;
11136  }
11137
11138  return false;
11139}
11140
11141bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11142  FindCXXThisExpr Finder(*this);
11143
11144  // Check attributes.
11145  for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11146       A != AEnd; ++A) {
11147    // FIXME: This should be emitted by tblgen.
11148    Expr *Arg = 0;
11149    ArrayRef<Expr *> Args;
11150    if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11151      Arg = G->getArg();
11152    else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11153      Arg = G->getArg();
11154    else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11155      Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11156    else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11157      Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11158    else if (ExclusiveLockFunctionAttr *ELF
11159               = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11160      Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11161    else if (SharedLockFunctionAttr *SLF
11162               = dyn_cast<SharedLockFunctionAttr>(*A))
11163      Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11164    else if (ExclusiveTrylockFunctionAttr *ETLF
11165               = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11166      Arg = ETLF->getSuccessValue();
11167      Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11168    } else if (SharedTrylockFunctionAttr *STLF
11169                 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11170      Arg = STLF->getSuccessValue();
11171      Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11172    } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11173      Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11174    else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11175      Arg = LR->getArg();
11176    else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11177      Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11178    else if (ExclusiveLocksRequiredAttr *ELR
11179               = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11180      Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11181    else if (SharedLocksRequiredAttr *SLR
11182               = dyn_cast<SharedLocksRequiredAttr>(*A))
11183      Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11184
11185    if (Arg && !Finder.TraverseStmt(Arg))
11186      return true;
11187
11188    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11189      if (!Finder.TraverseStmt(Args[I]))
11190        return true;
11191    }
11192  }
11193
11194  return false;
11195}
11196
11197void
11198Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11199                                  ArrayRef<ParsedType> DynamicExceptions,
11200                                  ArrayRef<SourceRange> DynamicExceptionRanges,
11201                                  Expr *NoexceptExpr,
11202                                  llvm::SmallVectorImpl<QualType> &Exceptions,
11203                                  FunctionProtoType::ExtProtoInfo &EPI) {
11204  Exceptions.clear();
11205  EPI.ExceptionSpecType = EST;
11206  if (EST == EST_Dynamic) {
11207    Exceptions.reserve(DynamicExceptions.size());
11208    for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11209      // FIXME: Preserve type source info.
11210      QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11211
11212      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11213      collectUnexpandedParameterPacks(ET, Unexpanded);
11214      if (!Unexpanded.empty()) {
11215        DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11216                                         UPPC_ExceptionType,
11217                                         Unexpanded);
11218        continue;
11219      }
11220
11221      // Check that the type is valid for an exception spec, and
11222      // drop it if not.
11223      if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11224        Exceptions.push_back(ET);
11225    }
11226    EPI.NumExceptions = Exceptions.size();
11227    EPI.Exceptions = Exceptions.data();
11228    return;
11229  }
11230
11231  if (EST == EST_ComputedNoexcept) {
11232    // If an error occurred, there's no expression here.
11233    if (NoexceptExpr) {
11234      assert((NoexceptExpr->isTypeDependent() ||
11235              NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11236              Context.BoolTy) &&
11237             "Parser should have made sure that the expression is boolean");
11238      if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11239        EPI.ExceptionSpecType = EST_BasicNoexcept;
11240        return;
11241      }
11242
11243      if (!NoexceptExpr->isValueDependent())
11244        NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
11245                         diag::err_noexcept_needs_constant_expression,
11246                         /*AllowFold*/ false).take();
11247      EPI.NoexceptExpr = NoexceptExpr;
11248    }
11249    return;
11250  }
11251}
11252
11253/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11254Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11255  // Implicitly declared functions (e.g. copy constructors) are
11256  // __host__ __device__
11257  if (D->isImplicit())
11258    return CFT_HostDevice;
11259
11260  if (D->hasAttr<CUDAGlobalAttr>())
11261    return CFT_Global;
11262
11263  if (D->hasAttr<CUDADeviceAttr>()) {
11264    if (D->hasAttr<CUDAHostAttr>())
11265      return CFT_HostDevice;
11266    else
11267      return CFT_Device;
11268  }
11269
11270  return CFT_Host;
11271}
11272
11273bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11274                           CUDAFunctionTarget CalleeTarget) {
11275  // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11276  // Callable from the device only."
11277  if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11278    return true;
11279
11280  // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11281  // Callable from the host only."
11282  // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11283  // Callable from the host only."
11284  if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11285      (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11286    return true;
11287
11288  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11289    return true;
11290
11291  return false;
11292}
11293