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