SemaDeclCXX.cpp revision e5e575ded9cd4b80229fb299a2d97e9d44728eda
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/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclVisitor.h"
21#include "clang/AST/EvaluatedExprVisitor.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/RecordLayout.h"
24#include "clang/AST/RecursiveASTVisitor.h"
25#include "clang/AST/StmtVisitor.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/AST/TypeOrdering.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/SmallString.h"
40#include <map>
41#include <set>
42
43using namespace clang;
44
45//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
49namespace {
50  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51  /// the default argument of a parameter to determine whether it
52  /// contains any ill-formed subexpressions. For example, this will
53  /// diagnose the use of local variables or parameters within the
54  /// default argument expression.
55  class CheckDefaultArgumentVisitor
56    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
57    Expr *DefaultArg;
58    Sema *S;
59
60  public:
61    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
62      : DefaultArg(defarg), S(s) {}
63
64    bool VisitExpr(Expr *Node);
65    bool VisitDeclRefExpr(DeclRefExpr *DRE);
66    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
67    bool VisitLambdaExpr(LambdaExpr *Lambda);
68    bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
69  };
70
71  /// VisitExpr - Visit all of the children of this expression.
72  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
73    bool IsInvalid = false;
74    for (Stmt::child_range I = Node->children(); I; ++I)
75      IsInvalid |= Visit(*I);
76    return IsInvalid;
77  }
78
79  /// VisitDeclRefExpr - Visit a reference to a declaration, to
80  /// determine whether this declaration can be used in the default
81  /// argument expression.
82  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
83    NamedDecl *Decl = DRE->getDecl();
84    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
85      // C++ [dcl.fct.default]p9
86      //   Default arguments are evaluated each time the function is
87      //   called. The order of evaluation of function arguments is
88      //   unspecified. Consequently, parameters of a function shall not
89      //   be used in default argument expressions, even if they are not
90      //   evaluated. Parameters of a function declared before a default
91      //   argument expression are in scope and can hide namespace and
92      //   class member names.
93      return S->Diag(DRE->getLocStart(),
94                     diag::err_param_default_argument_references_param)
95         << Param->getDeclName() << DefaultArg->getSourceRange();
96    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
97      // C++ [dcl.fct.default]p7
98      //   Local variables shall not be used in default argument
99      //   expressions.
100      if (VDecl->isLocalVarDecl())
101        return S->Diag(DRE->getLocStart(),
102                       diag::err_param_default_argument_references_local)
103          << VDecl->getDeclName() << DefaultArg->getSourceRange();
104    }
105
106    return false;
107  }
108
109  /// VisitCXXThisExpr - Visit a C++ "this" expression.
110  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
111    // C++ [dcl.fct.default]p8:
112    //   The keyword this shall not be used in a default argument of a
113    //   member function.
114    return S->Diag(ThisE->getLocStart(),
115                   diag::err_param_default_argument_references_this)
116               << ThisE->getSourceRange();
117  }
118
119  bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
120    bool Invalid = false;
121    for (PseudoObjectExpr::semantics_iterator
122           i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
123      Expr *E = *i;
124
125      // Look through bindings.
126      if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
127        E = OVE->getSourceExpr();
128        assert(E && "pseudo-object binding without source expression?");
129      }
130
131      Invalid |= Visit(E);
132    }
133    return Invalid;
134  }
135
136  bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
137    // C++11 [expr.lambda.prim]p13:
138    //   A lambda-expression appearing in a default argument shall not
139    //   implicitly or explicitly capture any entity.
140    if (Lambda->capture_begin() == Lambda->capture_end())
141      return false;
142
143    return S->Diag(Lambda->getLocStart(),
144                   diag::err_lambda_capture_default_arg);
145  }
146}
147
148void
149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
150                                                 const CXXMethodDecl *Method) {
151  // If we have an MSAny spec already, don't bother.
152  if (!Method || ComputedEST == EST_MSAny)
153    return;
154
155  const FunctionProtoType *Proto
156    = Method->getType()->getAs<FunctionProtoType>();
157  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
158  if (!Proto)
159    return;
160
161  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
162
163  // If this function can throw any exceptions, make a note of that.
164  if (EST == EST_MSAny || EST == EST_None) {
165    ClearExceptions();
166    ComputedEST = EST;
167    return;
168  }
169
170  // FIXME: If the call to this decl is using any of its default arguments, we
171  // need to search them for potentially-throwing calls.
172
173  // If this function has a basic noexcept, it doesn't affect the outcome.
174  if (EST == EST_BasicNoexcept)
175    return;
176
177  // If we have a throw-all spec at this point, ignore the function.
178  if (ComputedEST == EST_None)
179    return;
180
181  // If we're still at noexcept(true) and there's a nothrow() callee,
182  // change to that specification.
183  if (EST == EST_DynamicNone) {
184    if (ComputedEST == EST_BasicNoexcept)
185      ComputedEST = EST_DynamicNone;
186    return;
187  }
188
189  // Check out noexcept specs.
190  if (EST == EST_ComputedNoexcept) {
191    FunctionProtoType::NoexceptResult NR =
192        Proto->getNoexceptSpec(Self->Context);
193    assert(NR != FunctionProtoType::NR_NoNoexcept &&
194           "Must have noexcept result for EST_ComputedNoexcept.");
195    assert(NR != FunctionProtoType::NR_Dependent &&
196           "Should not generate implicit declarations for dependent cases, "
197           "and don't know how to handle them anyway.");
198
199    // noexcept(false) -> no spec on the new function
200    if (NR == FunctionProtoType::NR_Throw) {
201      ClearExceptions();
202      ComputedEST = EST_None;
203    }
204    // noexcept(true) won't change anything either.
205    return;
206  }
207
208  assert(EST == EST_Dynamic && "EST case not considered earlier.");
209  assert(ComputedEST != EST_None &&
210         "Shouldn't collect exceptions when throw-all is guaranteed.");
211  ComputedEST = EST_Dynamic;
212  // Record the exceptions in this function's exception specification.
213  for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
214                                          EEnd = Proto->exception_end();
215       E != EEnd; ++E)
216    if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
217      Exceptions.push_back(*E);
218}
219
220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
221  if (!E || ComputedEST == EST_MSAny)
222    return;
223
224  // FIXME:
225  //
226  // C++0x [except.spec]p14:
227  //   [An] implicit exception-specification specifies the type-id T if and
228  // only if T is allowed by the exception-specification of a function directly
229  // invoked by f's implicit definition; f shall allow all exceptions if any
230  // function it directly invokes allows all exceptions, and f shall allow no
231  // exceptions if every function it directly invokes allows no exceptions.
232  //
233  // Note in particular that if an implicit exception-specification is generated
234  // for a function containing a throw-expression, that specification can still
235  // be noexcept(true).
236  //
237  // Note also that 'directly invoked' is not defined in the standard, and there
238  // is no indication that we should only consider potentially-evaluated calls.
239  //
240  // Ultimately we should implement the intent of the standard: the exception
241  // specification should be the set of exceptions which can be thrown by the
242  // implicit definition. For now, we assume that any non-nothrow expression can
243  // throw any exception.
244
245  if (Self->canThrow(E))
246    ComputedEST = EST_None;
247}
248
249bool
250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
251                              SourceLocation EqualLoc) {
252  if (RequireCompleteType(Param->getLocation(), Param->getType(),
253                          diag::err_typecheck_decl_incomplete_type)) {
254    Param->setInvalidDecl();
255    return true;
256  }
257
258  // C++ [dcl.fct.default]p5
259  //   A default argument expression is implicitly converted (clause
260  //   4) to the parameter type. The default argument expression has
261  //   the same semantic constraints as the initializer expression in
262  //   a declaration of a variable of the parameter type, using the
263  //   copy-initialization semantics (8.5).
264  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265                                                                    Param);
266  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267                                                           EqualLoc);
268  InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
269  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
270  if (Result.isInvalid())
271    return true;
272  Arg = Result.takeAs<Expr>();
273
274  CheckCompletedExpr(Arg, EqualLoc);
275  Arg = MaybeCreateExprWithCleanups(Arg);
276
277  // Okay: add the default argument to the parameter
278  Param->setDefaultArg(Arg);
279
280  // We have already instantiated this parameter; provide each of the
281  // instantiations with the uninstantiated default argument.
282  UnparsedDefaultArgInstantiationsMap::iterator InstPos
283    = UnparsedDefaultArgInstantiations.find(Param);
284  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288    // We're done tracking this parameter's instantiations.
289    UnparsedDefaultArgInstantiations.erase(InstPos);
290  }
291
292  return false;
293}
294
295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
298void
299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
300                                Expr *DefaultArg) {
301  if (!param || !DefaultArg)
302    return;
303
304  ParmVarDecl *Param = cast<ParmVarDecl>(param);
305  UnparsedDefaultArgLocs.erase(Param);
306
307  // Default arguments are only permitted in C++
308  if (!getLangOpts().CPlusPlus) {
309    Diag(EqualLoc, diag::err_param_default_argument)
310      << DefaultArg->getSourceRange();
311    Param->setInvalidDecl();
312    return;
313  }
314
315  // Check for unexpanded parameter packs.
316  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317    Param->setInvalidDecl();
318    return;
319  }
320
321  // Check that the default argument is well-formed
322  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323  if (DefaultArgChecker.Visit(DefaultArg)) {
324    Param->setInvalidDecl();
325    return;
326  }
327
328  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
329}
330
331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
336                                             SourceLocation EqualLoc,
337                                             SourceLocation ArgLoc) {
338  if (!param)
339    return;
340
341  ParmVarDecl *Param = cast<ParmVarDecl>(param);
342  if (Param)
343    Param->setUnparsedDefaultArg();
344
345  UnparsedDefaultArgLocs[Param] = ArgLoc;
346}
347
348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
351  if (!param)
352    return;
353
354  ParmVarDecl *Param = cast<ParmVarDecl>(param);
355
356  Param->setInvalidDecl();
357
358  UnparsedDefaultArgLocs.erase(Param);
359}
360
361/// CheckExtraCXXDefaultArguments - Check for any extra default
362/// arguments in the declarator, which is not a function declaration
363/// or definition and therefore is not permitted to have default
364/// arguments. This routine should be invoked for every declarator
365/// that is not a function declaration or definition.
366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367  // C++ [dcl.fct.default]p3
368  //   A default argument expression shall be specified only in the
369  //   parameter-declaration-clause of a function declaration or in a
370  //   template-parameter (14.1). It shall not be specified for a
371  //   parameter pack. If it is specified in a
372  //   parameter-declaration-clause, it shall not occur within a
373  //   declarator or abstract-declarator of a parameter-declaration.
374  bool MightBeFunction = D.isFunctionDeclarationContext();
375  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
376    DeclaratorChunk &chunk = D.getTypeObject(i);
377    if (chunk.Kind == DeclaratorChunk::Function) {
378      if (MightBeFunction) {
379        // This is a function declaration. It can have default arguments, but
380        // keep looking in case its return type is a function type with default
381        // arguments.
382        MightBeFunction = false;
383        continue;
384      }
385      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
386        ParmVarDecl *Param =
387          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
388        if (Param->hasUnparsedDefaultArg()) {
389          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
390          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
391            << SourceRange((*Toks)[1].getLocation(),
392                           Toks->back().getLocation());
393          delete Toks;
394          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
395        } else if (Param->getDefaultArg()) {
396          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397            << Param->getDefaultArg()->getSourceRange();
398          Param->setDefaultArg(0);
399        }
400      }
401    } else if (chunk.Kind != DeclaratorChunk::Paren) {
402      MightBeFunction = false;
403    }
404  }
405}
406
407/// MergeCXXFunctionDecl - Merge two declarations of the same C++
408/// function, once we already know that they have the same
409/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
410/// error, false otherwise.
411bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
412                                Scope *S) {
413  bool Invalid = false;
414
415  // C++ [dcl.fct.default]p4:
416  //   For non-template functions, default arguments can be added in
417  //   later declarations of a function in the same
418  //   scope. Declarations in different scopes have completely
419  //   distinct sets of default arguments. That is, declarations in
420  //   inner scopes do not acquire default arguments from
421  //   declarations in outer scopes, and vice versa. In a given
422  //   function declaration, all parameters subsequent to a
423  //   parameter with a default argument shall have default
424  //   arguments supplied in this or previous declarations. A
425  //   default argument shall not be redefined by a later
426  //   declaration (not even to the same value).
427  //
428  // C++ [dcl.fct.default]p6:
429  //   Except for member functions of class templates, the default arguments
430  //   in a member function definition that appears outside of the class
431  //   definition are added to the set of default arguments provided by the
432  //   member function declaration in the class definition.
433  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
434    ParmVarDecl *OldParam = Old->getParamDecl(p);
435    ParmVarDecl *NewParam = New->getParamDecl(p);
436
437    bool OldParamHasDfl = OldParam->hasDefaultArg();
438    bool NewParamHasDfl = NewParam->hasDefaultArg();
439
440    NamedDecl *ND = Old;
441    if (S && !isDeclInScope(ND, New->getDeclContext(), S))
442      // Ignore default parameters of old decl if they are not in
443      // the same scope.
444      OldParamHasDfl = false;
445
446    if (OldParamHasDfl && NewParamHasDfl) {
447
448      unsigned DiagDefaultParamID =
449        diag::err_param_default_argument_redefinition;
450
451      // MSVC accepts that default parameters be redefined for member functions
452      // of template class. The new default parameter's value is ignored.
453      Invalid = true;
454      if (getLangOpts().MicrosoftExt) {
455        CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
456        if (MD && MD->getParent()->getDescribedClassTemplate()) {
457          // Merge the old default argument into the new parameter.
458          NewParam->setHasInheritedDefaultArg();
459          if (OldParam->hasUninstantiatedDefaultArg())
460            NewParam->setUninstantiatedDefaultArg(
461                                      OldParam->getUninstantiatedDefaultArg());
462          else
463            NewParam->setDefaultArg(OldParam->getInit());
464          DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
465          Invalid = false;
466        }
467      }
468
469      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
470      // hint here. Alternatively, we could walk the type-source information
471      // for NewParam to find the last source location in the type... but it
472      // isn't worth the effort right now. This is the kind of test case that
473      // is hard to get right:
474      //   int f(int);
475      //   void g(int (*fp)(int) = f);
476      //   void g(int (*fp)(int) = &f);
477      Diag(NewParam->getLocation(), DiagDefaultParamID)
478        << NewParam->getDefaultArgRange();
479
480      // Look for the function declaration where the default argument was
481      // actually written, which may be a declaration prior to Old.
482      for (FunctionDecl *Older = Old->getPreviousDecl();
483           Older; Older = Older->getPreviousDecl()) {
484        if (!Older->getParamDecl(p)->hasDefaultArg())
485          break;
486
487        OldParam = Older->getParamDecl(p);
488      }
489
490      Diag(OldParam->getLocation(), diag::note_previous_definition)
491        << OldParam->getDefaultArgRange();
492    } else if (OldParamHasDfl) {
493      // Merge the old default argument into the new parameter.
494      // It's important to use getInit() here;  getDefaultArg()
495      // strips off any top-level ExprWithCleanups.
496      NewParam->setHasInheritedDefaultArg();
497      if (OldParam->hasUninstantiatedDefaultArg())
498        NewParam->setUninstantiatedDefaultArg(
499                                      OldParam->getUninstantiatedDefaultArg());
500      else
501        NewParam->setDefaultArg(OldParam->getInit());
502    } else if (NewParamHasDfl) {
503      if (New->getDescribedFunctionTemplate()) {
504        // Paragraph 4, quoted above, only applies to non-template functions.
505        Diag(NewParam->getLocation(),
506             diag::err_param_default_argument_template_redecl)
507          << NewParam->getDefaultArgRange();
508        Diag(Old->getLocation(), diag::note_template_prev_declaration)
509          << false;
510      } else if (New->getTemplateSpecializationKind()
511                   != TSK_ImplicitInstantiation &&
512                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
513        // C++ [temp.expr.spec]p21:
514        //   Default function arguments shall not be specified in a declaration
515        //   or a definition for one of the following explicit specializations:
516        //     - the explicit specialization of a function template;
517        //     - the explicit specialization of a member function template;
518        //     - the explicit specialization of a member function of a class
519        //       template where the class template specialization to which the
520        //       member function specialization belongs is implicitly
521        //       instantiated.
522        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
523          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
524          << New->getDeclName()
525          << NewParam->getDefaultArgRange();
526      } else if (New->getDeclContext()->isDependentContext()) {
527        // C++ [dcl.fct.default]p6 (DR217):
528        //   Default arguments for a member function of a class template shall
529        //   be specified on the initial declaration of the member function
530        //   within the class template.
531        //
532        // Reading the tea leaves a bit in DR217 and its reference to DR205
533        // leads me to the conclusion that one cannot add default function
534        // arguments for an out-of-line definition of a member function of a
535        // dependent type.
536        int WhichKind = 2;
537        if (CXXRecordDecl *Record
538              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
539          if (Record->getDescribedClassTemplate())
540            WhichKind = 0;
541          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
542            WhichKind = 1;
543          else
544            WhichKind = 2;
545        }
546
547        Diag(NewParam->getLocation(),
548             diag::err_param_default_argument_member_template_redecl)
549          << WhichKind
550          << NewParam->getDefaultArgRange();
551      }
552    }
553  }
554
555  // DR1344: If a default argument is added outside a class definition and that
556  // default argument makes the function a special member function, the program
557  // is ill-formed. This can only happen for constructors.
558  if (isa<CXXConstructorDecl>(New) &&
559      New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
560    CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
561                     OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
562    if (NewSM != OldSM) {
563      ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
564      assert(NewParam->hasDefaultArg());
565      Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
566        << NewParam->getDefaultArgRange() << NewSM;
567      Diag(Old->getLocation(), diag::note_previous_declaration);
568    }
569  }
570
571  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
572  // template has a constexpr specifier then all its declarations shall
573  // contain the constexpr specifier.
574  if (New->isConstexpr() != Old->isConstexpr()) {
575    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
576      << New << New->isConstexpr();
577    Diag(Old->getLocation(), diag::note_previous_declaration);
578    Invalid = true;
579  }
580
581  if (CheckEquivalentExceptionSpec(Old, New))
582    Invalid = true;
583
584  return Invalid;
585}
586
587/// \brief Merge the exception specifications of two variable declarations.
588///
589/// This is called when there's a redeclaration of a VarDecl. The function
590/// checks if the redeclaration might have an exception specification and
591/// validates compatibility and merges the specs if necessary.
592void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
593  // Shortcut if exceptions are disabled.
594  if (!getLangOpts().CXXExceptions)
595    return;
596
597  assert(Context.hasSameType(New->getType(), Old->getType()) &&
598         "Should only be called if types are otherwise the same.");
599
600  QualType NewType = New->getType();
601  QualType OldType = Old->getType();
602
603  // We're only interested in pointers and references to functions, as well
604  // as pointers to member functions.
605  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
606    NewType = R->getPointeeType();
607    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
608  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
609    NewType = P->getPointeeType();
610    OldType = OldType->getAs<PointerType>()->getPointeeType();
611  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
612    NewType = M->getPointeeType();
613    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
614  }
615
616  if (!NewType->isFunctionProtoType())
617    return;
618
619  // There's lots of special cases for functions. For function pointers, system
620  // libraries are hopefully not as broken so that we don't need these
621  // workarounds.
622  if (CheckEquivalentExceptionSpec(
623        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
624        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
625    New->setInvalidDecl();
626  }
627}
628
629/// CheckCXXDefaultArguments - Verify that the default arguments for a
630/// function declaration are well-formed according to C++
631/// [dcl.fct.default].
632void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
633  unsigned NumParams = FD->getNumParams();
634  unsigned p;
635
636  // Find first parameter with a default argument
637  for (p = 0; p < NumParams; ++p) {
638    ParmVarDecl *Param = FD->getParamDecl(p);
639    if (Param->hasDefaultArg())
640      break;
641  }
642
643  // C++ [dcl.fct.default]p4:
644  //   In a given function declaration, all parameters
645  //   subsequent to a parameter with a default argument shall
646  //   have default arguments supplied in this or previous
647  //   declarations. A default argument shall not be redefined
648  //   by a later declaration (not even to the same value).
649  unsigned LastMissingDefaultArg = 0;
650  for (; p < NumParams; ++p) {
651    ParmVarDecl *Param = FD->getParamDecl(p);
652    if (!Param->hasDefaultArg()) {
653      if (Param->isInvalidDecl())
654        /* We already complained about this parameter. */;
655      else if (Param->getIdentifier())
656        Diag(Param->getLocation(),
657             diag::err_param_default_argument_missing_name)
658          << Param->getIdentifier();
659      else
660        Diag(Param->getLocation(),
661             diag::err_param_default_argument_missing);
662
663      LastMissingDefaultArg = p;
664    }
665  }
666
667  if (LastMissingDefaultArg > 0) {
668    // Some default arguments were missing. Clear out all of the
669    // default arguments up to (and including) the last missing
670    // default argument, so that we leave the function parameters
671    // in a semantically valid state.
672    for (p = 0; p <= LastMissingDefaultArg; ++p) {
673      ParmVarDecl *Param = FD->getParamDecl(p);
674      if (Param->hasDefaultArg()) {
675        Param->setDefaultArg(0);
676      }
677    }
678  }
679}
680
681// CheckConstexprParameterTypes - Check whether a function's parameter types
682// are all literal types. If so, return true. If not, produce a suitable
683// diagnostic and return false.
684static bool CheckConstexprParameterTypes(Sema &SemaRef,
685                                         const FunctionDecl *FD) {
686  unsigned ArgIndex = 0;
687  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
688  for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
689       e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
690    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
691    SourceLocation ParamLoc = PD->getLocation();
692    if (!(*i)->isDependentType() &&
693        SemaRef.RequireLiteralType(ParamLoc, *i,
694                                   diag::err_constexpr_non_literal_param,
695                                   ArgIndex+1, PD->getSourceRange(),
696                                   isa<CXXConstructorDecl>(FD)))
697      return false;
698  }
699  return true;
700}
701
702/// \brief Get diagnostic %select index for tag kind for
703/// record diagnostic message.
704/// WARNING: Indexes apply to particular diagnostics only!
705///
706/// \returns diagnostic %select index.
707static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
708  switch (Tag) {
709  case TTK_Struct: return 0;
710  case TTK_Interface: return 1;
711  case TTK_Class:  return 2;
712  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
713  }
714}
715
716// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
717// the requirements of a constexpr function definition or a constexpr
718// constructor definition. If so, return true. If not, produce appropriate
719// diagnostics and return false.
720//
721// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
722bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
723  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
724  if (MD && MD->isInstance()) {
725    // C++11 [dcl.constexpr]p4:
726    //  The definition of a constexpr constructor shall satisfy the following
727    //  constraints:
728    //  - the class shall not have any virtual base classes;
729    const CXXRecordDecl *RD = MD->getParent();
730    if (RD->getNumVBases()) {
731      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
732        << isa<CXXConstructorDecl>(NewFD)
733        << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
734      for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
735             E = RD->vbases_end(); I != E; ++I)
736        Diag(I->getLocStart(),
737             diag::note_constexpr_virtual_base_here) << I->getSourceRange();
738      return false;
739    }
740  }
741
742  if (!isa<CXXConstructorDecl>(NewFD)) {
743    // C++11 [dcl.constexpr]p3:
744    //  The definition of a constexpr function shall satisfy the following
745    //  constraints:
746    // - it shall not be virtual;
747    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
748    if (Method && Method->isVirtual()) {
749      Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
750
751      // If it's not obvious why this function is virtual, find an overridden
752      // function which uses the 'virtual' keyword.
753      const CXXMethodDecl *WrittenVirtual = Method;
754      while (!WrittenVirtual->isVirtualAsWritten())
755        WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
756      if (WrittenVirtual != Method)
757        Diag(WrittenVirtual->getLocation(),
758             diag::note_overridden_virtual_function);
759      return false;
760    }
761
762    // - its return type shall be a literal type;
763    QualType RT = NewFD->getResultType();
764    if (!RT->isDependentType() &&
765        RequireLiteralType(NewFD->getLocation(), RT,
766                           diag::err_constexpr_non_literal_return))
767      return false;
768  }
769
770  // - each of its parameter types shall be a literal type;
771  if (!CheckConstexprParameterTypes(*this, NewFD))
772    return false;
773
774  return true;
775}
776
777/// Check the given declaration statement is legal within a constexpr function
778/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
779///
780/// \return true if the body is OK (maybe only as an extension), false if we
781///         have diagnosed a problem.
782static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
783                                   DeclStmt *DS, SourceLocation &Cxx1yLoc) {
784  // C++11 [dcl.constexpr]p3 and p4:
785  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
786  //  contain only
787  for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
788         DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
789    switch ((*DclIt)->getKind()) {
790    case Decl::StaticAssert:
791    case Decl::Using:
792    case Decl::UsingShadow:
793    case Decl::UsingDirective:
794    case Decl::UnresolvedUsingTypename:
795    case Decl::UnresolvedUsingValue:
796      //   - static_assert-declarations
797      //   - using-declarations,
798      //   - using-directives,
799      continue;
800
801    case Decl::Typedef:
802    case Decl::TypeAlias: {
803      //   - typedef declarations and alias-declarations that do not define
804      //     classes or enumerations,
805      TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
806      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
807        // Don't allow variably-modified types in constexpr functions.
808        TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
809        SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
810          << TL.getSourceRange() << TL.getType()
811          << isa<CXXConstructorDecl>(Dcl);
812        return false;
813      }
814      continue;
815    }
816
817    case Decl::Enum:
818    case Decl::CXXRecord:
819      // C++1y allows types to be defined, not just declared.
820      if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
821        SemaRef.Diag(DS->getLocStart(),
822                     SemaRef.getLangOpts().CPlusPlus1y
823                       ? diag::warn_cxx11_compat_constexpr_type_definition
824                       : diag::ext_constexpr_type_definition)
825          << isa<CXXConstructorDecl>(Dcl);
826      continue;
827
828    case Decl::EnumConstant:
829    case Decl::IndirectField:
830    case Decl::ParmVar:
831      // These can only appear with other declarations which are banned in
832      // C++11 and permitted in C++1y, so ignore them.
833      continue;
834
835    case Decl::Var: {
836      // C++1y [dcl.constexpr]p3 allows anything except:
837      //   a definition of a variable of non-literal type or of static or
838      //   thread storage duration or for which no initialization is performed.
839      VarDecl *VD = cast<VarDecl>(*DclIt);
840      if (VD->isThisDeclarationADefinition()) {
841        if (VD->isStaticLocal()) {
842          SemaRef.Diag(VD->getLocation(),
843                       diag::err_constexpr_local_var_static)
844            << isa<CXXConstructorDecl>(Dcl)
845            << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
846          return false;
847        }
848        if (SemaRef.RequireLiteralType(
849              VD->getLocation(), VD->getType(),
850              diag::err_constexpr_local_var_non_literal_type,
851              isa<CXXConstructorDecl>(Dcl)))
852          return false;
853        if (!VD->hasInit()) {
854          SemaRef.Diag(VD->getLocation(),
855                       diag::err_constexpr_local_var_no_init)
856            << isa<CXXConstructorDecl>(Dcl);
857          return false;
858        }
859      }
860      SemaRef.Diag(VD->getLocation(),
861                   SemaRef.getLangOpts().CPlusPlus1y
862                    ? diag::warn_cxx11_compat_constexpr_local_var
863                    : diag::ext_constexpr_local_var)
864        << isa<CXXConstructorDecl>(Dcl);
865      continue;
866    }
867
868    case Decl::NamespaceAlias:
869    case Decl::Function:
870      // These are disallowed in C++11 and permitted in C++1y. Allow them
871      // everywhere as an extension.
872      if (!Cxx1yLoc.isValid())
873        Cxx1yLoc = DS->getLocStart();
874      continue;
875
876    default:
877      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
878        << isa<CXXConstructorDecl>(Dcl);
879      return false;
880    }
881  }
882
883  return true;
884}
885
886/// Check that the given field is initialized within a constexpr constructor.
887///
888/// \param Dcl The constexpr constructor being checked.
889/// \param Field The field being checked. This may be a member of an anonymous
890///        struct or union nested within the class being checked.
891/// \param Inits All declarations, including anonymous struct/union members and
892///        indirect members, for which any initialization was provided.
893/// \param Diagnosed Set to true if an error is produced.
894static void CheckConstexprCtorInitializer(Sema &SemaRef,
895                                          const FunctionDecl *Dcl,
896                                          FieldDecl *Field,
897                                          llvm::SmallSet<Decl*, 16> &Inits,
898                                          bool &Diagnosed) {
899  if (Field->isUnnamedBitfield())
900    return;
901
902  if (Field->isAnonymousStructOrUnion() &&
903      Field->getType()->getAsCXXRecordDecl()->isEmpty())
904    return;
905
906  if (!Inits.count(Field)) {
907    if (!Diagnosed) {
908      SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
909      Diagnosed = true;
910    }
911    SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
912  } else if (Field->isAnonymousStructOrUnion()) {
913    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
914    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
915         I != E; ++I)
916      // If an anonymous union contains an anonymous struct of which any member
917      // is initialized, all members must be initialized.
918      if (!RD->isUnion() || Inits.count(*I))
919        CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
920  }
921}
922
923/// Check the provided statement is allowed in a constexpr function
924/// definition.
925static bool
926CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
927                           llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
928                           SourceLocation &Cxx1yLoc) {
929  // - its function-body shall be [...] a compound-statement that contains only
930  switch (S->getStmtClass()) {
931  case Stmt::NullStmtClass:
932    //   - null statements,
933    return true;
934
935  case Stmt::DeclStmtClass:
936    //   - static_assert-declarations
937    //   - using-declarations,
938    //   - using-directives,
939    //   - typedef declarations and alias-declarations that do not define
940    //     classes or enumerations,
941    if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
942      return false;
943    return true;
944
945  case Stmt::ReturnStmtClass:
946    //   - and exactly one return statement;
947    if (isa<CXXConstructorDecl>(Dcl)) {
948      // C++1y allows return statements in constexpr constructors.
949      if (!Cxx1yLoc.isValid())
950        Cxx1yLoc = S->getLocStart();
951      return true;
952    }
953
954    ReturnStmts.push_back(S->getLocStart());
955    return true;
956
957  case Stmt::CompoundStmtClass: {
958    // C++1y allows compound-statements.
959    if (!Cxx1yLoc.isValid())
960      Cxx1yLoc = S->getLocStart();
961
962    CompoundStmt *CompStmt = cast<CompoundStmt>(S);
963    for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
964           BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
965      if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
966                                      Cxx1yLoc))
967        return false;
968    }
969    return true;
970  }
971
972  case Stmt::AttributedStmtClass:
973    if (!Cxx1yLoc.isValid())
974      Cxx1yLoc = S->getLocStart();
975    return true;
976
977  case Stmt::IfStmtClass: {
978    // C++1y allows if-statements.
979    if (!Cxx1yLoc.isValid())
980      Cxx1yLoc = S->getLocStart();
981
982    IfStmt *If = cast<IfStmt>(S);
983    if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
984                                    Cxx1yLoc))
985      return false;
986    if (If->getElse() &&
987        !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
988                                    Cxx1yLoc))
989      return false;
990    return true;
991  }
992
993  case Stmt::WhileStmtClass:
994  case Stmt::DoStmtClass:
995  case Stmt::ForStmtClass:
996  case Stmt::CXXForRangeStmtClass:
997  case Stmt::ContinueStmtClass:
998    // C++1y allows all of these. We don't allow them as extensions in C++11,
999    // because they don't make sense without variable mutation.
1000    if (!SemaRef.getLangOpts().CPlusPlus1y)
1001      break;
1002    if (!Cxx1yLoc.isValid())
1003      Cxx1yLoc = S->getLocStart();
1004    for (Stmt::child_range Children = S->children(); Children; ++Children)
1005      if (*Children &&
1006          !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1007                                      Cxx1yLoc))
1008        return false;
1009    return true;
1010
1011  case Stmt::SwitchStmtClass:
1012  case Stmt::CaseStmtClass:
1013  case Stmt::DefaultStmtClass:
1014  case Stmt::BreakStmtClass:
1015    // C++1y allows switch-statements, and since they don't need variable
1016    // mutation, we can reasonably allow them in C++11 as an extension.
1017    if (!Cxx1yLoc.isValid())
1018      Cxx1yLoc = S->getLocStart();
1019    for (Stmt::child_range Children = S->children(); Children; ++Children)
1020      if (*Children &&
1021          !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1022                                      Cxx1yLoc))
1023        return false;
1024    return true;
1025
1026  default:
1027    if (!isa<Expr>(S))
1028      break;
1029
1030    // C++1y allows expression-statements.
1031    if (!Cxx1yLoc.isValid())
1032      Cxx1yLoc = S->getLocStart();
1033    return true;
1034  }
1035
1036  SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1037    << isa<CXXConstructorDecl>(Dcl);
1038  return false;
1039}
1040
1041/// Check the body for the given constexpr function declaration only contains
1042/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1043///
1044/// \return true if the body is OK, false if we have diagnosed a problem.
1045bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1046  if (isa<CXXTryStmt>(Body)) {
1047    // C++11 [dcl.constexpr]p3:
1048    //  The definition of a constexpr function shall satisfy the following
1049    //  constraints: [...]
1050    // - its function-body shall be = delete, = default, or a
1051    //   compound-statement
1052    //
1053    // C++11 [dcl.constexpr]p4:
1054    //  In the definition of a constexpr constructor, [...]
1055    // - its function-body shall not be a function-try-block;
1056    Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1057      << isa<CXXConstructorDecl>(Dcl);
1058    return false;
1059  }
1060
1061  SmallVector<SourceLocation, 4> ReturnStmts;
1062
1063  // - its function-body shall be [...] a compound-statement that contains only
1064  //   [... list of cases ...]
1065  CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1066  SourceLocation Cxx1yLoc;
1067  for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1068         BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
1069    if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1070      return false;
1071  }
1072
1073  if (Cxx1yLoc.isValid())
1074    Diag(Cxx1yLoc,
1075         getLangOpts().CPlusPlus1y
1076           ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1077           : diag::ext_constexpr_body_invalid_stmt)
1078      << isa<CXXConstructorDecl>(Dcl);
1079
1080  if (const CXXConstructorDecl *Constructor
1081        = dyn_cast<CXXConstructorDecl>(Dcl)) {
1082    const CXXRecordDecl *RD = Constructor->getParent();
1083    // DR1359:
1084    // - every non-variant non-static data member and base class sub-object
1085    //   shall be initialized;
1086    // - if the class is a non-empty union, or for each non-empty anonymous
1087    //   union member of a non-union class, exactly one non-static data member
1088    //   shall be initialized;
1089    if (RD->isUnion()) {
1090      if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
1091        Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1092        return false;
1093      }
1094    } else if (!Constructor->isDependentContext() &&
1095               !Constructor->isDelegatingConstructor()) {
1096      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1097
1098      // Skip detailed checking if we have enough initializers, and we would
1099      // allow at most one initializer per member.
1100      bool AnyAnonStructUnionMembers = false;
1101      unsigned Fields = 0;
1102      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1103           E = RD->field_end(); I != E; ++I, ++Fields) {
1104        if (I->isAnonymousStructOrUnion()) {
1105          AnyAnonStructUnionMembers = true;
1106          break;
1107        }
1108      }
1109      if (AnyAnonStructUnionMembers ||
1110          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1111        // Check initialization of non-static data members. Base classes are
1112        // always initialized so do not need to be checked. Dependent bases
1113        // might not have initializers in the member initializer list.
1114        llvm::SmallSet<Decl*, 16> Inits;
1115        for (CXXConstructorDecl::init_const_iterator
1116               I = Constructor->init_begin(), E = Constructor->init_end();
1117             I != E; ++I) {
1118          if (FieldDecl *FD = (*I)->getMember())
1119            Inits.insert(FD);
1120          else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1121            Inits.insert(ID->chain_begin(), ID->chain_end());
1122        }
1123
1124        bool Diagnosed = false;
1125        for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1126             E = RD->field_end(); I != E; ++I)
1127          CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
1128        if (Diagnosed)
1129          return false;
1130      }
1131    }
1132  } else {
1133    if (ReturnStmts.empty()) {
1134      // C++1y doesn't require constexpr functions to contain a 'return'
1135      // statement. We still do, unless the return type is void, because
1136      // otherwise if there's no return statement, the function cannot
1137      // be used in a core constant expression.
1138      Diag(Dcl->getLocation(),
1139           getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType()
1140             ? diag::warn_cxx11_compat_constexpr_body_no_return
1141             : diag::err_constexpr_body_no_return);
1142      return false;
1143    }
1144    if (ReturnStmts.size() > 1) {
1145      Diag(ReturnStmts.back(),
1146           getLangOpts().CPlusPlus1y
1147             ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1148             : diag::ext_constexpr_body_multiple_return);
1149      for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1150        Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1151    }
1152  }
1153
1154  // C++11 [dcl.constexpr]p5:
1155  //   if no function argument values exist such that the function invocation
1156  //   substitution would produce a constant expression, the program is
1157  //   ill-formed; no diagnostic required.
1158  // C++11 [dcl.constexpr]p3:
1159  //   - every constructor call and implicit conversion used in initializing the
1160  //     return value shall be one of those allowed in a constant expression.
1161  // C++11 [dcl.constexpr]p4:
1162  //   - every constructor involved in initializing non-static data members and
1163  //     base class sub-objects shall be a constexpr constructor.
1164  SmallVector<PartialDiagnosticAt, 8> Diags;
1165  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1166    Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1167      << isa<CXXConstructorDecl>(Dcl);
1168    for (size_t I = 0, N = Diags.size(); I != N; ++I)
1169      Diag(Diags[I].first, Diags[I].second);
1170    // Don't return false here: we allow this for compatibility in
1171    // system headers.
1172  }
1173
1174  return true;
1175}
1176
1177/// isCurrentClassName - Determine whether the identifier II is the
1178/// name of the class type currently being defined. In the case of
1179/// nested classes, this will only return true if II is the name of
1180/// the innermost class.
1181bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1182                              const CXXScopeSpec *SS) {
1183  assert(getLangOpts().CPlusPlus && "No class names in C!");
1184
1185  CXXRecordDecl *CurDecl;
1186  if (SS && SS->isSet() && !SS->isInvalid()) {
1187    DeclContext *DC = computeDeclContext(*SS, true);
1188    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1189  } else
1190    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1191
1192  if (CurDecl && CurDecl->getIdentifier())
1193    return &II == CurDecl->getIdentifier();
1194  else
1195    return false;
1196}
1197
1198/// \brief Determine whether the given class is a base class of the given
1199/// class, including looking at dependent bases.
1200static bool findCircularInheritance(const CXXRecordDecl *Class,
1201                                    const CXXRecordDecl *Current) {
1202  SmallVector<const CXXRecordDecl*, 8> Queue;
1203
1204  Class = Class->getCanonicalDecl();
1205  while (true) {
1206    for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1207                                                  E = Current->bases_end();
1208         I != E; ++I) {
1209      CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1210      if (!Base)
1211        continue;
1212
1213      Base = Base->getDefinition();
1214      if (!Base)
1215        continue;
1216
1217      if (Base->getCanonicalDecl() == Class)
1218        return true;
1219
1220      Queue.push_back(Base);
1221    }
1222
1223    if (Queue.empty())
1224      return false;
1225
1226    Current = Queue.back();
1227    Queue.pop_back();
1228  }
1229
1230  return false;
1231}
1232
1233/// \brief Check the validity of a C++ base class specifier.
1234///
1235/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1236/// and returns NULL otherwise.
1237CXXBaseSpecifier *
1238Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1239                         SourceRange SpecifierRange,
1240                         bool Virtual, AccessSpecifier Access,
1241                         TypeSourceInfo *TInfo,
1242                         SourceLocation EllipsisLoc) {
1243  QualType BaseType = TInfo->getType();
1244
1245  // C++ [class.union]p1:
1246  //   A union shall not have base classes.
1247  if (Class->isUnion()) {
1248    Diag(Class->getLocation(), diag::err_base_clause_on_union)
1249      << SpecifierRange;
1250    return 0;
1251  }
1252
1253  if (EllipsisLoc.isValid() &&
1254      !TInfo->getType()->containsUnexpandedParameterPack()) {
1255    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1256      << TInfo->getTypeLoc().getSourceRange();
1257    EllipsisLoc = SourceLocation();
1258  }
1259
1260  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1261
1262  if (BaseType->isDependentType()) {
1263    // Make sure that we don't have circular inheritance among our dependent
1264    // bases. For non-dependent bases, the check for completeness below handles
1265    // this.
1266    if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1267      if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1268          ((BaseDecl = BaseDecl->getDefinition()) &&
1269           findCircularInheritance(Class, BaseDecl))) {
1270        Diag(BaseLoc, diag::err_circular_inheritance)
1271          << BaseType << Context.getTypeDeclType(Class);
1272
1273        if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1274          Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1275            << BaseType;
1276
1277        return 0;
1278      }
1279    }
1280
1281    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1282                                          Class->getTagKind() == TTK_Class,
1283                                          Access, TInfo, EllipsisLoc);
1284  }
1285
1286  // Base specifiers must be record types.
1287  if (!BaseType->isRecordType()) {
1288    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1289    return 0;
1290  }
1291
1292  // C++ [class.union]p1:
1293  //   A union shall not be used as a base class.
1294  if (BaseType->isUnionType()) {
1295    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1296    return 0;
1297  }
1298
1299  // C++ [class.derived]p2:
1300  //   The class-name in a base-specifier shall not be an incompletely
1301  //   defined class.
1302  if (RequireCompleteType(BaseLoc, BaseType,
1303                          diag::err_incomplete_base_class, SpecifierRange)) {
1304    Class->setInvalidDecl();
1305    return 0;
1306  }
1307
1308  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1309  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1310  assert(BaseDecl && "Record type has no declaration");
1311  BaseDecl = BaseDecl->getDefinition();
1312  assert(BaseDecl && "Base type is not incomplete, but has no definition");
1313  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1314  assert(CXXBaseDecl && "Base type is not a C++ type");
1315
1316  // C++ [class]p3:
1317  //   If a class is marked final and it appears as a base-type-specifier in
1318  //   base-clause, the program is ill-formed.
1319  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1320    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1321      << CXXBaseDecl->getDeclName();
1322    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1323      << CXXBaseDecl->getDeclName();
1324    return 0;
1325  }
1326
1327  if (BaseDecl->isInvalidDecl())
1328    Class->setInvalidDecl();
1329
1330  // Create the base specifier.
1331  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1332                                        Class->getTagKind() == TTK_Class,
1333                                        Access, TInfo, EllipsisLoc);
1334}
1335
1336/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1337/// one entry in the base class list of a class specifier, for
1338/// example:
1339///    class foo : public bar, virtual private baz {
1340/// 'public bar' and 'virtual private baz' are each base-specifiers.
1341BaseResult
1342Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1343                         ParsedAttributes &Attributes,
1344                         bool Virtual, AccessSpecifier Access,
1345                         ParsedType basetype, SourceLocation BaseLoc,
1346                         SourceLocation EllipsisLoc) {
1347  if (!classdecl)
1348    return true;
1349
1350  AdjustDeclIfTemplate(classdecl);
1351  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1352  if (!Class)
1353    return true;
1354
1355  // We do not support any C++11 attributes on base-specifiers yet.
1356  // Diagnose any attributes we see.
1357  if (!Attributes.empty()) {
1358    for (AttributeList *Attr = Attributes.getList(); Attr;
1359         Attr = Attr->getNext()) {
1360      if (Attr->isInvalid() ||
1361          Attr->getKind() == AttributeList::IgnoredAttribute)
1362        continue;
1363      Diag(Attr->getLoc(),
1364           Attr->getKind() == AttributeList::UnknownAttribute
1365             ? diag::warn_unknown_attribute_ignored
1366             : diag::err_base_specifier_attribute)
1367        << Attr->getName();
1368    }
1369  }
1370
1371  TypeSourceInfo *TInfo = 0;
1372  GetTypeFromParser(basetype, &TInfo);
1373
1374  if (EllipsisLoc.isInvalid() &&
1375      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1376                                      UPPC_BaseType))
1377    return true;
1378
1379  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1380                                                      Virtual, Access, TInfo,
1381                                                      EllipsisLoc))
1382    return BaseSpec;
1383  else
1384    Class->setInvalidDecl();
1385
1386  return true;
1387}
1388
1389/// \brief Performs the actual work of attaching the given base class
1390/// specifiers to a C++ class.
1391bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1392                                unsigned NumBases) {
1393 if (NumBases == 0)
1394    return false;
1395
1396  // Used to keep track of which base types we have already seen, so
1397  // that we can properly diagnose redundant direct base types. Note
1398  // that the key is always the unqualified canonical type of the base
1399  // class.
1400  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1401
1402  // Copy non-redundant base specifiers into permanent storage.
1403  unsigned NumGoodBases = 0;
1404  bool Invalid = false;
1405  for (unsigned idx = 0; idx < NumBases; ++idx) {
1406    QualType NewBaseType
1407      = Context.getCanonicalType(Bases[idx]->getType());
1408    NewBaseType = NewBaseType.getLocalUnqualifiedType();
1409
1410    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1411    if (KnownBase) {
1412      // C++ [class.mi]p3:
1413      //   A class shall not be specified as a direct base class of a
1414      //   derived class more than once.
1415      Diag(Bases[idx]->getLocStart(),
1416           diag::err_duplicate_base_class)
1417        << KnownBase->getType()
1418        << Bases[idx]->getSourceRange();
1419
1420      // Delete the duplicate base class specifier; we're going to
1421      // overwrite its pointer later.
1422      Context.Deallocate(Bases[idx]);
1423
1424      Invalid = true;
1425    } else {
1426      // Okay, add this new base class.
1427      KnownBase = Bases[idx];
1428      Bases[NumGoodBases++] = Bases[idx];
1429      if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1430        const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1431        if (Class->isInterface() &&
1432              (!RD->isInterface() ||
1433               KnownBase->getAccessSpecifier() != AS_public)) {
1434          // The Microsoft extension __interface does not permit bases that
1435          // are not themselves public interfaces.
1436          Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1437            << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1438            << RD->getSourceRange();
1439          Invalid = true;
1440        }
1441        if (RD->hasAttr<WeakAttr>())
1442          Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1443      }
1444    }
1445  }
1446
1447  // Attach the remaining base class specifiers to the derived class.
1448  Class->setBases(Bases, NumGoodBases);
1449
1450  // Delete the remaining (good) base class specifiers, since their
1451  // data has been copied into the CXXRecordDecl.
1452  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1453    Context.Deallocate(Bases[idx]);
1454
1455  return Invalid;
1456}
1457
1458/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1459/// class, after checking whether there are any duplicate base
1460/// classes.
1461void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1462                               unsigned NumBases) {
1463  if (!ClassDecl || !Bases || !NumBases)
1464    return;
1465
1466  AdjustDeclIfTemplate(ClassDecl);
1467  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1468                       (CXXBaseSpecifier**)(Bases), NumBases);
1469}
1470
1471/// \brief Determine whether the type \p Derived is a C++ class that is
1472/// derived from the type \p Base.
1473bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1474  if (!getLangOpts().CPlusPlus)
1475    return false;
1476
1477  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1478  if (!DerivedRD)
1479    return false;
1480
1481  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1482  if (!BaseRD)
1483    return false;
1484
1485  // If either the base or the derived type is invalid, don't try to
1486  // check whether one is derived from the other.
1487  if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1488    return false;
1489
1490  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1491  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1492}
1493
1494/// \brief Determine whether the type \p Derived is a C++ class that is
1495/// derived from the type \p Base.
1496bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1497  if (!getLangOpts().CPlusPlus)
1498    return false;
1499
1500  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1501  if (!DerivedRD)
1502    return false;
1503
1504  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1505  if (!BaseRD)
1506    return false;
1507
1508  return DerivedRD->isDerivedFrom(BaseRD, Paths);
1509}
1510
1511void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1512                              CXXCastPath &BasePathArray) {
1513  assert(BasePathArray.empty() && "Base path array must be empty!");
1514  assert(Paths.isRecordingPaths() && "Must record paths!");
1515
1516  const CXXBasePath &Path = Paths.front();
1517
1518  // We first go backward and check if we have a virtual base.
1519  // FIXME: It would be better if CXXBasePath had the base specifier for
1520  // the nearest virtual base.
1521  unsigned Start = 0;
1522  for (unsigned I = Path.size(); I != 0; --I) {
1523    if (Path[I - 1].Base->isVirtual()) {
1524      Start = I - 1;
1525      break;
1526    }
1527  }
1528
1529  // Now add all bases.
1530  for (unsigned I = Start, E = Path.size(); I != E; ++I)
1531    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1532}
1533
1534/// \brief Determine whether the given base path includes a virtual
1535/// base class.
1536bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1537  for (CXXCastPath::const_iterator B = BasePath.begin(),
1538                                BEnd = BasePath.end();
1539       B != BEnd; ++B)
1540    if ((*B)->isVirtual())
1541      return true;
1542
1543  return false;
1544}
1545
1546/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1547/// conversion (where Derived and Base are class types) is
1548/// well-formed, meaning that the conversion is unambiguous (and
1549/// that all of the base classes are accessible). Returns true
1550/// and emits a diagnostic if the code is ill-formed, returns false
1551/// otherwise. Loc is the location where this routine should point to
1552/// if there is an error, and Range is the source range to highlight
1553/// if there is an error.
1554bool
1555Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1556                                   unsigned InaccessibleBaseID,
1557                                   unsigned AmbigiousBaseConvID,
1558                                   SourceLocation Loc, SourceRange Range,
1559                                   DeclarationName Name,
1560                                   CXXCastPath *BasePath) {
1561  // First, determine whether the path from Derived to Base is
1562  // ambiguous. This is slightly more expensive than checking whether
1563  // the Derived to Base conversion exists, because here we need to
1564  // explore multiple paths to determine if there is an ambiguity.
1565  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1566                     /*DetectVirtual=*/false);
1567  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1568  assert(DerivationOkay &&
1569         "Can only be used with a derived-to-base conversion");
1570  (void)DerivationOkay;
1571
1572  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1573    if (InaccessibleBaseID) {
1574      // Check that the base class can be accessed.
1575      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1576                                   InaccessibleBaseID)) {
1577        case AR_inaccessible:
1578          return true;
1579        case AR_accessible:
1580        case AR_dependent:
1581        case AR_delayed:
1582          break;
1583      }
1584    }
1585
1586    // Build a base path if necessary.
1587    if (BasePath)
1588      BuildBasePathArray(Paths, *BasePath);
1589    return false;
1590  }
1591
1592  // We know that the derived-to-base conversion is ambiguous, and
1593  // we're going to produce a diagnostic. Perform the derived-to-base
1594  // search just one more time to compute all of the possible paths so
1595  // that we can print them out. This is more expensive than any of
1596  // the previous derived-to-base checks we've done, but at this point
1597  // performance isn't as much of an issue.
1598  Paths.clear();
1599  Paths.setRecordingPaths(true);
1600  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1601  assert(StillOkay && "Can only be used with a derived-to-base conversion");
1602  (void)StillOkay;
1603
1604  // Build up a textual representation of the ambiguous paths, e.g.,
1605  // D -> B -> A, that will be used to illustrate the ambiguous
1606  // conversions in the diagnostic. We only print one of the paths
1607  // to each base class subobject.
1608  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1609
1610  Diag(Loc, AmbigiousBaseConvID)
1611  << Derived << Base << PathDisplayStr << Range << Name;
1612  return true;
1613}
1614
1615bool
1616Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1617                                   SourceLocation Loc, SourceRange Range,
1618                                   CXXCastPath *BasePath,
1619                                   bool IgnoreAccess) {
1620  return CheckDerivedToBaseConversion(Derived, Base,
1621                                      IgnoreAccess ? 0
1622                                       : diag::err_upcast_to_inaccessible_base,
1623                                      diag::err_ambiguous_derived_to_base_conv,
1624                                      Loc, Range, DeclarationName(),
1625                                      BasePath);
1626}
1627
1628
1629/// @brief Builds a string representing ambiguous paths from a
1630/// specific derived class to different subobjects of the same base
1631/// class.
1632///
1633/// This function builds a string that can be used in error messages
1634/// to show the different paths that one can take through the
1635/// inheritance hierarchy to go from the derived class to different
1636/// subobjects of a base class. The result looks something like this:
1637/// @code
1638/// struct D -> struct B -> struct A
1639/// struct D -> struct C -> struct A
1640/// @endcode
1641std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1642  std::string PathDisplayStr;
1643  std::set<unsigned> DisplayedPaths;
1644  for (CXXBasePaths::paths_iterator Path = Paths.begin();
1645       Path != Paths.end(); ++Path) {
1646    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1647      // We haven't displayed a path to this particular base
1648      // class subobject yet.
1649      PathDisplayStr += "\n    ";
1650      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1651      for (CXXBasePath::const_iterator Element = Path->begin();
1652           Element != Path->end(); ++Element)
1653        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1654    }
1655  }
1656
1657  return PathDisplayStr;
1658}
1659
1660//===----------------------------------------------------------------------===//
1661// C++ class member Handling
1662//===----------------------------------------------------------------------===//
1663
1664/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1665bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1666                                SourceLocation ASLoc,
1667                                SourceLocation ColonLoc,
1668                                AttributeList *Attrs) {
1669  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1670  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1671                                                  ASLoc, ColonLoc);
1672  CurContext->addHiddenDecl(ASDecl);
1673  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1674}
1675
1676/// CheckOverrideControl - Check C++11 override control semantics.
1677void Sema::CheckOverrideControl(Decl *D) {
1678  if (D->isInvalidDecl())
1679    return;
1680
1681  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1682
1683  // Do we know which functions this declaration might be overriding?
1684  bool OverridesAreKnown = !MD ||
1685      (!MD->getParent()->hasAnyDependentBases() &&
1686       !MD->getType()->isDependentType());
1687
1688  if (!MD || !MD->isVirtual()) {
1689    if (OverridesAreKnown) {
1690      if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1691        Diag(OA->getLocation(),
1692             diag::override_keyword_only_allowed_on_virtual_member_functions)
1693          << "override" << FixItHint::CreateRemoval(OA->getLocation());
1694        D->dropAttr<OverrideAttr>();
1695      }
1696      if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1697        Diag(FA->getLocation(),
1698             diag::override_keyword_only_allowed_on_virtual_member_functions)
1699          << "final" << FixItHint::CreateRemoval(FA->getLocation());
1700        D->dropAttr<FinalAttr>();
1701      }
1702    }
1703    return;
1704  }
1705
1706  if (!OverridesAreKnown)
1707    return;
1708
1709  // C++11 [class.virtual]p5:
1710  //   If a virtual function is marked with the virt-specifier override and
1711  //   does not override a member function of a base class, the program is
1712  //   ill-formed.
1713  bool HasOverriddenMethods =
1714    MD->begin_overridden_methods() != MD->end_overridden_methods();
1715  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1716    Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1717      << MD->getDeclName();
1718}
1719
1720/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1721/// function overrides a virtual member function marked 'final', according to
1722/// C++11 [class.virtual]p4.
1723bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1724                                                  const CXXMethodDecl *Old) {
1725  if (!Old->hasAttr<FinalAttr>())
1726    return false;
1727
1728  Diag(New->getLocation(), diag::err_final_function_overridden)
1729    << New->getDeclName();
1730  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1731  return true;
1732}
1733
1734static bool InitializationHasSideEffects(const FieldDecl &FD) {
1735  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1736  // FIXME: Destruction of ObjC lifetime types has side-effects.
1737  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1738    return !RD->isCompleteDefinition() ||
1739           !RD->hasTrivialDefaultConstructor() ||
1740           !RD->hasTrivialDestructor();
1741  return false;
1742}
1743
1744static AttributeList *getMSPropertyAttr(AttributeList *list) {
1745  for (AttributeList* it = list; it != 0; it = it->getNext())
1746    if (it->isDeclspecPropertyAttribute())
1747      return it;
1748  return 0;
1749}
1750
1751/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1752/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1753/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1754/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1755/// present (but parsing it has been deferred).
1756NamedDecl *
1757Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1758                               MultiTemplateParamsArg TemplateParameterLists,
1759                               Expr *BW, const VirtSpecifiers &VS,
1760                               InClassInitStyle InitStyle) {
1761  const DeclSpec &DS = D.getDeclSpec();
1762  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1763  DeclarationName Name = NameInfo.getName();
1764  SourceLocation Loc = NameInfo.getLoc();
1765
1766  // For anonymous bitfields, the location should point to the type.
1767  if (Loc.isInvalid())
1768    Loc = D.getLocStart();
1769
1770  Expr *BitWidth = static_cast<Expr*>(BW);
1771
1772  assert(isa<CXXRecordDecl>(CurContext));
1773  assert(!DS.isFriendSpecified());
1774
1775  bool isFunc = D.isDeclarationOfFunction();
1776
1777  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1778    // The Microsoft extension __interface only permits public member functions
1779    // and prohibits constructors, destructors, operators, non-public member
1780    // functions, static methods and data members.
1781    unsigned InvalidDecl;
1782    bool ShowDeclName = true;
1783    if (!isFunc)
1784      InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1785    else if (AS != AS_public)
1786      InvalidDecl = 2;
1787    else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1788      InvalidDecl = 3;
1789    else switch (Name.getNameKind()) {
1790      case DeclarationName::CXXConstructorName:
1791        InvalidDecl = 4;
1792        ShowDeclName = false;
1793        break;
1794
1795      case DeclarationName::CXXDestructorName:
1796        InvalidDecl = 5;
1797        ShowDeclName = false;
1798        break;
1799
1800      case DeclarationName::CXXOperatorName:
1801      case DeclarationName::CXXConversionFunctionName:
1802        InvalidDecl = 6;
1803        break;
1804
1805      default:
1806        InvalidDecl = 0;
1807        break;
1808    }
1809
1810    if (InvalidDecl) {
1811      if (ShowDeclName)
1812        Diag(Loc, diag::err_invalid_member_in_interface)
1813          << (InvalidDecl-1) << Name;
1814      else
1815        Diag(Loc, diag::err_invalid_member_in_interface)
1816          << (InvalidDecl-1) << "";
1817      return 0;
1818    }
1819  }
1820
1821  // C++ 9.2p6: A member shall not be declared to have automatic storage
1822  // duration (auto, register) or with the extern storage-class-specifier.
1823  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1824  // data members and cannot be applied to names declared const or static,
1825  // and cannot be applied to reference members.
1826  switch (DS.getStorageClassSpec()) {
1827  case DeclSpec::SCS_unspecified:
1828  case DeclSpec::SCS_typedef:
1829  case DeclSpec::SCS_static:
1830    break;
1831  case DeclSpec::SCS_mutable:
1832    if (isFunc) {
1833      Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1834
1835      // FIXME: It would be nicer if the keyword was ignored only for this
1836      // declarator. Otherwise we could get follow-up errors.
1837      D.getMutableDeclSpec().ClearStorageClassSpecs();
1838    }
1839    break;
1840  default:
1841    Diag(DS.getStorageClassSpecLoc(),
1842         diag::err_storageclass_invalid_for_member);
1843    D.getMutableDeclSpec().ClearStorageClassSpecs();
1844    break;
1845  }
1846
1847  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1848                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1849                      !isFunc);
1850
1851  if (DS.isConstexprSpecified() && isInstField) {
1852    SemaDiagnosticBuilder B =
1853        Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1854    SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1855    if (InitStyle == ICIS_NoInit) {
1856      B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1857      D.getMutableDeclSpec().ClearConstexprSpec();
1858      const char *PrevSpec;
1859      unsigned DiagID;
1860      bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1861                                         PrevSpec, DiagID, getLangOpts());
1862      (void)Failed;
1863      assert(!Failed && "Making a constexpr member const shouldn't fail");
1864    } else {
1865      B << 1;
1866      const char *PrevSpec;
1867      unsigned DiagID;
1868      if (D.getMutableDeclSpec().SetStorageClassSpec(
1869          *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
1870        assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
1871               "This is the only DeclSpec that should fail to be applied");
1872        B << 1;
1873      } else {
1874        B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1875        isInstField = false;
1876      }
1877    }
1878  }
1879
1880  NamedDecl *Member;
1881  if (isInstField) {
1882    CXXScopeSpec &SS = D.getCXXScopeSpec();
1883
1884    // Data members must have identifiers for names.
1885    if (!Name.isIdentifier()) {
1886      Diag(Loc, diag::err_bad_variable_name)
1887        << Name;
1888      return 0;
1889    }
1890
1891    IdentifierInfo *II = Name.getAsIdentifierInfo();
1892
1893    // Member field could not be with "template" keyword.
1894    // So TemplateParameterLists should be empty in this case.
1895    if (TemplateParameterLists.size()) {
1896      TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1897      if (TemplateParams->size()) {
1898        // There is no such thing as a member field template.
1899        Diag(D.getIdentifierLoc(), diag::err_template_member)
1900            << II
1901            << SourceRange(TemplateParams->getTemplateLoc(),
1902                TemplateParams->getRAngleLoc());
1903      } else {
1904        // There is an extraneous 'template<>' for this member.
1905        Diag(TemplateParams->getTemplateLoc(),
1906            diag::err_template_member_noparams)
1907            << II
1908            << SourceRange(TemplateParams->getTemplateLoc(),
1909                TemplateParams->getRAngleLoc());
1910      }
1911      return 0;
1912    }
1913
1914    if (SS.isSet() && !SS.isInvalid()) {
1915      // The user provided a superfluous scope specifier inside a class
1916      // definition:
1917      //
1918      // class X {
1919      //   int X::member;
1920      // };
1921      if (DeclContext *DC = computeDeclContext(SS, false))
1922        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1923      else
1924        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1925          << Name << SS.getRange();
1926
1927      SS.clear();
1928    }
1929
1930    AttributeList *MSPropertyAttr =
1931      getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1932    if (MSPropertyAttr) {
1933      Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1934                                BitWidth, InitStyle, AS, MSPropertyAttr);
1935      isInstField = false;
1936    } else {
1937      Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1938                                BitWidth, InitStyle, AS);
1939    }
1940    assert(Member && "HandleField never returns null");
1941  } else {
1942    assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1943
1944    Member = HandleDeclarator(S, D, TemplateParameterLists);
1945    if (!Member) {
1946      return 0;
1947    }
1948
1949    // Non-instance-fields can't have a bitfield.
1950    if (BitWidth) {
1951      if (Member->isInvalidDecl()) {
1952        // don't emit another diagnostic.
1953      } else if (isa<VarDecl>(Member)) {
1954        // C++ 9.6p3: A bit-field shall not be a static member.
1955        // "static member 'A' cannot be a bit-field"
1956        Diag(Loc, diag::err_static_not_bitfield)
1957          << Name << BitWidth->getSourceRange();
1958      } else if (isa<TypedefDecl>(Member)) {
1959        // "typedef member 'x' cannot be a bit-field"
1960        Diag(Loc, diag::err_typedef_not_bitfield)
1961          << Name << BitWidth->getSourceRange();
1962      } else {
1963        // A function typedef ("typedef int f(); f a;").
1964        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1965        Diag(Loc, diag::err_not_integral_type_bitfield)
1966          << Name << cast<ValueDecl>(Member)->getType()
1967          << BitWidth->getSourceRange();
1968      }
1969
1970      BitWidth = 0;
1971      Member->setInvalidDecl();
1972    }
1973
1974    Member->setAccess(AS);
1975
1976    // If we have declared a member function template, set the access of the
1977    // templated declaration as well.
1978    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1979      FunTmpl->getTemplatedDecl()->setAccess(AS);
1980  }
1981
1982  if (VS.isOverrideSpecified())
1983    Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1984  if (VS.isFinalSpecified())
1985    Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1986
1987  if (VS.getLastLocation().isValid()) {
1988    // Update the end location of a method that has a virt-specifiers.
1989    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1990      MD->setRangeEnd(VS.getLastLocation());
1991  }
1992
1993  CheckOverrideControl(Member);
1994
1995  assert((Name || isInstField) && "No identifier for non-field ?");
1996
1997  if (isInstField) {
1998    FieldDecl *FD = cast<FieldDecl>(Member);
1999    FieldCollector->Add(FD);
2000
2001    if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2002                                 FD->getLocation())
2003          != DiagnosticsEngine::Ignored) {
2004      // Remember all explicit private FieldDecls that have a name, no side
2005      // effects and are not part of a dependent type declaration.
2006      if (!FD->isImplicit() && FD->getDeclName() &&
2007          FD->getAccess() == AS_private &&
2008          !FD->hasAttr<UnusedAttr>() &&
2009          !FD->getParent()->isDependentContext() &&
2010          !InitializationHasSideEffects(*FD))
2011        UnusedPrivateFields.insert(FD);
2012    }
2013  }
2014
2015  return Member;
2016}
2017
2018namespace {
2019  class UninitializedFieldVisitor
2020      : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2021    Sema &S;
2022    ValueDecl *VD;
2023  public:
2024    typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2025    UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
2026                                                        S(S) {
2027      if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2028        this->VD = IFD->getAnonField();
2029      else
2030        this->VD = VD;
2031    }
2032
2033    void HandleExpr(Expr *E) {
2034      if (!E) return;
2035
2036      // Expressions like x(x) sometimes lack the surrounding expressions
2037      // but need to be checked anyways.
2038      HandleValue(E);
2039      Visit(E);
2040    }
2041
2042    void HandleValue(Expr *E) {
2043      E = E->IgnoreParens();
2044
2045      if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2046        if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2047          return;
2048
2049        // FieldME is the inner-most MemberExpr that is not an anonymous struct
2050        // or union.
2051        MemberExpr *FieldME = ME;
2052
2053        Expr *Base = E;
2054        while (isa<MemberExpr>(Base)) {
2055          ME = cast<MemberExpr>(Base);
2056
2057          if (isa<VarDecl>(ME->getMemberDecl()))
2058            return;
2059
2060          if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2061            if (!FD->isAnonymousStructOrUnion())
2062              FieldME = ME;
2063
2064          Base = ME->getBase();
2065        }
2066
2067        if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
2068          unsigned diag = VD->getType()->isReferenceType()
2069              ? diag::warn_reference_field_is_uninit
2070              : diag::warn_field_is_uninit;
2071          S.Diag(FieldME->getExprLoc(), diag) << VD;
2072        }
2073        return;
2074      }
2075
2076      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2077        HandleValue(CO->getTrueExpr());
2078        HandleValue(CO->getFalseExpr());
2079        return;
2080      }
2081
2082      if (BinaryConditionalOperator *BCO =
2083              dyn_cast<BinaryConditionalOperator>(E)) {
2084        HandleValue(BCO->getCommon());
2085        HandleValue(BCO->getFalseExpr());
2086        return;
2087      }
2088
2089      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2090        switch (BO->getOpcode()) {
2091        default:
2092          return;
2093        case(BO_PtrMemD):
2094        case(BO_PtrMemI):
2095          HandleValue(BO->getLHS());
2096          return;
2097        case(BO_Comma):
2098          HandleValue(BO->getRHS());
2099          return;
2100        }
2101      }
2102    }
2103
2104    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2105      if (E->getCastKind() == CK_LValueToRValue)
2106        HandleValue(E->getSubExpr());
2107
2108      Inherited::VisitImplicitCastExpr(E);
2109    }
2110
2111    void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2112      Expr *Callee = E->getCallee();
2113      if (isa<MemberExpr>(Callee))
2114        HandleValue(Callee);
2115
2116      Inherited::VisitCXXMemberCallExpr(E);
2117    }
2118  };
2119  static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2120                                                       ValueDecl *VD) {
2121    UninitializedFieldVisitor(S, VD).HandleExpr(E);
2122  }
2123} // namespace
2124
2125/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
2126/// in-class initializer for a non-static C++ class member, and after
2127/// instantiating an in-class initializer in a class template. Such actions
2128/// are deferred until the class is complete.
2129void
2130Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
2131                                       Expr *InitExpr) {
2132  FieldDecl *FD = cast<FieldDecl>(D);
2133  assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2134         "must set init style when field is created");
2135
2136  if (!InitExpr) {
2137    FD->setInvalidDecl();
2138    FD->removeInClassInitializer();
2139    return;
2140  }
2141
2142  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2143    FD->setInvalidDecl();
2144    FD->removeInClassInitializer();
2145    return;
2146  }
2147
2148  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2149      != DiagnosticsEngine::Ignored) {
2150    CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2151  }
2152
2153  ExprResult Init = InitExpr;
2154  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2155    if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
2156      Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
2157        << /*at end of ctor*/1 << InitExpr->getSourceRange();
2158    }
2159    Expr **Inits = &InitExpr;
2160    unsigned NumInits = 1;
2161    InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2162    InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2163        ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2164        : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2165    InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
2166    Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
2167    if (Init.isInvalid()) {
2168      FD->setInvalidDecl();
2169      return;
2170    }
2171  }
2172
2173  // C++11 [class.base.init]p7:
2174  //   The initialization of each base and member constitutes a
2175  //   full-expression.
2176  Init = ActOnFinishFullExpr(Init.take(), InitLoc);
2177  if (Init.isInvalid()) {
2178    FD->setInvalidDecl();
2179    return;
2180  }
2181
2182  InitExpr = Init.release();
2183
2184  FD->setInClassInitializer(InitExpr);
2185}
2186
2187/// \brief Find the direct and/or virtual base specifiers that
2188/// correspond to the given base type, for use in base initialization
2189/// within a constructor.
2190static bool FindBaseInitializer(Sema &SemaRef,
2191                                CXXRecordDecl *ClassDecl,
2192                                QualType BaseType,
2193                                const CXXBaseSpecifier *&DirectBaseSpec,
2194                                const CXXBaseSpecifier *&VirtualBaseSpec) {
2195  // First, check for a direct base class.
2196  DirectBaseSpec = 0;
2197  for (CXXRecordDecl::base_class_const_iterator Base
2198         = ClassDecl->bases_begin();
2199       Base != ClassDecl->bases_end(); ++Base) {
2200    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2201      // We found a direct base of this type. That's what we're
2202      // initializing.
2203      DirectBaseSpec = &*Base;
2204      break;
2205    }
2206  }
2207
2208  // Check for a virtual base class.
2209  // FIXME: We might be able to short-circuit this if we know in advance that
2210  // there are no virtual bases.
2211  VirtualBaseSpec = 0;
2212  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2213    // We haven't found a base yet; search the class hierarchy for a
2214    // virtual base class.
2215    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2216                       /*DetectVirtual=*/false);
2217    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2218                              BaseType, Paths)) {
2219      for (CXXBasePaths::paths_iterator Path = Paths.begin();
2220           Path != Paths.end(); ++Path) {
2221        if (Path->back().Base->isVirtual()) {
2222          VirtualBaseSpec = Path->back().Base;
2223          break;
2224        }
2225      }
2226    }
2227  }
2228
2229  return DirectBaseSpec || VirtualBaseSpec;
2230}
2231
2232/// \brief Handle a C++ member initializer using braced-init-list syntax.
2233MemInitResult
2234Sema::ActOnMemInitializer(Decl *ConstructorD,
2235                          Scope *S,
2236                          CXXScopeSpec &SS,
2237                          IdentifierInfo *MemberOrBase,
2238                          ParsedType TemplateTypeTy,
2239                          const DeclSpec &DS,
2240                          SourceLocation IdLoc,
2241                          Expr *InitList,
2242                          SourceLocation EllipsisLoc) {
2243  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2244                             DS, IdLoc, InitList,
2245                             EllipsisLoc);
2246}
2247
2248/// \brief Handle a C++ member initializer using parentheses syntax.
2249MemInitResult
2250Sema::ActOnMemInitializer(Decl *ConstructorD,
2251                          Scope *S,
2252                          CXXScopeSpec &SS,
2253                          IdentifierInfo *MemberOrBase,
2254                          ParsedType TemplateTypeTy,
2255                          const DeclSpec &DS,
2256                          SourceLocation IdLoc,
2257                          SourceLocation LParenLoc,
2258                          Expr **Args, unsigned NumArgs,
2259                          SourceLocation RParenLoc,
2260                          SourceLocation EllipsisLoc) {
2261  Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2262                                           llvm::makeArrayRef(Args, NumArgs),
2263                                           RParenLoc);
2264  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2265                             DS, IdLoc, List, EllipsisLoc);
2266}
2267
2268namespace {
2269
2270// Callback to only accept typo corrections that can be a valid C++ member
2271// intializer: either a non-static field member or a base class.
2272class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2273 public:
2274  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2275      : ClassDecl(ClassDecl) {}
2276
2277  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2278    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2279      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2280        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2281      else
2282        return isa<TypeDecl>(ND);
2283    }
2284    return false;
2285  }
2286
2287 private:
2288  CXXRecordDecl *ClassDecl;
2289};
2290
2291}
2292
2293/// \brief Handle a C++ member initializer.
2294MemInitResult
2295Sema::BuildMemInitializer(Decl *ConstructorD,
2296                          Scope *S,
2297                          CXXScopeSpec &SS,
2298                          IdentifierInfo *MemberOrBase,
2299                          ParsedType TemplateTypeTy,
2300                          const DeclSpec &DS,
2301                          SourceLocation IdLoc,
2302                          Expr *Init,
2303                          SourceLocation EllipsisLoc) {
2304  if (!ConstructorD)
2305    return true;
2306
2307  AdjustDeclIfTemplate(ConstructorD);
2308
2309  CXXConstructorDecl *Constructor
2310    = dyn_cast<CXXConstructorDecl>(ConstructorD);
2311  if (!Constructor) {
2312    // The user wrote a constructor initializer on a function that is
2313    // not a C++ constructor. Ignore the error for now, because we may
2314    // have more member initializers coming; we'll diagnose it just
2315    // once in ActOnMemInitializers.
2316    return true;
2317  }
2318
2319  CXXRecordDecl *ClassDecl = Constructor->getParent();
2320
2321  // C++ [class.base.init]p2:
2322  //   Names in a mem-initializer-id are looked up in the scope of the
2323  //   constructor's class and, if not found in that scope, are looked
2324  //   up in the scope containing the constructor's definition.
2325  //   [Note: if the constructor's class contains a member with the
2326  //   same name as a direct or virtual base class of the class, a
2327  //   mem-initializer-id naming the member or base class and composed
2328  //   of a single identifier refers to the class member. A
2329  //   mem-initializer-id for the hidden base class may be specified
2330  //   using a qualified name. ]
2331  if (!SS.getScopeRep() && !TemplateTypeTy) {
2332    // Look for a member, first.
2333    DeclContext::lookup_result Result
2334      = ClassDecl->lookup(MemberOrBase);
2335    if (!Result.empty()) {
2336      ValueDecl *Member;
2337      if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2338          (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2339        if (EllipsisLoc.isValid())
2340          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2341            << MemberOrBase
2342            << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2343
2344        return BuildMemberInitializer(Member, Init, IdLoc);
2345      }
2346    }
2347  }
2348  // It didn't name a member, so see if it names a class.
2349  QualType BaseType;
2350  TypeSourceInfo *TInfo = 0;
2351
2352  if (TemplateTypeTy) {
2353    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2354  } else if (DS.getTypeSpecType() == TST_decltype) {
2355    BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2356  } else {
2357    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2358    LookupParsedName(R, S, &SS);
2359
2360    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2361    if (!TyD) {
2362      if (R.isAmbiguous()) return true;
2363
2364      // We don't want access-control diagnostics here.
2365      R.suppressDiagnostics();
2366
2367      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2368        bool NotUnknownSpecialization = false;
2369        DeclContext *DC = computeDeclContext(SS, false);
2370        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2371          NotUnknownSpecialization = !Record->hasAnyDependentBases();
2372
2373        if (!NotUnknownSpecialization) {
2374          // When the scope specifier can refer to a member of an unknown
2375          // specialization, we take it as a type name.
2376          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2377                                       SS.getWithLocInContext(Context),
2378                                       *MemberOrBase, IdLoc);
2379          if (BaseType.isNull())
2380            return true;
2381
2382          R.clear();
2383          R.setLookupName(MemberOrBase);
2384        }
2385      }
2386
2387      // If no results were found, try to correct typos.
2388      TypoCorrection Corr;
2389      MemInitializerValidatorCCC Validator(ClassDecl);
2390      if (R.empty() && BaseType.isNull() &&
2391          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2392                              Validator, ClassDecl))) {
2393        std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2394        std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
2395        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2396          // We have found a non-static data member with a similar
2397          // name to what was typed; complain and initialize that
2398          // member.
2399          Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2400            << MemberOrBase << true << CorrectedQuotedStr
2401            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2402          Diag(Member->getLocation(), diag::note_previous_decl)
2403            << CorrectedQuotedStr;
2404
2405          return BuildMemberInitializer(Member, Init, IdLoc);
2406        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2407          const CXXBaseSpecifier *DirectBaseSpec;
2408          const CXXBaseSpecifier *VirtualBaseSpec;
2409          if (FindBaseInitializer(*this, ClassDecl,
2410                                  Context.getTypeDeclType(Type),
2411                                  DirectBaseSpec, VirtualBaseSpec)) {
2412            // We have found a direct or virtual base class with a
2413            // similar name to what was typed; complain and initialize
2414            // that base class.
2415            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2416              << MemberOrBase << false << CorrectedQuotedStr
2417              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2418
2419            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2420                                                             : VirtualBaseSpec;
2421            Diag(BaseSpec->getLocStart(),
2422                 diag::note_base_class_specified_here)
2423              << BaseSpec->getType()
2424              << BaseSpec->getSourceRange();
2425
2426            TyD = Type;
2427          }
2428        }
2429      }
2430
2431      if (!TyD && BaseType.isNull()) {
2432        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2433          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2434        return true;
2435      }
2436    }
2437
2438    if (BaseType.isNull()) {
2439      BaseType = Context.getTypeDeclType(TyD);
2440      if (SS.isSet()) {
2441        NestedNameSpecifier *Qualifier =
2442          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2443
2444        // FIXME: preserve source range information
2445        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
2446      }
2447    }
2448  }
2449
2450  if (!TInfo)
2451    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2452
2453  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2454}
2455
2456/// Checks a member initializer expression for cases where reference (or
2457/// pointer) members are bound to by-value parameters (or their addresses).
2458static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2459                                               Expr *Init,
2460                                               SourceLocation IdLoc) {
2461  QualType MemberTy = Member->getType();
2462
2463  // We only handle pointers and references currently.
2464  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2465  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2466    return;
2467
2468  const bool IsPointer = MemberTy->isPointerType();
2469  if (IsPointer) {
2470    if (const UnaryOperator *Op
2471          = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2472      // The only case we're worried about with pointers requires taking the
2473      // address.
2474      if (Op->getOpcode() != UO_AddrOf)
2475        return;
2476
2477      Init = Op->getSubExpr();
2478    } else {
2479      // We only handle address-of expression initializers for pointers.
2480      return;
2481    }
2482  }
2483
2484  if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2485    // Taking the address of a temporary will be diagnosed as a hard error.
2486    if (IsPointer)
2487      return;
2488
2489    S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2490      << Member << Init->getSourceRange();
2491  } else if (const DeclRefExpr *DRE
2492               = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2493    // We only warn when referring to a non-reference parameter declaration.
2494    const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2495    if (!Parameter || Parameter->getType()->isReferenceType())
2496      return;
2497
2498    S.Diag(Init->getExprLoc(),
2499           IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2500                     : diag::warn_bind_ref_member_to_parameter)
2501      << Member << Parameter << Init->getSourceRange();
2502  } else {
2503    // Other initializers are fine.
2504    return;
2505  }
2506
2507  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2508    << (unsigned)IsPointer;
2509}
2510
2511MemInitResult
2512Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2513                             SourceLocation IdLoc) {
2514  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2515  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2516  assert((DirectMember || IndirectMember) &&
2517         "Member must be a FieldDecl or IndirectFieldDecl");
2518
2519  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2520    return true;
2521
2522  if (Member->isInvalidDecl())
2523    return true;
2524
2525  // Diagnose value-uses of fields to initialize themselves, e.g.
2526  //   foo(foo)
2527  // where foo is not also a parameter to the constructor.
2528  // TODO: implement -Wuninitialized and fold this into that framework.
2529  Expr **Args;
2530  unsigned NumArgs;
2531  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2532    Args = ParenList->getExprs();
2533    NumArgs = ParenList->getNumExprs();
2534  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2535    Args = InitList->getInits();
2536    NumArgs = InitList->getNumInits();
2537  } else {
2538    // Template instantiation doesn't reconstruct ParenListExprs for us.
2539    Args = &Init;
2540    NumArgs = 1;
2541  }
2542
2543  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2544        != DiagnosticsEngine::Ignored)
2545    for (unsigned i = 0; i < NumArgs; ++i)
2546      // FIXME: Warn about the case when other fields are used before being
2547      // initialized. For example, let this field be the i'th field. When
2548      // initializing the i'th field, throw a warning if any of the >= i'th
2549      // fields are used, as they are not yet initialized.
2550      // Right now we are only handling the case where the i'th field uses
2551      // itself in its initializer.
2552      // Also need to take into account that some fields may be initialized by
2553      // in-class initializers, see C++11 [class.base.init]p9.
2554      CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
2555
2556  SourceRange InitRange = Init->getSourceRange();
2557
2558  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2559    // Can't check initialization for a member of dependent type or when
2560    // any of the arguments are type-dependent expressions.
2561    DiscardCleanupsInEvaluationContext();
2562  } else {
2563    bool InitList = false;
2564    if (isa<InitListExpr>(Init)) {
2565      InitList = true;
2566      Args = &Init;
2567      NumArgs = 1;
2568
2569      if (isStdInitializerList(Member->getType(), 0)) {
2570        Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2571            << /*at end of ctor*/1 << InitRange;
2572      }
2573    }
2574
2575    // Initialize the member.
2576    InitializedEntity MemberEntity =
2577      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2578                   : InitializedEntity::InitializeMember(IndirectMember, 0);
2579    InitializationKind Kind =
2580      InitList ? InitializationKind::CreateDirectList(IdLoc)
2581               : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2582                                                  InitRange.getEnd());
2583
2584    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2585    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2586                                            MultiExprArg(Args, NumArgs),
2587                                            0);
2588    if (MemberInit.isInvalid())
2589      return true;
2590
2591    // C++11 [class.base.init]p7:
2592    //   The initialization of each base and member constitutes a
2593    //   full-expression.
2594    MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2595    if (MemberInit.isInvalid())
2596      return true;
2597
2598    Init = MemberInit.get();
2599    CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2600  }
2601
2602  if (DirectMember) {
2603    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2604                                            InitRange.getBegin(), Init,
2605                                            InitRange.getEnd());
2606  } else {
2607    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2608                                            InitRange.getBegin(), Init,
2609                                            InitRange.getEnd());
2610  }
2611}
2612
2613MemInitResult
2614Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2615                                 CXXRecordDecl *ClassDecl) {
2616  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2617  if (!LangOpts.CPlusPlus11)
2618    return Diag(NameLoc, diag::err_delegating_ctor)
2619      << TInfo->getTypeLoc().getLocalSourceRange();
2620  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2621
2622  bool InitList = true;
2623  Expr **Args = &Init;
2624  unsigned NumArgs = 1;
2625  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2626    InitList = false;
2627    Args = ParenList->getExprs();
2628    NumArgs = ParenList->getNumExprs();
2629  }
2630
2631  SourceRange InitRange = Init->getSourceRange();
2632  // Initialize the object.
2633  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2634                                     QualType(ClassDecl->getTypeForDecl(), 0));
2635  InitializationKind Kind =
2636    InitList ? InitializationKind::CreateDirectList(NameLoc)
2637             : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2638                                                InitRange.getEnd());
2639  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2640  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2641                                              MultiExprArg(Args, NumArgs),
2642                                              0);
2643  if (DelegationInit.isInvalid())
2644    return true;
2645
2646  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2647         "Delegating constructor with no target?");
2648
2649  // C++11 [class.base.init]p7:
2650  //   The initialization of each base and member constitutes a
2651  //   full-expression.
2652  DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2653                                       InitRange.getBegin());
2654  if (DelegationInit.isInvalid())
2655    return true;
2656
2657  // If we are in a dependent context, template instantiation will
2658  // perform this type-checking again. Just save the arguments that we
2659  // received in a ParenListExpr.
2660  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2661  // of the information that we have about the base
2662  // initializer. However, deconstructing the ASTs is a dicey process,
2663  // and this approach is far more likely to get the corner cases right.
2664  if (CurContext->isDependentContext())
2665    DelegationInit = Owned(Init);
2666
2667  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2668                                          DelegationInit.takeAs<Expr>(),
2669                                          InitRange.getEnd());
2670}
2671
2672MemInitResult
2673Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2674                           Expr *Init, CXXRecordDecl *ClassDecl,
2675                           SourceLocation EllipsisLoc) {
2676  SourceLocation BaseLoc
2677    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2678
2679  if (!BaseType->isDependentType() && !BaseType->isRecordType())
2680    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2681             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2682
2683  // C++ [class.base.init]p2:
2684  //   [...] Unless the mem-initializer-id names a nonstatic data
2685  //   member of the constructor's class or a direct or virtual base
2686  //   of that class, the mem-initializer is ill-formed. A
2687  //   mem-initializer-list can initialize a base class using any
2688  //   name that denotes that base class type.
2689  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2690
2691  SourceRange InitRange = Init->getSourceRange();
2692  if (EllipsisLoc.isValid()) {
2693    // This is a pack expansion.
2694    if (!BaseType->containsUnexpandedParameterPack())  {
2695      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2696        << SourceRange(BaseLoc, InitRange.getEnd());
2697
2698      EllipsisLoc = SourceLocation();
2699    }
2700  } else {
2701    // Check for any unexpanded parameter packs.
2702    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2703      return true;
2704
2705    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2706      return true;
2707  }
2708
2709  // Check for direct and virtual base classes.
2710  const CXXBaseSpecifier *DirectBaseSpec = 0;
2711  const CXXBaseSpecifier *VirtualBaseSpec = 0;
2712  if (!Dependent) {
2713    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2714                                       BaseType))
2715      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2716
2717    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2718                        VirtualBaseSpec);
2719
2720    // C++ [base.class.init]p2:
2721    // Unless the mem-initializer-id names a nonstatic data member of the
2722    // constructor's class or a direct or virtual base of that class, the
2723    // mem-initializer is ill-formed.
2724    if (!DirectBaseSpec && !VirtualBaseSpec) {
2725      // If the class has any dependent bases, then it's possible that
2726      // one of those types will resolve to the same type as
2727      // BaseType. Therefore, just treat this as a dependent base
2728      // class initialization.  FIXME: Should we try to check the
2729      // initialization anyway? It seems odd.
2730      if (ClassDecl->hasAnyDependentBases())
2731        Dependent = true;
2732      else
2733        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2734          << BaseType << Context.getTypeDeclType(ClassDecl)
2735          << BaseTInfo->getTypeLoc().getLocalSourceRange();
2736    }
2737  }
2738
2739  if (Dependent) {
2740    DiscardCleanupsInEvaluationContext();
2741
2742    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2743                                            /*IsVirtual=*/false,
2744                                            InitRange.getBegin(), Init,
2745                                            InitRange.getEnd(), EllipsisLoc);
2746  }
2747
2748  // C++ [base.class.init]p2:
2749  //   If a mem-initializer-id is ambiguous because it designates both
2750  //   a direct non-virtual base class and an inherited virtual base
2751  //   class, the mem-initializer is ill-formed.
2752  if (DirectBaseSpec && VirtualBaseSpec)
2753    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2754      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2755
2756  CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2757  if (!BaseSpec)
2758    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2759
2760  // Initialize the base.
2761  bool InitList = true;
2762  Expr **Args = &Init;
2763  unsigned NumArgs = 1;
2764  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2765    InitList = false;
2766    Args = ParenList->getExprs();
2767    NumArgs = ParenList->getNumExprs();
2768  }
2769
2770  InitializedEntity BaseEntity =
2771    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2772  InitializationKind Kind =
2773    InitList ? InitializationKind::CreateDirectList(BaseLoc)
2774             : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2775                                                InitRange.getEnd());
2776  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2777  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2778                                        MultiExprArg(Args, NumArgs), 0);
2779  if (BaseInit.isInvalid())
2780    return true;
2781
2782  // C++11 [class.base.init]p7:
2783  //   The initialization of each base and member constitutes a
2784  //   full-expression.
2785  BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
2786  if (BaseInit.isInvalid())
2787    return true;
2788
2789  // If we are in a dependent context, template instantiation will
2790  // perform this type-checking again. Just save the arguments that we
2791  // received in a ParenListExpr.
2792  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2793  // of the information that we have about the base
2794  // initializer. However, deconstructing the ASTs is a dicey process,
2795  // and this approach is far more likely to get the corner cases right.
2796  if (CurContext->isDependentContext())
2797    BaseInit = Owned(Init);
2798
2799  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2800                                          BaseSpec->isVirtual(),
2801                                          InitRange.getBegin(),
2802                                          BaseInit.takeAs<Expr>(),
2803                                          InitRange.getEnd(), EllipsisLoc);
2804}
2805
2806// Create a static_cast\<T&&>(expr).
2807static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2808  if (T.isNull()) T = E->getType();
2809  QualType TargetType = SemaRef.BuildReferenceType(
2810      T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
2811  SourceLocation ExprLoc = E->getLocStart();
2812  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2813      TargetType, ExprLoc);
2814
2815  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2816                                   SourceRange(ExprLoc, ExprLoc),
2817                                   E->getSourceRange()).take();
2818}
2819
2820/// ImplicitInitializerKind - How an implicit base or member initializer should
2821/// initialize its base or member.
2822enum ImplicitInitializerKind {
2823  IIK_Default,
2824  IIK_Copy,
2825  IIK_Move,
2826  IIK_Inherit
2827};
2828
2829static bool
2830BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2831                             ImplicitInitializerKind ImplicitInitKind,
2832                             CXXBaseSpecifier *BaseSpec,
2833                             bool IsInheritedVirtualBase,
2834                             CXXCtorInitializer *&CXXBaseInit) {
2835  InitializedEntity InitEntity
2836    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2837                                        IsInheritedVirtualBase);
2838
2839  ExprResult BaseInit;
2840
2841  switch (ImplicitInitKind) {
2842  case IIK_Inherit: {
2843    const CXXRecordDecl *Inherited =
2844        Constructor->getInheritedConstructor()->getParent();
2845    const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2846    if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2847      // C++11 [class.inhctor]p8:
2848      //   Each expression in the expression-list is of the form
2849      //   static_cast<T&&>(p), where p is the name of the corresponding
2850      //   constructor parameter and T is the declared type of p.
2851      SmallVector<Expr*, 16> Args;
2852      for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2853        ParmVarDecl *PD = Constructor->getParamDecl(I);
2854        ExprResult ArgExpr =
2855            SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2856                                     VK_LValue, SourceLocation());
2857        if (ArgExpr.isInvalid())
2858          return true;
2859        Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2860      }
2861
2862      InitializationKind InitKind = InitializationKind::CreateDirect(
2863          Constructor->getLocation(), SourceLocation(), SourceLocation());
2864      InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2865                                     Args.data(), Args.size());
2866      BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2867      break;
2868    }
2869  }
2870  // Fall through.
2871  case IIK_Default: {
2872    InitializationKind InitKind
2873      = InitializationKind::CreateDefault(Constructor->getLocation());
2874    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2875    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2876    break;
2877  }
2878
2879  case IIK_Move:
2880  case IIK_Copy: {
2881    bool Moving = ImplicitInitKind == IIK_Move;
2882    ParmVarDecl *Param = Constructor->getParamDecl(0);
2883    QualType ParamType = Param->getType().getNonReferenceType();
2884
2885    Expr *CopyCtorArg =
2886      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2887                          SourceLocation(), Param, false,
2888                          Constructor->getLocation(), ParamType,
2889                          VK_LValue, 0);
2890
2891    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2892
2893    // Cast to the base class to avoid ambiguities.
2894    QualType ArgTy =
2895      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2896                                       ParamType.getQualifiers());
2897
2898    if (Moving) {
2899      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2900    }
2901
2902    CXXCastPath BasePath;
2903    BasePath.push_back(BaseSpec);
2904    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2905                                            CK_UncheckedDerivedToBase,
2906                                            Moving ? VK_XValue : VK_LValue,
2907                                            &BasePath).take();
2908
2909    InitializationKind InitKind
2910      = InitializationKind::CreateDirect(Constructor->getLocation(),
2911                                         SourceLocation(), SourceLocation());
2912    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2913                                   &CopyCtorArg, 1);
2914    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2915                               MultiExprArg(&CopyCtorArg, 1));
2916    break;
2917  }
2918  }
2919
2920  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2921  if (BaseInit.isInvalid())
2922    return true;
2923
2924  CXXBaseInit =
2925    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2926               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2927                                                        SourceLocation()),
2928                                             BaseSpec->isVirtual(),
2929                                             SourceLocation(),
2930                                             BaseInit.takeAs<Expr>(),
2931                                             SourceLocation(),
2932                                             SourceLocation());
2933
2934  return false;
2935}
2936
2937static bool RefersToRValueRef(Expr *MemRef) {
2938  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2939  return Referenced->getType()->isRValueReferenceType();
2940}
2941
2942static bool
2943BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2944                               ImplicitInitializerKind ImplicitInitKind,
2945                               FieldDecl *Field, IndirectFieldDecl *Indirect,
2946                               CXXCtorInitializer *&CXXMemberInit) {
2947  if (Field->isInvalidDecl())
2948    return true;
2949
2950  SourceLocation Loc = Constructor->getLocation();
2951
2952  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2953    bool Moving = ImplicitInitKind == IIK_Move;
2954    ParmVarDecl *Param = Constructor->getParamDecl(0);
2955    QualType ParamType = Param->getType().getNonReferenceType();
2956
2957    // Suppress copying zero-width bitfields.
2958    if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2959      return false;
2960
2961    Expr *MemberExprBase =
2962      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2963                          SourceLocation(), Param, false,
2964                          Loc, ParamType, VK_LValue, 0);
2965
2966    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2967
2968    if (Moving) {
2969      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2970    }
2971
2972    // Build a reference to this field within the parameter.
2973    CXXScopeSpec SS;
2974    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2975                              Sema::LookupMemberName);
2976    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2977                                  : cast<ValueDecl>(Field), AS_public);
2978    MemberLookup.resolveKind();
2979    ExprResult CtorArg
2980      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2981                                         ParamType, Loc,
2982                                         /*IsArrow=*/false,
2983                                         SS,
2984                                         /*TemplateKWLoc=*/SourceLocation(),
2985                                         /*FirstQualifierInScope=*/0,
2986                                         MemberLookup,
2987                                         /*TemplateArgs=*/0);
2988    if (CtorArg.isInvalid())
2989      return true;
2990
2991    // C++11 [class.copy]p15:
2992    //   - if a member m has rvalue reference type T&&, it is direct-initialized
2993    //     with static_cast<T&&>(x.m);
2994    if (RefersToRValueRef(CtorArg.get())) {
2995      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2996    }
2997
2998    // When the field we are copying is an array, create index variables for
2999    // each dimension of the array. We use these index variables to subscript
3000    // the source array, and other clients (e.g., CodeGen) will perform the
3001    // necessary iteration with these index variables.
3002    SmallVector<VarDecl *, 4> IndexVariables;
3003    QualType BaseType = Field->getType();
3004    QualType SizeType = SemaRef.Context.getSizeType();
3005    bool InitializingArray = false;
3006    while (const ConstantArrayType *Array
3007                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3008      InitializingArray = true;
3009      // Create the iteration variable for this array index.
3010      IdentifierInfo *IterationVarName = 0;
3011      {
3012        SmallString<8> Str;
3013        llvm::raw_svector_ostream OS(Str);
3014        OS << "__i" << IndexVariables.size();
3015        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3016      }
3017      VarDecl *IterationVar
3018        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3019                          IterationVarName, SizeType,
3020                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3021                          SC_None);
3022      IndexVariables.push_back(IterationVar);
3023
3024      // Create a reference to the iteration variable.
3025      ExprResult IterationVarRef
3026        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3027      assert(!IterationVarRef.isInvalid() &&
3028             "Reference to invented variable cannot fail!");
3029      IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3030      assert(!IterationVarRef.isInvalid() &&
3031             "Conversion of invented variable cannot fail!");
3032
3033      // Subscript the array with this iteration variable.
3034      CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
3035                                                        IterationVarRef.take(),
3036                                                        Loc);
3037      if (CtorArg.isInvalid())
3038        return true;
3039
3040      BaseType = Array->getElementType();
3041    }
3042
3043    // The array subscript expression is an lvalue, which is wrong for moving.
3044    if (Moving && InitializingArray)
3045      CtorArg = CastForMoving(SemaRef, CtorArg.take());
3046
3047    // Construct the entity that we will be initializing. For an array, this
3048    // will be first element in the array, which may require several levels
3049    // of array-subscript entities.
3050    SmallVector<InitializedEntity, 4> Entities;
3051    Entities.reserve(1 + IndexVariables.size());
3052    if (Indirect)
3053      Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3054    else
3055      Entities.push_back(InitializedEntity::InitializeMember(Field));
3056    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3057      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3058                                                              0,
3059                                                              Entities.back()));
3060
3061    // Direct-initialize to use the copy constructor.
3062    InitializationKind InitKind =
3063      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3064
3065    Expr *CtorArgE = CtorArg.takeAs<Expr>();
3066    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3067                                   &CtorArgE, 1);
3068
3069    ExprResult MemberInit
3070      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3071                        MultiExprArg(&CtorArgE, 1));
3072    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3073    if (MemberInit.isInvalid())
3074      return true;
3075
3076    if (Indirect) {
3077      assert(IndexVariables.size() == 0 &&
3078             "Indirect field improperly initialized");
3079      CXXMemberInit
3080        = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3081                                                   Loc, Loc,
3082                                                   MemberInit.takeAs<Expr>(),
3083                                                   Loc);
3084    } else
3085      CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3086                                                 Loc, MemberInit.takeAs<Expr>(),
3087                                                 Loc,
3088                                                 IndexVariables.data(),
3089                                                 IndexVariables.size());
3090    return false;
3091  }
3092
3093  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3094         "Unhandled implicit init kind!");
3095
3096  QualType FieldBaseElementType =
3097    SemaRef.Context.getBaseElementType(Field->getType());
3098
3099  if (FieldBaseElementType->isRecordType()) {
3100    InitializedEntity InitEntity
3101      = Indirect? InitializedEntity::InitializeMember(Indirect)
3102                : InitializedEntity::InitializeMember(Field);
3103    InitializationKind InitKind =
3104      InitializationKind::CreateDefault(Loc);
3105
3106    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
3107    ExprResult MemberInit =
3108      InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
3109
3110    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3111    if (MemberInit.isInvalid())
3112      return true;
3113
3114    if (Indirect)
3115      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3116                                                               Indirect, Loc,
3117                                                               Loc,
3118                                                               MemberInit.get(),
3119                                                               Loc);
3120    else
3121      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3122                                                               Field, Loc, Loc,
3123                                                               MemberInit.get(),
3124                                                               Loc);
3125    return false;
3126  }
3127
3128  if (!Field->getParent()->isUnion()) {
3129    if (FieldBaseElementType->isReferenceType()) {
3130      SemaRef.Diag(Constructor->getLocation(),
3131                   diag::err_uninitialized_member_in_ctor)
3132      << (int)Constructor->isImplicit()
3133      << SemaRef.Context.getTagDeclType(Constructor->getParent())
3134      << 0 << Field->getDeclName();
3135      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3136      return true;
3137    }
3138
3139    if (FieldBaseElementType.isConstQualified()) {
3140      SemaRef.Diag(Constructor->getLocation(),
3141                   diag::err_uninitialized_member_in_ctor)
3142      << (int)Constructor->isImplicit()
3143      << SemaRef.Context.getTagDeclType(Constructor->getParent())
3144      << 1 << Field->getDeclName();
3145      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3146      return true;
3147    }
3148  }
3149
3150  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3151      FieldBaseElementType->isObjCRetainableType() &&
3152      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3153      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3154    // ARC:
3155    //   Default-initialize Objective-C pointers to NULL.
3156    CXXMemberInit
3157      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3158                                                 Loc, Loc,
3159                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3160                                                 Loc);
3161    return false;
3162  }
3163
3164  // Nothing to initialize.
3165  CXXMemberInit = 0;
3166  return false;
3167}
3168
3169namespace {
3170struct BaseAndFieldInfo {
3171  Sema &S;
3172  CXXConstructorDecl *Ctor;
3173  bool AnyErrorsInInits;
3174  ImplicitInitializerKind IIK;
3175  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3176  SmallVector<CXXCtorInitializer*, 8> AllToInit;
3177
3178  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3179    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3180    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3181    if (Generated && Ctor->isCopyConstructor())
3182      IIK = IIK_Copy;
3183    else if (Generated && Ctor->isMoveConstructor())
3184      IIK = IIK_Move;
3185    else if (Ctor->getInheritedConstructor())
3186      IIK = IIK_Inherit;
3187    else
3188      IIK = IIK_Default;
3189  }
3190
3191  bool isImplicitCopyOrMove() const {
3192    switch (IIK) {
3193    case IIK_Copy:
3194    case IIK_Move:
3195      return true;
3196
3197    case IIK_Default:
3198    case IIK_Inherit:
3199      return false;
3200    }
3201
3202    llvm_unreachable("Invalid ImplicitInitializerKind!");
3203  }
3204
3205  bool addFieldInitializer(CXXCtorInitializer *Init) {
3206    AllToInit.push_back(Init);
3207
3208    // Check whether this initializer makes the field "used".
3209    if (Init->getInit()->HasSideEffects(S.Context))
3210      S.UnusedPrivateFields.remove(Init->getAnyMember());
3211
3212    return false;
3213  }
3214};
3215}
3216
3217/// \brief Determine whether the given indirect field declaration is somewhere
3218/// within an anonymous union.
3219static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3220  for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3221                                      CEnd = F->chain_end();
3222       C != CEnd; ++C)
3223    if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3224      if (Record->isUnion())
3225        return true;
3226
3227  return false;
3228}
3229
3230/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3231/// array type.
3232static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3233  if (T->isIncompleteArrayType())
3234    return true;
3235
3236  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3237    if (!ArrayT->getSize())
3238      return true;
3239
3240    T = ArrayT->getElementType();
3241  }
3242
3243  return false;
3244}
3245
3246static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3247                                    FieldDecl *Field,
3248                                    IndirectFieldDecl *Indirect = 0) {
3249
3250  // Overwhelmingly common case: we have a direct initializer for this field.
3251  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3252    return Info.addFieldInitializer(Init);
3253
3254  // C++11 [class.base.init]p8: if the entity is a non-static data member that
3255  // has a brace-or-equal-initializer, the entity is initialized as specified
3256  // in [dcl.init].
3257  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3258    Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3259                                           Info.Ctor->getLocation(), Field);
3260    CXXCtorInitializer *Init;
3261    if (Indirect)
3262      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3263                                                      SourceLocation(),
3264                                                      SourceLocation(), DIE,
3265                                                      SourceLocation());
3266    else
3267      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3268                                                      SourceLocation(),
3269                                                      SourceLocation(), DIE,
3270                                                      SourceLocation());
3271    return Info.addFieldInitializer(Init);
3272  }
3273
3274  // Don't build an implicit initializer for union members if none was
3275  // explicitly specified.
3276  if (Field->getParent()->isUnion() ||
3277      (Indirect && isWithinAnonymousUnion(Indirect)))
3278    return false;
3279
3280  // Don't initialize incomplete or zero-length arrays.
3281  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3282    return false;
3283
3284  // Don't try to build an implicit initializer if there were semantic
3285  // errors in any of the initializers (and therefore we might be
3286  // missing some that the user actually wrote).
3287  if (Info.AnyErrorsInInits || Field->isInvalidDecl())
3288    return false;
3289
3290  CXXCtorInitializer *Init = 0;
3291  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3292                                     Indirect, Init))
3293    return true;
3294
3295  if (!Init)
3296    return false;
3297
3298  return Info.addFieldInitializer(Init);
3299}
3300
3301bool
3302Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3303                               CXXCtorInitializer *Initializer) {
3304  assert(Initializer->isDelegatingInitializer());
3305  Constructor->setNumCtorInitializers(1);
3306  CXXCtorInitializer **initializer =
3307    new (Context) CXXCtorInitializer*[1];
3308  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3309  Constructor->setCtorInitializers(initializer);
3310
3311  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3312    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3313    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3314  }
3315
3316  DelegatingCtorDecls.push_back(Constructor);
3317
3318  return false;
3319}
3320
3321bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3322                               ArrayRef<CXXCtorInitializer *> Initializers) {
3323  if (Constructor->isDependentContext()) {
3324    // Just store the initializers as written, they will be checked during
3325    // instantiation.
3326    if (!Initializers.empty()) {
3327      Constructor->setNumCtorInitializers(Initializers.size());
3328      CXXCtorInitializer **baseOrMemberInitializers =
3329        new (Context) CXXCtorInitializer*[Initializers.size()];
3330      memcpy(baseOrMemberInitializers, Initializers.data(),
3331             Initializers.size() * sizeof(CXXCtorInitializer*));
3332      Constructor->setCtorInitializers(baseOrMemberInitializers);
3333    }
3334
3335    // Let template instantiation know whether we had errors.
3336    if (AnyErrors)
3337      Constructor->setInvalidDecl();
3338
3339    return false;
3340  }
3341
3342  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3343
3344  // We need to build the initializer AST according to order of construction
3345  // and not what user specified in the Initializers list.
3346  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3347  if (!ClassDecl)
3348    return true;
3349
3350  bool HadError = false;
3351
3352  for (unsigned i = 0; i < Initializers.size(); i++) {
3353    CXXCtorInitializer *Member = Initializers[i];
3354
3355    if (Member->isBaseInitializer())
3356      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3357    else
3358      Info.AllBaseFields[Member->getAnyMember()] = Member;
3359  }
3360
3361  // Keep track of the direct virtual bases.
3362  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3363  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3364       E = ClassDecl->bases_end(); I != E; ++I) {
3365    if (I->isVirtual())
3366      DirectVBases.insert(I);
3367  }
3368
3369  // Push virtual bases before others.
3370  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3371       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3372
3373    if (CXXCtorInitializer *Value
3374        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3375      Info.AllToInit.push_back(Value);
3376    } else if (!AnyErrors) {
3377      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3378      CXXCtorInitializer *CXXBaseInit;
3379      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3380                                       VBase, IsInheritedVirtualBase,
3381                                       CXXBaseInit)) {
3382        HadError = true;
3383        continue;
3384      }
3385
3386      Info.AllToInit.push_back(CXXBaseInit);
3387    }
3388  }
3389
3390  // Non-virtual bases.
3391  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3392       E = ClassDecl->bases_end(); Base != E; ++Base) {
3393    // Virtuals are in the virtual base list and already constructed.
3394    if (Base->isVirtual())
3395      continue;
3396
3397    if (CXXCtorInitializer *Value
3398          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3399      Info.AllToInit.push_back(Value);
3400    } else if (!AnyErrors) {
3401      CXXCtorInitializer *CXXBaseInit;
3402      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3403                                       Base, /*IsInheritedVirtualBase=*/false,
3404                                       CXXBaseInit)) {
3405        HadError = true;
3406        continue;
3407      }
3408
3409      Info.AllToInit.push_back(CXXBaseInit);
3410    }
3411  }
3412
3413  // Fields.
3414  for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3415                               MemEnd = ClassDecl->decls_end();
3416       Mem != MemEnd; ++Mem) {
3417    if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3418      // C++ [class.bit]p2:
3419      //   A declaration for a bit-field that omits the identifier declares an
3420      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3421      //   initialized.
3422      if (F->isUnnamedBitfield())
3423        continue;
3424
3425      // If we're not generating the implicit copy/move constructor, then we'll
3426      // handle anonymous struct/union fields based on their individual
3427      // indirect fields.
3428      if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3429        continue;
3430
3431      if (CollectFieldInitializer(*this, Info, F))
3432        HadError = true;
3433      continue;
3434    }
3435
3436    // Beyond this point, we only consider default initialization.
3437    if (Info.isImplicitCopyOrMove())
3438      continue;
3439
3440    if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3441      if (F->getType()->isIncompleteArrayType()) {
3442        assert(ClassDecl->hasFlexibleArrayMember() &&
3443               "Incomplete array type is not valid");
3444        continue;
3445      }
3446
3447      // Initialize each field of an anonymous struct individually.
3448      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3449        HadError = true;
3450
3451      continue;
3452    }
3453  }
3454
3455  unsigned NumInitializers = Info.AllToInit.size();
3456  if (NumInitializers > 0) {
3457    Constructor->setNumCtorInitializers(NumInitializers);
3458    CXXCtorInitializer **baseOrMemberInitializers =
3459      new (Context) CXXCtorInitializer*[NumInitializers];
3460    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3461           NumInitializers * sizeof(CXXCtorInitializer*));
3462    Constructor->setCtorInitializers(baseOrMemberInitializers);
3463
3464    // Constructors implicitly reference the base and member
3465    // destructors.
3466    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3467                                           Constructor->getParent());
3468  }
3469
3470  return HadError;
3471}
3472
3473static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3474  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3475    const RecordDecl *RD = RT->getDecl();
3476    if (RD->isAnonymousStructOrUnion()) {
3477      for (RecordDecl::field_iterator Field = RD->field_begin(),
3478          E = RD->field_end(); Field != E; ++Field)
3479        PopulateKeysForFields(*Field, IdealInits);
3480      return;
3481    }
3482  }
3483  IdealInits.push_back(Field);
3484}
3485
3486static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3487  return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3488}
3489
3490static void *GetKeyForMember(ASTContext &Context,
3491                             CXXCtorInitializer *Member) {
3492  if (!Member->isAnyMemberInitializer())
3493    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3494
3495  return Member->getAnyMember();
3496}
3497
3498static void DiagnoseBaseOrMemInitializerOrder(
3499    Sema &SemaRef, const CXXConstructorDecl *Constructor,
3500    ArrayRef<CXXCtorInitializer *> Inits) {
3501  if (Constructor->getDeclContext()->isDependentContext())
3502    return;
3503
3504  // Don't check initializers order unless the warning is enabled at the
3505  // location of at least one initializer.
3506  bool ShouldCheckOrder = false;
3507  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3508    CXXCtorInitializer *Init = Inits[InitIndex];
3509    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3510                                         Init->getSourceLocation())
3511          != DiagnosticsEngine::Ignored) {
3512      ShouldCheckOrder = true;
3513      break;
3514    }
3515  }
3516  if (!ShouldCheckOrder)
3517    return;
3518
3519  // Build the list of bases and members in the order that they'll
3520  // actually be initialized.  The explicit initializers should be in
3521  // this same order but may be missing things.
3522  SmallVector<const void*, 32> IdealInitKeys;
3523
3524  const CXXRecordDecl *ClassDecl = Constructor->getParent();
3525
3526  // 1. Virtual bases.
3527  for (CXXRecordDecl::base_class_const_iterator VBase =
3528       ClassDecl->vbases_begin(),
3529       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3530    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3531
3532  // 2. Non-virtual bases.
3533  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3534       E = ClassDecl->bases_end(); Base != E; ++Base) {
3535    if (Base->isVirtual())
3536      continue;
3537    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3538  }
3539
3540  // 3. Direct fields.
3541  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3542       E = ClassDecl->field_end(); Field != E; ++Field) {
3543    if (Field->isUnnamedBitfield())
3544      continue;
3545
3546    PopulateKeysForFields(*Field, IdealInitKeys);
3547  }
3548
3549  unsigned NumIdealInits = IdealInitKeys.size();
3550  unsigned IdealIndex = 0;
3551
3552  CXXCtorInitializer *PrevInit = 0;
3553  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3554    CXXCtorInitializer *Init = Inits[InitIndex];
3555    void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3556
3557    // Scan forward to try to find this initializer in the idealized
3558    // initializers list.
3559    for (; IdealIndex != NumIdealInits; ++IdealIndex)
3560      if (InitKey == IdealInitKeys[IdealIndex])
3561        break;
3562
3563    // If we didn't find this initializer, it must be because we
3564    // scanned past it on a previous iteration.  That can only
3565    // happen if we're out of order;  emit a warning.
3566    if (IdealIndex == NumIdealInits && PrevInit) {
3567      Sema::SemaDiagnosticBuilder D =
3568        SemaRef.Diag(PrevInit->getSourceLocation(),
3569                     diag::warn_initializer_out_of_order);
3570
3571      if (PrevInit->isAnyMemberInitializer())
3572        D << 0 << PrevInit->getAnyMember()->getDeclName();
3573      else
3574        D << 1 << PrevInit->getTypeSourceInfo()->getType();
3575
3576      if (Init->isAnyMemberInitializer())
3577        D << 0 << Init->getAnyMember()->getDeclName();
3578      else
3579        D << 1 << Init->getTypeSourceInfo()->getType();
3580
3581      // Move back to the initializer's location in the ideal list.
3582      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3583        if (InitKey == IdealInitKeys[IdealIndex])
3584          break;
3585
3586      assert(IdealIndex != NumIdealInits &&
3587             "initializer not found in initializer list");
3588    }
3589
3590    PrevInit = Init;
3591  }
3592}
3593
3594namespace {
3595bool CheckRedundantInit(Sema &S,
3596                        CXXCtorInitializer *Init,
3597                        CXXCtorInitializer *&PrevInit) {
3598  if (!PrevInit) {
3599    PrevInit = Init;
3600    return false;
3601  }
3602
3603  if (FieldDecl *Field = Init->getAnyMember())
3604    S.Diag(Init->getSourceLocation(),
3605           diag::err_multiple_mem_initialization)
3606      << Field->getDeclName()
3607      << Init->getSourceRange();
3608  else {
3609    const Type *BaseClass = Init->getBaseClass();
3610    assert(BaseClass && "neither field nor base");
3611    S.Diag(Init->getSourceLocation(),
3612           diag::err_multiple_base_initialization)
3613      << QualType(BaseClass, 0)
3614      << Init->getSourceRange();
3615  }
3616  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3617    << 0 << PrevInit->getSourceRange();
3618
3619  return true;
3620}
3621
3622typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3623typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3624
3625bool CheckRedundantUnionInit(Sema &S,
3626                             CXXCtorInitializer *Init,
3627                             RedundantUnionMap &Unions) {
3628  FieldDecl *Field = Init->getAnyMember();
3629  RecordDecl *Parent = Field->getParent();
3630  NamedDecl *Child = Field;
3631
3632  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3633    if (Parent->isUnion()) {
3634      UnionEntry &En = Unions[Parent];
3635      if (En.first && En.first != Child) {
3636        S.Diag(Init->getSourceLocation(),
3637               diag::err_multiple_mem_union_initialization)
3638          << Field->getDeclName()
3639          << Init->getSourceRange();
3640        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3641          << 0 << En.second->getSourceRange();
3642        return true;
3643      }
3644      if (!En.first) {
3645        En.first = Child;
3646        En.second = Init;
3647      }
3648      if (!Parent->isAnonymousStructOrUnion())
3649        return false;
3650    }
3651
3652    Child = Parent;
3653    Parent = cast<RecordDecl>(Parent->getDeclContext());
3654  }
3655
3656  return false;
3657}
3658}
3659
3660/// ActOnMemInitializers - Handle the member initializers for a constructor.
3661void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3662                                SourceLocation ColonLoc,
3663                                ArrayRef<CXXCtorInitializer*> MemInits,
3664                                bool AnyErrors) {
3665  if (!ConstructorDecl)
3666    return;
3667
3668  AdjustDeclIfTemplate(ConstructorDecl);
3669
3670  CXXConstructorDecl *Constructor
3671    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3672
3673  if (!Constructor) {
3674    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3675    return;
3676  }
3677
3678  // Mapping for the duplicate initializers check.
3679  // For member initializers, this is keyed with a FieldDecl*.
3680  // For base initializers, this is keyed with a Type*.
3681  llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3682
3683  // Mapping for the inconsistent anonymous-union initializers check.
3684  RedundantUnionMap MemberUnions;
3685
3686  bool HadError = false;
3687  for (unsigned i = 0; i < MemInits.size(); i++) {
3688    CXXCtorInitializer *Init = MemInits[i];
3689
3690    // Set the source order index.
3691    Init->setSourceOrder(i);
3692
3693    if (Init->isAnyMemberInitializer()) {
3694      FieldDecl *Field = Init->getAnyMember();
3695      if (CheckRedundantInit(*this, Init, Members[Field]) ||
3696          CheckRedundantUnionInit(*this, Init, MemberUnions))
3697        HadError = true;
3698    } else if (Init->isBaseInitializer()) {
3699      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3700      if (CheckRedundantInit(*this, Init, Members[Key]))
3701        HadError = true;
3702    } else {
3703      assert(Init->isDelegatingInitializer());
3704      // This must be the only initializer
3705      if (MemInits.size() != 1) {
3706        Diag(Init->getSourceLocation(),
3707             diag::err_delegating_initializer_alone)
3708          << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3709        // We will treat this as being the only initializer.
3710      }
3711      SetDelegatingInitializer(Constructor, MemInits[i]);
3712      // Return immediately as the initializer is set.
3713      return;
3714    }
3715  }
3716
3717  if (HadError)
3718    return;
3719
3720  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
3721
3722  SetCtorInitializers(Constructor, AnyErrors, MemInits);
3723}
3724
3725void
3726Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3727                                             CXXRecordDecl *ClassDecl) {
3728  // Ignore dependent contexts. Also ignore unions, since their members never
3729  // have destructors implicitly called.
3730  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3731    return;
3732
3733  // FIXME: all the access-control diagnostics are positioned on the
3734  // field/base declaration.  That's probably good; that said, the
3735  // user might reasonably want to know why the destructor is being
3736  // emitted, and we currently don't say.
3737
3738  // Non-static data members.
3739  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3740       E = ClassDecl->field_end(); I != E; ++I) {
3741    FieldDecl *Field = *I;
3742    if (Field->isInvalidDecl())
3743      continue;
3744
3745    // Don't destroy incomplete or zero-length arrays.
3746    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3747      continue;
3748
3749    QualType FieldType = Context.getBaseElementType(Field->getType());
3750
3751    const RecordType* RT = FieldType->getAs<RecordType>();
3752    if (!RT)
3753      continue;
3754
3755    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3756    if (FieldClassDecl->isInvalidDecl())
3757      continue;
3758    if (FieldClassDecl->hasIrrelevantDestructor())
3759      continue;
3760    // The destructor for an implicit anonymous union member is never invoked.
3761    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3762      continue;
3763
3764    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3765    assert(Dtor && "No dtor found for FieldClassDecl!");
3766    CheckDestructorAccess(Field->getLocation(), Dtor,
3767                          PDiag(diag::err_access_dtor_field)
3768                            << Field->getDeclName()
3769                            << FieldType);
3770
3771    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3772    DiagnoseUseOfDecl(Dtor, Location);
3773  }
3774
3775  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3776
3777  // Bases.
3778  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3779       E = ClassDecl->bases_end(); Base != E; ++Base) {
3780    // Bases are always records in a well-formed non-dependent class.
3781    const RecordType *RT = Base->getType()->getAs<RecordType>();
3782
3783    // Remember direct virtual bases.
3784    if (Base->isVirtual())
3785      DirectVirtualBases.insert(RT);
3786
3787    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3788    // If our base class is invalid, we probably can't get its dtor anyway.
3789    if (BaseClassDecl->isInvalidDecl())
3790      continue;
3791    if (BaseClassDecl->hasIrrelevantDestructor())
3792      continue;
3793
3794    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3795    assert(Dtor && "No dtor found for BaseClassDecl!");
3796
3797    // FIXME: caret should be on the start of the class name
3798    CheckDestructorAccess(Base->getLocStart(), Dtor,
3799                          PDiag(diag::err_access_dtor_base)
3800                            << Base->getType()
3801                            << Base->getSourceRange(),
3802                          Context.getTypeDeclType(ClassDecl));
3803
3804    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3805    DiagnoseUseOfDecl(Dtor, Location);
3806  }
3807
3808  // Virtual bases.
3809  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3810       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3811
3812    // Bases are always records in a well-formed non-dependent class.
3813    const RecordType *RT = VBase->getType()->castAs<RecordType>();
3814
3815    // Ignore direct virtual bases.
3816    if (DirectVirtualBases.count(RT))
3817      continue;
3818
3819    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3820    // If our base class is invalid, we probably can't get its dtor anyway.
3821    if (BaseClassDecl->isInvalidDecl())
3822      continue;
3823    if (BaseClassDecl->hasIrrelevantDestructor())
3824      continue;
3825
3826    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3827    assert(Dtor && "No dtor found for BaseClassDecl!");
3828    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3829                          PDiag(diag::err_access_dtor_vbase)
3830                            << VBase->getType(),
3831                          Context.getTypeDeclType(ClassDecl));
3832
3833    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3834    DiagnoseUseOfDecl(Dtor, Location);
3835  }
3836}
3837
3838void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3839  if (!CDtorDecl)
3840    return;
3841
3842  if (CXXConstructorDecl *Constructor
3843      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3844    SetCtorInitializers(Constructor, /*AnyErrors=*/false);
3845}
3846
3847bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3848                                  unsigned DiagID, AbstractDiagSelID SelID) {
3849  class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3850    unsigned DiagID;
3851    AbstractDiagSelID SelID;
3852
3853  public:
3854    NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3855      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3856
3857    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3858      if (Suppressed) return;
3859      if (SelID == -1)
3860        S.Diag(Loc, DiagID) << T;
3861      else
3862        S.Diag(Loc, DiagID) << SelID << T;
3863    }
3864  } Diagnoser(DiagID, SelID);
3865
3866  return RequireNonAbstractType(Loc, T, Diagnoser);
3867}
3868
3869bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3870                                  TypeDiagnoser &Diagnoser) {
3871  if (!getLangOpts().CPlusPlus)
3872    return false;
3873
3874  if (const ArrayType *AT = Context.getAsArrayType(T))
3875    return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3876
3877  if (const PointerType *PT = T->getAs<PointerType>()) {
3878    // Find the innermost pointer type.
3879    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3880      PT = T;
3881
3882    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3883      return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3884  }
3885
3886  const RecordType *RT = T->getAs<RecordType>();
3887  if (!RT)
3888    return false;
3889
3890  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3891
3892  // We can't answer whether something is abstract until it has a
3893  // definition.  If it's currently being defined, we'll walk back
3894  // over all the declarations when we have a full definition.
3895  const CXXRecordDecl *Def = RD->getDefinition();
3896  if (!Def || Def->isBeingDefined())
3897    return false;
3898
3899  if (!RD->isAbstract())
3900    return false;
3901
3902  Diagnoser.diagnose(*this, Loc, T);
3903  DiagnoseAbstractType(RD);
3904
3905  return true;
3906}
3907
3908void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3909  // Check if we've already emitted the list of pure virtual functions
3910  // for this class.
3911  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3912    return;
3913
3914  CXXFinalOverriderMap FinalOverriders;
3915  RD->getFinalOverriders(FinalOverriders);
3916
3917  // Keep a set of seen pure methods so we won't diagnose the same method
3918  // more than once.
3919  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3920
3921  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3922                                   MEnd = FinalOverriders.end();
3923       M != MEnd;
3924       ++M) {
3925    for (OverridingMethods::iterator SO = M->second.begin(),
3926                                  SOEnd = M->second.end();
3927         SO != SOEnd; ++SO) {
3928      // C++ [class.abstract]p4:
3929      //   A class is abstract if it contains or inherits at least one
3930      //   pure virtual function for which the final overrider is pure
3931      //   virtual.
3932
3933      //
3934      if (SO->second.size() != 1)
3935        continue;
3936
3937      if (!SO->second.front().Method->isPure())
3938        continue;
3939
3940      if (!SeenPureMethods.insert(SO->second.front().Method))
3941        continue;
3942
3943      Diag(SO->second.front().Method->getLocation(),
3944           diag::note_pure_virtual_function)
3945        << SO->second.front().Method->getDeclName() << RD->getDeclName();
3946    }
3947  }
3948
3949  if (!PureVirtualClassDiagSet)
3950    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3951  PureVirtualClassDiagSet->insert(RD);
3952}
3953
3954namespace {
3955struct AbstractUsageInfo {
3956  Sema &S;
3957  CXXRecordDecl *Record;
3958  CanQualType AbstractType;
3959  bool Invalid;
3960
3961  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3962    : S(S), Record(Record),
3963      AbstractType(S.Context.getCanonicalType(
3964                   S.Context.getTypeDeclType(Record))),
3965      Invalid(false) {}
3966
3967  void DiagnoseAbstractType() {
3968    if (Invalid) return;
3969    S.DiagnoseAbstractType(Record);
3970    Invalid = true;
3971  }
3972
3973  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3974};
3975
3976struct CheckAbstractUsage {
3977  AbstractUsageInfo &Info;
3978  const NamedDecl *Ctx;
3979
3980  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3981    : Info(Info), Ctx(Ctx) {}
3982
3983  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3984    switch (TL.getTypeLocClass()) {
3985#define ABSTRACT_TYPELOC(CLASS, PARENT)
3986#define TYPELOC(CLASS, PARENT) \
3987    case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
3988#include "clang/AST/TypeLocNodes.def"
3989    }
3990  }
3991
3992  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3993    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3994    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3995      if (!TL.getArg(I))
3996        continue;
3997
3998      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3999      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4000    }
4001  }
4002
4003  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4004    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4005  }
4006
4007  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4008    // Visit the type parameters from a permissive context.
4009    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4010      TemplateArgumentLoc TAL = TL.getArgLoc(I);
4011      if (TAL.getArgument().getKind() == TemplateArgument::Type)
4012        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4013          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4014      // TODO: other template argument types?
4015    }
4016  }
4017
4018  // Visit pointee types from a permissive context.
4019#define CheckPolymorphic(Type) \
4020  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4021    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4022  }
4023  CheckPolymorphic(PointerTypeLoc)
4024  CheckPolymorphic(ReferenceTypeLoc)
4025  CheckPolymorphic(MemberPointerTypeLoc)
4026  CheckPolymorphic(BlockPointerTypeLoc)
4027  CheckPolymorphic(AtomicTypeLoc)
4028
4029  /// Handle all the types we haven't given a more specific
4030  /// implementation for above.
4031  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4032    // Every other kind of type that we haven't called out already
4033    // that has an inner type is either (1) sugar or (2) contains that
4034    // inner type in some way as a subobject.
4035    if (TypeLoc Next = TL.getNextTypeLoc())
4036      return Visit(Next, Sel);
4037
4038    // If there's no inner type and we're in a permissive context,
4039    // don't diagnose.
4040    if (Sel == Sema::AbstractNone) return;
4041
4042    // Check whether the type matches the abstract type.
4043    QualType T = TL.getType();
4044    if (T->isArrayType()) {
4045      Sel = Sema::AbstractArrayType;
4046      T = Info.S.Context.getBaseElementType(T);
4047    }
4048    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4049    if (CT != Info.AbstractType) return;
4050
4051    // It matched; do some magic.
4052    if (Sel == Sema::AbstractArrayType) {
4053      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4054        << T << TL.getSourceRange();
4055    } else {
4056      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4057        << Sel << T << TL.getSourceRange();
4058    }
4059    Info.DiagnoseAbstractType();
4060  }
4061};
4062
4063void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4064                                  Sema::AbstractDiagSelID Sel) {
4065  CheckAbstractUsage(*this, D).Visit(TL, Sel);
4066}
4067
4068}
4069
4070/// Check for invalid uses of an abstract type in a method declaration.
4071static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4072                                    CXXMethodDecl *MD) {
4073  // No need to do the check on definitions, which require that
4074  // the return/param types be complete.
4075  if (MD->doesThisDeclarationHaveABody())
4076    return;
4077
4078  // For safety's sake, just ignore it if we don't have type source
4079  // information.  This should never happen for non-implicit methods,
4080  // but...
4081  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4082    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4083}
4084
4085/// Check for invalid uses of an abstract type within a class definition.
4086static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4087                                    CXXRecordDecl *RD) {
4088  for (CXXRecordDecl::decl_iterator
4089         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4090    Decl *D = *I;
4091    if (D->isImplicit()) continue;
4092
4093    // Methods and method templates.
4094    if (isa<CXXMethodDecl>(D)) {
4095      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4096    } else if (isa<FunctionTemplateDecl>(D)) {
4097      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4098      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4099
4100    // Fields and static variables.
4101    } else if (isa<FieldDecl>(D)) {
4102      FieldDecl *FD = cast<FieldDecl>(D);
4103      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4104        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4105    } else if (isa<VarDecl>(D)) {
4106      VarDecl *VD = cast<VarDecl>(D);
4107      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4108        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4109
4110    // Nested classes and class templates.
4111    } else if (isa<CXXRecordDecl>(D)) {
4112      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4113    } else if (isa<ClassTemplateDecl>(D)) {
4114      CheckAbstractClassUsage(Info,
4115                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4116    }
4117  }
4118}
4119
4120/// \brief Perform semantic checks on a class definition that has been
4121/// completing, introducing implicitly-declared members, checking for
4122/// abstract types, etc.
4123void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4124  if (!Record)
4125    return;
4126
4127  if (Record->isAbstract() && !Record->isInvalidDecl()) {
4128    AbstractUsageInfo Info(*this, Record);
4129    CheckAbstractClassUsage(Info, Record);
4130  }
4131
4132  // If this is not an aggregate type and has no user-declared constructor,
4133  // complain about any non-static data members of reference or const scalar
4134  // type, since they will never get initializers.
4135  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4136      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4137      !Record->isLambda()) {
4138    bool Complained = false;
4139    for (RecordDecl::field_iterator F = Record->field_begin(),
4140                                 FEnd = Record->field_end();
4141         F != FEnd; ++F) {
4142      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4143        continue;
4144
4145      if (F->getType()->isReferenceType() ||
4146          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4147        if (!Complained) {
4148          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4149            << Record->getTagKind() << Record;
4150          Complained = true;
4151        }
4152
4153        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4154          << F->getType()->isReferenceType()
4155          << F->getDeclName();
4156      }
4157    }
4158  }
4159
4160  if (Record->isDynamicClass() && !Record->isDependentType())
4161    DynamicClasses.push_back(Record);
4162
4163  if (Record->getIdentifier()) {
4164    // C++ [class.mem]p13:
4165    //   If T is the name of a class, then each of the following shall have a
4166    //   name different from T:
4167    //     - every member of every anonymous union that is a member of class T.
4168    //
4169    // C++ [class.mem]p14:
4170    //   In addition, if class T has a user-declared constructor (12.1), every
4171    //   non-static data member of class T shall have a name different from T.
4172    DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4173    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4174         ++I) {
4175      NamedDecl *D = *I;
4176      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4177          isa<IndirectFieldDecl>(D)) {
4178        Diag(D->getLocation(), diag::err_member_name_of_class)
4179          << D->getDeclName();
4180        break;
4181      }
4182    }
4183  }
4184
4185  // Warn if the class has virtual methods but non-virtual public destructor.
4186  if (Record->isPolymorphic() && !Record->isDependentType()) {
4187    CXXDestructorDecl *dtor = Record->getDestructor();
4188    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
4189      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4190           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4191  }
4192
4193  if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4194    Diag(Record->getLocation(), diag::warn_abstract_final_class);
4195    DiagnoseAbstractType(Record);
4196  }
4197
4198  if (!Record->isDependentType()) {
4199    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4200                                     MEnd = Record->method_end();
4201         M != MEnd; ++M) {
4202      // See if a method overloads virtual methods in a base
4203      // class without overriding any.
4204      if (!M->isStatic())
4205        DiagnoseHiddenVirtualMethods(Record, *M);
4206
4207      // Check whether the explicitly-defaulted special members are valid.
4208      if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4209        CheckExplicitlyDefaultedSpecialMember(*M);
4210
4211      // For an explicitly defaulted or deleted special member, we defer
4212      // determining triviality until the class is complete. That time is now!
4213      if (!M->isImplicit() && !M->isUserProvided()) {
4214        CXXSpecialMember CSM = getSpecialMember(*M);
4215        if (CSM != CXXInvalid) {
4216          M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4217
4218          // Inform the class that we've finished declaring this member.
4219          Record->finishedDefaultedOrDeletedMember(*M);
4220        }
4221      }
4222    }
4223  }
4224
4225  // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4226  // function that is not a constructor declares that member function to be
4227  // const. [...] The class of which that function is a member shall be
4228  // a literal type.
4229  //
4230  // If the class has virtual bases, any constexpr members will already have
4231  // been diagnosed by the checks performed on the member declaration, so
4232  // suppress this (less useful) diagnostic.
4233  //
4234  // We delay this until we know whether an explicitly-defaulted (or deleted)
4235  // destructor for the class is trivial.
4236  if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4237      !Record->isLiteral() && !Record->getNumVBases()) {
4238    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4239                                     MEnd = Record->method_end();
4240         M != MEnd; ++M) {
4241      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4242        switch (Record->getTemplateSpecializationKind()) {
4243        case TSK_ImplicitInstantiation:
4244        case TSK_ExplicitInstantiationDeclaration:
4245        case TSK_ExplicitInstantiationDefinition:
4246          // If a template instantiates to a non-literal type, but its members
4247          // instantiate to constexpr functions, the template is technically
4248          // ill-formed, but we allow it for sanity.
4249          continue;
4250
4251        case TSK_Undeclared:
4252        case TSK_ExplicitSpecialization:
4253          RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4254                             diag::err_constexpr_method_non_literal);
4255          break;
4256        }
4257
4258        // Only produce one error per class.
4259        break;
4260      }
4261    }
4262  }
4263
4264  // Declare inheriting constructors. We do this eagerly here because:
4265  // - The standard requires an eager diagnostic for conflicting inheriting
4266  //   constructors from different classes.
4267  // - The lazy declaration of the other implicit constructors is so as to not
4268  //   waste space and performance on classes that are not meant to be
4269  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4270  //   have inheriting constructors.
4271  DeclareInheritingConstructors(Record);
4272}
4273
4274/// Is the special member function which would be selected to perform the
4275/// specified operation on the specified class type a constexpr constructor?
4276static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4277                                     Sema::CXXSpecialMember CSM,
4278                                     bool ConstArg) {
4279  Sema::SpecialMemberOverloadResult *SMOR =
4280      S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4281                            false, false, false, false);
4282  if (!SMOR || !SMOR->getMethod())
4283    // A constructor we wouldn't select can't be "involved in initializing"
4284    // anything.
4285    return true;
4286  return SMOR->getMethod()->isConstexpr();
4287}
4288
4289/// Determine whether the specified special member function would be constexpr
4290/// if it were implicitly defined.
4291static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4292                                              Sema::CXXSpecialMember CSM,
4293                                              bool ConstArg) {
4294  if (!S.getLangOpts().CPlusPlus11)
4295    return false;
4296
4297  // C++11 [dcl.constexpr]p4:
4298  // In the definition of a constexpr constructor [...]
4299  switch (CSM) {
4300  case Sema::CXXDefaultConstructor:
4301    // Since default constructor lookup is essentially trivial (and cannot
4302    // involve, for instance, template instantiation), we compute whether a
4303    // defaulted default constructor is constexpr directly within CXXRecordDecl.
4304    //
4305    // This is important for performance; we need to know whether the default
4306    // constructor is constexpr to determine whether the type is a literal type.
4307    return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4308
4309  case Sema::CXXCopyConstructor:
4310  case Sema::CXXMoveConstructor:
4311    // For copy or move constructors, we need to perform overload resolution.
4312    break;
4313
4314  case Sema::CXXCopyAssignment:
4315  case Sema::CXXMoveAssignment:
4316  case Sema::CXXDestructor:
4317  case Sema::CXXInvalid:
4318    return false;
4319  }
4320
4321  //   -- if the class is a non-empty union, or for each non-empty anonymous
4322  //      union member of a non-union class, exactly one non-static data member
4323  //      shall be initialized; [DR1359]
4324  //
4325  // If we squint, this is guaranteed, since exactly one non-static data member
4326  // will be initialized (if the constructor isn't deleted), we just don't know
4327  // which one.
4328  if (ClassDecl->isUnion())
4329    return true;
4330
4331  //   -- the class shall not have any virtual base classes;
4332  if (ClassDecl->getNumVBases())
4333    return false;
4334
4335  //   -- every constructor involved in initializing [...] base class
4336  //      sub-objects shall be a constexpr constructor;
4337  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4338                                       BEnd = ClassDecl->bases_end();
4339       B != BEnd; ++B) {
4340    const RecordType *BaseType = B->getType()->getAs<RecordType>();
4341    if (!BaseType) continue;
4342
4343    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4344    if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4345      return false;
4346  }
4347
4348  //   -- every constructor involved in initializing non-static data members
4349  //      [...] shall be a constexpr constructor;
4350  //   -- every non-static data member and base class sub-object shall be
4351  //      initialized
4352  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4353                               FEnd = ClassDecl->field_end();
4354       F != FEnd; ++F) {
4355    if (F->isInvalidDecl())
4356      continue;
4357    if (const RecordType *RecordTy =
4358            S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4359      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4360      if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4361        return false;
4362    }
4363  }
4364
4365  // All OK, it's constexpr!
4366  return true;
4367}
4368
4369static Sema::ImplicitExceptionSpecification
4370computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4371  switch (S.getSpecialMember(MD)) {
4372  case Sema::CXXDefaultConstructor:
4373    return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4374  case Sema::CXXCopyConstructor:
4375    return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4376  case Sema::CXXCopyAssignment:
4377    return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4378  case Sema::CXXMoveConstructor:
4379    return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4380  case Sema::CXXMoveAssignment:
4381    return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4382  case Sema::CXXDestructor:
4383    return S.ComputeDefaultedDtorExceptionSpec(MD);
4384  case Sema::CXXInvalid:
4385    break;
4386  }
4387  assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4388         "only special members have implicit exception specs");
4389  return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4390}
4391
4392static void
4393updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4394                    const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4395  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4396  ExceptSpec.getEPI(EPI);
4397  FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4398                                        FPT->getArgTypes(), EPI));
4399}
4400
4401void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4402  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4403  if (FPT->getExceptionSpecType() != EST_Unevaluated)
4404    return;
4405
4406  // Evaluate the exception specification.
4407  ImplicitExceptionSpecification ExceptSpec =
4408      computeImplicitExceptionSpec(*this, Loc, MD);
4409
4410  // Update the type of the special member to use it.
4411  updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4412
4413  // A user-provided destructor can be defined outside the class. When that
4414  // happens, be sure to update the exception specification on both
4415  // declarations.
4416  const FunctionProtoType *CanonicalFPT =
4417    MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4418  if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4419    updateExceptionSpec(*this, MD->getCanonicalDecl(),
4420                        CanonicalFPT, ExceptSpec);
4421}
4422
4423void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4424  CXXRecordDecl *RD = MD->getParent();
4425  CXXSpecialMember CSM = getSpecialMember(MD);
4426
4427  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4428         "not an explicitly-defaulted special member");
4429
4430  // Whether this was the first-declared instance of the constructor.
4431  // This affects whether we implicitly add an exception spec and constexpr.
4432  bool First = MD == MD->getCanonicalDecl();
4433
4434  bool HadError = false;
4435
4436  // C++11 [dcl.fct.def.default]p1:
4437  //   A function that is explicitly defaulted shall
4438  //     -- be a special member function (checked elsewhere),
4439  //     -- have the same type (except for ref-qualifiers, and except that a
4440  //        copy operation can take a non-const reference) as an implicit
4441  //        declaration, and
4442  //     -- not have default arguments.
4443  unsigned ExpectedParams = 1;
4444  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4445    ExpectedParams = 0;
4446  if (MD->getNumParams() != ExpectedParams) {
4447    // This also checks for default arguments: a copy or move constructor with a
4448    // default argument is classified as a default constructor, and assignment
4449    // operations and destructors can't have default arguments.
4450    Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4451      << CSM << MD->getSourceRange();
4452    HadError = true;
4453  } else if (MD->isVariadic()) {
4454    Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4455      << CSM << MD->getSourceRange();
4456    HadError = true;
4457  }
4458
4459  const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4460
4461  bool CanHaveConstParam = false;
4462  if (CSM == CXXCopyConstructor)
4463    CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4464  else if (CSM == CXXCopyAssignment)
4465    CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4466
4467  QualType ReturnType = Context.VoidTy;
4468  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4469    // Check for return type matching.
4470    ReturnType = Type->getResultType();
4471    QualType ExpectedReturnType =
4472        Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4473    if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4474      Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4475        << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4476      HadError = true;
4477    }
4478
4479    // A defaulted special member cannot have cv-qualifiers.
4480    if (Type->getTypeQuals()) {
4481      Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4482        << (CSM == CXXMoveAssignment);
4483      HadError = true;
4484    }
4485  }
4486
4487  // Check for parameter type matching.
4488  QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4489  bool HasConstParam = false;
4490  if (ExpectedParams && ArgType->isReferenceType()) {
4491    // Argument must be reference to possibly-const T.
4492    QualType ReferentType = ArgType->getPointeeType();
4493    HasConstParam = ReferentType.isConstQualified();
4494
4495    if (ReferentType.isVolatileQualified()) {
4496      Diag(MD->getLocation(),
4497           diag::err_defaulted_special_member_volatile_param) << CSM;
4498      HadError = true;
4499    }
4500
4501    if (HasConstParam && !CanHaveConstParam) {
4502      if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4503        Diag(MD->getLocation(),
4504             diag::err_defaulted_special_member_copy_const_param)
4505          << (CSM == CXXCopyAssignment);
4506        // FIXME: Explain why this special member can't be const.
4507      } else {
4508        Diag(MD->getLocation(),
4509             diag::err_defaulted_special_member_move_const_param)
4510          << (CSM == CXXMoveAssignment);
4511      }
4512      HadError = true;
4513    }
4514  } else if (ExpectedParams) {
4515    // A copy assignment operator can take its argument by value, but a
4516    // defaulted one cannot.
4517    assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4518    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4519    HadError = true;
4520  }
4521
4522  // C++11 [dcl.fct.def.default]p2:
4523  //   An explicitly-defaulted function may be declared constexpr only if it
4524  //   would have been implicitly declared as constexpr,
4525  // Do not apply this rule to members of class templates, since core issue 1358
4526  // makes such functions always instantiate to constexpr functions. For
4527  // non-constructors, this is checked elsewhere.
4528  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4529                                                     HasConstParam);
4530  if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4531      MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4532    Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4533    // FIXME: Explain why the constructor can't be constexpr.
4534    HadError = true;
4535  }
4536
4537  //   and may have an explicit exception-specification only if it is compatible
4538  //   with the exception-specification on the implicit declaration.
4539  if (Type->hasExceptionSpec()) {
4540    // Delay the check if this is the first declaration of the special member,
4541    // since we may not have parsed some necessary in-class initializers yet.
4542    if (First) {
4543      // If the exception specification needs to be instantiated, do so now,
4544      // before we clobber it with an EST_Unevaluated specification below.
4545      if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4546        InstantiateExceptionSpec(MD->getLocStart(), MD);
4547        Type = MD->getType()->getAs<FunctionProtoType>();
4548      }
4549      DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4550    } else
4551      CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4552  }
4553
4554  //   If a function is explicitly defaulted on its first declaration,
4555  if (First) {
4556    //  -- it is implicitly considered to be constexpr if the implicit
4557    //     definition would be,
4558    MD->setConstexpr(Constexpr);
4559
4560    //  -- it is implicitly considered to have the same exception-specification
4561    //     as if it had been implicitly declared,
4562    FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4563    EPI.ExceptionSpecType = EST_Unevaluated;
4564    EPI.ExceptionSpecDecl = MD;
4565    MD->setType(Context.getFunctionType(ReturnType,
4566                                        ArrayRef<QualType>(&ArgType,
4567                                                           ExpectedParams),
4568                                        EPI));
4569  }
4570
4571  if (ShouldDeleteSpecialMember(MD, CSM)) {
4572    if (First) {
4573      SetDeclDeleted(MD, MD->getLocation());
4574    } else {
4575      // C++11 [dcl.fct.def.default]p4:
4576      //   [For a] user-provided explicitly-defaulted function [...] if such a
4577      //   function is implicitly defined as deleted, the program is ill-formed.
4578      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4579      HadError = true;
4580    }
4581  }
4582
4583  if (HadError)
4584    MD->setInvalidDecl();
4585}
4586
4587/// Check whether the exception specification provided for an
4588/// explicitly-defaulted special member matches the exception specification
4589/// that would have been generated for an implicit special member, per
4590/// C++11 [dcl.fct.def.default]p2.
4591void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4592    CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4593  // Compute the implicit exception specification.
4594  FunctionProtoType::ExtProtoInfo EPI;
4595  computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4596  const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4597    Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI));
4598
4599  // Ensure that it matches.
4600  CheckEquivalentExceptionSpec(
4601    PDiag(diag::err_incorrect_defaulted_exception_spec)
4602      << getSpecialMember(MD), PDiag(),
4603    ImplicitType, SourceLocation(),
4604    SpecifiedType, MD->getLocation());
4605}
4606
4607void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4608  for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4609       I != N; ++I)
4610    CheckExplicitlyDefaultedMemberExceptionSpec(
4611      DelayedDefaultedMemberExceptionSpecs[I].first,
4612      DelayedDefaultedMemberExceptionSpecs[I].second);
4613
4614  DelayedDefaultedMemberExceptionSpecs.clear();
4615}
4616
4617namespace {
4618struct SpecialMemberDeletionInfo {
4619  Sema &S;
4620  CXXMethodDecl *MD;
4621  Sema::CXXSpecialMember CSM;
4622  bool Diagnose;
4623
4624  // Properties of the special member, computed for convenience.
4625  bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4626  SourceLocation Loc;
4627
4628  bool AllFieldsAreConst;
4629
4630  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4631                            Sema::CXXSpecialMember CSM, bool Diagnose)
4632    : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4633      IsConstructor(false), IsAssignment(false), IsMove(false),
4634      ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4635      AllFieldsAreConst(true) {
4636    switch (CSM) {
4637      case Sema::CXXDefaultConstructor:
4638      case Sema::CXXCopyConstructor:
4639        IsConstructor = true;
4640        break;
4641      case Sema::CXXMoveConstructor:
4642        IsConstructor = true;
4643        IsMove = true;
4644        break;
4645      case Sema::CXXCopyAssignment:
4646        IsAssignment = true;
4647        break;
4648      case Sema::CXXMoveAssignment:
4649        IsAssignment = true;
4650        IsMove = true;
4651        break;
4652      case Sema::CXXDestructor:
4653        break;
4654      case Sema::CXXInvalid:
4655        llvm_unreachable("invalid special member kind");
4656    }
4657
4658    if (MD->getNumParams()) {
4659      ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4660      VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4661    }
4662  }
4663
4664  bool inUnion() const { return MD->getParent()->isUnion(); }
4665
4666  /// Look up the corresponding special member in the given class.
4667  Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4668                                              unsigned Quals) {
4669    unsigned TQ = MD->getTypeQualifiers();
4670    // cv-qualifiers on class members don't affect default ctor / dtor calls.
4671    if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4672      Quals = 0;
4673    return S.LookupSpecialMember(Class, CSM,
4674                                 ConstArg || (Quals & Qualifiers::Const),
4675                                 VolatileArg || (Quals & Qualifiers::Volatile),
4676                                 MD->getRefQualifier() == RQ_RValue,
4677                                 TQ & Qualifiers::Const,
4678                                 TQ & Qualifiers::Volatile);
4679  }
4680
4681  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4682
4683  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4684  bool shouldDeleteForField(FieldDecl *FD);
4685  bool shouldDeleteForAllConstMembers();
4686
4687  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4688                                     unsigned Quals);
4689  bool shouldDeleteForSubobjectCall(Subobject Subobj,
4690                                    Sema::SpecialMemberOverloadResult *SMOR,
4691                                    bool IsDtorCallInCtor);
4692
4693  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4694};
4695}
4696
4697/// Is the given special member inaccessible when used on the given
4698/// sub-object.
4699bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4700                                             CXXMethodDecl *target) {
4701  /// If we're operating on a base class, the object type is the
4702  /// type of this special member.
4703  QualType objectTy;
4704  AccessSpecifier access = target->getAccess();
4705  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4706    objectTy = S.Context.getTypeDeclType(MD->getParent());
4707    access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4708
4709  // If we're operating on a field, the object type is the type of the field.
4710  } else {
4711    objectTy = S.Context.getTypeDeclType(target->getParent());
4712  }
4713
4714  return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4715}
4716
4717/// Check whether we should delete a special member due to the implicit
4718/// definition containing a call to a special member of a subobject.
4719bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4720    Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4721    bool IsDtorCallInCtor) {
4722  CXXMethodDecl *Decl = SMOR->getMethod();
4723  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4724
4725  int DiagKind = -1;
4726
4727  if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4728    DiagKind = !Decl ? 0 : 1;
4729  else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4730    DiagKind = 2;
4731  else if (!isAccessible(Subobj, Decl))
4732    DiagKind = 3;
4733  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4734           !Decl->isTrivial()) {
4735    // A member of a union must have a trivial corresponding special member.
4736    // As a weird special case, a destructor call from a union's constructor
4737    // must be accessible and non-deleted, but need not be trivial. Such a
4738    // destructor is never actually called, but is semantically checked as
4739    // if it were.
4740    DiagKind = 4;
4741  }
4742
4743  if (DiagKind == -1)
4744    return false;
4745
4746  if (Diagnose) {
4747    if (Field) {
4748      S.Diag(Field->getLocation(),
4749             diag::note_deleted_special_member_class_subobject)
4750        << CSM << MD->getParent() << /*IsField*/true
4751        << Field << DiagKind << IsDtorCallInCtor;
4752    } else {
4753      CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4754      S.Diag(Base->getLocStart(),
4755             diag::note_deleted_special_member_class_subobject)
4756        << CSM << MD->getParent() << /*IsField*/false
4757        << Base->getType() << DiagKind << IsDtorCallInCtor;
4758    }
4759
4760    if (DiagKind == 1)
4761      S.NoteDeletedFunction(Decl);
4762    // FIXME: Explain inaccessibility if DiagKind == 3.
4763  }
4764
4765  return true;
4766}
4767
4768/// Check whether we should delete a special member function due to having a
4769/// direct or virtual base class or non-static data member of class type M.
4770bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4771    CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
4772  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4773
4774  // C++11 [class.ctor]p5:
4775  // -- any direct or virtual base class, or non-static data member with no
4776  //    brace-or-equal-initializer, has class type M (or array thereof) and
4777  //    either M has no default constructor or overload resolution as applied
4778  //    to M's default constructor results in an ambiguity or in a function
4779  //    that is deleted or inaccessible
4780  // C++11 [class.copy]p11, C++11 [class.copy]p23:
4781  // -- a direct or virtual base class B that cannot be copied/moved because
4782  //    overload resolution, as applied to B's corresponding special member,
4783  //    results in an ambiguity or a function that is deleted or inaccessible
4784  //    from the defaulted special member
4785  // C++11 [class.dtor]p5:
4786  // -- any direct or virtual base class [...] has a type with a destructor
4787  //    that is deleted or inaccessible
4788  if (!(CSM == Sema::CXXDefaultConstructor &&
4789        Field && Field->hasInClassInitializer()) &&
4790      shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
4791    return true;
4792
4793  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4794  // -- any direct or virtual base class or non-static data member has a
4795  //    type with a destructor that is deleted or inaccessible
4796  if (IsConstructor) {
4797    Sema::SpecialMemberOverloadResult *SMOR =
4798        S.LookupSpecialMember(Class, Sema::CXXDestructor,
4799                              false, false, false, false, false);
4800    if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4801      return true;
4802  }
4803
4804  return false;
4805}
4806
4807/// Check whether we should delete a special member function due to the class
4808/// having a particular direct or virtual base class.
4809bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4810  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4811  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
4812}
4813
4814/// Check whether we should delete a special member function due to the class
4815/// having a particular non-static data member.
4816bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4817  QualType FieldType = S.Context.getBaseElementType(FD->getType());
4818  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4819
4820  if (CSM == Sema::CXXDefaultConstructor) {
4821    // For a default constructor, all references must be initialized in-class
4822    // and, if a union, it must have a non-const member.
4823    if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4824      if (Diagnose)
4825        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4826          << MD->getParent() << FD << FieldType << /*Reference*/0;
4827      return true;
4828    }
4829    // C++11 [class.ctor]p5: any non-variant non-static data member of
4830    // const-qualified type (or array thereof) with no
4831    // brace-or-equal-initializer does not have a user-provided default
4832    // constructor.
4833    if (!inUnion() && FieldType.isConstQualified() &&
4834        !FD->hasInClassInitializer() &&
4835        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4836      if (Diagnose)
4837        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4838          << MD->getParent() << FD << FD->getType() << /*Const*/1;
4839      return true;
4840    }
4841
4842    if (inUnion() && !FieldType.isConstQualified())
4843      AllFieldsAreConst = false;
4844  } else if (CSM == Sema::CXXCopyConstructor) {
4845    // For a copy constructor, data members must not be of rvalue reference
4846    // type.
4847    if (FieldType->isRValueReferenceType()) {
4848      if (Diagnose)
4849        S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4850          << MD->getParent() << FD << FieldType;
4851      return true;
4852    }
4853  } else if (IsAssignment) {
4854    // For an assignment operator, data members must not be of reference type.
4855    if (FieldType->isReferenceType()) {
4856      if (Diagnose)
4857        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4858          << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4859      return true;
4860    }
4861    if (!FieldRecord && FieldType.isConstQualified()) {
4862      // C++11 [class.copy]p23:
4863      // -- a non-static data member of const non-class type (or array thereof)
4864      if (Diagnose)
4865        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4866          << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
4867      return true;
4868    }
4869  }
4870
4871  if (FieldRecord) {
4872    // Some additional restrictions exist on the variant members.
4873    if (!inUnion() && FieldRecord->isUnion() &&
4874        FieldRecord->isAnonymousStructOrUnion()) {
4875      bool AllVariantFieldsAreConst = true;
4876
4877      // FIXME: Handle anonymous unions declared within anonymous unions.
4878      for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4879                                         UE = FieldRecord->field_end();
4880           UI != UE; ++UI) {
4881        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4882
4883        if (!UnionFieldType.isConstQualified())
4884          AllVariantFieldsAreConst = false;
4885
4886        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4887        if (UnionFieldRecord &&
4888            shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4889                                          UnionFieldType.getCVRQualifiers()))
4890          return true;
4891      }
4892
4893      // At least one member in each anonymous union must be non-const
4894      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4895          FieldRecord->field_begin() != FieldRecord->field_end()) {
4896        if (Diagnose)
4897          S.Diag(FieldRecord->getLocation(),
4898                 diag::note_deleted_default_ctor_all_const)
4899            << MD->getParent() << /*anonymous union*/1;
4900        return true;
4901      }
4902
4903      // Don't check the implicit member of the anonymous union type.
4904      // This is technically non-conformant, but sanity demands it.
4905      return false;
4906    }
4907
4908    if (shouldDeleteForClassSubobject(FieldRecord, FD,
4909                                      FieldType.getCVRQualifiers()))
4910      return true;
4911  }
4912
4913  return false;
4914}
4915
4916/// C++11 [class.ctor] p5:
4917///   A defaulted default constructor for a class X is defined as deleted if
4918/// X is a union and all of its variant members are of const-qualified type.
4919bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4920  // This is a silly definition, because it gives an empty union a deleted
4921  // default constructor. Don't do that.
4922  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4923      (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4924    if (Diagnose)
4925      S.Diag(MD->getParent()->getLocation(),
4926             diag::note_deleted_default_ctor_all_const)
4927        << MD->getParent() << /*not anonymous union*/0;
4928    return true;
4929  }
4930  return false;
4931}
4932
4933/// Determine whether a defaulted special member function should be defined as
4934/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4935/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
4936bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4937                                     bool Diagnose) {
4938  if (MD->isInvalidDecl())
4939    return false;
4940  CXXRecordDecl *RD = MD->getParent();
4941  assert(!RD->isDependentType() && "do deletion after instantiation");
4942  if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
4943    return false;
4944
4945  // C++11 [expr.lambda.prim]p19:
4946  //   The closure type associated with a lambda-expression has a
4947  //   deleted (8.4.3) default constructor and a deleted copy
4948  //   assignment operator.
4949  if (RD->isLambda() &&
4950      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4951    if (Diagnose)
4952      Diag(RD->getLocation(), diag::note_lambda_decl);
4953    return true;
4954  }
4955
4956  // For an anonymous struct or union, the copy and assignment special members
4957  // will never be used, so skip the check. For an anonymous union declared at
4958  // namespace scope, the constructor and destructor are used.
4959  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4960      RD->isAnonymousStructOrUnion())
4961    return false;
4962
4963  // C++11 [class.copy]p7, p18:
4964  //   If the class definition declares a move constructor or move assignment
4965  //   operator, an implicitly declared copy constructor or copy assignment
4966  //   operator is defined as deleted.
4967  if (MD->isImplicit() &&
4968      (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4969    CXXMethodDecl *UserDeclaredMove = 0;
4970
4971    // In Microsoft mode, a user-declared move only causes the deletion of the
4972    // corresponding copy operation, not both copy operations.
4973    if (RD->hasUserDeclaredMoveConstructor() &&
4974        (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4975      if (!Diagnose) return true;
4976
4977      // Find any user-declared move constructor.
4978      for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4979                                        E = RD->ctor_end(); I != E; ++I) {
4980        if (I->isMoveConstructor()) {
4981          UserDeclaredMove = *I;
4982          break;
4983        }
4984      }
4985      assert(UserDeclaredMove);
4986    } else if (RD->hasUserDeclaredMoveAssignment() &&
4987               (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4988      if (!Diagnose) return true;
4989
4990      // Find any user-declared move assignment operator.
4991      for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4992                                          E = RD->method_end(); I != E; ++I) {
4993        if (I->isMoveAssignmentOperator()) {
4994          UserDeclaredMove = *I;
4995          break;
4996        }
4997      }
4998      assert(UserDeclaredMove);
4999    }
5000
5001    if (UserDeclaredMove) {
5002      Diag(UserDeclaredMove->getLocation(),
5003           diag::note_deleted_copy_user_declared_move)
5004        << (CSM == CXXCopyAssignment) << RD
5005        << UserDeclaredMove->isMoveAssignmentOperator();
5006      return true;
5007    }
5008  }
5009
5010  // Do access control from the special member function
5011  ContextRAII MethodContext(*this, MD);
5012
5013  // C++11 [class.dtor]p5:
5014  // -- for a virtual destructor, lookup of the non-array deallocation function
5015  //    results in an ambiguity or in a function that is deleted or inaccessible
5016  if (CSM == CXXDestructor && MD->isVirtual()) {
5017    FunctionDecl *OperatorDelete = 0;
5018    DeclarationName Name =
5019      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5020    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5021                                 OperatorDelete, false)) {
5022      if (Diagnose)
5023        Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5024      return true;
5025    }
5026  }
5027
5028  SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5029
5030  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5031                                          BE = RD->bases_end(); BI != BE; ++BI)
5032    if (!BI->isVirtual() &&
5033        SMI.shouldDeleteForBase(BI))
5034      return true;
5035
5036  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5037                                          BE = RD->vbases_end(); BI != BE; ++BI)
5038    if (SMI.shouldDeleteForBase(BI))
5039      return true;
5040
5041  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5042                                     FE = RD->field_end(); FI != FE; ++FI)
5043    if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5044        SMI.shouldDeleteForField(*FI))
5045      return true;
5046
5047  if (SMI.shouldDeleteForAllConstMembers())
5048    return true;
5049
5050  return false;
5051}
5052
5053/// Perform lookup for a special member of the specified kind, and determine
5054/// whether it is trivial. If the triviality can be determined without the
5055/// lookup, skip it. This is intended for use when determining whether a
5056/// special member of a containing object is trivial, and thus does not ever
5057/// perform overload resolution for default constructors.
5058///
5059/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5060/// member that was most likely to be intended to be trivial, if any.
5061static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5062                                     Sema::CXXSpecialMember CSM, unsigned Quals,
5063                                     CXXMethodDecl **Selected) {
5064  if (Selected)
5065    *Selected = 0;
5066
5067  switch (CSM) {
5068  case Sema::CXXInvalid:
5069    llvm_unreachable("not a special member");
5070
5071  case Sema::CXXDefaultConstructor:
5072    // C++11 [class.ctor]p5:
5073    //   A default constructor is trivial if:
5074    //    - all the [direct subobjects] have trivial default constructors
5075    //
5076    // Note, no overload resolution is performed in this case.
5077    if (RD->hasTrivialDefaultConstructor())
5078      return true;
5079
5080    if (Selected) {
5081      // If there's a default constructor which could have been trivial, dig it
5082      // out. Otherwise, if there's any user-provided default constructor, point
5083      // to that as an example of why there's not a trivial one.
5084      CXXConstructorDecl *DefCtor = 0;
5085      if (RD->needsImplicitDefaultConstructor())
5086        S.DeclareImplicitDefaultConstructor(RD);
5087      for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5088                                        CE = RD->ctor_end(); CI != CE; ++CI) {
5089        if (!CI->isDefaultConstructor())
5090          continue;
5091        DefCtor = *CI;
5092        if (!DefCtor->isUserProvided())
5093          break;
5094      }
5095
5096      *Selected = DefCtor;
5097    }
5098
5099    return false;
5100
5101  case Sema::CXXDestructor:
5102    // C++11 [class.dtor]p5:
5103    //   A destructor is trivial if:
5104    //    - all the direct [subobjects] have trivial destructors
5105    if (RD->hasTrivialDestructor())
5106      return true;
5107
5108    if (Selected) {
5109      if (RD->needsImplicitDestructor())
5110        S.DeclareImplicitDestructor(RD);
5111      *Selected = RD->getDestructor();
5112    }
5113
5114    return false;
5115
5116  case Sema::CXXCopyConstructor:
5117    // C++11 [class.copy]p12:
5118    //   A copy constructor is trivial if:
5119    //    - the constructor selected to copy each direct [subobject] is trivial
5120    if (RD->hasTrivialCopyConstructor()) {
5121      if (Quals == Qualifiers::Const)
5122        // We must either select the trivial copy constructor or reach an
5123        // ambiguity; no need to actually perform overload resolution.
5124        return true;
5125    } else if (!Selected) {
5126      return false;
5127    }
5128    // In C++98, we are not supposed to perform overload resolution here, but we
5129    // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5130    // cases like B as having a non-trivial copy constructor:
5131    //   struct A { template<typename T> A(T&); };
5132    //   struct B { mutable A a; };
5133    goto NeedOverloadResolution;
5134
5135  case Sema::CXXCopyAssignment:
5136    // C++11 [class.copy]p25:
5137    //   A copy assignment operator is trivial if:
5138    //    - the assignment operator selected to copy each direct [subobject] is
5139    //      trivial
5140    if (RD->hasTrivialCopyAssignment()) {
5141      if (Quals == Qualifiers::Const)
5142        return true;
5143    } else if (!Selected) {
5144      return false;
5145    }
5146    // In C++98, we are not supposed to perform overload resolution here, but we
5147    // treat that as a language defect.
5148    goto NeedOverloadResolution;
5149
5150  case Sema::CXXMoveConstructor:
5151  case Sema::CXXMoveAssignment:
5152  NeedOverloadResolution:
5153    Sema::SpecialMemberOverloadResult *SMOR =
5154      S.LookupSpecialMember(RD, CSM,
5155                            Quals & Qualifiers::Const,
5156                            Quals & Qualifiers::Volatile,
5157                            /*RValueThis*/false, /*ConstThis*/false,
5158                            /*VolatileThis*/false);
5159
5160    // The standard doesn't describe how to behave if the lookup is ambiguous.
5161    // We treat it as not making the member non-trivial, just like the standard
5162    // mandates for the default constructor. This should rarely matter, because
5163    // the member will also be deleted.
5164    if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5165      return true;
5166
5167    if (!SMOR->getMethod()) {
5168      assert(SMOR->getKind() ==
5169             Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5170      return false;
5171    }
5172
5173    // We deliberately don't check if we found a deleted special member. We're
5174    // not supposed to!
5175    if (Selected)
5176      *Selected = SMOR->getMethod();
5177    return SMOR->getMethod()->isTrivial();
5178  }
5179
5180  llvm_unreachable("unknown special method kind");
5181}
5182
5183static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5184  for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5185       CI != CE; ++CI)
5186    if (!CI->isImplicit())
5187      return *CI;
5188
5189  // Look for constructor templates.
5190  typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5191  for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5192    if (CXXConstructorDecl *CD =
5193          dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5194      return CD;
5195  }
5196
5197  return 0;
5198}
5199
5200/// The kind of subobject we are checking for triviality. The values of this
5201/// enumeration are used in diagnostics.
5202enum TrivialSubobjectKind {
5203  /// The subobject is a base class.
5204  TSK_BaseClass,
5205  /// The subobject is a non-static data member.
5206  TSK_Field,
5207  /// The object is actually the complete object.
5208  TSK_CompleteObject
5209};
5210
5211/// Check whether the special member selected for a given type would be trivial.
5212static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5213                                      QualType SubType,
5214                                      Sema::CXXSpecialMember CSM,
5215                                      TrivialSubobjectKind Kind,
5216                                      bool Diagnose) {
5217  CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5218  if (!SubRD)
5219    return true;
5220
5221  CXXMethodDecl *Selected;
5222  if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5223                               Diagnose ? &Selected : 0))
5224    return true;
5225
5226  if (Diagnose) {
5227    if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5228      S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5229        << Kind << SubType.getUnqualifiedType();
5230      if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5231        S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5232    } else if (!Selected)
5233      S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5234        << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5235    else if (Selected->isUserProvided()) {
5236      if (Kind == TSK_CompleteObject)
5237        S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5238          << Kind << SubType.getUnqualifiedType() << CSM;
5239      else {
5240        S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5241          << Kind << SubType.getUnqualifiedType() << CSM;
5242        S.Diag(Selected->getLocation(), diag::note_declared_at);
5243      }
5244    } else {
5245      if (Kind != TSK_CompleteObject)
5246        S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5247          << Kind << SubType.getUnqualifiedType() << CSM;
5248
5249      // Explain why the defaulted or deleted special member isn't trivial.
5250      S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5251    }
5252  }
5253
5254  return false;
5255}
5256
5257/// Check whether the members of a class type allow a special member to be
5258/// trivial.
5259static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5260                                     Sema::CXXSpecialMember CSM,
5261                                     bool ConstArg, bool Diagnose) {
5262  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5263                                     FE = RD->field_end(); FI != FE; ++FI) {
5264    if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5265      continue;
5266
5267    QualType FieldType = S.Context.getBaseElementType(FI->getType());
5268
5269    // Pretend anonymous struct or union members are members of this class.
5270    if (FI->isAnonymousStructOrUnion()) {
5271      if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5272                                    CSM, ConstArg, Diagnose))
5273        return false;
5274      continue;
5275    }
5276
5277    // C++11 [class.ctor]p5:
5278    //   A default constructor is trivial if [...]
5279    //    -- no non-static data member of its class has a
5280    //       brace-or-equal-initializer
5281    if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5282      if (Diagnose)
5283        S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5284      return false;
5285    }
5286
5287    // Objective C ARC 4.3.5:
5288    //   [...] nontrivally ownership-qualified types are [...] not trivially
5289    //   default constructible, copy constructible, move constructible, copy
5290    //   assignable, move assignable, or destructible [...]
5291    if (S.getLangOpts().ObjCAutoRefCount &&
5292        FieldType.hasNonTrivialObjCLifetime()) {
5293      if (Diagnose)
5294        S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5295          << RD << FieldType.getObjCLifetime();
5296      return false;
5297    }
5298
5299    if (ConstArg && !FI->isMutable())
5300      FieldType.addConst();
5301    if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5302                                   TSK_Field, Diagnose))
5303      return false;
5304  }
5305
5306  return true;
5307}
5308
5309/// Diagnose why the specified class does not have a trivial special member of
5310/// the given kind.
5311void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5312  QualType Ty = Context.getRecordType(RD);
5313  if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5314    Ty.addConst();
5315
5316  checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5317                            TSK_CompleteObject, /*Diagnose*/true);
5318}
5319
5320/// Determine whether a defaulted or deleted special member function is trivial,
5321/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5322/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5323bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5324                                  bool Diagnose) {
5325  assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5326
5327  CXXRecordDecl *RD = MD->getParent();
5328
5329  bool ConstArg = false;
5330
5331  // C++11 [class.copy]p12, p25:
5332  //   A [special member] is trivial if its declared parameter type is the same
5333  //   as if it had been implicitly declared [...]
5334  switch (CSM) {
5335  case CXXDefaultConstructor:
5336  case CXXDestructor:
5337    // Trivial default constructors and destructors cannot have parameters.
5338    break;
5339
5340  case CXXCopyConstructor:
5341  case CXXCopyAssignment: {
5342    // Trivial copy operations always have const, non-volatile parameter types.
5343    ConstArg = true;
5344    const ParmVarDecl *Param0 = MD->getParamDecl(0);
5345    const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5346    if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5347      if (Diagnose)
5348        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5349          << Param0->getSourceRange() << Param0->getType()
5350          << Context.getLValueReferenceType(
5351               Context.getRecordType(RD).withConst());
5352      return false;
5353    }
5354    break;
5355  }
5356
5357  case CXXMoveConstructor:
5358  case CXXMoveAssignment: {
5359    // Trivial move operations always have non-cv-qualified parameters.
5360    const ParmVarDecl *Param0 = MD->getParamDecl(0);
5361    const RValueReferenceType *RT =
5362      Param0->getType()->getAs<RValueReferenceType>();
5363    if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5364      if (Diagnose)
5365        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5366          << Param0->getSourceRange() << Param0->getType()
5367          << Context.getRValueReferenceType(Context.getRecordType(RD));
5368      return false;
5369    }
5370    break;
5371  }
5372
5373  case CXXInvalid:
5374    llvm_unreachable("not a special member");
5375  }
5376
5377  // FIXME: We require that the parameter-declaration-clause is equivalent to
5378  // that of an implicit declaration, not just that the declared parameter type
5379  // matches, in order to prevent absuridities like a function simultaneously
5380  // being a trivial copy constructor and a non-trivial default constructor.
5381  // This issue has not yet been assigned a core issue number.
5382  if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5383    if (Diagnose)
5384      Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5385           diag::note_nontrivial_default_arg)
5386        << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5387    return false;
5388  }
5389  if (MD->isVariadic()) {
5390    if (Diagnose)
5391      Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5392    return false;
5393  }
5394
5395  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5396  //   A copy/move [constructor or assignment operator] is trivial if
5397  //    -- the [member] selected to copy/move each direct base class subobject
5398  //       is trivial
5399  //
5400  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5401  //   A [default constructor or destructor] is trivial if
5402  //    -- all the direct base classes have trivial [default constructors or
5403  //       destructors]
5404  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5405                                          BE = RD->bases_end(); BI != BE; ++BI)
5406    if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5407                                   ConstArg ? BI->getType().withConst()
5408                                            : BI->getType(),
5409                                   CSM, TSK_BaseClass, Diagnose))
5410      return false;
5411
5412  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5413  //   A copy/move [constructor or assignment operator] for a class X is
5414  //   trivial if
5415  //    -- for each non-static data member of X that is of class type (or array
5416  //       thereof), the constructor selected to copy/move that member is
5417  //       trivial
5418  //
5419  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5420  //   A [default constructor or destructor] is trivial if
5421  //    -- for all of the non-static data members of its class that are of class
5422  //       type (or array thereof), each such class has a trivial [default
5423  //       constructor or destructor]
5424  if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5425    return false;
5426
5427  // C++11 [class.dtor]p5:
5428  //   A destructor is trivial if [...]
5429  //    -- the destructor is not virtual
5430  if (CSM == CXXDestructor && MD->isVirtual()) {
5431    if (Diagnose)
5432      Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5433    return false;
5434  }
5435
5436  // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5437  //   A [special member] for class X is trivial if [...]
5438  //    -- class X has no virtual functions and no virtual base classes
5439  if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5440    if (!Diagnose)
5441      return false;
5442
5443    if (RD->getNumVBases()) {
5444      // Check for virtual bases. We already know that the corresponding
5445      // member in all bases is trivial, so vbases must all be direct.
5446      CXXBaseSpecifier &BS = *RD->vbases_begin();
5447      assert(BS.isVirtual());
5448      Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5449      return false;
5450    }
5451
5452    // Must have a virtual method.
5453    for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5454                                        ME = RD->method_end(); MI != ME; ++MI) {
5455      if (MI->isVirtual()) {
5456        SourceLocation MLoc = MI->getLocStart();
5457        Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5458        return false;
5459      }
5460    }
5461
5462    llvm_unreachable("dynamic class with no vbases and no virtual functions");
5463  }
5464
5465  // Looks like it's trivial!
5466  return true;
5467}
5468
5469/// \brief Data used with FindHiddenVirtualMethod
5470namespace {
5471  struct FindHiddenVirtualMethodData {
5472    Sema *S;
5473    CXXMethodDecl *Method;
5474    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5475    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5476  };
5477}
5478
5479/// \brief Check whether any most overriden method from MD in Methods
5480static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5481                   const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5482  if (MD->size_overridden_methods() == 0)
5483    return Methods.count(MD->getCanonicalDecl());
5484  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5485                                      E = MD->end_overridden_methods();
5486       I != E; ++I)
5487    if (CheckMostOverridenMethods(*I, Methods))
5488      return true;
5489  return false;
5490}
5491
5492/// \brief Member lookup function that determines whether a given C++
5493/// method overloads virtual methods in a base class without overriding any,
5494/// to be used with CXXRecordDecl::lookupInBases().
5495static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5496                                    CXXBasePath &Path,
5497                                    void *UserData) {
5498  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5499
5500  FindHiddenVirtualMethodData &Data
5501    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5502
5503  DeclarationName Name = Data.Method->getDeclName();
5504  assert(Name.getNameKind() == DeclarationName::Identifier);
5505
5506  bool foundSameNameMethod = false;
5507  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5508  for (Path.Decls = BaseRecord->lookup(Name);
5509       !Path.Decls.empty();
5510       Path.Decls = Path.Decls.slice(1)) {
5511    NamedDecl *D = Path.Decls.front();
5512    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5513      MD = MD->getCanonicalDecl();
5514      foundSameNameMethod = true;
5515      // Interested only in hidden virtual methods.
5516      if (!MD->isVirtual())
5517        continue;
5518      // If the method we are checking overrides a method from its base
5519      // don't warn about the other overloaded methods.
5520      if (!Data.S->IsOverload(Data.Method, MD, false))
5521        return true;
5522      // Collect the overload only if its hidden.
5523      if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5524        overloadedMethods.push_back(MD);
5525    }
5526  }
5527
5528  if (foundSameNameMethod)
5529    Data.OverloadedMethods.append(overloadedMethods.begin(),
5530                                   overloadedMethods.end());
5531  return foundSameNameMethod;
5532}
5533
5534/// \brief Add the most overriden methods from MD to Methods
5535static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5536                         llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5537  if (MD->size_overridden_methods() == 0)
5538    Methods.insert(MD->getCanonicalDecl());
5539  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5540                                      E = MD->end_overridden_methods();
5541       I != E; ++I)
5542    AddMostOverridenMethods(*I, Methods);
5543}
5544
5545/// \brief See if a method overloads virtual methods in a base class without
5546/// overriding any.
5547void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5548  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5549                               MD->getLocation()) == DiagnosticsEngine::Ignored)
5550    return;
5551  if (!MD->getDeclName().isIdentifier())
5552    return;
5553
5554  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5555                     /*bool RecordPaths=*/false,
5556                     /*bool DetectVirtual=*/false);
5557  FindHiddenVirtualMethodData Data;
5558  Data.Method = MD;
5559  Data.S = this;
5560
5561  // Keep the base methods that were overriden or introduced in the subclass
5562  // by 'using' in a set. A base method not in this set is hidden.
5563  DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5564  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5565    NamedDecl *ND = *I;
5566    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5567      ND = shad->getTargetDecl();
5568    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5569      AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5570  }
5571
5572  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5573      !Data.OverloadedMethods.empty()) {
5574    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5575      << MD << (Data.OverloadedMethods.size() > 1);
5576
5577    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5578      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5579      PartialDiagnostic PD = PDiag(
5580           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5581      HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5582      Diag(overloadedMD->getLocation(), PD);
5583    }
5584  }
5585}
5586
5587void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5588                                             Decl *TagDecl,
5589                                             SourceLocation LBrac,
5590                                             SourceLocation RBrac,
5591                                             AttributeList *AttrList) {
5592  if (!TagDecl)
5593    return;
5594
5595  AdjustDeclIfTemplate(TagDecl);
5596
5597  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5598    if (l->getKind() != AttributeList::AT_Visibility)
5599      continue;
5600    l->setInvalid();
5601    Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5602      l->getName();
5603  }
5604
5605  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5606              // strict aliasing violation!
5607              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5608              FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5609
5610  CheckCompletedCXXClass(
5611                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5612}
5613
5614/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5615/// special functions, such as the default constructor, copy
5616/// constructor, or destructor, to the given C++ class (C++
5617/// [special]p1).  This routine can only be executed just before the
5618/// definition of the class is complete.
5619void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
5620  if (!ClassDecl->hasUserDeclaredConstructor())
5621    ++ASTContext::NumImplicitDefaultConstructors;
5622
5623  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
5624    ++ASTContext::NumImplicitCopyConstructors;
5625
5626    // If the properties or semantics of the copy constructor couldn't be
5627    // determined while the class was being declared, force a declaration
5628    // of it now.
5629    if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5630      DeclareImplicitCopyConstructor(ClassDecl);
5631  }
5632
5633  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
5634    ++ASTContext::NumImplicitMoveConstructors;
5635
5636    if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5637      DeclareImplicitMoveConstructor(ClassDecl);
5638  }
5639
5640  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5641    ++ASTContext::NumImplicitCopyAssignmentOperators;
5642
5643    // If we have a dynamic class, then the copy assignment operator may be
5644    // virtual, so we have to declare it immediately. This ensures that, e.g.,
5645    // it shows up in the right place in the vtable and that we diagnose
5646    // problems with the implicit exception specification.
5647    if (ClassDecl->isDynamicClass() ||
5648        ClassDecl->needsOverloadResolutionForCopyAssignment())
5649      DeclareImplicitCopyAssignment(ClassDecl);
5650  }
5651
5652  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
5653    ++ASTContext::NumImplicitMoveAssignmentOperators;
5654
5655    // Likewise for the move assignment operator.
5656    if (ClassDecl->isDynamicClass() ||
5657        ClassDecl->needsOverloadResolutionForMoveAssignment())
5658      DeclareImplicitMoveAssignment(ClassDecl);
5659  }
5660
5661  if (!ClassDecl->hasUserDeclaredDestructor()) {
5662    ++ASTContext::NumImplicitDestructors;
5663
5664    // If we have a dynamic class, then the destructor may be virtual, so we
5665    // have to declare the destructor immediately. This ensures that, e.g., it
5666    // shows up in the right place in the vtable and that we diagnose problems
5667    // with the implicit exception specification.
5668    if (ClassDecl->isDynamicClass() ||
5669        ClassDecl->needsOverloadResolutionForDestructor())
5670      DeclareImplicitDestructor(ClassDecl);
5671  }
5672}
5673
5674void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5675  if (!D)
5676    return;
5677
5678  int NumParamList = D->getNumTemplateParameterLists();
5679  for (int i = 0; i < NumParamList; i++) {
5680    TemplateParameterList* Params = D->getTemplateParameterList(i);
5681    for (TemplateParameterList::iterator Param = Params->begin(),
5682                                      ParamEnd = Params->end();
5683          Param != ParamEnd; ++Param) {
5684      NamedDecl *Named = cast<NamedDecl>(*Param);
5685      if (Named->getDeclName()) {
5686        S->AddDecl(Named);
5687        IdResolver.AddDecl(Named);
5688      }
5689    }
5690  }
5691}
5692
5693void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
5694  if (!D)
5695    return;
5696
5697  TemplateParameterList *Params = 0;
5698  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5699    Params = Template->getTemplateParameters();
5700  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5701           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5702    Params = PartialSpec->getTemplateParameters();
5703  else
5704    return;
5705
5706  for (TemplateParameterList::iterator Param = Params->begin(),
5707                                    ParamEnd = Params->end();
5708       Param != ParamEnd; ++Param) {
5709    NamedDecl *Named = cast<NamedDecl>(*Param);
5710    if (Named->getDeclName()) {
5711      S->AddDecl(Named);
5712      IdResolver.AddDecl(Named);
5713    }
5714  }
5715}
5716
5717void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5718  if (!RecordD) return;
5719  AdjustDeclIfTemplate(RecordD);
5720  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
5721  PushDeclContext(S, Record);
5722}
5723
5724void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5725  if (!RecordD) return;
5726  PopDeclContext();
5727}
5728
5729/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5730/// parsing a top-level (non-nested) C++ class, and we are now
5731/// parsing those parts of the given Method declaration that could
5732/// not be parsed earlier (C++ [class.mem]p2), such as default
5733/// arguments. This action should enter the scope of the given
5734/// Method declaration as if we had just parsed the qualified method
5735/// name. However, it should not bring the parameters into scope;
5736/// that will be performed by ActOnDelayedCXXMethodParameter.
5737void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5738}
5739
5740/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5741/// C++ method declaration. We're (re-)introducing the given
5742/// function parameter into scope for use in parsing later parts of
5743/// the method declaration. For example, we could see an
5744/// ActOnParamDefaultArgument event for this parameter.
5745void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
5746  if (!ParamD)
5747    return;
5748
5749  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
5750
5751  // If this parameter has an unparsed default argument, clear it out
5752  // to make way for the parsed default argument.
5753  if (Param->hasUnparsedDefaultArg())
5754    Param->setDefaultArg(0);
5755
5756  S->AddDecl(Param);
5757  if (Param->getDeclName())
5758    IdResolver.AddDecl(Param);
5759}
5760
5761/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5762/// processing the delayed method declaration for Method. The method
5763/// declaration is now considered finished. There may be a separate
5764/// ActOnStartOfFunctionDef action later (not necessarily
5765/// immediately!) for this method, if it was also defined inside the
5766/// class body.
5767void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5768  if (!MethodD)
5769    return;
5770
5771  AdjustDeclIfTemplate(MethodD);
5772
5773  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
5774
5775  // Now that we have our default arguments, check the constructor
5776  // again. It could produce additional diagnostics or affect whether
5777  // the class has implicitly-declared destructors, among other
5778  // things.
5779  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5780    CheckConstructor(Constructor);
5781
5782  // Check the default arguments, which we may have added.
5783  if (!Method->isInvalidDecl())
5784    CheckCXXDefaultArguments(Method);
5785}
5786
5787/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
5788/// the well-formedness of the constructor declarator @p D with type @p
5789/// R. If there are any errors in the declarator, this routine will
5790/// emit diagnostics and set the invalid bit to true.  In any case, the type
5791/// will be updated to reflect a well-formed type for the constructor and
5792/// returned.
5793QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
5794                                          StorageClass &SC) {
5795  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5796
5797  // C++ [class.ctor]p3:
5798  //   A constructor shall not be virtual (10.3) or static (9.4). A
5799  //   constructor can be invoked for a const, volatile or const
5800  //   volatile object. A constructor shall not be declared const,
5801  //   volatile, or const volatile (9.3.2).
5802  if (isVirtual) {
5803    if (!D.isInvalidType())
5804      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5805        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5806        << SourceRange(D.getIdentifierLoc());
5807    D.setInvalidType();
5808  }
5809  if (SC == SC_Static) {
5810    if (!D.isInvalidType())
5811      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5812        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5813        << SourceRange(D.getIdentifierLoc());
5814    D.setInvalidType();
5815    SC = SC_None;
5816  }
5817
5818  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5819  if (FTI.TypeQuals != 0) {
5820    if (FTI.TypeQuals & Qualifiers::Const)
5821      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5822        << "const" << SourceRange(D.getIdentifierLoc());
5823    if (FTI.TypeQuals & Qualifiers::Volatile)
5824      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5825        << "volatile" << SourceRange(D.getIdentifierLoc());
5826    if (FTI.TypeQuals & Qualifiers::Restrict)
5827      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5828        << "restrict" << SourceRange(D.getIdentifierLoc());
5829    D.setInvalidType();
5830  }
5831
5832  // C++0x [class.ctor]p4:
5833  //   A constructor shall not be declared with a ref-qualifier.
5834  if (FTI.hasRefQualifier()) {
5835    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5836      << FTI.RefQualifierIsLValueRef
5837      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5838    D.setInvalidType();
5839  }
5840
5841  // Rebuild the function type "R" without any type qualifiers (in
5842  // case any of the errors above fired) and with "void" as the
5843  // return type, since constructors don't have return types.
5844  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5845  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5846    return R;
5847
5848  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5849  EPI.TypeQuals = 0;
5850  EPI.RefQualifier = RQ_None;
5851
5852  return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
5853}
5854
5855/// CheckConstructor - Checks a fully-formed constructor for
5856/// well-formedness, issuing any diagnostics required. Returns true if
5857/// the constructor declarator is invalid.
5858void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5859  CXXRecordDecl *ClassDecl
5860    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5861  if (!ClassDecl)
5862    return Constructor->setInvalidDecl();
5863
5864  // C++ [class.copy]p3:
5865  //   A declaration of a constructor for a class X is ill-formed if
5866  //   its first parameter is of type (optionally cv-qualified) X and
5867  //   either there are no other parameters or else all other
5868  //   parameters have default arguments.
5869  if (!Constructor->isInvalidDecl() &&
5870      ((Constructor->getNumParams() == 1) ||
5871       (Constructor->getNumParams() > 1 &&
5872        Constructor->getParamDecl(1)->hasDefaultArg())) &&
5873      Constructor->getTemplateSpecializationKind()
5874                                              != TSK_ImplicitInstantiation) {
5875    QualType ParamType = Constructor->getParamDecl(0)->getType();
5876    QualType ClassTy = Context.getTagDeclType(ClassDecl);
5877    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5878      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5879      const char *ConstRef
5880        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5881                                                        : " const &";
5882      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5883        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5884
5885      // FIXME: Rather that making the constructor invalid, we should endeavor
5886      // to fix the type.
5887      Constructor->setInvalidDecl();
5888    }
5889  }
5890}
5891
5892/// CheckDestructor - Checks a fully-formed destructor definition for
5893/// well-formedness, issuing any diagnostics required.  Returns true
5894/// on error.
5895bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5896  CXXRecordDecl *RD = Destructor->getParent();
5897
5898  if (Destructor->isVirtual()) {
5899    SourceLocation Loc;
5900
5901    if (!Destructor->isImplicit())
5902      Loc = Destructor->getLocation();
5903    else
5904      Loc = RD->getLocation();
5905
5906    // If we have a virtual destructor, look up the deallocation function
5907    FunctionDecl *OperatorDelete = 0;
5908    DeclarationName Name =
5909    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5910    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5911      return true;
5912
5913    MarkFunctionReferenced(Loc, OperatorDelete);
5914
5915    Destructor->setOperatorDelete(OperatorDelete);
5916  }
5917
5918  return false;
5919}
5920
5921static inline bool
5922FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5923  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5924          FTI.ArgInfo[0].Param &&
5925          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5926}
5927
5928/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5929/// the well-formednes of the destructor declarator @p D with type @p
5930/// R. If there are any errors in the declarator, this routine will
5931/// emit diagnostics and set the declarator to invalid.  Even if this happens,
5932/// will be updated to reflect a well-formed type for the destructor and
5933/// returned.
5934QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5935                                         StorageClass& SC) {
5936  // C++ [class.dtor]p1:
5937  //   [...] A typedef-name that names a class is a class-name
5938  //   (7.1.3); however, a typedef-name that names a class shall not
5939  //   be used as the identifier in the declarator for a destructor
5940  //   declaration.
5941  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5942  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5943    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5944      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5945  else if (const TemplateSpecializationType *TST =
5946             DeclaratorType->getAs<TemplateSpecializationType>())
5947    if (TST->isTypeAlias())
5948      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5949        << DeclaratorType << 1;
5950
5951  // C++ [class.dtor]p2:
5952  //   A destructor is used to destroy objects of its class type. A
5953  //   destructor takes no parameters, and no return type can be
5954  //   specified for it (not even void). The address of a destructor
5955  //   shall not be taken. A destructor shall not be static. A
5956  //   destructor can be invoked for a const, volatile or const
5957  //   volatile object. A destructor shall not be declared const,
5958  //   volatile or const volatile (9.3.2).
5959  if (SC == SC_Static) {
5960    if (!D.isInvalidType())
5961      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5962        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5963        << SourceRange(D.getIdentifierLoc())
5964        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5965
5966    SC = SC_None;
5967  }
5968  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5969    // Destructors don't have return types, but the parser will
5970    // happily parse something like:
5971    //
5972    //   class X {
5973    //     float ~X();
5974    //   };
5975    //
5976    // The return type will be eliminated later.
5977    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5978      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5979      << SourceRange(D.getIdentifierLoc());
5980  }
5981
5982  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5983  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5984    if (FTI.TypeQuals & Qualifiers::Const)
5985      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5986        << "const" << SourceRange(D.getIdentifierLoc());
5987    if (FTI.TypeQuals & Qualifiers::Volatile)
5988      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5989        << "volatile" << SourceRange(D.getIdentifierLoc());
5990    if (FTI.TypeQuals & Qualifiers::Restrict)
5991      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5992        << "restrict" << SourceRange(D.getIdentifierLoc());
5993    D.setInvalidType();
5994  }
5995
5996  // C++0x [class.dtor]p2:
5997  //   A destructor shall not be declared with a ref-qualifier.
5998  if (FTI.hasRefQualifier()) {
5999    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6000      << FTI.RefQualifierIsLValueRef
6001      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6002    D.setInvalidType();
6003  }
6004
6005  // Make sure we don't have any parameters.
6006  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
6007    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6008
6009    // Delete the parameters.
6010    FTI.freeArgs();
6011    D.setInvalidType();
6012  }
6013
6014  // Make sure the destructor isn't variadic.
6015  if (FTI.isVariadic) {
6016    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6017    D.setInvalidType();
6018  }
6019
6020  // Rebuild the function type "R" without any type qualifiers or
6021  // parameters (in case any of the errors above fired) and with
6022  // "void" as the return type, since destructors don't have return
6023  // types.
6024  if (!D.isInvalidType())
6025    return R;
6026
6027  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6028  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6029  EPI.Variadic = false;
6030  EPI.TypeQuals = 0;
6031  EPI.RefQualifier = RQ_None;
6032  return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI);
6033}
6034
6035/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6036/// well-formednes of the conversion function declarator @p D with
6037/// type @p R. If there are any errors in the declarator, this routine
6038/// will emit diagnostics and return true. Otherwise, it will return
6039/// false. Either way, the type @p R will be updated to reflect a
6040/// well-formed type for the conversion operator.
6041void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6042                                     StorageClass& SC) {
6043  // C++ [class.conv.fct]p1:
6044  //   Neither parameter types nor return type can be specified. The
6045  //   type of a conversion function (8.3.5) is "function taking no
6046  //   parameter returning conversion-type-id."
6047  if (SC == SC_Static) {
6048    if (!D.isInvalidType())
6049      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6050        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6051        << SourceRange(D.getIdentifierLoc());
6052    D.setInvalidType();
6053    SC = SC_None;
6054  }
6055
6056  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6057
6058  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6059    // Conversion functions don't have return types, but the parser will
6060    // happily parse something like:
6061    //
6062    //   class X {
6063    //     float operator bool();
6064    //   };
6065    //
6066    // The return type will be changed later anyway.
6067    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6068      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6069      << SourceRange(D.getIdentifierLoc());
6070    D.setInvalidType();
6071  }
6072
6073  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6074
6075  // Make sure we don't have any parameters.
6076  if (Proto->getNumArgs() > 0) {
6077    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6078
6079    // Delete the parameters.
6080    D.getFunctionTypeInfo().freeArgs();
6081    D.setInvalidType();
6082  } else if (Proto->isVariadic()) {
6083    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6084    D.setInvalidType();
6085  }
6086
6087  // Diagnose "&operator bool()" and other such nonsense.  This
6088  // is actually a gcc extension which we don't support.
6089  if (Proto->getResultType() != ConvType) {
6090    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6091      << Proto->getResultType();
6092    D.setInvalidType();
6093    ConvType = Proto->getResultType();
6094  }
6095
6096  // C++ [class.conv.fct]p4:
6097  //   The conversion-type-id shall not represent a function type nor
6098  //   an array type.
6099  if (ConvType->isArrayType()) {
6100    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6101    ConvType = Context.getPointerType(ConvType);
6102    D.setInvalidType();
6103  } else if (ConvType->isFunctionType()) {
6104    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6105    ConvType = Context.getPointerType(ConvType);
6106    D.setInvalidType();
6107  }
6108
6109  // Rebuild the function type "R" without any parameters (in case any
6110  // of the errors above fired) and with the conversion type as the
6111  // return type.
6112  if (D.isInvalidType())
6113    R = Context.getFunctionType(ConvType, ArrayRef<QualType>(),
6114                                Proto->getExtProtoInfo());
6115
6116  // C++0x explicit conversion operators.
6117  if (D.getDeclSpec().isExplicitSpecified())
6118    Diag(D.getDeclSpec().getExplicitSpecLoc(),
6119         getLangOpts().CPlusPlus11 ?
6120           diag::warn_cxx98_compat_explicit_conversion_functions :
6121           diag::ext_explicit_conversion_functions)
6122      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6123}
6124
6125/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6126/// the declaration of the given C++ conversion function. This routine
6127/// is responsible for recording the conversion function in the C++
6128/// class, if possible.
6129Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6130  assert(Conversion && "Expected to receive a conversion function declaration");
6131
6132  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6133
6134  // Make sure we aren't redeclaring the conversion function.
6135  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6136
6137  // C++ [class.conv.fct]p1:
6138  //   [...] A conversion function is never used to convert a
6139  //   (possibly cv-qualified) object to the (possibly cv-qualified)
6140  //   same object type (or a reference to it), to a (possibly
6141  //   cv-qualified) base class of that type (or a reference to it),
6142  //   or to (possibly cv-qualified) void.
6143  // FIXME: Suppress this warning if the conversion function ends up being a
6144  // virtual function that overrides a virtual function in a base class.
6145  QualType ClassType
6146    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6147  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6148    ConvType = ConvTypeRef->getPointeeType();
6149  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6150      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6151    /* Suppress diagnostics for instantiations. */;
6152  else if (ConvType->isRecordType()) {
6153    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6154    if (ConvType == ClassType)
6155      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6156        << ClassType;
6157    else if (IsDerivedFrom(ClassType, ConvType))
6158      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6159        <<  ClassType << ConvType;
6160  } else if (ConvType->isVoidType()) {
6161    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6162      << ClassType << ConvType;
6163  }
6164
6165  if (FunctionTemplateDecl *ConversionTemplate
6166                                = Conversion->getDescribedFunctionTemplate())
6167    return ConversionTemplate;
6168
6169  return Conversion;
6170}
6171
6172//===----------------------------------------------------------------------===//
6173// Namespace Handling
6174//===----------------------------------------------------------------------===//
6175
6176/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6177/// reopened.
6178static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6179                                            SourceLocation Loc,
6180                                            IdentifierInfo *II, bool *IsInline,
6181                                            NamespaceDecl *PrevNS) {
6182  assert(*IsInline != PrevNS->isInline());
6183
6184  // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6185  // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6186  // inline namespaces, with the intention of bringing names into namespace std.
6187  //
6188  // We support this just well enough to get that case working; this is not
6189  // sufficient to support reopening namespaces as inline in general.
6190  if (*IsInline && II && II->getName().startswith("__atomic") &&
6191      S.getSourceManager().isInSystemHeader(Loc)) {
6192    // Mark all prior declarations of the namespace as inline.
6193    for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6194         NS = NS->getPreviousDecl())
6195      NS->setInline(*IsInline);
6196    // Patch up the lookup table for the containing namespace. This isn't really
6197    // correct, but it's good enough for this particular case.
6198    for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6199                                    E = PrevNS->decls_end(); I != E; ++I)
6200      if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6201        PrevNS->getParent()->makeDeclVisibleInContext(ND);
6202    return;
6203  }
6204
6205  if (PrevNS->isInline())
6206    // The user probably just forgot the 'inline', so suggest that it
6207    // be added back.
6208    S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6209      << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6210  else
6211    S.Diag(Loc, diag::err_inline_namespace_mismatch)
6212      << IsInline;
6213
6214  S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6215  *IsInline = PrevNS->isInline();
6216}
6217
6218/// ActOnStartNamespaceDef - This is called at the start of a namespace
6219/// definition.
6220Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6221                                   SourceLocation InlineLoc,
6222                                   SourceLocation NamespaceLoc,
6223                                   SourceLocation IdentLoc,
6224                                   IdentifierInfo *II,
6225                                   SourceLocation LBrace,
6226                                   AttributeList *AttrList) {
6227  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6228  // For anonymous namespace, take the location of the left brace.
6229  SourceLocation Loc = II ? IdentLoc : LBrace;
6230  bool IsInline = InlineLoc.isValid();
6231  bool IsInvalid = false;
6232  bool IsStd = false;
6233  bool AddToKnown = false;
6234  Scope *DeclRegionScope = NamespcScope->getParent();
6235
6236  NamespaceDecl *PrevNS = 0;
6237  if (II) {
6238    // C++ [namespace.def]p2:
6239    //   The identifier in an original-namespace-definition shall not
6240    //   have been previously defined in the declarative region in
6241    //   which the original-namespace-definition appears. The
6242    //   identifier in an original-namespace-definition is the name of
6243    //   the namespace. Subsequently in that declarative region, it is
6244    //   treated as an original-namespace-name.
6245    //
6246    // Since namespace names are unique in their scope, and we don't
6247    // look through using directives, just look for any ordinary names.
6248
6249    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6250    Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6251    Decl::IDNS_Namespace;
6252    NamedDecl *PrevDecl = 0;
6253    DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6254    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6255         ++I) {
6256      if ((*I)->getIdentifierNamespace() & IDNS) {
6257        PrevDecl = *I;
6258        break;
6259      }
6260    }
6261
6262    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6263
6264    if (PrevNS) {
6265      // This is an extended namespace definition.
6266      if (IsInline != PrevNS->isInline())
6267        DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6268                                        &IsInline, PrevNS);
6269    } else if (PrevDecl) {
6270      // This is an invalid name redefinition.
6271      Diag(Loc, diag::err_redefinition_different_kind)
6272        << II;
6273      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6274      IsInvalid = true;
6275      // Continue on to push Namespc as current DeclContext and return it.
6276    } else if (II->isStr("std") &&
6277               CurContext->getRedeclContext()->isTranslationUnit()) {
6278      // This is the first "real" definition of the namespace "std", so update
6279      // our cache of the "std" namespace to point at this definition.
6280      PrevNS = getStdNamespace();
6281      IsStd = true;
6282      AddToKnown = !IsInline;
6283    } else {
6284      // We've seen this namespace for the first time.
6285      AddToKnown = !IsInline;
6286    }
6287  } else {
6288    // Anonymous namespaces.
6289
6290    // Determine whether the parent already has an anonymous namespace.
6291    DeclContext *Parent = CurContext->getRedeclContext();
6292    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6293      PrevNS = TU->getAnonymousNamespace();
6294    } else {
6295      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6296      PrevNS = ND->getAnonymousNamespace();
6297    }
6298
6299    if (PrevNS && IsInline != PrevNS->isInline())
6300      DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6301                                      &IsInline, PrevNS);
6302  }
6303
6304  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6305                                                 StartLoc, Loc, II, PrevNS);
6306  if (IsInvalid)
6307    Namespc->setInvalidDecl();
6308
6309  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6310
6311  // FIXME: Should we be merging attributes?
6312  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6313    PushNamespaceVisibilityAttr(Attr, Loc);
6314
6315  if (IsStd)
6316    StdNamespace = Namespc;
6317  if (AddToKnown)
6318    KnownNamespaces[Namespc] = false;
6319
6320  if (II) {
6321    PushOnScopeChains(Namespc, DeclRegionScope);
6322  } else {
6323    // Link the anonymous namespace into its parent.
6324    DeclContext *Parent = CurContext->getRedeclContext();
6325    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6326      TU->setAnonymousNamespace(Namespc);
6327    } else {
6328      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6329    }
6330
6331    CurContext->addDecl(Namespc);
6332
6333    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6334    //   behaves as if it were replaced by
6335    //     namespace unique { /* empty body */ }
6336    //     using namespace unique;
6337    //     namespace unique { namespace-body }
6338    //   where all occurrences of 'unique' in a translation unit are
6339    //   replaced by the same identifier and this identifier differs
6340    //   from all other identifiers in the entire program.
6341
6342    // We just create the namespace with an empty name and then add an
6343    // implicit using declaration, just like the standard suggests.
6344    //
6345    // CodeGen enforces the "universally unique" aspect by giving all
6346    // declarations semantically contained within an anonymous
6347    // namespace internal linkage.
6348
6349    if (!PrevNS) {
6350      UsingDirectiveDecl* UD
6351        = UsingDirectiveDecl::Create(Context, Parent,
6352                                     /* 'using' */ LBrace,
6353                                     /* 'namespace' */ SourceLocation(),
6354                                     /* qualifier */ NestedNameSpecifierLoc(),
6355                                     /* identifier */ SourceLocation(),
6356                                     Namespc,
6357                                     /* Ancestor */ Parent);
6358      UD->setImplicit();
6359      Parent->addDecl(UD);
6360    }
6361  }
6362
6363  ActOnDocumentableDecl(Namespc);
6364
6365  // Although we could have an invalid decl (i.e. the namespace name is a
6366  // redefinition), push it as current DeclContext and try to continue parsing.
6367  // FIXME: We should be able to push Namespc here, so that the each DeclContext
6368  // for the namespace has the declarations that showed up in that particular
6369  // namespace definition.
6370  PushDeclContext(NamespcScope, Namespc);
6371  return Namespc;
6372}
6373
6374/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6375/// is a namespace alias, returns the namespace it points to.
6376static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6377  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6378    return AD->getNamespace();
6379  return dyn_cast_or_null<NamespaceDecl>(D);
6380}
6381
6382/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6383/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6384void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6385  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6386  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6387  Namespc->setRBraceLoc(RBrace);
6388  PopDeclContext();
6389  if (Namespc->hasAttr<VisibilityAttr>())
6390    PopPragmaVisibility(true, RBrace);
6391}
6392
6393CXXRecordDecl *Sema::getStdBadAlloc() const {
6394  return cast_or_null<CXXRecordDecl>(
6395                                  StdBadAlloc.get(Context.getExternalSource()));
6396}
6397
6398NamespaceDecl *Sema::getStdNamespace() const {
6399  return cast_or_null<NamespaceDecl>(
6400                                 StdNamespace.get(Context.getExternalSource()));
6401}
6402
6403/// \brief Retrieve the special "std" namespace, which may require us to
6404/// implicitly define the namespace.
6405NamespaceDecl *Sema::getOrCreateStdNamespace() {
6406  if (!StdNamespace) {
6407    // The "std" namespace has not yet been defined, so build one implicitly.
6408    StdNamespace = NamespaceDecl::Create(Context,
6409                                         Context.getTranslationUnitDecl(),
6410                                         /*Inline=*/false,
6411                                         SourceLocation(), SourceLocation(),
6412                                         &PP.getIdentifierTable().get("std"),
6413                                         /*PrevDecl=*/0);
6414    getStdNamespace()->setImplicit(true);
6415  }
6416
6417  return getStdNamespace();
6418}
6419
6420bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6421  assert(getLangOpts().CPlusPlus &&
6422         "Looking for std::initializer_list outside of C++.");
6423
6424  // We're looking for implicit instantiations of
6425  // template <typename E> class std::initializer_list.
6426
6427  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6428    return false;
6429
6430  ClassTemplateDecl *Template = 0;
6431  const TemplateArgument *Arguments = 0;
6432
6433  if (const RecordType *RT = Ty->getAs<RecordType>()) {
6434
6435    ClassTemplateSpecializationDecl *Specialization =
6436        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6437    if (!Specialization)
6438      return false;
6439
6440    Template = Specialization->getSpecializedTemplate();
6441    Arguments = Specialization->getTemplateArgs().data();
6442  } else if (const TemplateSpecializationType *TST =
6443                 Ty->getAs<TemplateSpecializationType>()) {
6444    Template = dyn_cast_or_null<ClassTemplateDecl>(
6445        TST->getTemplateName().getAsTemplateDecl());
6446    Arguments = TST->getArgs();
6447  }
6448  if (!Template)
6449    return false;
6450
6451  if (!StdInitializerList) {
6452    // Haven't recognized std::initializer_list yet, maybe this is it.
6453    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6454    if (TemplateClass->getIdentifier() !=
6455            &PP.getIdentifierTable().get("initializer_list") ||
6456        !getStdNamespace()->InEnclosingNamespaceSetOf(
6457            TemplateClass->getDeclContext()))
6458      return false;
6459    // This is a template called std::initializer_list, but is it the right
6460    // template?
6461    TemplateParameterList *Params = Template->getTemplateParameters();
6462    if (Params->getMinRequiredArguments() != 1)
6463      return false;
6464    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6465      return false;
6466
6467    // It's the right template.
6468    StdInitializerList = Template;
6469  }
6470
6471  if (Template != StdInitializerList)
6472    return false;
6473
6474  // This is an instance of std::initializer_list. Find the argument type.
6475  if (Element)
6476    *Element = Arguments[0].getAsType();
6477  return true;
6478}
6479
6480static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6481  NamespaceDecl *Std = S.getStdNamespace();
6482  if (!Std) {
6483    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6484    return 0;
6485  }
6486
6487  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6488                      Loc, Sema::LookupOrdinaryName);
6489  if (!S.LookupQualifiedName(Result, Std)) {
6490    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6491    return 0;
6492  }
6493  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6494  if (!Template) {
6495    Result.suppressDiagnostics();
6496    // We found something weird. Complain about the first thing we found.
6497    NamedDecl *Found = *Result.begin();
6498    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6499    return 0;
6500  }
6501
6502  // We found some template called std::initializer_list. Now verify that it's
6503  // correct.
6504  TemplateParameterList *Params = Template->getTemplateParameters();
6505  if (Params->getMinRequiredArguments() != 1 ||
6506      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6507    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6508    return 0;
6509  }
6510
6511  return Template;
6512}
6513
6514QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6515  if (!StdInitializerList) {
6516    StdInitializerList = LookupStdInitializerList(*this, Loc);
6517    if (!StdInitializerList)
6518      return QualType();
6519  }
6520
6521  TemplateArgumentListInfo Args(Loc, Loc);
6522  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6523                                       Context.getTrivialTypeSourceInfo(Element,
6524                                                                        Loc)));
6525  return Context.getCanonicalType(
6526      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6527}
6528
6529bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6530  // C++ [dcl.init.list]p2:
6531  //   A constructor is an initializer-list constructor if its first parameter
6532  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
6533  //   std::initializer_list<E> for some type E, and either there are no other
6534  //   parameters or else all other parameters have default arguments.
6535  if (Ctor->getNumParams() < 1 ||
6536      (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6537    return false;
6538
6539  QualType ArgType = Ctor->getParamDecl(0)->getType();
6540  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6541    ArgType = RT->getPointeeType().getUnqualifiedType();
6542
6543  return isStdInitializerList(ArgType, 0);
6544}
6545
6546/// \brief Determine whether a using statement is in a context where it will be
6547/// apply in all contexts.
6548static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6549  switch (CurContext->getDeclKind()) {
6550    case Decl::TranslationUnit:
6551      return true;
6552    case Decl::LinkageSpec:
6553      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6554    default:
6555      return false;
6556  }
6557}
6558
6559namespace {
6560
6561// Callback to only accept typo corrections that are namespaces.
6562class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6563 public:
6564  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6565    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6566      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6567    }
6568    return false;
6569  }
6570};
6571
6572}
6573
6574static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6575                                       CXXScopeSpec &SS,
6576                                       SourceLocation IdentLoc,
6577                                       IdentifierInfo *Ident) {
6578  NamespaceValidatorCCC Validator;
6579  R.clear();
6580  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6581                                               R.getLookupKind(), Sc, &SS,
6582                                               Validator)) {
6583    std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6584    std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
6585    if (DeclContext *DC = S.computeDeclContext(SS, false))
6586      S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6587        << Ident << DC << CorrectedQuotedStr << SS.getRange()
6588        << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6589                                        CorrectedStr);
6590    else
6591      S.Diag(IdentLoc, diag::err_using_directive_suggest)
6592        << Ident << CorrectedQuotedStr
6593        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
6594
6595    S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6596         diag::note_namespace_defined_here) << CorrectedQuotedStr;
6597
6598    R.addDecl(Corrected.getCorrectionDecl());
6599    return true;
6600  }
6601  return false;
6602}
6603
6604Decl *Sema::ActOnUsingDirective(Scope *S,
6605                                          SourceLocation UsingLoc,
6606                                          SourceLocation NamespcLoc,
6607                                          CXXScopeSpec &SS,
6608                                          SourceLocation IdentLoc,
6609                                          IdentifierInfo *NamespcName,
6610                                          AttributeList *AttrList) {
6611  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6612  assert(NamespcName && "Invalid NamespcName.");
6613  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
6614
6615  // This can only happen along a recovery path.
6616  while (S->getFlags() & Scope::TemplateParamScope)
6617    S = S->getParent();
6618  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6619
6620  UsingDirectiveDecl *UDir = 0;
6621  NestedNameSpecifier *Qualifier = 0;
6622  if (SS.isSet())
6623    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6624
6625  // Lookup namespace name.
6626  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6627  LookupParsedName(R, S, &SS);
6628  if (R.isAmbiguous())
6629    return 0;
6630
6631  if (R.empty()) {
6632    R.clear();
6633    // Allow "using namespace std;" or "using namespace ::std;" even if
6634    // "std" hasn't been defined yet, for GCC compatibility.
6635    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6636        NamespcName->isStr("std")) {
6637      Diag(IdentLoc, diag::ext_using_undefined_std);
6638      R.addDecl(getOrCreateStdNamespace());
6639      R.resolveKind();
6640    }
6641    // Otherwise, attempt typo correction.
6642    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
6643  }
6644
6645  if (!R.empty()) {
6646    NamedDecl *Named = R.getFoundDecl();
6647    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6648        && "expected namespace decl");
6649    // C++ [namespace.udir]p1:
6650    //   A using-directive specifies that the names in the nominated
6651    //   namespace can be used in the scope in which the
6652    //   using-directive appears after the using-directive. During
6653    //   unqualified name lookup (3.4.1), the names appear as if they
6654    //   were declared in the nearest enclosing namespace which
6655    //   contains both the using-directive and the nominated
6656    //   namespace. [Note: in this context, "contains" means "contains
6657    //   directly or indirectly". ]
6658
6659    // Find enclosing context containing both using-directive and
6660    // nominated namespace.
6661    NamespaceDecl *NS = getNamespaceDecl(Named);
6662    DeclContext *CommonAncestor = cast<DeclContext>(NS);
6663    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6664      CommonAncestor = CommonAncestor->getParent();
6665
6666    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
6667                                      SS.getWithLocInContext(Context),
6668                                      IdentLoc, Named, CommonAncestor);
6669
6670    if (IsUsingDirectiveInToplevelContext(CurContext) &&
6671        !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
6672      Diag(IdentLoc, diag::warn_using_directive_in_header);
6673    }
6674
6675    PushUsingDirective(S, UDir);
6676  } else {
6677    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6678  }
6679
6680  if (UDir)
6681    ProcessDeclAttributeList(S, UDir, AttrList);
6682
6683  return UDir;
6684}
6685
6686void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6687  // If the scope has an associated entity and the using directive is at
6688  // namespace or translation unit scope, add the UsingDirectiveDecl into
6689  // its lookup structure so qualified name lookup can find it.
6690  DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6691  if (Ctx && !Ctx->isFunctionOrMethod())
6692    Ctx->addDecl(UDir);
6693  else
6694    // Otherwise, it is at block sope. The using-directives will affect lookup
6695    // only to the end of the scope.
6696    S->PushUsingDirective(UDir);
6697}
6698
6699
6700Decl *Sema::ActOnUsingDeclaration(Scope *S,
6701                                  AccessSpecifier AS,
6702                                  bool HasUsingKeyword,
6703                                  SourceLocation UsingLoc,
6704                                  CXXScopeSpec &SS,
6705                                  UnqualifiedId &Name,
6706                                  AttributeList *AttrList,
6707                                  bool IsTypeName,
6708                                  SourceLocation TypenameLoc) {
6709  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6710
6711  switch (Name.getKind()) {
6712  case UnqualifiedId::IK_ImplicitSelfParam:
6713  case UnqualifiedId::IK_Identifier:
6714  case UnqualifiedId::IK_OperatorFunctionId:
6715  case UnqualifiedId::IK_LiteralOperatorId:
6716  case UnqualifiedId::IK_ConversionFunctionId:
6717    break;
6718
6719  case UnqualifiedId::IK_ConstructorName:
6720  case UnqualifiedId::IK_ConstructorTemplateId:
6721    // C++11 inheriting constructors.
6722    Diag(Name.getLocStart(),
6723         getLangOpts().CPlusPlus11 ?
6724           diag::warn_cxx98_compat_using_decl_constructor :
6725           diag::err_using_decl_constructor)
6726      << SS.getRange();
6727
6728    if (getLangOpts().CPlusPlus11) break;
6729
6730    return 0;
6731
6732  case UnqualifiedId::IK_DestructorName:
6733    Diag(Name.getLocStart(), diag::err_using_decl_destructor)
6734      << SS.getRange();
6735    return 0;
6736
6737  case UnqualifiedId::IK_TemplateId:
6738    Diag(Name.getLocStart(), diag::err_using_decl_template_id)
6739      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
6740    return 0;
6741  }
6742
6743  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6744  DeclarationName TargetName = TargetNameInfo.getName();
6745  if (!TargetName)
6746    return 0;
6747
6748  // Warn about access declarations.
6749  // TODO: store that the declaration was written without 'using' and
6750  // talk about access decls instead of using decls in the
6751  // diagnostics.
6752  if (!HasUsingKeyword) {
6753    UsingLoc = Name.getLocStart();
6754
6755    Diag(UsingLoc, diag::warn_access_decl_deprecated)
6756      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
6757  }
6758
6759  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6760      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6761    return 0;
6762
6763  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
6764                                        TargetNameInfo, AttrList,
6765                                        /* IsInstantiation */ false,
6766                                        IsTypeName, TypenameLoc);
6767  if (UD)
6768    PushOnScopeChains(UD, S, /*AddToContext*/ false);
6769
6770  return UD;
6771}
6772
6773/// \brief Determine whether a using declaration considers the given
6774/// declarations as "equivalent", e.g., if they are redeclarations of
6775/// the same entity or are both typedefs of the same type.
6776static bool
6777IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6778                         bool &SuppressRedeclaration) {
6779  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6780    SuppressRedeclaration = false;
6781    return true;
6782  }
6783
6784  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6785    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
6786      SuppressRedeclaration = true;
6787      return Context.hasSameType(TD1->getUnderlyingType(),
6788                                 TD2->getUnderlyingType());
6789    }
6790
6791  return false;
6792}
6793
6794
6795/// Determines whether to create a using shadow decl for a particular
6796/// decl, given the set of decls existing prior to this using lookup.
6797bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6798                                const LookupResult &Previous) {
6799  // Diagnose finding a decl which is not from a base class of the
6800  // current class.  We do this now because there are cases where this
6801  // function will silently decide not to build a shadow decl, which
6802  // will pre-empt further diagnostics.
6803  //
6804  // We don't need to do this in C++0x because we do the check once on
6805  // the qualifier.
6806  //
6807  // FIXME: diagnose the following if we care enough:
6808  //   struct A { int foo; };
6809  //   struct B : A { using A::foo; };
6810  //   template <class T> struct C : A {};
6811  //   template <class T> struct D : C<T> { using B::foo; } // <---
6812  // This is invalid (during instantiation) in C++03 because B::foo
6813  // resolves to the using decl in B, which is not a base class of D<T>.
6814  // We can't diagnose it immediately because C<T> is an unknown
6815  // specialization.  The UsingShadowDecl in D<T> then points directly
6816  // to A::foo, which will look well-formed when we instantiate.
6817  // The right solution is to not collapse the shadow-decl chain.
6818  if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
6819    DeclContext *OrigDC = Orig->getDeclContext();
6820
6821    // Handle enums and anonymous structs.
6822    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6823    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6824    while (OrigRec->isAnonymousStructOrUnion())
6825      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6826
6827    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6828      if (OrigDC == CurContext) {
6829        Diag(Using->getLocation(),
6830             diag::err_using_decl_nested_name_specifier_is_current_class)
6831          << Using->getQualifierLoc().getSourceRange();
6832        Diag(Orig->getLocation(), diag::note_using_decl_target);
6833        return true;
6834      }
6835
6836      Diag(Using->getQualifierLoc().getBeginLoc(),
6837           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6838        << Using->getQualifier()
6839        << cast<CXXRecordDecl>(CurContext)
6840        << Using->getQualifierLoc().getSourceRange();
6841      Diag(Orig->getLocation(), diag::note_using_decl_target);
6842      return true;
6843    }
6844  }
6845
6846  if (Previous.empty()) return false;
6847
6848  NamedDecl *Target = Orig;
6849  if (isa<UsingShadowDecl>(Target))
6850    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6851
6852  // If the target happens to be one of the previous declarations, we
6853  // don't have a conflict.
6854  //
6855  // FIXME: but we might be increasing its access, in which case we
6856  // should redeclare it.
6857  NamedDecl *NonTag = 0, *Tag = 0;
6858  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6859         I != E; ++I) {
6860    NamedDecl *D = (*I)->getUnderlyingDecl();
6861    bool Result;
6862    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6863      return Result;
6864
6865    (isa<TagDecl>(D) ? Tag : NonTag) = D;
6866  }
6867
6868  if (Target->isFunctionOrFunctionTemplate()) {
6869    FunctionDecl *FD;
6870    if (isa<FunctionTemplateDecl>(Target))
6871      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6872    else
6873      FD = cast<FunctionDecl>(Target);
6874
6875    NamedDecl *OldDecl = 0;
6876    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6877    case Ovl_Overload:
6878      return false;
6879
6880    case Ovl_NonFunction:
6881      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6882      break;
6883
6884    // We found a decl with the exact signature.
6885    case Ovl_Match:
6886      // If we're in a record, we want to hide the target, so we
6887      // return true (without a diagnostic) to tell the caller not to
6888      // build a shadow decl.
6889      if (CurContext->isRecord())
6890        return true;
6891
6892      // If we're not in a record, this is an error.
6893      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6894      break;
6895    }
6896
6897    Diag(Target->getLocation(), diag::note_using_decl_target);
6898    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6899    return true;
6900  }
6901
6902  // Target is not a function.
6903
6904  if (isa<TagDecl>(Target)) {
6905    // No conflict between a tag and a non-tag.
6906    if (!Tag) return false;
6907
6908    Diag(Using->getLocation(), diag::err_using_decl_conflict);
6909    Diag(Target->getLocation(), diag::note_using_decl_target);
6910    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6911    return true;
6912  }
6913
6914  // No conflict between a tag and a non-tag.
6915  if (!NonTag) return false;
6916
6917  Diag(Using->getLocation(), diag::err_using_decl_conflict);
6918  Diag(Target->getLocation(), diag::note_using_decl_target);
6919  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6920  return true;
6921}
6922
6923/// Builds a shadow declaration corresponding to a 'using' declaration.
6924UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6925                                            UsingDecl *UD,
6926                                            NamedDecl *Orig) {
6927
6928  // If we resolved to another shadow declaration, just coalesce them.
6929  NamedDecl *Target = Orig;
6930  if (isa<UsingShadowDecl>(Target)) {
6931    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6932    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6933  }
6934
6935  UsingShadowDecl *Shadow
6936    = UsingShadowDecl::Create(Context, CurContext,
6937                              UD->getLocation(), UD, Target);
6938  UD->addShadowDecl(Shadow);
6939
6940  Shadow->setAccess(UD->getAccess());
6941  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6942    Shadow->setInvalidDecl();
6943
6944  if (S)
6945    PushOnScopeChains(Shadow, S);
6946  else
6947    CurContext->addDecl(Shadow);
6948
6949
6950  return Shadow;
6951}
6952
6953/// Hides a using shadow declaration.  This is required by the current
6954/// using-decl implementation when a resolvable using declaration in a
6955/// class is followed by a declaration which would hide or override
6956/// one or more of the using decl's targets; for example:
6957///
6958///   struct Base { void foo(int); };
6959///   struct Derived : Base {
6960///     using Base::foo;
6961///     void foo(int);
6962///   };
6963///
6964/// The governing language is C++03 [namespace.udecl]p12:
6965///
6966///   When a using-declaration brings names from a base class into a
6967///   derived class scope, member functions in the derived class
6968///   override and/or hide member functions with the same name and
6969///   parameter types in a base class (rather than conflicting).
6970///
6971/// There are two ways to implement this:
6972///   (1) optimistically create shadow decls when they're not hidden
6973///       by existing declarations, or
6974///   (2) don't create any shadow decls (or at least don't make them
6975///       visible) until we've fully parsed/instantiated the class.
6976/// The problem with (1) is that we might have to retroactively remove
6977/// a shadow decl, which requires several O(n) operations because the
6978/// decl structures are (very reasonably) not designed for removal.
6979/// (2) avoids this but is very fiddly and phase-dependent.
6980void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6981  if (Shadow->getDeclName().getNameKind() ==
6982        DeclarationName::CXXConversionFunctionName)
6983    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6984
6985  // Remove it from the DeclContext...
6986  Shadow->getDeclContext()->removeDecl(Shadow);
6987
6988  // ...and the scope, if applicable...
6989  if (S) {
6990    S->RemoveDecl(Shadow);
6991    IdResolver.RemoveDecl(Shadow);
6992  }
6993
6994  // ...and the using decl.
6995  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6996
6997  // TODO: complain somehow if Shadow was used.  It shouldn't
6998  // be possible for this to happen, because...?
6999}
7000
7001/// Builds a using declaration.
7002///
7003/// \param IsInstantiation - Whether this call arises from an
7004///   instantiation of an unresolved using declaration.  We treat
7005///   the lookup differently for these declarations.
7006NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7007                                       SourceLocation UsingLoc,
7008                                       CXXScopeSpec &SS,
7009                                       const DeclarationNameInfo &NameInfo,
7010                                       AttributeList *AttrList,
7011                                       bool IsInstantiation,
7012                                       bool IsTypeName,
7013                                       SourceLocation TypenameLoc) {
7014  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7015  SourceLocation IdentLoc = NameInfo.getLoc();
7016  assert(IdentLoc.isValid() && "Invalid TargetName location.");
7017
7018  // FIXME: We ignore attributes for now.
7019
7020  if (SS.isEmpty()) {
7021    Diag(IdentLoc, diag::err_using_requires_qualname);
7022    return 0;
7023  }
7024
7025  // Do the redeclaration lookup in the current scope.
7026  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7027                        ForRedeclaration);
7028  Previous.setHideTags(false);
7029  if (S) {
7030    LookupName(Previous, S);
7031
7032    // It is really dumb that we have to do this.
7033    LookupResult::Filter F = Previous.makeFilter();
7034    while (F.hasNext()) {
7035      NamedDecl *D = F.next();
7036      if (!isDeclInScope(D, CurContext, S))
7037        F.erase();
7038    }
7039    F.done();
7040  } else {
7041    assert(IsInstantiation && "no scope in non-instantiation");
7042    assert(CurContext->isRecord() && "scope not record in instantiation");
7043    LookupQualifiedName(Previous, CurContext);
7044  }
7045
7046  // Check for invalid redeclarations.
7047  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7048    return 0;
7049
7050  // Check for bad qualifiers.
7051  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7052    return 0;
7053
7054  DeclContext *LookupContext = computeDeclContext(SS);
7055  NamedDecl *D;
7056  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7057  if (!LookupContext) {
7058    if (IsTypeName) {
7059      // FIXME: not all declaration name kinds are legal here
7060      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7061                                              UsingLoc, TypenameLoc,
7062                                              QualifierLoc,
7063                                              IdentLoc, NameInfo.getName());
7064    } else {
7065      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7066                                           QualifierLoc, NameInfo);
7067    }
7068  } else {
7069    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7070                          NameInfo, IsTypeName);
7071  }
7072  D->setAccess(AS);
7073  CurContext->addDecl(D);
7074
7075  if (!LookupContext) return D;
7076  UsingDecl *UD = cast<UsingDecl>(D);
7077
7078  if (RequireCompleteDeclContext(SS, LookupContext)) {
7079    UD->setInvalidDecl();
7080    return UD;
7081  }
7082
7083  // The normal rules do not apply to inheriting constructor declarations.
7084  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7085    if (CheckInheritingConstructorUsingDecl(UD))
7086      UD->setInvalidDecl();
7087    return UD;
7088  }
7089
7090  // Otherwise, look up the target name.
7091
7092  LookupResult R(*this, NameInfo, LookupOrdinaryName);
7093
7094  // Unlike most lookups, we don't always want to hide tag
7095  // declarations: tag names are visible through the using declaration
7096  // even if hidden by ordinary names, *except* in a dependent context
7097  // where it's important for the sanity of two-phase lookup.
7098  if (!IsInstantiation)
7099    R.setHideTags(false);
7100
7101  // For the purposes of this lookup, we have a base object type
7102  // equal to that of the current context.
7103  if (CurContext->isRecord()) {
7104    R.setBaseObjectType(
7105                   Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7106  }
7107
7108  LookupQualifiedName(R, LookupContext);
7109
7110  if (R.empty()) {
7111    Diag(IdentLoc, diag::err_no_member)
7112      << NameInfo.getName() << LookupContext << SS.getRange();
7113    UD->setInvalidDecl();
7114    return UD;
7115  }
7116
7117  if (R.isAmbiguous()) {
7118    UD->setInvalidDecl();
7119    return UD;
7120  }
7121
7122  if (IsTypeName) {
7123    // If we asked for a typename and got a non-type decl, error out.
7124    if (!R.getAsSingle<TypeDecl>()) {
7125      Diag(IdentLoc, diag::err_using_typename_non_type);
7126      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7127        Diag((*I)->getUnderlyingDecl()->getLocation(),
7128             diag::note_using_decl_target);
7129      UD->setInvalidDecl();
7130      return UD;
7131    }
7132  } else {
7133    // If we asked for a non-typename and we got a type, error out,
7134    // but only if this is an instantiation of an unresolved using
7135    // decl.  Otherwise just silently find the type name.
7136    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7137      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7138      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7139      UD->setInvalidDecl();
7140      return UD;
7141    }
7142  }
7143
7144  // C++0x N2914 [namespace.udecl]p6:
7145  // A using-declaration shall not name a namespace.
7146  if (R.getAsSingle<NamespaceDecl>()) {
7147    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7148      << SS.getRange();
7149    UD->setInvalidDecl();
7150    return UD;
7151  }
7152
7153  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7154    if (!CheckUsingShadowDecl(UD, *I, Previous))
7155      BuildUsingShadowDecl(S, UD, *I);
7156  }
7157
7158  return UD;
7159}
7160
7161/// Additional checks for a using declaration referring to a constructor name.
7162bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7163  assert(!UD->isTypeName() && "expecting a constructor name");
7164
7165  const Type *SourceType = UD->getQualifier()->getAsType();
7166  assert(SourceType &&
7167         "Using decl naming constructor doesn't have type in scope spec.");
7168  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7169
7170  // Check whether the named type is a direct base class.
7171  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7172  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7173  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7174       BaseIt != BaseE; ++BaseIt) {
7175    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7176    if (CanonicalSourceType == BaseType)
7177      break;
7178    if (BaseIt->getType()->isDependentType())
7179      break;
7180  }
7181
7182  if (BaseIt == BaseE) {
7183    // Did not find SourceType in the bases.
7184    Diag(UD->getUsingLocation(),
7185         diag::err_using_decl_constructor_not_in_direct_base)
7186      << UD->getNameInfo().getSourceRange()
7187      << QualType(SourceType, 0) << TargetClass;
7188    return true;
7189  }
7190
7191  if (!CurContext->isDependentContext())
7192    BaseIt->setInheritConstructors();
7193
7194  return false;
7195}
7196
7197/// Checks that the given using declaration is not an invalid
7198/// redeclaration.  Note that this is checking only for the using decl
7199/// itself, not for any ill-formedness among the UsingShadowDecls.
7200bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7201                                       bool isTypeName,
7202                                       const CXXScopeSpec &SS,
7203                                       SourceLocation NameLoc,
7204                                       const LookupResult &Prev) {
7205  // C++03 [namespace.udecl]p8:
7206  // C++0x [namespace.udecl]p10:
7207  //   A using-declaration is a declaration and can therefore be used
7208  //   repeatedly where (and only where) multiple declarations are
7209  //   allowed.
7210  //
7211  // That's in non-member contexts.
7212  if (!CurContext->getRedeclContext()->isRecord())
7213    return false;
7214
7215  NestedNameSpecifier *Qual
7216    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7217
7218  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7219    NamedDecl *D = *I;
7220
7221    bool DTypename;
7222    NestedNameSpecifier *DQual;
7223    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7224      DTypename = UD->isTypeName();
7225      DQual = UD->getQualifier();
7226    } else if (UnresolvedUsingValueDecl *UD
7227                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7228      DTypename = false;
7229      DQual = UD->getQualifier();
7230    } else if (UnresolvedUsingTypenameDecl *UD
7231                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7232      DTypename = true;
7233      DQual = UD->getQualifier();
7234    } else continue;
7235
7236    // using decls differ if one says 'typename' and the other doesn't.
7237    // FIXME: non-dependent using decls?
7238    if (isTypeName != DTypename) continue;
7239
7240    // using decls differ if they name different scopes (but note that
7241    // template instantiation can cause this check to trigger when it
7242    // didn't before instantiation).
7243    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7244        Context.getCanonicalNestedNameSpecifier(DQual))
7245      continue;
7246
7247    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7248    Diag(D->getLocation(), diag::note_using_decl) << 1;
7249    return true;
7250  }
7251
7252  return false;
7253}
7254
7255
7256/// Checks that the given nested-name qualifier used in a using decl
7257/// in the current context is appropriately related to the current
7258/// scope.  If an error is found, diagnoses it and returns true.
7259bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7260                                   const CXXScopeSpec &SS,
7261                                   SourceLocation NameLoc) {
7262  DeclContext *NamedContext = computeDeclContext(SS);
7263
7264  if (!CurContext->isRecord()) {
7265    // C++03 [namespace.udecl]p3:
7266    // C++0x [namespace.udecl]p8:
7267    //   A using-declaration for a class member shall be a member-declaration.
7268
7269    // If we weren't able to compute a valid scope, it must be a
7270    // dependent class scope.
7271    if (!NamedContext || NamedContext->isRecord()) {
7272      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7273        << SS.getRange();
7274      return true;
7275    }
7276
7277    // Otherwise, everything is known to be fine.
7278    return false;
7279  }
7280
7281  // The current scope is a record.
7282
7283  // If the named context is dependent, we can't decide much.
7284  if (!NamedContext) {
7285    // FIXME: in C++0x, we can diagnose if we can prove that the
7286    // nested-name-specifier does not refer to a base class, which is
7287    // still possible in some cases.
7288
7289    // Otherwise we have to conservatively report that things might be
7290    // okay.
7291    return false;
7292  }
7293
7294  if (!NamedContext->isRecord()) {
7295    // Ideally this would point at the last name in the specifier,
7296    // but we don't have that level of source info.
7297    Diag(SS.getRange().getBegin(),
7298         diag::err_using_decl_nested_name_specifier_is_not_class)
7299      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7300    return true;
7301  }
7302
7303  if (!NamedContext->isDependentContext() &&
7304      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7305    return true;
7306
7307  if (getLangOpts().CPlusPlus11) {
7308    // C++0x [namespace.udecl]p3:
7309    //   In a using-declaration used as a member-declaration, the
7310    //   nested-name-specifier shall name a base class of the class
7311    //   being defined.
7312
7313    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7314                                 cast<CXXRecordDecl>(NamedContext))) {
7315      if (CurContext == NamedContext) {
7316        Diag(NameLoc,
7317             diag::err_using_decl_nested_name_specifier_is_current_class)
7318          << SS.getRange();
7319        return true;
7320      }
7321
7322      Diag(SS.getRange().getBegin(),
7323           diag::err_using_decl_nested_name_specifier_is_not_base_class)
7324        << (NestedNameSpecifier*) SS.getScopeRep()
7325        << cast<CXXRecordDecl>(CurContext)
7326        << SS.getRange();
7327      return true;
7328    }
7329
7330    return false;
7331  }
7332
7333  // C++03 [namespace.udecl]p4:
7334  //   A using-declaration used as a member-declaration shall refer
7335  //   to a member of a base class of the class being defined [etc.].
7336
7337  // Salient point: SS doesn't have to name a base class as long as
7338  // lookup only finds members from base classes.  Therefore we can
7339  // diagnose here only if we can prove that that can't happen,
7340  // i.e. if the class hierarchies provably don't intersect.
7341
7342  // TODO: it would be nice if "definitely valid" results were cached
7343  // in the UsingDecl and UsingShadowDecl so that these checks didn't
7344  // need to be repeated.
7345
7346  struct UserData {
7347    llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7348
7349    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7350      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7351      Data->Bases.insert(Base);
7352      return true;
7353    }
7354
7355    bool hasDependentBases(const CXXRecordDecl *Class) {
7356      return !Class->forallBases(collect, this);
7357    }
7358
7359    /// Returns true if the base is dependent or is one of the
7360    /// accumulated base classes.
7361    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7362      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7363      return !Data->Bases.count(Base);
7364    }
7365
7366    bool mightShareBases(const CXXRecordDecl *Class) {
7367      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7368    }
7369  };
7370
7371  UserData Data;
7372
7373  // Returns false if we find a dependent base.
7374  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7375    return false;
7376
7377  // Returns false if the class has a dependent base or if it or one
7378  // of its bases is present in the base set of the current context.
7379  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7380    return false;
7381
7382  Diag(SS.getRange().getBegin(),
7383       diag::err_using_decl_nested_name_specifier_is_not_base_class)
7384    << (NestedNameSpecifier*) SS.getScopeRep()
7385    << cast<CXXRecordDecl>(CurContext)
7386    << SS.getRange();
7387
7388  return true;
7389}
7390
7391Decl *Sema::ActOnAliasDeclaration(Scope *S,
7392                                  AccessSpecifier AS,
7393                                  MultiTemplateParamsArg TemplateParamLists,
7394                                  SourceLocation UsingLoc,
7395                                  UnqualifiedId &Name,
7396                                  AttributeList *AttrList,
7397                                  TypeResult Type) {
7398  // Skip up to the relevant declaration scope.
7399  while (S->getFlags() & Scope::TemplateParamScope)
7400    S = S->getParent();
7401  assert((S->getFlags() & Scope::DeclScope) &&
7402         "got alias-declaration outside of declaration scope");
7403
7404  if (Type.isInvalid())
7405    return 0;
7406
7407  bool Invalid = false;
7408  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7409  TypeSourceInfo *TInfo = 0;
7410  GetTypeFromParser(Type.get(), &TInfo);
7411
7412  if (DiagnoseClassNameShadow(CurContext, NameInfo))
7413    return 0;
7414
7415  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7416                                      UPPC_DeclarationType)) {
7417    Invalid = true;
7418    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7419                                             TInfo->getTypeLoc().getBeginLoc());
7420  }
7421
7422  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7423  LookupName(Previous, S);
7424
7425  // Warn about shadowing the name of a template parameter.
7426  if (Previous.isSingleResult() &&
7427      Previous.getFoundDecl()->isTemplateParameter()) {
7428    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
7429    Previous.clear();
7430  }
7431
7432  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7433         "name in alias declaration must be an identifier");
7434  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7435                                               Name.StartLocation,
7436                                               Name.Identifier, TInfo);
7437
7438  NewTD->setAccess(AS);
7439
7440  if (Invalid)
7441    NewTD->setInvalidDecl();
7442
7443  ProcessDeclAttributeList(S, NewTD, AttrList);
7444
7445  CheckTypedefForVariablyModifiedType(S, NewTD);
7446  Invalid |= NewTD->isInvalidDecl();
7447
7448  bool Redeclaration = false;
7449
7450  NamedDecl *NewND;
7451  if (TemplateParamLists.size()) {
7452    TypeAliasTemplateDecl *OldDecl = 0;
7453    TemplateParameterList *OldTemplateParams = 0;
7454
7455    if (TemplateParamLists.size() != 1) {
7456      Diag(UsingLoc, diag::err_alias_template_extra_headers)
7457        << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7458         TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
7459    }
7460    TemplateParameterList *TemplateParams = TemplateParamLists[0];
7461
7462    // Only consider previous declarations in the same scope.
7463    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7464                         /*ExplicitInstantiationOrSpecialization*/false);
7465    if (!Previous.empty()) {
7466      Redeclaration = true;
7467
7468      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7469      if (!OldDecl && !Invalid) {
7470        Diag(UsingLoc, diag::err_redefinition_different_kind)
7471          << Name.Identifier;
7472
7473        NamedDecl *OldD = Previous.getRepresentativeDecl();
7474        if (OldD->getLocation().isValid())
7475          Diag(OldD->getLocation(), diag::note_previous_definition);
7476
7477        Invalid = true;
7478      }
7479
7480      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7481        if (TemplateParameterListsAreEqual(TemplateParams,
7482                                           OldDecl->getTemplateParameters(),
7483                                           /*Complain=*/true,
7484                                           TPL_TemplateMatch))
7485          OldTemplateParams = OldDecl->getTemplateParameters();
7486        else
7487          Invalid = true;
7488
7489        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7490        if (!Invalid &&
7491            !Context.hasSameType(OldTD->getUnderlyingType(),
7492                                 NewTD->getUnderlyingType())) {
7493          // FIXME: The C++0x standard does not clearly say this is ill-formed,
7494          // but we can't reasonably accept it.
7495          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7496            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7497          if (OldTD->getLocation().isValid())
7498            Diag(OldTD->getLocation(), diag::note_previous_definition);
7499          Invalid = true;
7500        }
7501      }
7502    }
7503
7504    // Merge any previous default template arguments into our parameters,
7505    // and check the parameter list.
7506    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7507                                   TPC_TypeAliasTemplate))
7508      return 0;
7509
7510    TypeAliasTemplateDecl *NewDecl =
7511      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7512                                    Name.Identifier, TemplateParams,
7513                                    NewTD);
7514
7515    NewDecl->setAccess(AS);
7516
7517    if (Invalid)
7518      NewDecl->setInvalidDecl();
7519    else if (OldDecl)
7520      NewDecl->setPreviousDeclaration(OldDecl);
7521
7522    NewND = NewDecl;
7523  } else {
7524    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7525    NewND = NewTD;
7526  }
7527
7528  if (!Redeclaration)
7529    PushOnScopeChains(NewND, S);
7530
7531  ActOnDocumentableDecl(NewND);
7532  return NewND;
7533}
7534
7535Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
7536                                             SourceLocation NamespaceLoc,
7537                                             SourceLocation AliasLoc,
7538                                             IdentifierInfo *Alias,
7539                                             CXXScopeSpec &SS,
7540                                             SourceLocation IdentLoc,
7541                                             IdentifierInfo *Ident) {
7542
7543  // Lookup the namespace name.
7544  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7545  LookupParsedName(R, S, &SS);
7546
7547  // Check if we have a previous declaration with the same name.
7548  NamedDecl *PrevDecl
7549    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7550                       ForRedeclaration);
7551  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7552    PrevDecl = 0;
7553
7554  if (PrevDecl) {
7555    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
7556      // We already have an alias with the same name that points to the same
7557      // namespace, so don't create a new one.
7558      // FIXME: At some point, we'll want to create the (redundant)
7559      // declaration to maintain better source information.
7560      if (!R.isAmbiguous() && !R.empty() &&
7561          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
7562        return 0;
7563    }
7564
7565    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7566      diag::err_redefinition_different_kind;
7567    Diag(AliasLoc, DiagID) << Alias;
7568    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7569    return 0;
7570  }
7571
7572  if (R.isAmbiguous())
7573    return 0;
7574
7575  if (R.empty()) {
7576    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
7577      Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7578      return 0;
7579    }
7580  }
7581
7582  NamespaceAliasDecl *AliasDecl =
7583    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
7584                               Alias, SS.getWithLocInContext(Context),
7585                               IdentLoc, R.getFoundDecl());
7586
7587  PushOnScopeChains(AliasDecl, S);
7588  return AliasDecl;
7589}
7590
7591Sema::ImplicitExceptionSpecification
7592Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7593                                               CXXMethodDecl *MD) {
7594  CXXRecordDecl *ClassDecl = MD->getParent();
7595
7596  // C++ [except.spec]p14:
7597  //   An implicitly declared special member function (Clause 12) shall have an
7598  //   exception-specification. [...]
7599  ImplicitExceptionSpecification ExceptSpec(*this);
7600  if (ClassDecl->isInvalidDecl())
7601    return ExceptSpec;
7602
7603  // Direct base-class constructors.
7604  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7605                                       BEnd = ClassDecl->bases_end();
7606       B != BEnd; ++B) {
7607    if (B->isVirtual()) // Handled below.
7608      continue;
7609
7610    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7611      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7612      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7613      // If this is a deleted function, add it anyway. This might be conformant
7614      // with the standard. This might not. I'm not sure. It might not matter.
7615      if (Constructor)
7616        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7617    }
7618  }
7619
7620  // Virtual base-class constructors.
7621  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7622                                       BEnd = ClassDecl->vbases_end();
7623       B != BEnd; ++B) {
7624    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7625      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7626      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7627      // If this is a deleted function, add it anyway. This might be conformant
7628      // with the standard. This might not. I'm not sure. It might not matter.
7629      if (Constructor)
7630        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7631    }
7632  }
7633
7634  // Field constructors.
7635  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7636                               FEnd = ClassDecl->field_end();
7637       F != FEnd; ++F) {
7638    if (F->hasInClassInitializer()) {
7639      if (Expr *E = F->getInClassInitializer())
7640        ExceptSpec.CalledExpr(E);
7641      else if (!F->isInvalidDecl())
7642        // DR1351:
7643        //   If the brace-or-equal-initializer of a non-static data member
7644        //   invokes a defaulted default constructor of its class or of an
7645        //   enclosing class in a potentially evaluated subexpression, the
7646        //   program is ill-formed.
7647        //
7648        // This resolution is unworkable: the exception specification of the
7649        // default constructor can be needed in an unevaluated context, in
7650        // particular, in the operand of a noexcept-expression, and we can be
7651        // unable to compute an exception specification for an enclosed class.
7652        //
7653        // We do not allow an in-class initializer to require the evaluation
7654        // of the exception specification for any in-class initializer whose
7655        // definition is not lexically complete.
7656        Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
7657    } else if (const RecordType *RecordTy
7658              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7659      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7660      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7661      // If this is a deleted function, add it anyway. This might be conformant
7662      // with the standard. This might not. I'm not sure. It might not matter.
7663      // In particular, the problem is that this function never gets called. It
7664      // might just be ill-formed because this function attempts to refer to
7665      // a deleted function here.
7666      if (Constructor)
7667        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7668    }
7669  }
7670
7671  return ExceptSpec;
7672}
7673
7674Sema::ImplicitExceptionSpecification
7675Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7676  CXXRecordDecl *ClassDecl = CD->getParent();
7677
7678  // C++ [except.spec]p14:
7679  //   An inheriting constructor [...] shall have an exception-specification. [...]
7680  ImplicitExceptionSpecification ExceptSpec(*this);
7681  if (ClassDecl->isInvalidDecl())
7682    return ExceptSpec;
7683
7684  // Inherited constructor.
7685  const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7686  const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7687  // FIXME: Copying or moving the parameters could add extra exceptions to the
7688  // set, as could the default arguments for the inherited constructor. This
7689  // will be addressed when we implement the resolution of core issue 1351.
7690  ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7691
7692  // Direct base-class constructors.
7693  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7694                                       BEnd = ClassDecl->bases_end();
7695       B != BEnd; ++B) {
7696    if (B->isVirtual()) // Handled below.
7697      continue;
7698
7699    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7700      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7701      if (BaseClassDecl == InheritedDecl)
7702        continue;
7703      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7704      if (Constructor)
7705        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7706    }
7707  }
7708
7709  // Virtual base-class constructors.
7710  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7711                                       BEnd = ClassDecl->vbases_end();
7712       B != BEnd; ++B) {
7713    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7714      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7715      if (BaseClassDecl == InheritedDecl)
7716        continue;
7717      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7718      if (Constructor)
7719        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7720    }
7721  }
7722
7723  // Field constructors.
7724  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7725                               FEnd = ClassDecl->field_end();
7726       F != FEnd; ++F) {
7727    if (F->hasInClassInitializer()) {
7728      if (Expr *E = F->getInClassInitializer())
7729        ExceptSpec.CalledExpr(E);
7730      else if (!F->isInvalidDecl())
7731        Diag(CD->getLocation(),
7732             diag::err_in_class_initializer_references_def_ctor) << CD;
7733    } else if (const RecordType *RecordTy
7734              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7735      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7736      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7737      if (Constructor)
7738        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7739    }
7740  }
7741
7742  return ExceptSpec;
7743}
7744
7745namespace {
7746/// RAII object to register a special member as being currently declared.
7747struct DeclaringSpecialMember {
7748  Sema &S;
7749  Sema::SpecialMemberDecl D;
7750  bool WasAlreadyBeingDeclared;
7751
7752  DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7753    : S(S), D(RD, CSM) {
7754    WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7755    if (WasAlreadyBeingDeclared)
7756      // This almost never happens, but if it does, ensure that our cache
7757      // doesn't contain a stale result.
7758      S.SpecialMemberCache.clear();
7759
7760    // FIXME: Register a note to be produced if we encounter an error while
7761    // declaring the special member.
7762  }
7763  ~DeclaringSpecialMember() {
7764    if (!WasAlreadyBeingDeclared)
7765      S.SpecialMembersBeingDeclared.erase(D);
7766  }
7767
7768  /// \brief Are we already trying to declare this special member?
7769  bool isAlreadyBeingDeclared() const {
7770    return WasAlreadyBeingDeclared;
7771  }
7772};
7773}
7774
7775CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7776                                                     CXXRecordDecl *ClassDecl) {
7777  // C++ [class.ctor]p5:
7778  //   A default constructor for a class X is a constructor of class X
7779  //   that can be called without an argument. If there is no
7780  //   user-declared constructor for class X, a default constructor is
7781  //   implicitly declared. An implicitly-declared default constructor
7782  //   is an inline public member of its class.
7783  assert(ClassDecl->needsImplicitDefaultConstructor() &&
7784         "Should not build implicit default constructor!");
7785
7786  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7787  if (DSM.isAlreadyBeingDeclared())
7788    return 0;
7789
7790  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7791                                                     CXXDefaultConstructor,
7792                                                     false);
7793
7794  // Create the actual constructor declaration.
7795  CanQualType ClassType
7796    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7797  SourceLocation ClassLoc = ClassDecl->getLocation();
7798  DeclarationName Name
7799    = Context.DeclarationNames.getCXXConstructorName(ClassType);
7800  DeclarationNameInfo NameInfo(Name, ClassLoc);
7801  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7802      Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
7803      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7804      Constexpr);
7805  DefaultCon->setAccess(AS_public);
7806  DefaultCon->setDefaulted();
7807  DefaultCon->setImplicit();
7808
7809  // Build an exception specification pointing back at this constructor.
7810  FunctionProtoType::ExtProtoInfo EPI;
7811  EPI.ExceptionSpecType = EST_Unevaluated;
7812  EPI.ExceptionSpecDecl = DefaultCon;
7813  DefaultCon->setType(Context.getFunctionType(Context.VoidTy,
7814                                              ArrayRef<QualType>(),
7815                                              EPI));
7816
7817  // We don't need to use SpecialMemberIsTrivial here; triviality for default
7818  // constructors is easy to compute.
7819  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7820
7821  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7822    SetDeclDeleted(DefaultCon, ClassLoc);
7823
7824  // Note that we have declared this constructor.
7825  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7826
7827  if (Scope *S = getScopeForContext(ClassDecl))
7828    PushOnScopeChains(DefaultCon, S, false);
7829  ClassDecl->addDecl(DefaultCon);
7830
7831  return DefaultCon;
7832}
7833
7834void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7835                                            CXXConstructorDecl *Constructor) {
7836  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7837          !Constructor->doesThisDeclarationHaveABody() &&
7838          !Constructor->isDeleted()) &&
7839    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
7840
7841  CXXRecordDecl *ClassDecl = Constructor->getParent();
7842  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
7843
7844  SynthesizedFunctionScope Scope(*this, Constructor);
7845  DiagnosticErrorTrap Trap(Diags);
7846  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
7847      Trap.hasErrorOccurred()) {
7848    Diag(CurrentLocation, diag::note_member_synthesized_at)
7849      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
7850    Constructor->setInvalidDecl();
7851    return;
7852  }
7853
7854  SourceLocation Loc = Constructor->getLocation();
7855  Constructor->setBody(new (Context) CompoundStmt(Loc));
7856
7857  Constructor->setUsed();
7858  MarkVTableUsed(CurrentLocation, ClassDecl);
7859
7860  if (ASTMutationListener *L = getASTMutationListener()) {
7861    L->CompletedImplicitDefinition(Constructor);
7862  }
7863}
7864
7865void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7866  // Check that any explicitly-defaulted methods have exception specifications
7867  // compatible with their implicit exception specifications.
7868  CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
7869}
7870
7871namespace {
7872/// Information on inheriting constructors to declare.
7873class InheritingConstructorInfo {
7874public:
7875  InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7876      : SemaRef(SemaRef), Derived(Derived) {
7877    // Mark the constructors that we already have in the derived class.
7878    //
7879    // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7880    //   unless there is a user-declared constructor with the same signature in
7881    //   the class where the using-declaration appears.
7882    visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7883  }
7884
7885  void inheritAll(CXXRecordDecl *RD) {
7886    visitAll(RD, &InheritingConstructorInfo::inherit);
7887  }
7888
7889private:
7890  /// Information about an inheriting constructor.
7891  struct InheritingConstructor {
7892    InheritingConstructor()
7893      : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7894
7895    /// If \c true, a constructor with this signature is already declared
7896    /// in the derived class.
7897    bool DeclaredInDerived;
7898
7899    /// The constructor which is inherited.
7900    const CXXConstructorDecl *BaseCtor;
7901
7902    /// The derived constructor we declared.
7903    CXXConstructorDecl *DerivedCtor;
7904  };
7905
7906  /// Inheriting constructors with a given canonical type. There can be at
7907  /// most one such non-template constructor, and any number of templated
7908  /// constructors.
7909  struct InheritingConstructorsForType {
7910    InheritingConstructor NonTemplate;
7911    llvm::SmallVector<
7912      std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7913
7914    InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7915      if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7916        TemplateParameterList *ParamList = FTD->getTemplateParameters();
7917        for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7918          if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7919                                               false, S.TPL_TemplateMatch))
7920            return Templates[I].second;
7921        Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7922        return Templates.back().second;
7923      }
7924
7925      return NonTemplate;
7926    }
7927  };
7928
7929  /// Get or create the inheriting constructor record for a constructor.
7930  InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7931                                  QualType CtorType) {
7932    return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7933        .getEntry(SemaRef, Ctor);
7934  }
7935
7936  typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7937
7938  /// Process all constructors for a class.
7939  void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7940    for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7941                                      CtorE = RD->ctor_end();
7942         CtorIt != CtorE; ++CtorIt)
7943      (this->*Callback)(*CtorIt);
7944    for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7945             I(RD->decls_begin()), E(RD->decls_end());
7946         I != E; ++I) {
7947      const FunctionDecl *FD = (*I)->getTemplatedDecl();
7948      if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7949        (this->*Callback)(CD);
7950    }
7951  }
7952
7953  /// Note that a constructor (or constructor template) was declared in Derived.
7954  void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7955    getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7956  }
7957
7958  /// Inherit a single constructor.
7959  void inherit(const CXXConstructorDecl *Ctor) {
7960    const FunctionProtoType *CtorType =
7961        Ctor->getType()->castAs<FunctionProtoType>();
7962    ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7963    FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7964
7965    SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7966
7967    // Core issue (no number yet): the ellipsis is always discarded.
7968    if (EPI.Variadic) {
7969      SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7970      SemaRef.Diag(Ctor->getLocation(),
7971                   diag::note_using_decl_constructor_ellipsis);
7972      EPI.Variadic = false;
7973    }
7974
7975    // Declare a constructor for each number of parameters.
7976    //
7977    // C++11 [class.inhctor]p1:
7978    //   The candidate set of inherited constructors from the class X named in
7979    //   the using-declaration consists of [... modulo defects ...] for each
7980    //   constructor or constructor template of X, the set of constructors or
7981    //   constructor templates that results from omitting any ellipsis parameter
7982    //   specification and successively omitting parameters with a default
7983    //   argument from the end of the parameter-type-list
7984    unsigned MinParams = minParamsToInherit(Ctor);
7985    unsigned Params = Ctor->getNumParams();
7986    if (Params >= MinParams) {
7987      do
7988        declareCtor(UsingLoc, Ctor,
7989                    SemaRef.Context.getFunctionType(
7990                        Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7991      while (Params > MinParams &&
7992             Ctor->getParamDecl(--Params)->hasDefaultArg());
7993    }
7994  }
7995
7996  /// Find the using-declaration which specified that we should inherit the
7997  /// constructors of \p Base.
7998  SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
7999    // No fancy lookup required; just look for the base constructor name
8000    // directly within the derived class.
8001    ASTContext &Context = SemaRef.Context;
8002    DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8003        Context.getCanonicalType(Context.getRecordType(Base)));
8004    DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8005    return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8006  }
8007
8008  unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8009    // C++11 [class.inhctor]p3:
8010    //   [F]or each constructor template in the candidate set of inherited
8011    //   constructors, a constructor template is implicitly declared
8012    if (Ctor->getDescribedFunctionTemplate())
8013      return 0;
8014
8015    //   For each non-template constructor in the candidate set of inherited
8016    //   constructors other than a constructor having no parameters or a
8017    //   copy/move constructor having a single parameter, a constructor is
8018    //   implicitly declared [...]
8019    if (Ctor->getNumParams() == 0)
8020      return 1;
8021    if (Ctor->isCopyOrMoveConstructor())
8022      return 2;
8023
8024    // Per discussion on core reflector, never inherit a constructor which
8025    // would become a default, copy, or move constructor of Derived either.
8026    const ParmVarDecl *PD = Ctor->getParamDecl(0);
8027    const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8028    return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8029  }
8030
8031  /// Declare a single inheriting constructor, inheriting the specified
8032  /// constructor, with the given type.
8033  void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8034                   QualType DerivedType) {
8035    InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8036
8037    // C++11 [class.inhctor]p3:
8038    //   ... a constructor is implicitly declared with the same constructor
8039    //   characteristics unless there is a user-declared constructor with
8040    //   the same signature in the class where the using-declaration appears
8041    if (Entry.DeclaredInDerived)
8042      return;
8043
8044    // C++11 [class.inhctor]p7:
8045    //   If two using-declarations declare inheriting constructors with the
8046    //   same signature, the program is ill-formed
8047    if (Entry.DerivedCtor) {
8048      if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8049        // Only diagnose this once per constructor.
8050        if (Entry.DerivedCtor->isInvalidDecl())
8051          return;
8052        Entry.DerivedCtor->setInvalidDecl();
8053
8054        SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8055        SemaRef.Diag(BaseCtor->getLocation(),
8056                     diag::note_using_decl_constructor_conflict_current_ctor);
8057        SemaRef.Diag(Entry.BaseCtor->getLocation(),
8058                     diag::note_using_decl_constructor_conflict_previous_ctor);
8059        SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8060                     diag::note_using_decl_constructor_conflict_previous_using);
8061      } else {
8062        // Core issue (no number): if the same inheriting constructor is
8063        // produced by multiple base class constructors from the same base
8064        // class, the inheriting constructor is defined as deleted.
8065        SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8066      }
8067
8068      return;
8069    }
8070
8071    ASTContext &Context = SemaRef.Context;
8072    DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8073        Context.getCanonicalType(Context.getRecordType(Derived)));
8074    DeclarationNameInfo NameInfo(Name, UsingLoc);
8075
8076    TemplateParameterList *TemplateParams = 0;
8077    if (const FunctionTemplateDecl *FTD =
8078            BaseCtor->getDescribedFunctionTemplate()) {
8079      TemplateParams = FTD->getTemplateParameters();
8080      // We're reusing template parameters from a different DeclContext. This
8081      // is questionable at best, but works out because the template depth in
8082      // both places is guaranteed to be 0.
8083      // FIXME: Rebuild the template parameters in the new context, and
8084      // transform the function type to refer to them.
8085    }
8086
8087    // Build type source info pointing at the using-declaration. This is
8088    // required by template instantiation.
8089    TypeSourceInfo *TInfo =
8090        Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8091    FunctionProtoTypeLoc ProtoLoc =
8092        TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8093
8094    CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8095        Context, Derived, UsingLoc, NameInfo, DerivedType,
8096        TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8097        /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8098
8099    // Build an unevaluated exception specification for this constructor.
8100    const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8101    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8102    EPI.ExceptionSpecType = EST_Unevaluated;
8103    EPI.ExceptionSpecDecl = DerivedCtor;
8104    DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8105                                                 FPT->getArgTypes(), EPI));
8106
8107    // Build the parameter declarations.
8108    SmallVector<ParmVarDecl *, 16> ParamDecls;
8109    for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8110      TypeSourceInfo *TInfo =
8111          Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8112      ParmVarDecl *PD = ParmVarDecl::Create(
8113          Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8114          FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8115      PD->setScopeInfo(0, I);
8116      PD->setImplicit();
8117      ParamDecls.push_back(PD);
8118      ProtoLoc.setArg(I, PD);
8119    }
8120
8121    // Set up the new constructor.
8122    DerivedCtor->setAccess(BaseCtor->getAccess());
8123    DerivedCtor->setParams(ParamDecls);
8124    DerivedCtor->setInheritedConstructor(BaseCtor);
8125    if (BaseCtor->isDeleted())
8126      SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8127
8128    // If this is a constructor template, build the template declaration.
8129    if (TemplateParams) {
8130      FunctionTemplateDecl *DerivedTemplate =
8131          FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8132                                       TemplateParams, DerivedCtor);
8133      DerivedTemplate->setAccess(BaseCtor->getAccess());
8134      DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8135      Derived->addDecl(DerivedTemplate);
8136    } else {
8137      Derived->addDecl(DerivedCtor);
8138    }
8139
8140    Entry.BaseCtor = BaseCtor;
8141    Entry.DerivedCtor = DerivedCtor;
8142  }
8143
8144  Sema &SemaRef;
8145  CXXRecordDecl *Derived;
8146  typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8147  MapType Map;
8148};
8149}
8150
8151void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8152  // Defer declaring the inheriting constructors until the class is
8153  // instantiated.
8154  if (ClassDecl->isDependentContext())
8155    return;
8156
8157  // Find base classes from which we might inherit constructors.
8158  SmallVector<CXXRecordDecl*, 4> InheritedBases;
8159  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8160                                          BaseE = ClassDecl->bases_end();
8161       BaseIt != BaseE; ++BaseIt)
8162    if (BaseIt->getInheritConstructors())
8163      InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
8164
8165  // Go no further if we're not inheriting any constructors.
8166  if (InheritedBases.empty())
8167    return;
8168
8169  // Declare the inherited constructors.
8170  InheritingConstructorInfo ICI(*this, ClassDecl);
8171  for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8172    ICI.inheritAll(InheritedBases[I]);
8173}
8174
8175void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8176                                       CXXConstructorDecl *Constructor) {
8177  CXXRecordDecl *ClassDecl = Constructor->getParent();
8178  assert(Constructor->getInheritedConstructor() &&
8179         !Constructor->doesThisDeclarationHaveABody() &&
8180         !Constructor->isDeleted());
8181
8182  SynthesizedFunctionScope Scope(*this, Constructor);
8183  DiagnosticErrorTrap Trap(Diags);
8184  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8185      Trap.hasErrorOccurred()) {
8186    Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8187      << Context.getTagDeclType(ClassDecl);
8188    Constructor->setInvalidDecl();
8189    return;
8190  }
8191
8192  SourceLocation Loc = Constructor->getLocation();
8193  Constructor->setBody(new (Context) CompoundStmt(Loc));
8194
8195  Constructor->setUsed();
8196  MarkVTableUsed(CurrentLocation, ClassDecl);
8197
8198  if (ASTMutationListener *L = getASTMutationListener()) {
8199    L->CompletedImplicitDefinition(Constructor);
8200  }
8201}
8202
8203
8204Sema::ImplicitExceptionSpecification
8205Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8206  CXXRecordDecl *ClassDecl = MD->getParent();
8207
8208  // C++ [except.spec]p14:
8209  //   An implicitly declared special member function (Clause 12) shall have
8210  //   an exception-specification.
8211  ImplicitExceptionSpecification ExceptSpec(*this);
8212  if (ClassDecl->isInvalidDecl())
8213    return ExceptSpec;
8214
8215  // Direct base-class destructors.
8216  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8217                                       BEnd = ClassDecl->bases_end();
8218       B != BEnd; ++B) {
8219    if (B->isVirtual()) // Handled below.
8220      continue;
8221
8222    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8223      ExceptSpec.CalledDecl(B->getLocStart(),
8224                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8225  }
8226
8227  // Virtual base-class destructors.
8228  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8229                                       BEnd = ClassDecl->vbases_end();
8230       B != BEnd; ++B) {
8231    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8232      ExceptSpec.CalledDecl(B->getLocStart(),
8233                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8234  }
8235
8236  // Field destructors.
8237  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8238                               FEnd = ClassDecl->field_end();
8239       F != FEnd; ++F) {
8240    if (const RecordType *RecordTy
8241        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8242      ExceptSpec.CalledDecl(F->getLocation(),
8243                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8244  }
8245
8246  return ExceptSpec;
8247}
8248
8249CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8250  // C++ [class.dtor]p2:
8251  //   If a class has no user-declared destructor, a destructor is
8252  //   declared implicitly. An implicitly-declared destructor is an
8253  //   inline public member of its class.
8254  assert(ClassDecl->needsImplicitDestructor());
8255
8256  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8257  if (DSM.isAlreadyBeingDeclared())
8258    return 0;
8259
8260  // Create the actual destructor declaration.
8261  CanQualType ClassType
8262    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8263  SourceLocation ClassLoc = ClassDecl->getLocation();
8264  DeclarationName Name
8265    = Context.DeclarationNames.getCXXDestructorName(ClassType);
8266  DeclarationNameInfo NameInfo(Name, ClassLoc);
8267  CXXDestructorDecl *Destructor
8268      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8269                                  QualType(), 0, /*isInline=*/true,
8270                                  /*isImplicitlyDeclared=*/true);
8271  Destructor->setAccess(AS_public);
8272  Destructor->setDefaulted();
8273  Destructor->setImplicit();
8274
8275  // Build an exception specification pointing back at this destructor.
8276  FunctionProtoType::ExtProtoInfo EPI;
8277  EPI.ExceptionSpecType = EST_Unevaluated;
8278  EPI.ExceptionSpecDecl = Destructor;
8279  Destructor->setType(Context.getFunctionType(Context.VoidTy,
8280                                              ArrayRef<QualType>(),
8281                                              EPI));
8282
8283  AddOverriddenMethods(ClassDecl, Destructor);
8284
8285  // We don't need to use SpecialMemberIsTrivial here; triviality for
8286  // destructors is easy to compute.
8287  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8288
8289  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8290    SetDeclDeleted(Destructor, ClassLoc);
8291
8292  // Note that we have declared this destructor.
8293  ++ASTContext::NumImplicitDestructorsDeclared;
8294
8295  // Introduce this destructor into its scope.
8296  if (Scope *S = getScopeForContext(ClassDecl))
8297    PushOnScopeChains(Destructor, S, false);
8298  ClassDecl->addDecl(Destructor);
8299
8300  return Destructor;
8301}
8302
8303void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
8304                                    CXXDestructorDecl *Destructor) {
8305  assert((Destructor->isDefaulted() &&
8306          !Destructor->doesThisDeclarationHaveABody() &&
8307          !Destructor->isDeleted()) &&
8308         "DefineImplicitDestructor - call it for implicit default dtor");
8309  CXXRecordDecl *ClassDecl = Destructor->getParent();
8310  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
8311
8312  if (Destructor->isInvalidDecl())
8313    return;
8314
8315  SynthesizedFunctionScope Scope(*this, Destructor);
8316
8317  DiagnosticErrorTrap Trap(Diags);
8318  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8319                                         Destructor->getParent());
8320
8321  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
8322    Diag(CurrentLocation, diag::note_member_synthesized_at)
8323      << CXXDestructor << Context.getTagDeclType(ClassDecl);
8324
8325    Destructor->setInvalidDecl();
8326    return;
8327  }
8328
8329  SourceLocation Loc = Destructor->getLocation();
8330  Destructor->setBody(new (Context) CompoundStmt(Loc));
8331  Destructor->setImplicitlyDefined(true);
8332  Destructor->setUsed();
8333  MarkVTableUsed(CurrentLocation, ClassDecl);
8334
8335  if (ASTMutationListener *L = getASTMutationListener()) {
8336    L->CompletedImplicitDefinition(Destructor);
8337  }
8338}
8339
8340/// \brief Perform any semantic analysis which needs to be delayed until all
8341/// pending class member declarations have been parsed.
8342void Sema::ActOnFinishCXXMemberDecls() {
8343  // If the context is an invalid C++ class, just suppress these checks.
8344  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8345    if (Record->isInvalidDecl()) {
8346      DelayedDestructorExceptionSpecChecks.clear();
8347      return;
8348    }
8349  }
8350
8351  // Perform any deferred checking of exception specifications for virtual
8352  // destructors.
8353  for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8354       i != e; ++i) {
8355    const CXXDestructorDecl *Dtor =
8356        DelayedDestructorExceptionSpecChecks[i].first;
8357    assert(!Dtor->getParent()->isDependentType() &&
8358           "Should not ever add destructors of templates into the list.");
8359    CheckOverridingFunctionExceptionSpec(Dtor,
8360        DelayedDestructorExceptionSpecChecks[i].second);
8361  }
8362  DelayedDestructorExceptionSpecChecks.clear();
8363}
8364
8365void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8366                                         CXXDestructorDecl *Destructor) {
8367  assert(getLangOpts().CPlusPlus11 &&
8368         "adjusting dtor exception specs was introduced in c++11");
8369
8370  // C++11 [class.dtor]p3:
8371  //   A declaration of a destructor that does not have an exception-
8372  //   specification is implicitly considered to have the same exception-
8373  //   specification as an implicit declaration.
8374  const FunctionProtoType *DtorType = Destructor->getType()->
8375                                        getAs<FunctionProtoType>();
8376  if (DtorType->hasExceptionSpec())
8377    return;
8378
8379  // Replace the destructor's type, building off the existing one. Fortunately,
8380  // the only thing of interest in the destructor type is its extended info.
8381  // The return and arguments are fixed.
8382  FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8383  EPI.ExceptionSpecType = EST_Unevaluated;
8384  EPI.ExceptionSpecDecl = Destructor;
8385  Destructor->setType(Context.getFunctionType(Context.VoidTy,
8386                                              ArrayRef<QualType>(),
8387                                              EPI));
8388
8389  // FIXME: If the destructor has a body that could throw, and the newly created
8390  // spec doesn't allow exceptions, we should emit a warning, because this
8391  // change in behavior can break conforming C++03 programs at runtime.
8392  // However, we don't have a body or an exception specification yet, so it
8393  // needs to be done somewhere else.
8394}
8395
8396/// When generating a defaulted copy or move assignment operator, if a field
8397/// should be copied with __builtin_memcpy rather than via explicit assignments,
8398/// do so. This optimization only applies for arrays of scalars, and for arrays
8399/// of class type where the selected copy/move-assignment operator is trivial.
8400static StmtResult
8401buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8402                           Expr *To, Expr *From) {
8403  // Compute the size of the memory buffer to be copied.
8404  QualType SizeType = S.Context.getSizeType();
8405  llvm::APInt Size(S.Context.getTypeSize(SizeType),
8406                   S.Context.getTypeSizeInChars(T).getQuantity());
8407
8408  // Take the address of the field references for "from" and "to". We
8409  // directly construct UnaryOperators here because semantic analysis
8410  // does not permit us to take the address of an xvalue.
8411  From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8412                         S.Context.getPointerType(From->getType()),
8413                         VK_RValue, OK_Ordinary, Loc);
8414  To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8415                       S.Context.getPointerType(To->getType()),
8416                       VK_RValue, OK_Ordinary, Loc);
8417
8418  const Type *E = T->getBaseElementTypeUnsafe();
8419  bool NeedsCollectableMemCpy =
8420    E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8421
8422  // Create a reference to the __builtin_objc_memmove_collectable function
8423  StringRef MemCpyName = NeedsCollectableMemCpy ?
8424    "__builtin_objc_memmove_collectable" :
8425    "__builtin_memcpy";
8426  LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8427                 Sema::LookupOrdinaryName);
8428  S.LookupName(R, S.TUScope, true);
8429
8430  FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8431  if (!MemCpy)
8432    // Something went horribly wrong earlier, and we will have complained
8433    // about it.
8434    return StmtError();
8435
8436  ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8437                                            VK_RValue, Loc, 0);
8438  assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8439
8440  Expr *CallArgs[] = {
8441    To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8442  };
8443  ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8444                                    Loc, CallArgs, Loc);
8445
8446  assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8447  return S.Owned(Call.takeAs<Stmt>());
8448}
8449
8450/// \brief Builds a statement that copies/moves the given entity from \p From to
8451/// \c To.
8452///
8453/// This routine is used to copy/move the members of a class with an
8454/// implicitly-declared copy/move assignment operator. When the entities being
8455/// copied are arrays, this routine builds for loops to copy them.
8456///
8457/// \param S The Sema object used for type-checking.
8458///
8459/// \param Loc The location where the implicit copy/move is being generated.
8460///
8461/// \param T The type of the expressions being copied/moved. Both expressions
8462/// must have this type.
8463///
8464/// \param To The expression we are copying/moving to.
8465///
8466/// \param From The expression we are copying/moving from.
8467///
8468/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
8469/// Otherwise, it's a non-static member subobject.
8470///
8471/// \param Copying Whether we're copying or moving.
8472///
8473/// \param Depth Internal parameter recording the depth of the recursion.
8474///
8475/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8476/// if a memcpy should be used instead.
8477static StmtResult
8478buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8479                                 Expr *To, Expr *From,
8480                                 bool CopyingBaseSubobject, bool Copying,
8481                                 unsigned Depth = 0) {
8482  // C++11 [class.copy]p28:
8483  //   Each subobject is assigned in the manner appropriate to its type:
8484  //
8485  //     - if the subobject is of class type, as if by a call to operator= with
8486  //       the subobject as the object expression and the corresponding
8487  //       subobject of x as a single function argument (as if by explicit
8488  //       qualification; that is, ignoring any possible virtual overriding
8489  //       functions in more derived classes);
8490  //
8491  // C++03 [class.copy]p13:
8492  //     - if the subobject is of class type, the copy assignment operator for
8493  //       the class is used (as if by explicit qualification; that is,
8494  //       ignoring any possible virtual overriding functions in more derived
8495  //       classes);
8496  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8497    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8498
8499    // Look for operator=.
8500    DeclarationName Name
8501      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8502    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8503    S.LookupQualifiedName(OpLookup, ClassDecl, false);
8504
8505    // Prior to C++11, filter out any result that isn't a copy/move-assignment
8506    // operator.
8507    if (!S.getLangOpts().CPlusPlus11) {
8508      LookupResult::Filter F = OpLookup.makeFilter();
8509      while (F.hasNext()) {
8510        NamedDecl *D = F.next();
8511        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8512          if (Method->isCopyAssignmentOperator() ||
8513              (!Copying && Method->isMoveAssignmentOperator()))
8514            continue;
8515
8516        F.erase();
8517      }
8518      F.done();
8519    }
8520
8521    // Suppress the protected check (C++ [class.protected]) for each of the
8522    // assignment operators we found. This strange dance is required when
8523    // we're assigning via a base classes's copy-assignment operator. To
8524    // ensure that we're getting the right base class subobject (without
8525    // ambiguities), we need to cast "this" to that subobject type; to
8526    // ensure that we don't go through the virtual call mechanism, we need
8527    // to qualify the operator= name with the base class (see below). However,
8528    // this means that if the base class has a protected copy assignment
8529    // operator, the protected member access check will fail. So, we
8530    // rewrite "protected" access to "public" access in this case, since we
8531    // know by construction that we're calling from a derived class.
8532    if (CopyingBaseSubobject) {
8533      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8534           L != LEnd; ++L) {
8535        if (L.getAccess() == AS_protected)
8536          L.setAccess(AS_public);
8537      }
8538    }
8539
8540    // Create the nested-name-specifier that will be used to qualify the
8541    // reference to operator=; this is required to suppress the virtual
8542    // call mechanism.
8543    CXXScopeSpec SS;
8544    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
8545    SS.MakeTrivial(S.Context,
8546                   NestedNameSpecifier::Create(S.Context, 0, false,
8547                                               CanonicalT),
8548                   Loc);
8549
8550    // Create the reference to operator=.
8551    ExprResult OpEqualRef
8552      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
8553                                   /*TemplateKWLoc=*/SourceLocation(),
8554                                   /*FirstQualifierInScope=*/0,
8555                                   OpLookup,
8556                                   /*TemplateArgs=*/0,
8557                                   /*SuppressQualifierCheck=*/true);
8558    if (OpEqualRef.isInvalid())
8559      return StmtError();
8560
8561    // Build the call to the assignment operator.
8562
8563    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
8564                                                  OpEqualRef.takeAs<Expr>(),
8565                                                  Loc, &From, 1, Loc);
8566    if (Call.isInvalid())
8567      return StmtError();
8568
8569    // If we built a call to a trivial 'operator=' while copying an array,
8570    // bail out. We'll replace the whole shebang with a memcpy.
8571    CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8572    if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8573      return StmtResult((Stmt*)0);
8574
8575    // Convert to an expression-statement, and clean up any produced
8576    // temporaries.
8577    return S.ActOnExprStmt(Call);
8578  }
8579
8580  //     - if the subobject is of scalar type, the built-in assignment
8581  //       operator is used.
8582  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
8583  if (!ArrayTy) {
8584    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
8585    if (Assignment.isInvalid())
8586      return StmtError();
8587    return S.ActOnExprStmt(Assignment);
8588  }
8589
8590  //     - if the subobject is an array, each element is assigned, in the
8591  //       manner appropriate to the element type;
8592
8593  // Construct a loop over the array bounds, e.g.,
8594  //
8595  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8596  //
8597  // that will copy each of the array elements.
8598  QualType SizeType = S.Context.getSizeType();
8599
8600  // Create the iteration variable.
8601  IdentifierInfo *IterationVarName = 0;
8602  {
8603    SmallString<8> Str;
8604    llvm::raw_svector_ostream OS(Str);
8605    OS << "__i" << Depth;
8606    IterationVarName = &S.Context.Idents.get(OS.str());
8607  }
8608  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
8609                                          IterationVarName, SizeType,
8610                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
8611                                          SC_None);
8612
8613  // Initialize the iteration variable to zero.
8614  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8615  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8616
8617  // Create a reference to the iteration variable; we'll use this several
8618  // times throughout.
8619  Expr *IterationVarRef
8620    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
8621  assert(IterationVarRef && "Reference to invented variable cannot fail!");
8622  Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8623  assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8624
8625  // Create the DeclStmt that holds the iteration variable.
8626  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
8627
8628  // Subscript the "from" and "to" expressions with the iteration variable.
8629  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
8630                                                         IterationVarRefRVal,
8631                                                         Loc));
8632  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
8633                                                       IterationVarRefRVal,
8634                                                       Loc));
8635  if (!Copying) // Cast to rvalue
8636    From = CastForMoving(S, From);
8637
8638  // Build the copy/move for an individual element of the array.
8639  StmtResult Copy =
8640    buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8641                                     To, From, CopyingBaseSubobject,
8642                                     Copying, Depth + 1);
8643  // Bail out if copying fails or if we determined that we should use memcpy.
8644  if (Copy.isInvalid() || !Copy.get())
8645    return Copy;
8646
8647  // Create the comparison against the array bound.
8648  llvm::APInt Upper
8649    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8650  Expr *Comparison
8651    = new (S.Context) BinaryOperator(IterationVarRefRVal,
8652                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8653                                     BO_NE, S.Context.BoolTy,
8654                                     VK_RValue, OK_Ordinary, Loc, false);
8655
8656  // Create the pre-increment of the iteration variable.
8657  Expr *Increment
8658    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8659                                    VK_LValue, OK_Ordinary, Loc);
8660
8661  // Construct the loop that copies all elements of this array.
8662  return S.ActOnForStmt(Loc, Loc, InitStmt,
8663                        S.MakeFullExpr(Comparison),
8664                        0, S.MakeFullDiscardedValueExpr(Increment),
8665                        Loc, Copy.take());
8666}
8667
8668static StmtResult
8669buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8670                      Expr *To, Expr *From,
8671                      bool CopyingBaseSubobject, bool Copying) {
8672  // Maybe we should use a memcpy?
8673  if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8674      T.isTriviallyCopyableType(S.Context))
8675    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8676
8677  StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8678                                                     CopyingBaseSubobject,
8679                                                     Copying, 0));
8680
8681  // If we ended up picking a trivial assignment operator for an array of a
8682  // non-trivially-copyable class type, just emit a memcpy.
8683  if (!Result.isInvalid() && !Result.get())
8684    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8685
8686  return Result;
8687}
8688
8689Sema::ImplicitExceptionSpecification
8690Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8691  CXXRecordDecl *ClassDecl = MD->getParent();
8692
8693  ImplicitExceptionSpecification ExceptSpec(*this);
8694  if (ClassDecl->isInvalidDecl())
8695    return ExceptSpec;
8696
8697  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8698  assert(T->getNumArgs() == 1 && "not a copy assignment op");
8699  unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8700
8701  // C++ [except.spec]p14:
8702  //   An implicitly declared special member function (Clause 12) shall have an
8703  //   exception-specification. [...]
8704
8705  // It is unspecified whether or not an implicit copy assignment operator
8706  // attempts to deduplicate calls to assignment operators of virtual bases are
8707  // made. As such, this exception specification is effectively unspecified.
8708  // Based on a similar decision made for constness in C++0x, we're erring on
8709  // the side of assuming such calls to be made regardless of whether they
8710  // actually happen.
8711  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8712                                       BaseEnd = ClassDecl->bases_end();
8713       Base != BaseEnd; ++Base) {
8714    if (Base->isVirtual())
8715      continue;
8716
8717    CXXRecordDecl *BaseClassDecl
8718      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8719    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8720                                                            ArgQuals, false, 0))
8721      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8722  }
8723
8724  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8725                                       BaseEnd = ClassDecl->vbases_end();
8726       Base != BaseEnd; ++Base) {
8727    CXXRecordDecl *BaseClassDecl
8728      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8729    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8730                                                            ArgQuals, false, 0))
8731      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8732  }
8733
8734  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8735                                  FieldEnd = ClassDecl->field_end();
8736       Field != FieldEnd;
8737       ++Field) {
8738    QualType FieldType = Context.getBaseElementType(Field->getType());
8739    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8740      if (CXXMethodDecl *CopyAssign =
8741          LookupCopyingAssignment(FieldClassDecl,
8742                                  ArgQuals | FieldType.getCVRQualifiers(),
8743                                  false, 0))
8744        ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
8745    }
8746  }
8747
8748  return ExceptSpec;
8749}
8750
8751CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8752  // Note: The following rules are largely analoguous to the copy
8753  // constructor rules. Note that virtual bases are not taken into account
8754  // for determining the argument type of the operator. Note also that
8755  // operators taking an object instead of a reference are allowed.
8756  assert(ClassDecl->needsImplicitCopyAssignment());
8757
8758  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8759  if (DSM.isAlreadyBeingDeclared())
8760    return 0;
8761
8762  QualType ArgType = Context.getTypeDeclType(ClassDecl);
8763  QualType RetType = Context.getLValueReferenceType(ArgType);
8764  if (ClassDecl->implicitCopyAssignmentHasConstParam())
8765    ArgType = ArgType.withConst();
8766  ArgType = Context.getLValueReferenceType(ArgType);
8767
8768  //   An implicitly-declared copy assignment operator is an inline public
8769  //   member of its class.
8770  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8771  SourceLocation ClassLoc = ClassDecl->getLocation();
8772  DeclarationNameInfo NameInfo(Name, ClassLoc);
8773  CXXMethodDecl *CopyAssignment
8774    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8775                            /*TInfo=*/0,
8776                            /*StorageClass=*/SC_None,
8777                            /*isInline=*/true, /*isConstexpr=*/false,
8778                            SourceLocation());
8779  CopyAssignment->setAccess(AS_public);
8780  CopyAssignment->setDefaulted();
8781  CopyAssignment->setImplicit();
8782
8783  // Build an exception specification pointing back at this member.
8784  FunctionProtoType::ExtProtoInfo EPI;
8785  EPI.ExceptionSpecType = EST_Unevaluated;
8786  EPI.ExceptionSpecDecl = CopyAssignment;
8787  CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
8788
8789  // Add the parameter to the operator.
8790  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
8791                                               ClassLoc, ClassLoc, /*Id=*/0,
8792                                               ArgType, /*TInfo=*/0,
8793                                               SC_None, 0);
8794  CopyAssignment->setParams(FromParam);
8795
8796  AddOverriddenMethods(ClassDecl, CopyAssignment);
8797
8798  CopyAssignment->setTrivial(
8799    ClassDecl->needsOverloadResolutionForCopyAssignment()
8800      ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8801      : ClassDecl->hasTrivialCopyAssignment());
8802
8803  // C++0x [class.copy]p19:
8804  //   ....  If the class definition does not explicitly declare a copy
8805  //   assignment operator, there is no user-declared move constructor, and
8806  //   there is no user-declared move assignment operator, a copy assignment
8807  //   operator is implicitly declared as defaulted.
8808  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
8809    SetDeclDeleted(CopyAssignment, ClassLoc);
8810
8811  // Note that we have added this copy-assignment operator.
8812  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8813
8814  if (Scope *S = getScopeForContext(ClassDecl))
8815    PushOnScopeChains(CopyAssignment, S, false);
8816  ClassDecl->addDecl(CopyAssignment);
8817
8818  return CopyAssignment;
8819}
8820
8821void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8822                                        CXXMethodDecl *CopyAssignOperator) {
8823  assert((CopyAssignOperator->isDefaulted() &&
8824          CopyAssignOperator->isOverloadedOperator() &&
8825          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
8826          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8827          !CopyAssignOperator->isDeleted()) &&
8828         "DefineImplicitCopyAssignment called for wrong function");
8829
8830  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8831
8832  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8833    CopyAssignOperator->setInvalidDecl();
8834    return;
8835  }
8836
8837  CopyAssignOperator->setUsed();
8838
8839  SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
8840  DiagnosticErrorTrap Trap(Diags);
8841
8842  // C++0x [class.copy]p30:
8843  //   The implicitly-defined or explicitly-defaulted copy assignment operator
8844  //   for a non-union class X performs memberwise copy assignment of its
8845  //   subobjects. The direct base classes of X are assigned first, in the
8846  //   order of their declaration in the base-specifier-list, and then the
8847  //   immediate non-static data members of X are assigned, in the order in
8848  //   which they were declared in the class definition.
8849
8850  // The statements that form the synthesized function body.
8851  SmallVector<Stmt*, 8> Statements;
8852
8853  // The parameter for the "other" object, which we are copying from.
8854  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8855  Qualifiers OtherQuals = Other->getType().getQualifiers();
8856  QualType OtherRefType = Other->getType();
8857  if (const LValueReferenceType *OtherRef
8858                                = OtherRefType->getAs<LValueReferenceType>()) {
8859    OtherRefType = OtherRef->getPointeeType();
8860    OtherQuals = OtherRefType.getQualifiers();
8861  }
8862
8863  // Our location for everything implicitly-generated.
8864  SourceLocation Loc = CopyAssignOperator->getLocation();
8865
8866  // Construct a reference to the "other" object. We'll be using this
8867  // throughout the generated ASTs.
8868  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8869  assert(OtherRef && "Reference to parameter cannot fail!");
8870
8871  // Construct the "this" pointer. We'll be using this throughout the generated
8872  // ASTs.
8873  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8874  assert(This && "Reference to this cannot fail!");
8875
8876  // Assign base classes.
8877  bool Invalid = false;
8878  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8879       E = ClassDecl->bases_end(); Base != E; ++Base) {
8880    // Form the assignment:
8881    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8882    QualType BaseType = Base->getType().getUnqualifiedType();
8883    if (!BaseType->isRecordType()) {
8884      Invalid = true;
8885      continue;
8886    }
8887
8888    CXXCastPath BasePath;
8889    BasePath.push_back(Base);
8890
8891    // Construct the "from" expression, which is an implicit cast to the
8892    // appropriately-qualified base type.
8893    Expr *From = OtherRef;
8894    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8895                             CK_UncheckedDerivedToBase,
8896                             VK_LValue, &BasePath).take();
8897
8898    // Dereference "this".
8899    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8900
8901    // Implicitly cast "this" to the appropriately-qualified base type.
8902    To = ImpCastExprToType(To.take(),
8903                           Context.getCVRQualifiedType(BaseType,
8904                                     CopyAssignOperator->getTypeQualifiers()),
8905                           CK_UncheckedDerivedToBase,
8906                           VK_LValue, &BasePath);
8907
8908    // Build the copy.
8909    StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
8910                                            To.get(), From,
8911                                            /*CopyingBaseSubobject=*/true,
8912                                            /*Copying=*/true);
8913    if (Copy.isInvalid()) {
8914      Diag(CurrentLocation, diag::note_member_synthesized_at)
8915        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8916      CopyAssignOperator->setInvalidDecl();
8917      return;
8918    }
8919
8920    // Success! Record the copy.
8921    Statements.push_back(Copy.takeAs<Expr>());
8922  }
8923
8924  // Assign non-static members.
8925  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8926                                  FieldEnd = ClassDecl->field_end();
8927       Field != FieldEnd; ++Field) {
8928    if (Field->isUnnamedBitfield())
8929      continue;
8930
8931    // Check for members of reference type; we can't copy those.
8932    if (Field->getType()->isReferenceType()) {
8933      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8934        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8935      Diag(Field->getLocation(), diag::note_declared_at);
8936      Diag(CurrentLocation, diag::note_member_synthesized_at)
8937        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8938      Invalid = true;
8939      continue;
8940    }
8941
8942    // Check for members of const-qualified, non-class type.
8943    QualType BaseType = Context.getBaseElementType(Field->getType());
8944    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8945      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8946        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8947      Diag(Field->getLocation(), diag::note_declared_at);
8948      Diag(CurrentLocation, diag::note_member_synthesized_at)
8949        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8950      Invalid = true;
8951      continue;
8952    }
8953
8954    // Suppress assigning zero-width bitfields.
8955    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8956      continue;
8957
8958    QualType FieldType = Field->getType().getNonReferenceType();
8959    if (FieldType->isIncompleteArrayType()) {
8960      assert(ClassDecl->hasFlexibleArrayMember() &&
8961             "Incomplete array type is not valid");
8962      continue;
8963    }
8964
8965    // Build references to the field in the object we're copying from and to.
8966    CXXScopeSpec SS; // Intentionally empty
8967    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8968                              LookupMemberName);
8969    MemberLookup.addDecl(*Field);
8970    MemberLookup.resolveKind();
8971    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8972                                               Loc, /*IsArrow=*/false,
8973                                               SS, SourceLocation(), 0,
8974                                               MemberLookup, 0);
8975    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8976                                             Loc, /*IsArrow=*/true,
8977                                             SS, SourceLocation(), 0,
8978                                             MemberLookup, 0);
8979    assert(!From.isInvalid() && "Implicit field reference cannot fail");
8980    assert(!To.isInvalid() && "Implicit field reference cannot fail");
8981
8982    // Build the copy of this field.
8983    StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
8984                                            To.get(), From.get(),
8985                                            /*CopyingBaseSubobject=*/false,
8986                                            /*Copying=*/true);
8987    if (Copy.isInvalid()) {
8988      Diag(CurrentLocation, diag::note_member_synthesized_at)
8989        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8990      CopyAssignOperator->setInvalidDecl();
8991      return;
8992    }
8993
8994    // Success! Record the copy.
8995    Statements.push_back(Copy.takeAs<Stmt>());
8996  }
8997
8998  if (!Invalid) {
8999    // Add a "return *this;"
9000    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9001
9002    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9003    if (Return.isInvalid())
9004      Invalid = true;
9005    else {
9006      Statements.push_back(Return.takeAs<Stmt>());
9007
9008      if (Trap.hasErrorOccurred()) {
9009        Diag(CurrentLocation, diag::note_member_synthesized_at)
9010          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9011        Invalid = true;
9012      }
9013    }
9014  }
9015
9016  if (Invalid) {
9017    CopyAssignOperator->setInvalidDecl();
9018    return;
9019  }
9020
9021  StmtResult Body;
9022  {
9023    CompoundScopeRAII CompoundScope(*this);
9024    Body = ActOnCompoundStmt(Loc, Loc, Statements,
9025                             /*isStmtExpr=*/false);
9026    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9027  }
9028  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
9029
9030  if (ASTMutationListener *L = getASTMutationListener()) {
9031    L->CompletedImplicitDefinition(CopyAssignOperator);
9032  }
9033}
9034
9035Sema::ImplicitExceptionSpecification
9036Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9037  CXXRecordDecl *ClassDecl = MD->getParent();
9038
9039  ImplicitExceptionSpecification ExceptSpec(*this);
9040  if (ClassDecl->isInvalidDecl())
9041    return ExceptSpec;
9042
9043  // C++0x [except.spec]p14:
9044  //   An implicitly declared special member function (Clause 12) shall have an
9045  //   exception-specification. [...]
9046
9047  // It is unspecified whether or not an implicit move assignment operator
9048  // attempts to deduplicate calls to assignment operators of virtual bases are
9049  // made. As such, this exception specification is effectively unspecified.
9050  // Based on a similar decision made for constness in C++0x, we're erring on
9051  // the side of assuming such calls to be made regardless of whether they
9052  // actually happen.
9053  // Note that a move constructor is not implicitly declared when there are
9054  // virtual bases, but it can still be user-declared and explicitly defaulted.
9055  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9056                                       BaseEnd = ClassDecl->bases_end();
9057       Base != BaseEnd; ++Base) {
9058    if (Base->isVirtual())
9059      continue;
9060
9061    CXXRecordDecl *BaseClassDecl
9062      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9063    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9064                                                           0, false, 0))
9065      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9066  }
9067
9068  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9069                                       BaseEnd = ClassDecl->vbases_end();
9070       Base != BaseEnd; ++Base) {
9071    CXXRecordDecl *BaseClassDecl
9072      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9073    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9074                                                           0, false, 0))
9075      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9076  }
9077
9078  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9079                                  FieldEnd = ClassDecl->field_end();
9080       Field != FieldEnd;
9081       ++Field) {
9082    QualType FieldType = Context.getBaseElementType(Field->getType());
9083    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9084      if (CXXMethodDecl *MoveAssign =
9085              LookupMovingAssignment(FieldClassDecl,
9086                                     FieldType.getCVRQualifiers(),
9087                                     false, 0))
9088        ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
9089    }
9090  }
9091
9092  return ExceptSpec;
9093}
9094
9095/// Determine whether the class type has any direct or indirect virtual base
9096/// classes which have a non-trivial move assignment operator.
9097static bool
9098hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9099  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9100                                          BaseEnd = ClassDecl->vbases_end();
9101       Base != BaseEnd; ++Base) {
9102    CXXRecordDecl *BaseClass =
9103        cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9104
9105    // Try to declare the move assignment. If it would be deleted, then the
9106    // class does not have a non-trivial move assignment.
9107    if (BaseClass->needsImplicitMoveAssignment())
9108      S.DeclareImplicitMoveAssignment(BaseClass);
9109
9110    if (BaseClass->hasNonTrivialMoveAssignment())
9111      return true;
9112  }
9113
9114  return false;
9115}
9116
9117/// Determine whether the given type either has a move constructor or is
9118/// trivially copyable.
9119static bool
9120hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9121  Type = S.Context.getBaseElementType(Type);
9122
9123  // FIXME: Technically, non-trivially-copyable non-class types, such as
9124  // reference types, are supposed to return false here, but that appears
9125  // to be a standard defect.
9126  CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
9127  if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
9128    return true;
9129
9130  if (Type.isTriviallyCopyableType(S.Context))
9131    return true;
9132
9133  if (IsConstructor) {
9134    // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9135    // give the right answer.
9136    if (ClassDecl->needsImplicitMoveConstructor())
9137      S.DeclareImplicitMoveConstructor(ClassDecl);
9138    return ClassDecl->hasMoveConstructor();
9139  }
9140
9141  // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9142  // give the right answer.
9143  if (ClassDecl->needsImplicitMoveAssignment())
9144    S.DeclareImplicitMoveAssignment(ClassDecl);
9145  return ClassDecl->hasMoveAssignment();
9146}
9147
9148/// Determine whether all non-static data members and direct or virtual bases
9149/// of class \p ClassDecl have either a move operation, or are trivially
9150/// copyable.
9151static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9152                                            bool IsConstructor) {
9153  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9154                                          BaseEnd = ClassDecl->bases_end();
9155       Base != BaseEnd; ++Base) {
9156    if (Base->isVirtual())
9157      continue;
9158
9159    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9160      return false;
9161  }
9162
9163  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9164                                          BaseEnd = ClassDecl->vbases_end();
9165       Base != BaseEnd; ++Base) {
9166    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9167      return false;
9168  }
9169
9170  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9171                                     FieldEnd = ClassDecl->field_end();
9172       Field != FieldEnd; ++Field) {
9173    if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
9174      return false;
9175  }
9176
9177  return true;
9178}
9179
9180CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9181  // C++11 [class.copy]p20:
9182  //   If the definition of a class X does not explicitly declare a move
9183  //   assignment operator, one will be implicitly declared as defaulted
9184  //   if and only if:
9185  //
9186  //   - [first 4 bullets]
9187  assert(ClassDecl->needsImplicitMoveAssignment());
9188
9189  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9190  if (DSM.isAlreadyBeingDeclared())
9191    return 0;
9192
9193  // [Checked after we build the declaration]
9194  //   - the move assignment operator would not be implicitly defined as
9195  //     deleted,
9196
9197  // [DR1402]:
9198  //   - X has no direct or indirect virtual base class with a non-trivial
9199  //     move assignment operator, and
9200  //   - each of X's non-static data members and direct or virtual base classes
9201  //     has a type that either has a move assignment operator or is trivially
9202  //     copyable.
9203  if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9204      !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9205    ClassDecl->setFailedImplicitMoveAssignment();
9206    return 0;
9207  }
9208
9209  // Note: The following rules are largely analoguous to the move
9210  // constructor rules.
9211
9212  QualType ArgType = Context.getTypeDeclType(ClassDecl);
9213  QualType RetType = Context.getLValueReferenceType(ArgType);
9214  ArgType = Context.getRValueReferenceType(ArgType);
9215
9216  //   An implicitly-declared move assignment operator is an inline public
9217  //   member of its class.
9218  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9219  SourceLocation ClassLoc = ClassDecl->getLocation();
9220  DeclarationNameInfo NameInfo(Name, ClassLoc);
9221  CXXMethodDecl *MoveAssignment
9222    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9223                            /*TInfo=*/0,
9224                            /*StorageClass=*/SC_None,
9225                            /*isInline=*/true,
9226                            /*isConstexpr=*/false,
9227                            SourceLocation());
9228  MoveAssignment->setAccess(AS_public);
9229  MoveAssignment->setDefaulted();
9230  MoveAssignment->setImplicit();
9231
9232  // Build an exception specification pointing back at this member.
9233  FunctionProtoType::ExtProtoInfo EPI;
9234  EPI.ExceptionSpecType = EST_Unevaluated;
9235  EPI.ExceptionSpecDecl = MoveAssignment;
9236  MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9237
9238  // Add the parameter to the operator.
9239  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9240                                               ClassLoc, ClassLoc, /*Id=*/0,
9241                                               ArgType, /*TInfo=*/0,
9242                                               SC_None, 0);
9243  MoveAssignment->setParams(FromParam);
9244
9245  AddOverriddenMethods(ClassDecl, MoveAssignment);
9246
9247  MoveAssignment->setTrivial(
9248    ClassDecl->needsOverloadResolutionForMoveAssignment()
9249      ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9250      : ClassDecl->hasTrivialMoveAssignment());
9251
9252  // C++0x [class.copy]p9:
9253  //   If the definition of a class X does not explicitly declare a move
9254  //   assignment operator, one will be implicitly declared as defaulted if and
9255  //   only if:
9256  //   [...]
9257  //   - the move assignment operator would not be implicitly defined as
9258  //     deleted.
9259  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
9260    // Cache this result so that we don't try to generate this over and over
9261    // on every lookup, leaking memory and wasting time.
9262    ClassDecl->setFailedImplicitMoveAssignment();
9263    return 0;
9264  }
9265
9266  // Note that we have added this copy-assignment operator.
9267  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9268
9269  if (Scope *S = getScopeForContext(ClassDecl))
9270    PushOnScopeChains(MoveAssignment, S, false);
9271  ClassDecl->addDecl(MoveAssignment);
9272
9273  return MoveAssignment;
9274}
9275
9276void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9277                                        CXXMethodDecl *MoveAssignOperator) {
9278  assert((MoveAssignOperator->isDefaulted() &&
9279          MoveAssignOperator->isOverloadedOperator() &&
9280          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
9281          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9282          !MoveAssignOperator->isDeleted()) &&
9283         "DefineImplicitMoveAssignment called for wrong function");
9284
9285  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9286
9287  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9288    MoveAssignOperator->setInvalidDecl();
9289    return;
9290  }
9291
9292  MoveAssignOperator->setUsed();
9293
9294  SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
9295  DiagnosticErrorTrap Trap(Diags);
9296
9297  // C++0x [class.copy]p28:
9298  //   The implicitly-defined or move assignment operator for a non-union class
9299  //   X performs memberwise move assignment of its subobjects. The direct base
9300  //   classes of X are assigned first, in the order of their declaration in the
9301  //   base-specifier-list, and then the immediate non-static data members of X
9302  //   are assigned, in the order in which they were declared in the class
9303  //   definition.
9304
9305  // The statements that form the synthesized function body.
9306  SmallVector<Stmt*, 8> Statements;
9307
9308  // The parameter for the "other" object, which we are move from.
9309  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9310  QualType OtherRefType = Other->getType()->
9311      getAs<RValueReferenceType>()->getPointeeType();
9312  assert(OtherRefType.getQualifiers() == 0 &&
9313         "Bad argument type of defaulted move assignment");
9314
9315  // Our location for everything implicitly-generated.
9316  SourceLocation Loc = MoveAssignOperator->getLocation();
9317
9318  // Construct a reference to the "other" object. We'll be using this
9319  // throughout the generated ASTs.
9320  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9321  assert(OtherRef && "Reference to parameter cannot fail!");
9322  // Cast to rvalue.
9323  OtherRef = CastForMoving(*this, OtherRef);
9324
9325  // Construct the "this" pointer. We'll be using this throughout the generated
9326  // ASTs.
9327  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9328  assert(This && "Reference to this cannot fail!");
9329
9330  // Assign base classes.
9331  bool Invalid = false;
9332  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9333       E = ClassDecl->bases_end(); Base != E; ++Base) {
9334    // Form the assignment:
9335    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9336    QualType BaseType = Base->getType().getUnqualifiedType();
9337    if (!BaseType->isRecordType()) {
9338      Invalid = true;
9339      continue;
9340    }
9341
9342    CXXCastPath BasePath;
9343    BasePath.push_back(Base);
9344
9345    // Construct the "from" expression, which is an implicit cast to the
9346    // appropriately-qualified base type.
9347    Expr *From = OtherRef;
9348    From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
9349                             VK_XValue, &BasePath).take();
9350
9351    // Dereference "this".
9352    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9353
9354    // Implicitly cast "this" to the appropriately-qualified base type.
9355    To = ImpCastExprToType(To.take(),
9356                           Context.getCVRQualifiedType(BaseType,
9357                                     MoveAssignOperator->getTypeQualifiers()),
9358                           CK_UncheckedDerivedToBase,
9359                           VK_LValue, &BasePath);
9360
9361    // Build the move.
9362    StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
9363                                            To.get(), From,
9364                                            /*CopyingBaseSubobject=*/true,
9365                                            /*Copying=*/false);
9366    if (Move.isInvalid()) {
9367      Diag(CurrentLocation, diag::note_member_synthesized_at)
9368        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9369      MoveAssignOperator->setInvalidDecl();
9370      return;
9371    }
9372
9373    // Success! Record the move.
9374    Statements.push_back(Move.takeAs<Expr>());
9375  }
9376
9377  // Assign non-static members.
9378  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9379                                  FieldEnd = ClassDecl->field_end();
9380       Field != FieldEnd; ++Field) {
9381    if (Field->isUnnamedBitfield())
9382      continue;
9383
9384    // Check for members of reference type; we can't move those.
9385    if (Field->getType()->isReferenceType()) {
9386      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9387        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9388      Diag(Field->getLocation(), diag::note_declared_at);
9389      Diag(CurrentLocation, diag::note_member_synthesized_at)
9390        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9391      Invalid = true;
9392      continue;
9393    }
9394
9395    // Check for members of const-qualified, non-class type.
9396    QualType BaseType = Context.getBaseElementType(Field->getType());
9397    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9398      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9399        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9400      Diag(Field->getLocation(), diag::note_declared_at);
9401      Diag(CurrentLocation, diag::note_member_synthesized_at)
9402        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9403      Invalid = true;
9404      continue;
9405    }
9406
9407    // Suppress assigning zero-width bitfields.
9408    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9409      continue;
9410
9411    QualType FieldType = Field->getType().getNonReferenceType();
9412    if (FieldType->isIncompleteArrayType()) {
9413      assert(ClassDecl->hasFlexibleArrayMember() &&
9414             "Incomplete array type is not valid");
9415      continue;
9416    }
9417
9418    // Build references to the field in the object we're copying from and to.
9419    CXXScopeSpec SS; // Intentionally empty
9420    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9421                              LookupMemberName);
9422    MemberLookup.addDecl(*Field);
9423    MemberLookup.resolveKind();
9424    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9425                                               Loc, /*IsArrow=*/false,
9426                                               SS, SourceLocation(), 0,
9427                                               MemberLookup, 0);
9428    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9429                                             Loc, /*IsArrow=*/true,
9430                                             SS, SourceLocation(), 0,
9431                                             MemberLookup, 0);
9432    assert(!From.isInvalid() && "Implicit field reference cannot fail");
9433    assert(!To.isInvalid() && "Implicit field reference cannot fail");
9434
9435    assert(!From.get()->isLValue() && // could be xvalue or prvalue
9436        "Member reference with rvalue base must be rvalue except for reference "
9437        "members, which aren't allowed for move assignment.");
9438
9439    // Build the move of this field.
9440    StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
9441                                            To.get(), From.get(),
9442                                            /*CopyingBaseSubobject=*/false,
9443                                            /*Copying=*/false);
9444    if (Move.isInvalid()) {
9445      Diag(CurrentLocation, diag::note_member_synthesized_at)
9446        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9447      MoveAssignOperator->setInvalidDecl();
9448      return;
9449    }
9450
9451    // Success! Record the copy.
9452    Statements.push_back(Move.takeAs<Stmt>());
9453  }
9454
9455  if (!Invalid) {
9456    // Add a "return *this;"
9457    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9458
9459    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9460    if (Return.isInvalid())
9461      Invalid = true;
9462    else {
9463      Statements.push_back(Return.takeAs<Stmt>());
9464
9465      if (Trap.hasErrorOccurred()) {
9466        Diag(CurrentLocation, diag::note_member_synthesized_at)
9467          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9468        Invalid = true;
9469      }
9470    }
9471  }
9472
9473  if (Invalid) {
9474    MoveAssignOperator->setInvalidDecl();
9475    return;
9476  }
9477
9478  StmtResult Body;
9479  {
9480    CompoundScopeRAII CompoundScope(*this);
9481    Body = ActOnCompoundStmt(Loc, Loc, Statements,
9482                             /*isStmtExpr=*/false);
9483    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9484  }
9485  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9486
9487  if (ASTMutationListener *L = getASTMutationListener()) {
9488    L->CompletedImplicitDefinition(MoveAssignOperator);
9489  }
9490}
9491
9492Sema::ImplicitExceptionSpecification
9493Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9494  CXXRecordDecl *ClassDecl = MD->getParent();
9495
9496  ImplicitExceptionSpecification ExceptSpec(*this);
9497  if (ClassDecl->isInvalidDecl())
9498    return ExceptSpec;
9499
9500  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9501  assert(T->getNumArgs() >= 1 && "not a copy ctor");
9502  unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9503
9504  // C++ [except.spec]p14:
9505  //   An implicitly declared special member function (Clause 12) shall have an
9506  //   exception-specification. [...]
9507  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9508                                       BaseEnd = ClassDecl->bases_end();
9509       Base != BaseEnd;
9510       ++Base) {
9511    // Virtual bases are handled below.
9512    if (Base->isVirtual())
9513      continue;
9514
9515    CXXRecordDecl *BaseClassDecl
9516      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9517    if (CXXConstructorDecl *CopyConstructor =
9518          LookupCopyingConstructor(BaseClassDecl, Quals))
9519      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9520  }
9521  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9522                                       BaseEnd = ClassDecl->vbases_end();
9523       Base != BaseEnd;
9524       ++Base) {
9525    CXXRecordDecl *BaseClassDecl
9526      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9527    if (CXXConstructorDecl *CopyConstructor =
9528          LookupCopyingConstructor(BaseClassDecl, Quals))
9529      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9530  }
9531  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9532                                  FieldEnd = ClassDecl->field_end();
9533       Field != FieldEnd;
9534       ++Field) {
9535    QualType FieldType = Context.getBaseElementType(Field->getType());
9536    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9537      if (CXXConstructorDecl *CopyConstructor =
9538              LookupCopyingConstructor(FieldClassDecl,
9539                                       Quals | FieldType.getCVRQualifiers()))
9540      ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
9541    }
9542  }
9543
9544  return ExceptSpec;
9545}
9546
9547CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9548                                                    CXXRecordDecl *ClassDecl) {
9549  // C++ [class.copy]p4:
9550  //   If the class definition does not explicitly declare a copy
9551  //   constructor, one is declared implicitly.
9552  assert(ClassDecl->needsImplicitCopyConstructor());
9553
9554  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9555  if (DSM.isAlreadyBeingDeclared())
9556    return 0;
9557
9558  QualType ClassType = Context.getTypeDeclType(ClassDecl);
9559  QualType ArgType = ClassType;
9560  bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
9561  if (Const)
9562    ArgType = ArgType.withConst();
9563  ArgType = Context.getLValueReferenceType(ArgType);
9564
9565  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9566                                                     CXXCopyConstructor,
9567                                                     Const);
9568
9569  DeclarationName Name
9570    = Context.DeclarationNames.getCXXConstructorName(
9571                                           Context.getCanonicalType(ClassType));
9572  SourceLocation ClassLoc = ClassDecl->getLocation();
9573  DeclarationNameInfo NameInfo(Name, ClassLoc);
9574
9575  //   An implicitly-declared copy constructor is an inline public
9576  //   member of its class.
9577  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
9578      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9579      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9580      Constexpr);
9581  CopyConstructor->setAccess(AS_public);
9582  CopyConstructor->setDefaulted();
9583
9584  // Build an exception specification pointing back at this member.
9585  FunctionProtoType::ExtProtoInfo EPI;
9586  EPI.ExceptionSpecType = EST_Unevaluated;
9587  EPI.ExceptionSpecDecl = CopyConstructor;
9588  CopyConstructor->setType(
9589      Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9590
9591  // Add the parameter to the constructor.
9592  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
9593                                               ClassLoc, ClassLoc,
9594                                               /*IdentifierInfo=*/0,
9595                                               ArgType, /*TInfo=*/0,
9596                                               SC_None, 0);
9597  CopyConstructor->setParams(FromParam);
9598
9599  CopyConstructor->setTrivial(
9600    ClassDecl->needsOverloadResolutionForCopyConstructor()
9601      ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9602      : ClassDecl->hasTrivialCopyConstructor());
9603
9604  // C++11 [class.copy]p8:
9605  //   ... If the class definition does not explicitly declare a copy
9606  //   constructor, there is no user-declared move constructor, and there is no
9607  //   user-declared move assignment operator, a copy constructor is implicitly
9608  //   declared as defaulted.
9609  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
9610    SetDeclDeleted(CopyConstructor, ClassLoc);
9611
9612  // Note that we have declared this constructor.
9613  ++ASTContext::NumImplicitCopyConstructorsDeclared;
9614
9615  if (Scope *S = getScopeForContext(ClassDecl))
9616    PushOnScopeChains(CopyConstructor, S, false);
9617  ClassDecl->addDecl(CopyConstructor);
9618
9619  return CopyConstructor;
9620}
9621
9622void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
9623                                   CXXConstructorDecl *CopyConstructor) {
9624  assert((CopyConstructor->isDefaulted() &&
9625          CopyConstructor->isCopyConstructor() &&
9626          !CopyConstructor->doesThisDeclarationHaveABody() &&
9627          !CopyConstructor->isDeleted()) &&
9628         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
9629
9630  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
9631  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
9632
9633  SynthesizedFunctionScope Scope(*this, CopyConstructor);
9634  DiagnosticErrorTrap Trap(Diags);
9635
9636  if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
9637      Trap.hasErrorOccurred()) {
9638    Diag(CurrentLocation, diag::note_member_synthesized_at)
9639      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
9640    CopyConstructor->setInvalidDecl();
9641  }  else {
9642    Sema::CompoundScopeRAII CompoundScope(*this);
9643    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9644                                               CopyConstructor->getLocation(),
9645                                               MultiStmtArg(),
9646                                               /*isStmtExpr=*/false)
9647                                                              .takeAs<Stmt>());
9648    CopyConstructor->setImplicitlyDefined(true);
9649  }
9650
9651  CopyConstructor->setUsed();
9652  if (ASTMutationListener *L = getASTMutationListener()) {
9653    L->CompletedImplicitDefinition(CopyConstructor);
9654  }
9655}
9656
9657Sema::ImplicitExceptionSpecification
9658Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9659  CXXRecordDecl *ClassDecl = MD->getParent();
9660
9661  // C++ [except.spec]p14:
9662  //   An implicitly declared special member function (Clause 12) shall have an
9663  //   exception-specification. [...]
9664  ImplicitExceptionSpecification ExceptSpec(*this);
9665  if (ClassDecl->isInvalidDecl())
9666    return ExceptSpec;
9667
9668  // Direct base-class constructors.
9669  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9670                                       BEnd = ClassDecl->bases_end();
9671       B != BEnd; ++B) {
9672    if (B->isVirtual()) // Handled below.
9673      continue;
9674
9675    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9676      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9677      CXXConstructorDecl *Constructor =
9678          LookupMovingConstructor(BaseClassDecl, 0);
9679      // If this is a deleted function, add it anyway. This might be conformant
9680      // with the standard. This might not. I'm not sure. It might not matter.
9681      if (Constructor)
9682        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9683    }
9684  }
9685
9686  // Virtual base-class constructors.
9687  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9688                                       BEnd = ClassDecl->vbases_end();
9689       B != BEnd; ++B) {
9690    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9691      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9692      CXXConstructorDecl *Constructor =
9693          LookupMovingConstructor(BaseClassDecl, 0);
9694      // If this is a deleted function, add it anyway. This might be conformant
9695      // with the standard. This might not. I'm not sure. It might not matter.
9696      if (Constructor)
9697        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9698    }
9699  }
9700
9701  // Field constructors.
9702  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9703                               FEnd = ClassDecl->field_end();
9704       F != FEnd; ++F) {
9705    QualType FieldType = Context.getBaseElementType(F->getType());
9706    if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9707      CXXConstructorDecl *Constructor =
9708          LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
9709      // If this is a deleted function, add it anyway. This might be conformant
9710      // with the standard. This might not. I'm not sure. It might not matter.
9711      // In particular, the problem is that this function never gets called. It
9712      // might just be ill-formed because this function attempts to refer to
9713      // a deleted function here.
9714      if (Constructor)
9715        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9716    }
9717  }
9718
9719  return ExceptSpec;
9720}
9721
9722CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9723                                                    CXXRecordDecl *ClassDecl) {
9724  // C++11 [class.copy]p9:
9725  //   If the definition of a class X does not explicitly declare a move
9726  //   constructor, one will be implicitly declared as defaulted if and only if:
9727  //
9728  //   - [first 4 bullets]
9729  assert(ClassDecl->needsImplicitMoveConstructor());
9730
9731  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9732  if (DSM.isAlreadyBeingDeclared())
9733    return 0;
9734
9735  // [Checked after we build the declaration]
9736  //   - the move assignment operator would not be implicitly defined as
9737  //     deleted,
9738
9739  // [DR1402]:
9740  //   - each of X's non-static data members and direct or virtual base classes
9741  //     has a type that either has a move constructor or is trivially copyable.
9742  if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9743    ClassDecl->setFailedImplicitMoveConstructor();
9744    return 0;
9745  }
9746
9747  QualType ClassType = Context.getTypeDeclType(ClassDecl);
9748  QualType ArgType = Context.getRValueReferenceType(ClassType);
9749
9750  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9751                                                     CXXMoveConstructor,
9752                                                     false);
9753
9754  DeclarationName Name
9755    = Context.DeclarationNames.getCXXConstructorName(
9756                                           Context.getCanonicalType(ClassType));
9757  SourceLocation ClassLoc = ClassDecl->getLocation();
9758  DeclarationNameInfo NameInfo(Name, ClassLoc);
9759
9760  // C++0x [class.copy]p11:
9761  //   An implicitly-declared copy/move constructor is an inline public
9762  //   member of its class.
9763  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
9764      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9765      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9766      Constexpr);
9767  MoveConstructor->setAccess(AS_public);
9768  MoveConstructor->setDefaulted();
9769
9770  // Build an exception specification pointing back at this member.
9771  FunctionProtoType::ExtProtoInfo EPI;
9772  EPI.ExceptionSpecType = EST_Unevaluated;
9773  EPI.ExceptionSpecDecl = MoveConstructor;
9774  MoveConstructor->setType(
9775      Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9776
9777  // Add the parameter to the constructor.
9778  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9779                                               ClassLoc, ClassLoc,
9780                                               /*IdentifierInfo=*/0,
9781                                               ArgType, /*TInfo=*/0,
9782                                               SC_None, 0);
9783  MoveConstructor->setParams(FromParam);
9784
9785  MoveConstructor->setTrivial(
9786    ClassDecl->needsOverloadResolutionForMoveConstructor()
9787      ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9788      : ClassDecl->hasTrivialMoveConstructor());
9789
9790  // C++0x [class.copy]p9:
9791  //   If the definition of a class X does not explicitly declare a move
9792  //   constructor, one will be implicitly declared as defaulted if and only if:
9793  //   [...]
9794  //   - the move constructor would not be implicitly defined as deleted.
9795  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
9796    // Cache this result so that we don't try to generate this over and over
9797    // on every lookup, leaking memory and wasting time.
9798    ClassDecl->setFailedImplicitMoveConstructor();
9799    return 0;
9800  }
9801
9802  // Note that we have declared this constructor.
9803  ++ASTContext::NumImplicitMoveConstructorsDeclared;
9804
9805  if (Scope *S = getScopeForContext(ClassDecl))
9806    PushOnScopeChains(MoveConstructor, S, false);
9807  ClassDecl->addDecl(MoveConstructor);
9808
9809  return MoveConstructor;
9810}
9811
9812void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9813                                   CXXConstructorDecl *MoveConstructor) {
9814  assert((MoveConstructor->isDefaulted() &&
9815          MoveConstructor->isMoveConstructor() &&
9816          !MoveConstructor->doesThisDeclarationHaveABody() &&
9817          !MoveConstructor->isDeleted()) &&
9818         "DefineImplicitMoveConstructor - call it for implicit move ctor");
9819
9820  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9821  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9822
9823  SynthesizedFunctionScope Scope(*this, MoveConstructor);
9824  DiagnosticErrorTrap Trap(Diags);
9825
9826  if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
9827      Trap.hasErrorOccurred()) {
9828    Diag(CurrentLocation, diag::note_member_synthesized_at)
9829      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9830    MoveConstructor->setInvalidDecl();
9831  }  else {
9832    Sema::CompoundScopeRAII CompoundScope(*this);
9833    MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9834                                               MoveConstructor->getLocation(),
9835                                               MultiStmtArg(),
9836                                               /*isStmtExpr=*/false)
9837                                                              .takeAs<Stmt>());
9838    MoveConstructor->setImplicitlyDefined(true);
9839  }
9840
9841  MoveConstructor->setUsed();
9842
9843  if (ASTMutationListener *L = getASTMutationListener()) {
9844    L->CompletedImplicitDefinition(MoveConstructor);
9845  }
9846}
9847
9848bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9849  return FD->isDeleted() &&
9850         (FD->isDefaulted() || FD->isImplicit()) &&
9851         isa<CXXMethodDecl>(FD);
9852}
9853
9854/// \brief Mark the call operator of the given lambda closure type as "used".
9855static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9856  CXXMethodDecl *CallOperator
9857    = cast<CXXMethodDecl>(
9858        Lambda->lookup(
9859          S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
9860  CallOperator->setReferenced();
9861  CallOperator->setUsed();
9862}
9863
9864void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9865       SourceLocation CurrentLocation,
9866       CXXConversionDecl *Conv)
9867{
9868  CXXRecordDecl *Lambda = Conv->getParent();
9869
9870  // Make sure that the lambda call operator is marked used.
9871  markLambdaCallOperatorUsed(*this, Lambda);
9872
9873  Conv->setUsed();
9874
9875  SynthesizedFunctionScope Scope(*this, Conv);
9876  DiagnosticErrorTrap Trap(Diags);
9877
9878  // Return the address of the __invoke function.
9879  DeclarationName InvokeName = &Context.Idents.get("__invoke");
9880  CXXMethodDecl *Invoke
9881    = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
9882  Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9883                                       VK_LValue, Conv->getLocation()).take();
9884  assert(FunctionRef && "Can't refer to __invoke function?");
9885  Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
9886  Conv->setBody(new (Context) CompoundStmt(Context, Return,
9887                                           Conv->getLocation(),
9888                                           Conv->getLocation()));
9889
9890  // Fill in the __invoke function with a dummy implementation. IR generation
9891  // will fill in the actual details.
9892  Invoke->setUsed();
9893  Invoke->setReferenced();
9894  Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
9895
9896  if (ASTMutationListener *L = getASTMutationListener()) {
9897    L->CompletedImplicitDefinition(Conv);
9898    L->CompletedImplicitDefinition(Invoke);
9899  }
9900}
9901
9902void Sema::DefineImplicitLambdaToBlockPointerConversion(
9903       SourceLocation CurrentLocation,
9904       CXXConversionDecl *Conv)
9905{
9906  Conv->setUsed();
9907
9908  SynthesizedFunctionScope Scope(*this, Conv);
9909  DiagnosticErrorTrap Trap(Diags);
9910
9911  // Copy-initialize the lambda object as needed to capture it.
9912  Expr *This = ActOnCXXThis(CurrentLocation).take();
9913  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
9914
9915  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9916                                                        Conv->getLocation(),
9917                                                        Conv, DerefThis);
9918
9919  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9920  // behavior.  Note that only the general conversion function does this
9921  // (since it's unusable otherwise); in the case where we inline the
9922  // block literal, it has block literal lifetime semantics.
9923  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
9924    BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9925                                          CK_CopyAndAutoreleaseBlockObject,
9926                                          BuildBlock.get(), 0, VK_RValue);
9927
9928  if (BuildBlock.isInvalid()) {
9929    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9930    Conv->setInvalidDecl();
9931    return;
9932  }
9933
9934  // Create the return statement that returns the block from the conversion
9935  // function.
9936  StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
9937  if (Return.isInvalid()) {
9938    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9939    Conv->setInvalidDecl();
9940    return;
9941  }
9942
9943  // Set the body of the conversion function.
9944  Stmt *ReturnS = Return.take();
9945  Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
9946                                           Conv->getLocation(),
9947                                           Conv->getLocation()));
9948
9949  // We're done; notify the mutation listener, if any.
9950  if (ASTMutationListener *L = getASTMutationListener()) {
9951    L->CompletedImplicitDefinition(Conv);
9952  }
9953}
9954
9955/// \brief Determine whether the given list arguments contains exactly one
9956/// "real" (non-default) argument.
9957static bool hasOneRealArgument(MultiExprArg Args) {
9958  switch (Args.size()) {
9959  case 0:
9960    return false;
9961
9962  default:
9963    if (!Args[1]->isDefaultArgument())
9964      return false;
9965
9966    // fall through
9967  case 1:
9968    return !Args[0]->isDefaultArgument();
9969  }
9970
9971  return false;
9972}
9973
9974ExprResult
9975Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9976                            CXXConstructorDecl *Constructor,
9977                            MultiExprArg ExprArgs,
9978                            bool HadMultipleCandidates,
9979                            bool IsListInitialization,
9980                            bool RequiresZeroInit,
9981                            unsigned ConstructKind,
9982                            SourceRange ParenRange) {
9983  bool Elidable = false;
9984
9985  // C++0x [class.copy]p34:
9986  //   When certain criteria are met, an implementation is allowed to
9987  //   omit the copy/move construction of a class object, even if the
9988  //   copy/move constructor and/or destructor for the object have
9989  //   side effects. [...]
9990  //     - when a temporary class object that has not been bound to a
9991  //       reference (12.2) would be copied/moved to a class object
9992  //       with the same cv-unqualified type, the copy/move operation
9993  //       can be omitted by constructing the temporary object
9994  //       directly into the target of the omitted copy/move
9995  if (ConstructKind == CXXConstructExpr::CK_Complete &&
9996      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
9997    Expr *SubExpr = ExprArgs[0];
9998    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
9999  }
10000
10001  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
10002                               Elidable, ExprArgs, HadMultipleCandidates,
10003                               IsListInitialization, RequiresZeroInit,
10004                               ConstructKind, ParenRange);
10005}
10006
10007/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10008/// including handling of its default argument expressions.
10009ExprResult
10010Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10011                            CXXConstructorDecl *Constructor, bool Elidable,
10012                            MultiExprArg ExprArgs,
10013                            bool HadMultipleCandidates,
10014                            bool IsListInitialization,
10015                            bool RequiresZeroInit,
10016                            unsigned ConstructKind,
10017                            SourceRange ParenRange) {
10018  MarkFunctionReferenced(ConstructLoc, Constructor);
10019  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
10020                                        Constructor, Elidable, ExprArgs,
10021                                        HadMultipleCandidates,
10022                                        IsListInitialization, RequiresZeroInit,
10023              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10024                                        ParenRange));
10025}
10026
10027void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
10028  if (VD->isInvalidDecl()) return;
10029
10030  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
10031  if (ClassDecl->isInvalidDecl()) return;
10032  if (ClassDecl->hasIrrelevantDestructor()) return;
10033  if (ClassDecl->isDependentContext()) return;
10034
10035  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10036  MarkFunctionReferenced(VD->getLocation(), Destructor);
10037  CheckDestructorAccess(VD->getLocation(), Destructor,
10038                        PDiag(diag::err_access_dtor_var)
10039                        << VD->getDeclName()
10040                        << VD->getType());
10041  DiagnoseUseOfDecl(Destructor, VD->getLocation());
10042
10043  if (!VD->hasGlobalStorage()) return;
10044
10045  // Emit warning for non-trivial dtor in global scope (a real global,
10046  // class-static, function-static).
10047  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10048
10049  // TODO: this should be re-enabled for static locals by !CXAAtExit
10050  if (!VD->isStaticLocal())
10051    Diag(VD->getLocation(), diag::warn_global_destructor);
10052}
10053
10054/// \brief Given a constructor and the set of arguments provided for the
10055/// constructor, convert the arguments and add any required default arguments
10056/// to form a proper call to this constructor.
10057///
10058/// \returns true if an error occurred, false otherwise.
10059bool
10060Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10061                              MultiExprArg ArgsPtr,
10062                              SourceLocation Loc,
10063                              SmallVectorImpl<Expr*> &ConvertedArgs,
10064                              bool AllowExplicit,
10065                              bool IsListInitialization) {
10066  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10067  unsigned NumArgs = ArgsPtr.size();
10068  Expr **Args = ArgsPtr.data();
10069
10070  const FunctionProtoType *Proto
10071    = Constructor->getType()->getAs<FunctionProtoType>();
10072  assert(Proto && "Constructor without a prototype?");
10073  unsigned NumArgsInProto = Proto->getNumArgs();
10074
10075  // If too few arguments are available, we'll fill in the rest with defaults.
10076  if (NumArgs < NumArgsInProto)
10077    ConvertedArgs.reserve(NumArgsInProto);
10078  else
10079    ConvertedArgs.reserve(NumArgs);
10080
10081  VariadicCallType CallType =
10082    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
10083  SmallVector<Expr *, 8> AllArgs;
10084  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10085                                        Proto, 0, Args, NumArgs, AllArgs,
10086                                        CallType, AllowExplicit,
10087                                        IsListInitialization);
10088  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
10089
10090  DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
10091
10092  CheckConstructorCall(Constructor,
10093                       llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10094                                                        AllArgs.size()),
10095                       Proto, Loc);
10096
10097  return Invalid;
10098}
10099
10100static inline bool
10101CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10102                                       const FunctionDecl *FnDecl) {
10103  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
10104  if (isa<NamespaceDecl>(DC)) {
10105    return SemaRef.Diag(FnDecl->getLocation(),
10106                        diag::err_operator_new_delete_declared_in_namespace)
10107      << FnDecl->getDeclName();
10108  }
10109
10110  if (isa<TranslationUnitDecl>(DC) &&
10111      FnDecl->getStorageClass() == SC_Static) {
10112    return SemaRef.Diag(FnDecl->getLocation(),
10113                        diag::err_operator_new_delete_declared_static)
10114      << FnDecl->getDeclName();
10115  }
10116
10117  return false;
10118}
10119
10120static inline bool
10121CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10122                            CanQualType ExpectedResultType,
10123                            CanQualType ExpectedFirstParamType,
10124                            unsigned DependentParamTypeDiag,
10125                            unsigned InvalidParamTypeDiag) {
10126  QualType ResultType =
10127    FnDecl->getType()->getAs<FunctionType>()->getResultType();
10128
10129  // Check that the result type is not dependent.
10130  if (ResultType->isDependentType())
10131    return SemaRef.Diag(FnDecl->getLocation(),
10132                        diag::err_operator_new_delete_dependent_result_type)
10133    << FnDecl->getDeclName() << ExpectedResultType;
10134
10135  // Check that the result type is what we expect.
10136  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10137    return SemaRef.Diag(FnDecl->getLocation(),
10138                        diag::err_operator_new_delete_invalid_result_type)
10139    << FnDecl->getDeclName() << ExpectedResultType;
10140
10141  // A function template must have at least 2 parameters.
10142  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10143    return SemaRef.Diag(FnDecl->getLocation(),
10144                      diag::err_operator_new_delete_template_too_few_parameters)
10145        << FnDecl->getDeclName();
10146
10147  // The function decl must have at least 1 parameter.
10148  if (FnDecl->getNumParams() == 0)
10149    return SemaRef.Diag(FnDecl->getLocation(),
10150                        diag::err_operator_new_delete_too_few_parameters)
10151      << FnDecl->getDeclName();
10152
10153  // Check the first parameter type is not dependent.
10154  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10155  if (FirstParamType->isDependentType())
10156    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10157      << FnDecl->getDeclName() << ExpectedFirstParamType;
10158
10159  // Check that the first parameter type is what we expect.
10160  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10161      ExpectedFirstParamType)
10162    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10163    << FnDecl->getDeclName() << ExpectedFirstParamType;
10164
10165  return false;
10166}
10167
10168static bool
10169CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10170  // C++ [basic.stc.dynamic.allocation]p1:
10171  //   A program is ill-formed if an allocation function is declared in a
10172  //   namespace scope other than global scope or declared static in global
10173  //   scope.
10174  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10175    return true;
10176
10177  CanQualType SizeTy =
10178    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10179
10180  // C++ [basic.stc.dynamic.allocation]p1:
10181  //  The return type shall be void*. The first parameter shall have type
10182  //  std::size_t.
10183  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10184                                  SizeTy,
10185                                  diag::err_operator_new_dependent_param_type,
10186                                  diag::err_operator_new_param_type))
10187    return true;
10188
10189  // C++ [basic.stc.dynamic.allocation]p1:
10190  //  The first parameter shall not have an associated default argument.
10191  if (FnDecl->getParamDecl(0)->hasDefaultArg())
10192    return SemaRef.Diag(FnDecl->getLocation(),
10193                        diag::err_operator_new_default_arg)
10194      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10195
10196  return false;
10197}
10198
10199static bool
10200CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
10201  // C++ [basic.stc.dynamic.deallocation]p1:
10202  //   A program is ill-formed if deallocation functions are declared in a
10203  //   namespace scope other than global scope or declared static in global
10204  //   scope.
10205  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10206    return true;
10207
10208  // C++ [basic.stc.dynamic.deallocation]p2:
10209  //   Each deallocation function shall return void and its first parameter
10210  //   shall be void*.
10211  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10212                                  SemaRef.Context.VoidPtrTy,
10213                                 diag::err_operator_delete_dependent_param_type,
10214                                 diag::err_operator_delete_param_type))
10215    return true;
10216
10217  return false;
10218}
10219
10220/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10221/// of this overloaded operator is well-formed. If so, returns false;
10222/// otherwise, emits appropriate diagnostics and returns true.
10223bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
10224  assert(FnDecl && FnDecl->isOverloadedOperator() &&
10225         "Expected an overloaded operator declaration");
10226
10227  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10228
10229  // C++ [over.oper]p5:
10230  //   The allocation and deallocation functions, operator new,
10231  //   operator new[], operator delete and operator delete[], are
10232  //   described completely in 3.7.3. The attributes and restrictions
10233  //   found in the rest of this subclause do not apply to them unless
10234  //   explicitly stated in 3.7.3.
10235  if (Op == OO_Delete || Op == OO_Array_Delete)
10236    return CheckOperatorDeleteDeclaration(*this, FnDecl);
10237
10238  if (Op == OO_New || Op == OO_Array_New)
10239    return CheckOperatorNewDeclaration(*this, FnDecl);
10240
10241  // C++ [over.oper]p6:
10242  //   An operator function shall either be a non-static member
10243  //   function or be a non-member function and have at least one
10244  //   parameter whose type is a class, a reference to a class, an
10245  //   enumeration, or a reference to an enumeration.
10246  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10247    if (MethodDecl->isStatic())
10248      return Diag(FnDecl->getLocation(),
10249                  diag::err_operator_overload_static) << FnDecl->getDeclName();
10250  } else {
10251    bool ClassOrEnumParam = false;
10252    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10253                                   ParamEnd = FnDecl->param_end();
10254         Param != ParamEnd; ++Param) {
10255      QualType ParamType = (*Param)->getType().getNonReferenceType();
10256      if (ParamType->isDependentType() || ParamType->isRecordType() ||
10257          ParamType->isEnumeralType()) {
10258        ClassOrEnumParam = true;
10259        break;
10260      }
10261    }
10262
10263    if (!ClassOrEnumParam)
10264      return Diag(FnDecl->getLocation(),
10265                  diag::err_operator_overload_needs_class_or_enum)
10266        << FnDecl->getDeclName();
10267  }
10268
10269  // C++ [over.oper]p8:
10270  //   An operator function cannot have default arguments (8.3.6),
10271  //   except where explicitly stated below.
10272  //
10273  // Only the function-call operator allows default arguments
10274  // (C++ [over.call]p1).
10275  if (Op != OO_Call) {
10276    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10277         Param != FnDecl->param_end(); ++Param) {
10278      if ((*Param)->hasDefaultArg())
10279        return Diag((*Param)->getLocation(),
10280                    diag::err_operator_overload_default_arg)
10281          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
10282    }
10283  }
10284
10285  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10286    { false, false, false }
10287#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10288    , { Unary, Binary, MemberOnly }
10289#include "clang/Basic/OperatorKinds.def"
10290  };
10291
10292  bool CanBeUnaryOperator = OperatorUses[Op][0];
10293  bool CanBeBinaryOperator = OperatorUses[Op][1];
10294  bool MustBeMemberOperator = OperatorUses[Op][2];
10295
10296  // C++ [over.oper]p8:
10297  //   [...] Operator functions cannot have more or fewer parameters
10298  //   than the number required for the corresponding operator, as
10299  //   described in the rest of this subclause.
10300  unsigned NumParams = FnDecl->getNumParams()
10301                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
10302  if (Op != OO_Call &&
10303      ((NumParams == 1 && !CanBeUnaryOperator) ||
10304       (NumParams == 2 && !CanBeBinaryOperator) ||
10305       (NumParams < 1) || (NumParams > 2))) {
10306    // We have the wrong number of parameters.
10307    unsigned ErrorKind;
10308    if (CanBeUnaryOperator && CanBeBinaryOperator) {
10309      ErrorKind = 2;  // 2 -> unary or binary.
10310    } else if (CanBeUnaryOperator) {
10311      ErrorKind = 0;  // 0 -> unary
10312    } else {
10313      assert(CanBeBinaryOperator &&
10314             "All non-call overloaded operators are unary or binary!");
10315      ErrorKind = 1;  // 1 -> binary
10316    }
10317
10318    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
10319      << FnDecl->getDeclName() << NumParams << ErrorKind;
10320  }
10321
10322  // Overloaded operators other than operator() cannot be variadic.
10323  if (Op != OO_Call &&
10324      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
10325    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
10326      << FnDecl->getDeclName();
10327  }
10328
10329  // Some operators must be non-static member functions.
10330  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10331    return Diag(FnDecl->getLocation(),
10332                diag::err_operator_overload_must_be_member)
10333      << FnDecl->getDeclName();
10334  }
10335
10336  // C++ [over.inc]p1:
10337  //   The user-defined function called operator++ implements the
10338  //   prefix and postfix ++ operator. If this function is a member
10339  //   function with no parameters, or a non-member function with one
10340  //   parameter of class or enumeration type, it defines the prefix
10341  //   increment operator ++ for objects of that type. If the function
10342  //   is a member function with one parameter (which shall be of type
10343  //   int) or a non-member function with two parameters (the second
10344  //   of which shall be of type int), it defines the postfix
10345  //   increment operator ++ for objects of that type.
10346  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10347    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10348    bool ParamIsInt = false;
10349    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
10350      ParamIsInt = BT->getKind() == BuiltinType::Int;
10351
10352    if (!ParamIsInt)
10353      return Diag(LastParam->getLocation(),
10354                  diag::err_operator_overload_post_incdec_must_be_int)
10355        << LastParam->getType() << (Op == OO_MinusMinus);
10356  }
10357
10358  return false;
10359}
10360
10361/// CheckLiteralOperatorDeclaration - Check whether the declaration
10362/// of this literal operator function is well-formed. If so, returns
10363/// false; otherwise, emits appropriate diagnostics and returns true.
10364bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
10365  if (isa<CXXMethodDecl>(FnDecl)) {
10366    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10367      << FnDecl->getDeclName();
10368    return true;
10369  }
10370
10371  if (FnDecl->isExternC()) {
10372    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10373    return true;
10374  }
10375
10376  bool Valid = false;
10377
10378  // This might be the definition of a literal operator template.
10379  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10380  // This might be a specialization of a literal operator template.
10381  if (!TpDecl)
10382    TpDecl = FnDecl->getPrimaryTemplate();
10383
10384  // template <char...> type operator "" name() is the only valid template
10385  // signature, and the only valid signature with no parameters.
10386  if (TpDecl) {
10387    if (FnDecl->param_size() == 0) {
10388      // Must have only one template parameter
10389      TemplateParameterList *Params = TpDecl->getTemplateParameters();
10390      if (Params->size() == 1) {
10391        NonTypeTemplateParmDecl *PmDecl =
10392          dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
10393
10394        // The template parameter must be a char parameter pack.
10395        if (PmDecl && PmDecl->isTemplateParameterPack() &&
10396            Context.hasSameType(PmDecl->getType(), Context.CharTy))
10397          Valid = true;
10398      }
10399    }
10400  } else if (FnDecl->param_size()) {
10401    // Check the first parameter
10402    FunctionDecl::param_iterator Param = FnDecl->param_begin();
10403
10404    QualType T = (*Param)->getType().getUnqualifiedType();
10405
10406    // unsigned long long int, long double, and any character type are allowed
10407    // as the only parameters.
10408    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10409        Context.hasSameType(T, Context.LongDoubleTy) ||
10410        Context.hasSameType(T, Context.CharTy) ||
10411        Context.hasSameType(T, Context.WCharTy) ||
10412        Context.hasSameType(T, Context.Char16Ty) ||
10413        Context.hasSameType(T, Context.Char32Ty)) {
10414      if (++Param == FnDecl->param_end())
10415        Valid = true;
10416      goto FinishedParams;
10417    }
10418
10419    // Otherwise it must be a pointer to const; let's strip those qualifiers.
10420    const PointerType *PT = T->getAs<PointerType>();
10421    if (!PT)
10422      goto FinishedParams;
10423    T = PT->getPointeeType();
10424    if (!T.isConstQualified() || T.isVolatileQualified())
10425      goto FinishedParams;
10426    T = T.getUnqualifiedType();
10427
10428    // Move on to the second parameter;
10429    ++Param;
10430
10431    // If there is no second parameter, the first must be a const char *
10432    if (Param == FnDecl->param_end()) {
10433      if (Context.hasSameType(T, Context.CharTy))
10434        Valid = true;
10435      goto FinishedParams;
10436    }
10437
10438    // const char *, const wchar_t*, const char16_t*, and const char32_t*
10439    // are allowed as the first parameter to a two-parameter function
10440    if (!(Context.hasSameType(T, Context.CharTy) ||
10441          Context.hasSameType(T, Context.WCharTy) ||
10442          Context.hasSameType(T, Context.Char16Ty) ||
10443          Context.hasSameType(T, Context.Char32Ty)))
10444      goto FinishedParams;
10445
10446    // The second and final parameter must be an std::size_t
10447    T = (*Param)->getType().getUnqualifiedType();
10448    if (Context.hasSameType(T, Context.getSizeType()) &&
10449        ++Param == FnDecl->param_end())
10450      Valid = true;
10451  }
10452
10453  // FIXME: This diagnostic is absolutely terrible.
10454FinishedParams:
10455  if (!Valid) {
10456    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10457      << FnDecl->getDeclName();
10458    return true;
10459  }
10460
10461  // A parameter-declaration-clause containing a default argument is not
10462  // equivalent to any of the permitted forms.
10463  for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10464                                    ParamEnd = FnDecl->param_end();
10465       Param != ParamEnd; ++Param) {
10466    if ((*Param)->hasDefaultArg()) {
10467      Diag((*Param)->getDefaultArgRange().getBegin(),
10468           diag::err_literal_operator_default_argument)
10469        << (*Param)->getDefaultArgRange();
10470      break;
10471    }
10472  }
10473
10474  StringRef LiteralName
10475    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10476  if (LiteralName[0] != '_') {
10477    // C++11 [usrlit.suffix]p1:
10478    //   Literal suffix identifiers that do not start with an underscore
10479    //   are reserved for future standardization.
10480    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
10481  }
10482
10483  return false;
10484}
10485
10486/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10487/// linkage specification, including the language and (if present)
10488/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10489/// the location of the language string literal, which is provided
10490/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10491/// the '{' brace. Otherwise, this linkage specification does not
10492/// have any braces.
10493Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10494                                           SourceLocation LangLoc,
10495                                           StringRef Lang,
10496                                           SourceLocation LBraceLoc) {
10497  LinkageSpecDecl::LanguageIDs Language;
10498  if (Lang == "\"C\"")
10499    Language = LinkageSpecDecl::lang_c;
10500  else if (Lang == "\"C++\"")
10501    Language = LinkageSpecDecl::lang_cxx;
10502  else {
10503    Diag(LangLoc, diag::err_bad_language);
10504    return 0;
10505  }
10506
10507  // FIXME: Add all the various semantics of linkage specifications
10508
10509  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
10510                                               ExternLoc, LangLoc, Language,
10511                                               LBraceLoc.isValid());
10512  CurContext->addDecl(D);
10513  PushDeclContext(S, D);
10514  return D;
10515}
10516
10517/// ActOnFinishLinkageSpecification - Complete the definition of
10518/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10519/// valid, it's the position of the closing '}' brace in a linkage
10520/// specification that uses braces.
10521Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
10522                                            Decl *LinkageSpec,
10523                                            SourceLocation RBraceLoc) {
10524  if (LinkageSpec) {
10525    if (RBraceLoc.isValid()) {
10526      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10527      LSDecl->setRBraceLoc(RBraceLoc);
10528    }
10529    PopDeclContext();
10530  }
10531  return LinkageSpec;
10532}
10533
10534Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10535                                  AttributeList *AttrList,
10536                                  SourceLocation SemiLoc) {
10537  Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10538  // Attribute declarations appertain to empty declaration so we handle
10539  // them here.
10540  if (AttrList)
10541    ProcessDeclAttributeList(S, ED, AttrList);
10542
10543  CurContext->addDecl(ED);
10544  return ED;
10545}
10546
10547/// \brief Perform semantic analysis for the variable declaration that
10548/// occurs within a C++ catch clause, returning the newly-created
10549/// variable.
10550VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
10551                                         TypeSourceInfo *TInfo,
10552                                         SourceLocation StartLoc,
10553                                         SourceLocation Loc,
10554                                         IdentifierInfo *Name) {
10555  bool Invalid = false;
10556  QualType ExDeclType = TInfo->getType();
10557
10558  // Arrays and functions decay.
10559  if (ExDeclType->isArrayType())
10560    ExDeclType = Context.getArrayDecayedType(ExDeclType);
10561  else if (ExDeclType->isFunctionType())
10562    ExDeclType = Context.getPointerType(ExDeclType);
10563
10564  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10565  // The exception-declaration shall not denote a pointer or reference to an
10566  // incomplete type, other than [cv] void*.
10567  // N2844 forbids rvalue references.
10568  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
10569    Diag(Loc, diag::err_catch_rvalue_ref);
10570    Invalid = true;
10571  }
10572
10573  QualType BaseType = ExDeclType;
10574  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
10575  unsigned DK = diag::err_catch_incomplete;
10576  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
10577    BaseType = Ptr->getPointeeType();
10578    Mode = 1;
10579    DK = diag::err_catch_incomplete_ptr;
10580  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
10581    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
10582    BaseType = Ref->getPointeeType();
10583    Mode = 2;
10584    DK = diag::err_catch_incomplete_ref;
10585  }
10586  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
10587      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
10588    Invalid = true;
10589
10590  if (!Invalid && !ExDeclType->isDependentType() &&
10591      RequireNonAbstractType(Loc, ExDeclType,
10592                             diag::err_abstract_type_in_decl,
10593                             AbstractVariableType))
10594    Invalid = true;
10595
10596  // Only the non-fragile NeXT runtime currently supports C++ catches
10597  // of ObjC types, and no runtime supports catching ObjC types by value.
10598  if (!Invalid && getLangOpts().ObjC1) {
10599    QualType T = ExDeclType;
10600    if (const ReferenceType *RT = T->getAs<ReferenceType>())
10601      T = RT->getPointeeType();
10602
10603    if (T->isObjCObjectType()) {
10604      Diag(Loc, diag::err_objc_object_catch);
10605      Invalid = true;
10606    } else if (T->isObjCObjectPointerType()) {
10607      // FIXME: should this be a test for macosx-fragile specifically?
10608      if (getLangOpts().ObjCRuntime.isFragile())
10609        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
10610    }
10611  }
10612
10613  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10614                                    ExDeclType, TInfo, SC_None);
10615  ExDecl->setExceptionVariable(true);
10616
10617  // In ARC, infer 'retaining' for variables of retainable type.
10618  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
10619    Invalid = true;
10620
10621  if (!Invalid && !ExDeclType->isDependentType()) {
10622    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
10623      // Insulate this from anything else we might currently be parsing.
10624      EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10625
10626      // C++ [except.handle]p16:
10627      //   The object declared in an exception-declaration or, if the
10628      //   exception-declaration does not specify a name, a temporary (12.2) is
10629      //   copy-initialized (8.5) from the exception object. [...]
10630      //   The object is destroyed when the handler exits, after the destruction
10631      //   of any automatic objects initialized within the handler.
10632      //
10633      // We just pretend to initialize the object with itself, then make sure
10634      // it can be destroyed later.
10635      QualType initType = ExDeclType;
10636
10637      InitializedEntity entity =
10638        InitializedEntity::InitializeVariable(ExDecl);
10639      InitializationKind initKind =
10640        InitializationKind::CreateCopy(Loc, SourceLocation());
10641
10642      Expr *opaqueValue =
10643        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10644      InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10645      ExprResult result = sequence.Perform(*this, entity, initKind,
10646                                           MultiExprArg(&opaqueValue, 1));
10647      if (result.isInvalid())
10648        Invalid = true;
10649      else {
10650        // If the constructor used was non-trivial, set this as the
10651        // "initializer".
10652        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10653        if (!construct->getConstructor()->isTrivial()) {
10654          Expr *init = MaybeCreateExprWithCleanups(construct);
10655          ExDecl->setInit(init);
10656        }
10657
10658        // And make sure it's destructable.
10659        FinalizeVarWithDestructor(ExDecl, recordType);
10660      }
10661    }
10662  }
10663
10664  if (Invalid)
10665    ExDecl->setInvalidDecl();
10666
10667  return ExDecl;
10668}
10669
10670/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10671/// handler.
10672Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
10673  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10674  bool Invalid = D.isInvalidType();
10675
10676  // Check for unexpanded parameter packs.
10677  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10678                                      UPPC_ExceptionType)) {
10679    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10680                                             D.getIdentifierLoc());
10681    Invalid = true;
10682  }
10683
10684  IdentifierInfo *II = D.getIdentifier();
10685  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
10686                                             LookupOrdinaryName,
10687                                             ForRedeclaration)) {
10688    // The scope should be freshly made just for us. There is just no way
10689    // it contains any previous declaration.
10690    assert(!S->isDeclScope(PrevDecl));
10691    if (PrevDecl->isTemplateParameter()) {
10692      // Maybe we will complain about the shadowed template parameter.
10693      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10694      PrevDecl = 0;
10695    }
10696  }
10697
10698  if (D.getCXXScopeSpec().isSet() && !Invalid) {
10699    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10700      << D.getCXXScopeSpec().getRange();
10701    Invalid = true;
10702  }
10703
10704  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
10705                                              D.getLocStart(),
10706                                              D.getIdentifierLoc(),
10707                                              D.getIdentifier());
10708  if (Invalid)
10709    ExDecl->setInvalidDecl();
10710
10711  // Add the exception declaration into this scope.
10712  if (II)
10713    PushOnScopeChains(ExDecl, S);
10714  else
10715    CurContext->addDecl(ExDecl);
10716
10717  ProcessDeclAttributes(S, ExDecl, D);
10718  return ExDecl;
10719}
10720
10721Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10722                                         Expr *AssertExpr,
10723                                         Expr *AssertMessageExpr,
10724                                         SourceLocation RParenLoc) {
10725  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
10726
10727  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10728    return 0;
10729
10730  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10731                                      AssertMessage, RParenLoc, false);
10732}
10733
10734Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10735                                         Expr *AssertExpr,
10736                                         StringLiteral *AssertMessage,
10737                                         SourceLocation RParenLoc,
10738                                         bool Failed) {
10739  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10740      !Failed) {
10741    // In a static_assert-declaration, the constant-expression shall be a
10742    // constant expression that can be contextually converted to bool.
10743    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10744    if (Converted.isInvalid())
10745      Failed = true;
10746
10747    llvm::APSInt Cond;
10748    if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
10749          diag::err_static_assert_expression_is_not_constant,
10750          /*AllowFold=*/false).isInvalid())
10751      Failed = true;
10752
10753    if (!Failed && !Cond) {
10754      SmallString<256> MsgBuffer;
10755      llvm::raw_svector_ostream Msg(MsgBuffer);
10756      AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
10757      Diag(StaticAssertLoc, diag::err_static_assert_failed)
10758        << Msg.str() << AssertExpr->getSourceRange();
10759      Failed = true;
10760    }
10761  }
10762
10763  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
10764                                        AssertExpr, AssertMessage, RParenLoc,
10765                                        Failed);
10766
10767  CurContext->addDecl(Decl);
10768  return Decl;
10769}
10770
10771/// \brief Perform semantic analysis of the given friend type declaration.
10772///
10773/// \returns A friend declaration that.
10774FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
10775                                      SourceLocation FriendLoc,
10776                                      TypeSourceInfo *TSInfo) {
10777  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10778
10779  QualType T = TSInfo->getType();
10780  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
10781
10782  // C++03 [class.friend]p2:
10783  //   An elaborated-type-specifier shall be used in a friend declaration
10784  //   for a class.*
10785  //
10786  //   * The class-key of the elaborated-type-specifier is required.
10787  if (!ActiveTemplateInstantiations.empty()) {
10788    // Do not complain about the form of friend template types during
10789    // template instantiation; we will already have complained when the
10790    // template was declared.
10791  } else {
10792    if (!T->isElaboratedTypeSpecifier()) {
10793      // If we evaluated the type to a record type, suggest putting
10794      // a tag in front.
10795      if (const RecordType *RT = T->getAs<RecordType>()) {
10796        RecordDecl *RD = RT->getDecl();
10797
10798        std::string InsertionText = std::string(" ") + RD->getKindName();
10799
10800        Diag(TypeRange.getBegin(),
10801             getLangOpts().CPlusPlus11 ?
10802               diag::warn_cxx98_compat_unelaborated_friend_type :
10803               diag::ext_unelaborated_friend_type)
10804          << (unsigned) RD->getTagKind()
10805          << T
10806          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10807                                        InsertionText);
10808      } else {
10809        Diag(FriendLoc,
10810             getLangOpts().CPlusPlus11 ?
10811               diag::warn_cxx98_compat_nonclass_type_friend :
10812               diag::ext_nonclass_type_friend)
10813          << T
10814          << TypeRange;
10815      }
10816    } else if (T->getAs<EnumType>()) {
10817      Diag(FriendLoc,
10818           getLangOpts().CPlusPlus11 ?
10819             diag::warn_cxx98_compat_enum_friend :
10820             diag::ext_enum_friend)
10821        << T
10822        << TypeRange;
10823    }
10824
10825    // C++11 [class.friend]p3:
10826    //   A friend declaration that does not declare a function shall have one
10827    //   of the following forms:
10828    //     friend elaborated-type-specifier ;
10829    //     friend simple-type-specifier ;
10830    //     friend typename-specifier ;
10831    if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10832      Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10833  }
10834
10835  //   If the type specifier in a friend declaration designates a (possibly
10836  //   cv-qualified) class type, that class is declared as a friend; otherwise,
10837  //   the friend declaration is ignored.
10838  return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
10839}
10840
10841/// Handle a friend tag declaration where the scope specifier was
10842/// templated.
10843Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10844                                    unsigned TagSpec, SourceLocation TagLoc,
10845                                    CXXScopeSpec &SS,
10846                                    IdentifierInfo *Name,
10847                                    SourceLocation NameLoc,
10848                                    AttributeList *Attr,
10849                                    MultiTemplateParamsArg TempParamLists) {
10850  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10851
10852  bool isExplicitSpecialization = false;
10853  bool Invalid = false;
10854
10855  if (TemplateParameterList *TemplateParams
10856        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
10857                                                  TempParamLists.data(),
10858                                                  TempParamLists.size(),
10859                                                  /*friend*/ true,
10860                                                  isExplicitSpecialization,
10861                                                  Invalid)) {
10862    if (TemplateParams->size() > 0) {
10863      // This is a declaration of a class template.
10864      if (Invalid)
10865        return 0;
10866
10867      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10868                                SS, Name, NameLoc, Attr,
10869                                TemplateParams, AS_public,
10870                                /*ModulePrivateLoc=*/SourceLocation(),
10871                                TempParamLists.size() - 1,
10872                                TempParamLists.data()).take();
10873    } else {
10874      // The "template<>" header is extraneous.
10875      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10876        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10877      isExplicitSpecialization = true;
10878    }
10879  }
10880
10881  if (Invalid) return 0;
10882
10883  bool isAllExplicitSpecializations = true;
10884  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
10885    if (TempParamLists[I]->size()) {
10886      isAllExplicitSpecializations = false;
10887      break;
10888    }
10889  }
10890
10891  // FIXME: don't ignore attributes.
10892
10893  // If it's explicit specializations all the way down, just forget
10894  // about the template header and build an appropriate non-templated
10895  // friend.  TODO: for source fidelity, remember the headers.
10896  if (isAllExplicitSpecializations) {
10897    if (SS.isEmpty()) {
10898      bool Owned = false;
10899      bool IsDependent = false;
10900      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10901                      Attr, AS_public,
10902                      /*ModulePrivateLoc=*/SourceLocation(),
10903                      MultiTemplateParamsArg(), Owned, IsDependent,
10904                      /*ScopedEnumKWLoc=*/SourceLocation(),
10905                      /*ScopedEnumUsesClassTag=*/false,
10906                      /*UnderlyingType=*/TypeResult());
10907    }
10908
10909    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10910    ElaboratedTypeKeyword Keyword
10911      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10912    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
10913                                   *Name, NameLoc);
10914    if (T.isNull())
10915      return 0;
10916
10917    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10918    if (isa<DependentNameType>(T)) {
10919      DependentNameTypeLoc TL =
10920          TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
10921      TL.setElaboratedKeywordLoc(TagLoc);
10922      TL.setQualifierLoc(QualifierLoc);
10923      TL.setNameLoc(NameLoc);
10924    } else {
10925      ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
10926      TL.setElaboratedKeywordLoc(TagLoc);
10927      TL.setQualifierLoc(QualifierLoc);
10928      TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
10929    }
10930
10931    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10932                                            TSI, FriendLoc, TempParamLists);
10933    Friend->setAccess(AS_public);
10934    CurContext->addDecl(Friend);
10935    return Friend;
10936  }
10937
10938  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10939
10940
10941
10942  // Handle the case of a templated-scope friend class.  e.g.
10943  //   template <class T> class A<T>::B;
10944  // FIXME: we don't support these right now.
10945  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10946  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10947  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10948  DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
10949  TL.setElaboratedKeywordLoc(TagLoc);
10950  TL.setQualifierLoc(SS.getWithLocInContext(Context));
10951  TL.setNameLoc(NameLoc);
10952
10953  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10954                                          TSI, FriendLoc, TempParamLists);
10955  Friend->setAccess(AS_public);
10956  Friend->setUnsupportedFriend(true);
10957  CurContext->addDecl(Friend);
10958  return Friend;
10959}
10960
10961
10962/// Handle a friend type declaration.  This works in tandem with
10963/// ActOnTag.
10964///
10965/// Notes on friend class templates:
10966///
10967/// We generally treat friend class declarations as if they were
10968/// declaring a class.  So, for example, the elaborated type specifier
10969/// in a friend declaration is required to obey the restrictions of a
10970/// class-head (i.e. no typedefs in the scope chain), template
10971/// parameters are required to match up with simple template-ids, &c.
10972/// However, unlike when declaring a template specialization, it's
10973/// okay to refer to a template specialization without an empty
10974/// template parameter declaration, e.g.
10975///   friend class A<T>::B<unsigned>;
10976/// We permit this as a special case; if there are any template
10977/// parameters present at all, require proper matching, i.e.
10978///   template <> template \<class T> friend class A<int>::B;
10979Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
10980                                MultiTemplateParamsArg TempParams) {
10981  SourceLocation Loc = DS.getLocStart();
10982
10983  assert(DS.isFriendSpecified());
10984  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10985
10986  // Try to convert the decl specifier to a type.  This works for
10987  // friend templates because ActOnTag never produces a ClassTemplateDecl
10988  // for a TUK_Friend.
10989  Declarator TheDeclarator(DS, Declarator::MemberContext);
10990  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10991  QualType T = TSI->getType();
10992  if (TheDeclarator.isInvalidType())
10993    return 0;
10994
10995  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10996    return 0;
10997
10998  // This is definitely an error in C++98.  It's probably meant to
10999  // be forbidden in C++0x, too, but the specification is just
11000  // poorly written.
11001  //
11002  // The problem is with declarations like the following:
11003  //   template <T> friend A<T>::foo;
11004  // where deciding whether a class C is a friend or not now hinges
11005  // on whether there exists an instantiation of A that causes
11006  // 'foo' to equal C.  There are restrictions on class-heads
11007  // (which we declare (by fiat) elaborated friend declarations to
11008  // be) that makes this tractable.
11009  //
11010  // FIXME: handle "template <> friend class A<T>;", which
11011  // is possibly well-formed?  Who even knows?
11012  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
11013    Diag(Loc, diag::err_tagless_friend_type_template)
11014      << DS.getSourceRange();
11015    return 0;
11016  }
11017
11018  // C++98 [class.friend]p1: A friend of a class is a function
11019  //   or class that is not a member of the class . . .
11020  // This is fixed in DR77, which just barely didn't make the C++03
11021  // deadline.  It's also a very silly restriction that seriously
11022  // affects inner classes and which nobody else seems to implement;
11023  // thus we never diagnose it, not even in -pedantic.
11024  //
11025  // But note that we could warn about it: it's always useless to
11026  // friend one of your own members (it's not, however, worthless to
11027  // friend a member of an arbitrary specialization of your template).
11028
11029  Decl *D;
11030  if (unsigned NumTempParamLists = TempParams.size())
11031    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
11032                                   NumTempParamLists,
11033                                   TempParams.data(),
11034                                   TSI,
11035                                   DS.getFriendSpecLoc());
11036  else
11037    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
11038
11039  if (!D)
11040    return 0;
11041
11042  D->setAccess(AS_public);
11043  CurContext->addDecl(D);
11044
11045  return D;
11046}
11047
11048NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11049                                        MultiTemplateParamsArg TemplateParams) {
11050  const DeclSpec &DS = D.getDeclSpec();
11051
11052  assert(DS.isFriendSpecified());
11053  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11054
11055  SourceLocation Loc = D.getIdentifierLoc();
11056  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11057
11058  // C++ [class.friend]p1
11059  //   A friend of a class is a function or class....
11060  // Note that this sees through typedefs, which is intended.
11061  // It *doesn't* see through dependent types, which is correct
11062  // according to [temp.arg.type]p3:
11063  //   If a declaration acquires a function type through a
11064  //   type dependent on a template-parameter and this causes
11065  //   a declaration that does not use the syntactic form of a
11066  //   function declarator to have a function type, the program
11067  //   is ill-formed.
11068  if (!TInfo->getType()->isFunctionType()) {
11069    Diag(Loc, diag::err_unexpected_friend);
11070
11071    // It might be worthwhile to try to recover by creating an
11072    // appropriate declaration.
11073    return 0;
11074  }
11075
11076  // C++ [namespace.memdef]p3
11077  //  - If a friend declaration in a non-local class first declares a
11078  //    class or function, the friend class or function is a member
11079  //    of the innermost enclosing namespace.
11080  //  - The name of the friend is not found by simple name lookup
11081  //    until a matching declaration is provided in that namespace
11082  //    scope (either before or after the class declaration granting
11083  //    friendship).
11084  //  - If a friend function is called, its name may be found by the
11085  //    name lookup that considers functions from namespaces and
11086  //    classes associated with the types of the function arguments.
11087  //  - When looking for a prior declaration of a class or a function
11088  //    declared as a friend, scopes outside the innermost enclosing
11089  //    namespace scope are not considered.
11090
11091  CXXScopeSpec &SS = D.getCXXScopeSpec();
11092  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11093  DeclarationName Name = NameInfo.getName();
11094  assert(Name);
11095
11096  // Check for unexpanded parameter packs.
11097  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11098      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11099      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11100    return 0;
11101
11102  // The context we found the declaration in, or in which we should
11103  // create the declaration.
11104  DeclContext *DC;
11105  Scope *DCScope = S;
11106  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
11107                        ForRedeclaration);
11108
11109  // FIXME: there are different rules in local classes
11110
11111  // There are four cases here.
11112  //   - There's no scope specifier, in which case we just go to the
11113  //     appropriate scope and look for a function or function template
11114  //     there as appropriate.
11115  // Recover from invalid scope qualifiers as if they just weren't there.
11116  if (SS.isInvalid() || !SS.isSet()) {
11117    // C++0x [namespace.memdef]p3:
11118    //   If the name in a friend declaration is neither qualified nor
11119    //   a template-id and the declaration is a function or an
11120    //   elaborated-type-specifier, the lookup to determine whether
11121    //   the entity has been previously declared shall not consider
11122    //   any scopes outside the innermost enclosing namespace.
11123    // C++0x [class.friend]p11:
11124    //   If a friend declaration appears in a local class and the name
11125    //   specified is an unqualified name, a prior declaration is
11126    //   looked up without considering scopes that are outside the
11127    //   innermost enclosing non-class scope. For a friend function
11128    //   declaration, if there is no prior declaration, the program is
11129    //   ill-formed.
11130    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
11131    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
11132
11133    // Find the appropriate context according to the above.
11134    DC = CurContext;
11135
11136    // Skip class contexts.  If someone can cite chapter and verse
11137    // for this behavior, that would be nice --- it's what GCC and
11138    // EDG do, and it seems like a reasonable intent, but the spec
11139    // really only says that checks for unqualified existing
11140    // declarations should stop at the nearest enclosing namespace,
11141    // not that they should only consider the nearest enclosing
11142    // namespace.
11143    while (DC->isRecord())
11144      DC = DC->getParent();
11145
11146    DeclContext *LookupDC = DC;
11147    while (LookupDC->isTransparentContext())
11148      LookupDC = LookupDC->getParent();
11149
11150    while (true) {
11151      LookupQualifiedName(Previous, LookupDC);
11152
11153      // TODO: decide what we think about using declarations.
11154      if (isLocal)
11155        break;
11156
11157      if (!Previous.empty()) {
11158        DC = LookupDC;
11159        break;
11160      }
11161
11162      if (isTemplateId) {
11163        if (isa<TranslationUnitDecl>(LookupDC)) break;
11164      } else {
11165        if (LookupDC->isFileContext()) break;
11166      }
11167      LookupDC = LookupDC->getParent();
11168    }
11169
11170    DCScope = getScopeForDeclContext(S, DC);
11171
11172    // C++ [class.friend]p6:
11173    //   A function can be defined in a friend declaration of a class if and
11174    //   only if the class is a non-local class (9.8), the function name is
11175    //   unqualified, and the function has namespace scope.
11176    if (isLocal && D.isFunctionDefinition()) {
11177      Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11178    }
11179
11180  //   - There's a non-dependent scope specifier, in which case we
11181  //     compute it and do a previous lookup there for a function
11182  //     or function template.
11183  } else if (!SS.getScopeRep()->isDependent()) {
11184    DC = computeDeclContext(SS);
11185    if (!DC) return 0;
11186
11187    if (RequireCompleteDeclContext(SS, DC)) return 0;
11188
11189    LookupQualifiedName(Previous, DC);
11190
11191    // Ignore things found implicitly in the wrong scope.
11192    // TODO: better diagnostics for this case.  Suggesting the right
11193    // qualified scope would be nice...
11194    LookupResult::Filter F = Previous.makeFilter();
11195    while (F.hasNext()) {
11196      NamedDecl *D = F.next();
11197      if (!DC->InEnclosingNamespaceSetOf(
11198              D->getDeclContext()->getRedeclContext()))
11199        F.erase();
11200    }
11201    F.done();
11202
11203    if (Previous.empty()) {
11204      D.setInvalidType();
11205      Diag(Loc, diag::err_qualified_friend_not_found)
11206          << Name << TInfo->getType();
11207      return 0;
11208    }
11209
11210    // C++ [class.friend]p1: A friend of a class is a function or
11211    //   class that is not a member of the class . . .
11212    if (DC->Equals(CurContext))
11213      Diag(DS.getFriendSpecLoc(),
11214           getLangOpts().CPlusPlus11 ?
11215             diag::warn_cxx98_compat_friend_is_member :
11216             diag::err_friend_is_member);
11217
11218    if (D.isFunctionDefinition()) {
11219      // C++ [class.friend]p6:
11220      //   A function can be defined in a friend declaration of a class if and
11221      //   only if the class is a non-local class (9.8), the function name is
11222      //   unqualified, and the function has namespace scope.
11223      SemaDiagnosticBuilder DB
11224        = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11225
11226      DB << SS.getScopeRep();
11227      if (DC->isFileContext())
11228        DB << FixItHint::CreateRemoval(SS.getRange());
11229      SS.clear();
11230    }
11231
11232  //   - There's a scope specifier that does not match any template
11233  //     parameter lists, in which case we use some arbitrary context,
11234  //     create a method or method template, and wait for instantiation.
11235  //   - There's a scope specifier that does match some template
11236  //     parameter lists, which we don't handle right now.
11237  } else {
11238    if (D.isFunctionDefinition()) {
11239      // C++ [class.friend]p6:
11240      //   A function can be defined in a friend declaration of a class if and
11241      //   only if the class is a non-local class (9.8), the function name is
11242      //   unqualified, and the function has namespace scope.
11243      Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11244        << SS.getScopeRep();
11245    }
11246
11247    DC = CurContext;
11248    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
11249  }
11250
11251  if (!DC->isRecord()) {
11252    // This implies that it has to be an operator or function.
11253    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11254        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11255        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
11256      Diag(Loc, diag::err_introducing_special_friend) <<
11257        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11258         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
11259      return 0;
11260    }
11261  }
11262
11263  // FIXME: This is an egregious hack to cope with cases where the scope stack
11264  // does not contain the declaration context, i.e., in an out-of-line
11265  // definition of a class.
11266  Scope FakeDCScope(S, Scope::DeclScope, Diags);
11267  if (!DCScope) {
11268    FakeDCScope.setEntity(DC);
11269    DCScope = &FakeDCScope;
11270  }
11271
11272  bool AddToScope = true;
11273  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
11274                                          TemplateParams, AddToScope);
11275  if (!ND) return 0;
11276
11277  assert(ND->getDeclContext() == DC);
11278  assert(ND->getLexicalDeclContext() == CurContext);
11279
11280  // Add the function declaration to the appropriate lookup tables,
11281  // adjusting the redeclarations list as necessary.  We don't
11282  // want to do this yet if the friending class is dependent.
11283  //
11284  // Also update the scope-based lookup if the target context's
11285  // lookup context is in lexical scope.
11286  if (!CurContext->isDependentContext()) {
11287    DC = DC->getRedeclContext();
11288    DC->makeDeclVisibleInContext(ND);
11289    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11290      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
11291  }
11292
11293  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
11294                                       D.getIdentifierLoc(), ND,
11295                                       DS.getFriendSpecLoc());
11296  FrD->setAccess(AS_public);
11297  CurContext->addDecl(FrD);
11298
11299  if (ND->isInvalidDecl()) {
11300    FrD->setInvalidDecl();
11301  } else {
11302    if (DC->isRecord()) CheckFriendAccess(ND);
11303
11304    FunctionDecl *FD;
11305    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11306      FD = FTD->getTemplatedDecl();
11307    else
11308      FD = cast<FunctionDecl>(ND);
11309
11310    // Mark templated-scope function declarations as unsupported.
11311    if (FD->getNumTemplateParameterLists())
11312      FrD->setUnsupportedFriend(true);
11313  }
11314
11315  return ND;
11316}
11317
11318void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11319  AdjustDeclIfTemplate(Dcl);
11320
11321  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
11322  if (!Fn) {
11323    Diag(DelLoc, diag::err_deleted_non_function);
11324    return;
11325  }
11326
11327  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
11328    // Don't consider the implicit declaration we generate for explicit
11329    // specializations. FIXME: Do not generate these implicit declarations.
11330    if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11331        || Prev->getPreviousDecl()) && !Prev->isDefined()) {
11332      Diag(DelLoc, diag::err_deleted_decl_not_first);
11333      Diag(Prev->getLocation(), diag::note_previous_declaration);
11334    }
11335    // If the declaration wasn't the first, we delete the function anyway for
11336    // recovery.
11337    Fn = Fn->getCanonicalDecl();
11338  }
11339
11340  if (Fn->isDeleted())
11341    return;
11342
11343  // See if we're deleting a function which is already known to override a
11344  // non-deleted virtual function.
11345  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11346    bool IssuedDiagnostic = false;
11347    for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11348                                        E = MD->end_overridden_methods();
11349         I != E; ++I) {
11350      if (!(*MD->begin_overridden_methods())->isDeleted()) {
11351        if (!IssuedDiagnostic) {
11352          Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11353          IssuedDiagnostic = true;
11354        }
11355        Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11356      }
11357    }
11358  }
11359
11360  Fn->setDeletedAsWritten();
11361}
11362
11363void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
11364  CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
11365
11366  if (MD) {
11367    if (MD->getParent()->isDependentType()) {
11368      MD->setDefaulted();
11369      MD->setExplicitlyDefaulted();
11370      return;
11371    }
11372
11373    CXXSpecialMember Member = getSpecialMember(MD);
11374    if (Member == CXXInvalid) {
11375      Diag(DefaultLoc, diag::err_default_special_members);
11376      return;
11377    }
11378
11379    MD->setDefaulted();
11380    MD->setExplicitlyDefaulted();
11381
11382    // If this definition appears within the record, do the checking when
11383    // the record is complete.
11384    const FunctionDecl *Primary = MD;
11385    if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
11386      // Find the uninstantiated declaration that actually had the '= default'
11387      // on it.
11388      Pattern->isDefined(Primary);
11389
11390    // If the method was defaulted on its first declaration, we will have
11391    // already performed the checking in CheckCompletedCXXClass. Such a
11392    // declaration doesn't trigger an implicit definition.
11393    if (Primary == Primary->getCanonicalDecl())
11394      return;
11395
11396    CheckExplicitlyDefaultedSpecialMember(MD);
11397
11398    // The exception specification is needed because we are defining the
11399    // function.
11400    ResolveExceptionSpec(DefaultLoc,
11401                         MD->getType()->castAs<FunctionProtoType>());
11402
11403    switch (Member) {
11404    case CXXDefaultConstructor: {
11405      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11406      if (!CD->isInvalidDecl())
11407        DefineImplicitDefaultConstructor(DefaultLoc, CD);
11408      break;
11409    }
11410
11411    case CXXCopyConstructor: {
11412      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11413      if (!CD->isInvalidDecl())
11414        DefineImplicitCopyConstructor(DefaultLoc, CD);
11415      break;
11416    }
11417
11418    case CXXCopyAssignment: {
11419      if (!MD->isInvalidDecl())
11420        DefineImplicitCopyAssignment(DefaultLoc, MD);
11421      break;
11422    }
11423
11424    case CXXDestructor: {
11425      CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
11426      if (!DD->isInvalidDecl())
11427        DefineImplicitDestructor(DefaultLoc, DD);
11428      break;
11429    }
11430
11431    case CXXMoveConstructor: {
11432      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11433      if (!CD->isInvalidDecl())
11434        DefineImplicitMoveConstructor(DefaultLoc, CD);
11435      break;
11436    }
11437
11438    case CXXMoveAssignment: {
11439      if (!MD->isInvalidDecl())
11440        DefineImplicitMoveAssignment(DefaultLoc, MD);
11441      break;
11442    }
11443
11444    case CXXInvalid:
11445      llvm_unreachable("Invalid special member.");
11446    }
11447  } else {
11448    Diag(DefaultLoc, diag::err_default_special_members);
11449  }
11450}
11451
11452static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
11453  for (Stmt::child_range CI = S->children(); CI; ++CI) {
11454    Stmt *SubStmt = *CI;
11455    if (!SubStmt)
11456      continue;
11457    if (isa<ReturnStmt>(SubStmt))
11458      Self.Diag(SubStmt->getLocStart(),
11459           diag::err_return_in_constructor_handler);
11460    if (!isa<Expr>(SubStmt))
11461      SearchForReturnInStmt(Self, SubStmt);
11462  }
11463}
11464
11465void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11466  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11467    CXXCatchStmt *Handler = TryBlock->getHandler(I);
11468    SearchForReturnInStmt(*this, Handler);
11469  }
11470}
11471
11472bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
11473                                             const CXXMethodDecl *Old) {
11474  const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11475  const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11476
11477  CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11478
11479  // If the calling conventions match, everything is fine
11480  if (NewCC == OldCC)
11481    return false;
11482
11483  // If either of the calling conventions are set to "default", we need to pick
11484  // something more sensible based on the target. This supports code where the
11485  // one method explicitly sets thiscall, and another has no explicit calling
11486  // convention.
11487  CallingConv Default =
11488    Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11489  if (NewCC == CC_Default)
11490    NewCC = Default;
11491  if (OldCC == CC_Default)
11492    OldCC = Default;
11493
11494  // If the calling conventions still don't match, then report the error
11495  if (NewCC != OldCC) {
11496    Diag(New->getLocation(),
11497         diag::err_conflicting_overriding_cc_attributes)
11498      << New->getDeclName() << New->getType() << Old->getType();
11499    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11500    return true;
11501  }
11502
11503  return false;
11504}
11505
11506bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
11507                                             const CXXMethodDecl *Old) {
11508  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11509  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
11510
11511  if (Context.hasSameType(NewTy, OldTy) ||
11512      NewTy->isDependentType() || OldTy->isDependentType())
11513    return false;
11514
11515  // Check if the return types are covariant
11516  QualType NewClassTy, OldClassTy;
11517
11518  /// Both types must be pointers or references to classes.
11519  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11520    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
11521      NewClassTy = NewPT->getPointeeType();
11522      OldClassTy = OldPT->getPointeeType();
11523    }
11524  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11525    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11526      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11527        NewClassTy = NewRT->getPointeeType();
11528        OldClassTy = OldRT->getPointeeType();
11529      }
11530    }
11531  }
11532
11533  // The return types aren't either both pointers or references to a class type.
11534  if (NewClassTy.isNull()) {
11535    Diag(New->getLocation(),
11536         diag::err_different_return_type_for_overriding_virtual_function)
11537      << New->getDeclName() << NewTy << OldTy;
11538    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11539
11540    return true;
11541  }
11542
11543  // C++ [class.virtual]p6:
11544  //   If the return type of D::f differs from the return type of B::f, the
11545  //   class type in the return type of D::f shall be complete at the point of
11546  //   declaration of D::f or shall be the class type D.
11547  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11548    if (!RT->isBeingDefined() &&
11549        RequireCompleteType(New->getLocation(), NewClassTy,
11550                            diag::err_covariant_return_incomplete,
11551                            New->getDeclName()))
11552    return true;
11553  }
11554
11555  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
11556    // Check if the new class derives from the old class.
11557    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11558      Diag(New->getLocation(),
11559           diag::err_covariant_return_not_derived)
11560      << New->getDeclName() << NewTy << OldTy;
11561      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11562      return true;
11563    }
11564
11565    // Check if we the conversion from derived to base is valid.
11566    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
11567                    diag::err_covariant_return_inaccessible_base,
11568                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
11569                    // FIXME: Should this point to the return type?
11570                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
11571      // FIXME: this note won't trigger for delayed access control
11572      // diagnostics, and it's impossible to get an undelayed error
11573      // here from access control during the original parse because
11574      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
11575      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11576      return true;
11577    }
11578  }
11579
11580  // The qualifiers of the return types must be the same.
11581  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
11582    Diag(New->getLocation(),
11583         diag::err_covariant_return_type_different_qualifications)
11584    << New->getDeclName() << NewTy << OldTy;
11585    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11586    return true;
11587  };
11588
11589
11590  // The new class type must have the same or less qualifiers as the old type.
11591  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11592    Diag(New->getLocation(),
11593         diag::err_covariant_return_type_class_type_more_qualified)
11594    << New->getDeclName() << NewTy << OldTy;
11595    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11596    return true;
11597  };
11598
11599  return false;
11600}
11601
11602/// \brief Mark the given method pure.
11603///
11604/// \param Method the method to be marked pure.
11605///
11606/// \param InitRange the source range that covers the "0" initializer.
11607bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
11608  SourceLocation EndLoc = InitRange.getEnd();
11609  if (EndLoc.isValid())
11610    Method->setRangeEnd(EndLoc);
11611
11612  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11613    Method->setPure();
11614    return false;
11615  }
11616
11617  if (!Method->isInvalidDecl())
11618    Diag(Method->getLocation(), diag::err_non_virtual_pure)
11619      << Method->getDeclName() << InitRange;
11620  return true;
11621}
11622
11623/// \brief Determine whether the given declaration is a static data member.
11624static bool isStaticDataMember(Decl *D) {
11625  VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11626  if (!Var)
11627    return false;
11628
11629  return Var->isStaticDataMember();
11630}
11631/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11632/// an initializer for the out-of-line declaration 'Dcl'.  The scope
11633/// is a fresh scope pushed for just this purpose.
11634///
11635/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11636/// static data member of class X, names should be looked up in the scope of
11637/// class X.
11638void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
11639  // If there is no declaration, there was an error parsing it.
11640  if (D == 0 || D->isInvalidDecl()) return;
11641
11642  // We should only get called for declarations with scope specifiers, like:
11643  //   int foo::bar;
11644  assert(D->isOutOfLine());
11645  EnterDeclaratorContext(S, D->getDeclContext());
11646
11647  // If we are parsing the initializer for a static data member, push a
11648  // new expression evaluation context that is associated with this static
11649  // data member.
11650  if (isStaticDataMember(D))
11651    PushExpressionEvaluationContext(PotentiallyEvaluated, D);
11652}
11653
11654/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
11655/// initializer for the out-of-line declaration 'D'.
11656void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
11657  // If there is no declaration, there was an error parsing it.
11658  if (D == 0 || D->isInvalidDecl()) return;
11659
11660  if (isStaticDataMember(D))
11661    PopExpressionEvaluationContext();
11662
11663  assert(D->isOutOfLine());
11664  ExitDeclaratorContext(S);
11665}
11666
11667/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11668/// C++ if/switch/while/for statement.
11669/// e.g: "if (int x = f()) {...}"
11670DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
11671  // C++ 6.4p2:
11672  // The declarator shall not specify a function or an array.
11673  // The type-specifier-seq shall not contain typedef and shall not declare a
11674  // new class or enumeration.
11675  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11676         "Parser allowed 'typedef' as storage class of condition decl.");
11677
11678  Decl *Dcl = ActOnDeclarator(S, D);
11679  if (!Dcl)
11680    return true;
11681
11682  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11683    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
11684      << D.getSourceRange();
11685    return true;
11686  }
11687
11688  return Dcl;
11689}
11690
11691void Sema::LoadExternalVTableUses() {
11692  if (!ExternalSource)
11693    return;
11694
11695  SmallVector<ExternalVTableUse, 4> VTables;
11696  ExternalSource->ReadUsedVTables(VTables);
11697  SmallVector<VTableUse, 4> NewUses;
11698  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11699    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11700      = VTablesUsed.find(VTables[I].Record);
11701    // Even if a definition wasn't required before, it may be required now.
11702    if (Pos != VTablesUsed.end()) {
11703      if (!Pos->second && VTables[I].DefinitionRequired)
11704        Pos->second = true;
11705      continue;
11706    }
11707
11708    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11709    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11710  }
11711
11712  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11713}
11714
11715void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11716                          bool DefinitionRequired) {
11717  // Ignore any vtable uses in unevaluated operands or for classes that do
11718  // not have a vtable.
11719  if (!Class->isDynamicClass() || Class->isDependentContext() ||
11720      CurContext->isDependentContext() ||
11721      ExprEvalContexts.back().Context == Unevaluated)
11722    return;
11723
11724  // Try to insert this class into the map.
11725  LoadExternalVTableUses();
11726  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11727  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11728    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11729  if (!Pos.second) {
11730    // If we already had an entry, check to see if we are promoting this vtable
11731    // to required a definition. If so, we need to reappend to the VTableUses
11732    // list, since we may have already processed the first entry.
11733    if (DefinitionRequired && !Pos.first->second) {
11734      Pos.first->second = true;
11735    } else {
11736      // Otherwise, we can early exit.
11737      return;
11738    }
11739  }
11740
11741  // Local classes need to have their virtual members marked
11742  // immediately. For all other classes, we mark their virtual members
11743  // at the end of the translation unit.
11744  if (Class->isLocalClass())
11745    MarkVirtualMembersReferenced(Loc, Class);
11746  else
11747    VTableUses.push_back(std::make_pair(Class, Loc));
11748}
11749
11750bool Sema::DefineUsedVTables() {
11751  LoadExternalVTableUses();
11752  if (VTableUses.empty())
11753    return false;
11754
11755  // Note: The VTableUses vector could grow as a result of marking
11756  // the members of a class as "used", so we check the size each
11757  // time through the loop and prefer indices (which are stable) to
11758  // iterators (which are not).
11759  bool DefinedAnything = false;
11760  for (unsigned I = 0; I != VTableUses.size(); ++I) {
11761    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
11762    if (!Class)
11763      continue;
11764
11765    SourceLocation Loc = VTableUses[I].second;
11766
11767    bool DefineVTable = true;
11768
11769    // If this class has a key function, but that key function is
11770    // defined in another translation unit, we don't need to emit the
11771    // vtable even though we're using it.
11772    const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
11773    if (KeyFunction && !KeyFunction->hasBody()) {
11774      switch (KeyFunction->getTemplateSpecializationKind()) {
11775      case TSK_Undeclared:
11776      case TSK_ExplicitSpecialization:
11777      case TSK_ExplicitInstantiationDeclaration:
11778        // The key function is in another translation unit.
11779        DefineVTable = false;
11780        break;
11781
11782      case TSK_ExplicitInstantiationDefinition:
11783      case TSK_ImplicitInstantiation:
11784        // We will be instantiating the key function.
11785        break;
11786      }
11787    } else if (!KeyFunction) {
11788      // If we have a class with no key function that is the subject
11789      // of an explicit instantiation declaration, suppress the
11790      // vtable; it will live with the explicit instantiation
11791      // definition.
11792      bool IsExplicitInstantiationDeclaration
11793        = Class->getTemplateSpecializationKind()
11794                                      == TSK_ExplicitInstantiationDeclaration;
11795      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11796                                 REnd = Class->redecls_end();
11797           R != REnd; ++R) {
11798        TemplateSpecializationKind TSK
11799          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11800        if (TSK == TSK_ExplicitInstantiationDeclaration)
11801          IsExplicitInstantiationDeclaration = true;
11802        else if (TSK == TSK_ExplicitInstantiationDefinition) {
11803          IsExplicitInstantiationDeclaration = false;
11804          break;
11805        }
11806      }
11807
11808      if (IsExplicitInstantiationDeclaration)
11809        DefineVTable = false;
11810    }
11811
11812    // The exception specifications for all virtual members may be needed even
11813    // if we are not providing an authoritative form of the vtable in this TU.
11814    // We may choose to emit it available_externally anyway.
11815    if (!DefineVTable) {
11816      MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11817      continue;
11818    }
11819
11820    // Mark all of the virtual members of this class as referenced, so
11821    // that we can build a vtable. Then, tell the AST consumer that a
11822    // vtable for this class is required.
11823    DefinedAnything = true;
11824    MarkVirtualMembersReferenced(Loc, Class);
11825    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11826    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11827
11828    // Optionally warn if we're emitting a weak vtable.
11829    if (Class->hasExternalLinkage() &&
11830        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
11831      const FunctionDecl *KeyFunctionDef = 0;
11832      if (!KeyFunction ||
11833          (KeyFunction->hasBody(KeyFunctionDef) &&
11834           KeyFunctionDef->isInlined()))
11835        Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11836             TSK_ExplicitInstantiationDefinition
11837             ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11838          << Class;
11839    }
11840  }
11841  VTableUses.clear();
11842
11843  return DefinedAnything;
11844}
11845
11846void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11847                                                 const CXXRecordDecl *RD) {
11848  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11849                                      E = RD->method_end(); I != E; ++I)
11850    if ((*I)->isVirtual() && !(*I)->isPure())
11851      ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11852}
11853
11854void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11855                                        const CXXRecordDecl *RD) {
11856  // Mark all functions which will appear in RD's vtable as used.
11857  CXXFinalOverriderMap FinalOverriders;
11858  RD->getFinalOverriders(FinalOverriders);
11859  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11860                                            E = FinalOverriders.end();
11861       I != E; ++I) {
11862    for (OverridingMethods::const_iterator OI = I->second.begin(),
11863                                           OE = I->second.end();
11864         OI != OE; ++OI) {
11865      assert(OI->second.size() > 0 && "no final overrider");
11866      CXXMethodDecl *Overrider = OI->second.front().Method;
11867
11868      // C++ [basic.def.odr]p2:
11869      //   [...] A virtual member function is used if it is not pure. [...]
11870      if (!Overrider->isPure())
11871        MarkFunctionReferenced(Loc, Overrider);
11872    }
11873  }
11874
11875  // Only classes that have virtual bases need a VTT.
11876  if (RD->getNumVBases() == 0)
11877    return;
11878
11879  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11880           e = RD->bases_end(); i != e; ++i) {
11881    const CXXRecordDecl *Base =
11882        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
11883    if (Base->getNumVBases() == 0)
11884      continue;
11885    MarkVirtualMembersReferenced(Loc, Base);
11886  }
11887}
11888
11889/// SetIvarInitializers - This routine builds initialization ASTs for the
11890/// Objective-C implementation whose ivars need be initialized.
11891void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
11892  if (!getLangOpts().CPlusPlus)
11893    return;
11894  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
11895    SmallVector<ObjCIvarDecl*, 8> ivars;
11896    CollectIvarsToConstructOrDestruct(OID, ivars);
11897    if (ivars.empty())
11898      return;
11899    SmallVector<CXXCtorInitializer*, 32> AllToInit;
11900    for (unsigned i = 0; i < ivars.size(); i++) {
11901      FieldDecl *Field = ivars[i];
11902      if (Field->isInvalidDecl())
11903        continue;
11904
11905      CXXCtorInitializer *Member;
11906      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11907      InitializationKind InitKind =
11908        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11909
11910      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
11911      ExprResult MemberInit =
11912        InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
11913      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
11914      // Note, MemberInit could actually come back empty if no initialization
11915      // is required (e.g., because it would call a trivial default constructor)
11916      if (!MemberInit.get() || MemberInit.isInvalid())
11917        continue;
11918
11919      Member =
11920        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11921                                         SourceLocation(),
11922                                         MemberInit.takeAs<Expr>(),
11923                                         SourceLocation());
11924      AllToInit.push_back(Member);
11925
11926      // Be sure that the destructor is accessible and is marked as referenced.
11927      if (const RecordType *RecordTy
11928                  = Context.getBaseElementType(Field->getType())
11929                                                        ->getAs<RecordType>()) {
11930                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
11931        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
11932          MarkFunctionReferenced(Field->getLocation(), Destructor);
11933          CheckDestructorAccess(Field->getLocation(), Destructor,
11934                            PDiag(diag::err_access_dtor_ivar)
11935                              << Context.getBaseElementType(Field->getType()));
11936        }
11937      }
11938    }
11939    ObjCImplementation->setIvarInitializers(Context,
11940                                            AllToInit.data(), AllToInit.size());
11941  }
11942}
11943
11944static
11945void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11946                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11947                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11948                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11949                           Sema &S) {
11950  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11951                                                   CE = Current.end();
11952  if (Ctor->isInvalidDecl())
11953    return;
11954
11955  CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11956
11957  // Target may not be determinable yet, for instance if this is a dependent
11958  // call in an uninstantiated template.
11959  if (Target) {
11960    const FunctionDecl *FNTarget = 0;
11961    (void)Target->hasBody(FNTarget);
11962    Target = const_cast<CXXConstructorDecl*>(
11963      cast_or_null<CXXConstructorDecl>(FNTarget));
11964  }
11965
11966  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11967                     // Avoid dereferencing a null pointer here.
11968                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11969
11970  if (!Current.insert(Canonical))
11971    return;
11972
11973  // We know that beyond here, we aren't chaining into a cycle.
11974  if (!Target || !Target->isDelegatingConstructor() ||
11975      Target->isInvalidDecl() || Valid.count(TCanonical)) {
11976    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11977      Valid.insert(*CI);
11978    Current.clear();
11979  // We've hit a cycle.
11980  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11981             Current.count(TCanonical)) {
11982    // If we haven't diagnosed this cycle yet, do so now.
11983    if (!Invalid.count(TCanonical)) {
11984      S.Diag((*Ctor->init_begin())->getSourceLocation(),
11985             diag::warn_delegating_ctor_cycle)
11986        << Ctor;
11987
11988      // Don't add a note for a function delegating directly to itself.
11989      if (TCanonical != Canonical)
11990        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11991
11992      CXXConstructorDecl *C = Target;
11993      while (C->getCanonicalDecl() != Canonical) {
11994        const FunctionDecl *FNTarget = 0;
11995        (void)C->getTargetConstructor()->hasBody(FNTarget);
11996        assert(FNTarget && "Ctor cycle through bodiless function");
11997
11998        C = const_cast<CXXConstructorDecl*>(
11999          cast<CXXConstructorDecl>(FNTarget));
12000        S.Diag(C->getLocation(), diag::note_which_delegates_to);
12001      }
12002    }
12003
12004    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12005      Invalid.insert(*CI);
12006    Current.clear();
12007  } else {
12008    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12009  }
12010}
12011
12012
12013void Sema::CheckDelegatingCtorCycles() {
12014  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12015
12016  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12017                                                   CE = Current.end();
12018
12019  for (DelegatingCtorDeclsType::iterator
12020         I = DelegatingCtorDecls.begin(ExternalSource),
12021         E = DelegatingCtorDecls.end();
12022       I != E; ++I)
12023    DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
12024
12025  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
12026    (*CI)->setInvalidDecl();
12027}
12028
12029namespace {
12030  /// \brief AST visitor that finds references to the 'this' expression.
12031  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12032    Sema &S;
12033
12034  public:
12035    explicit FindCXXThisExpr(Sema &S) : S(S) { }
12036
12037    bool VisitCXXThisExpr(CXXThisExpr *E) {
12038      S.Diag(E->getLocation(), diag::err_this_static_member_func)
12039        << E->isImplicit();
12040      return false;
12041    }
12042  };
12043}
12044
12045bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12046  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12047  if (!TSInfo)
12048    return false;
12049
12050  TypeLoc TL = TSInfo->getTypeLoc();
12051  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12052  if (!ProtoTL)
12053    return false;
12054
12055  // C++11 [expr.prim.general]p3:
12056  //   [The expression this] shall not appear before the optional
12057  //   cv-qualifier-seq and it shall not appear within the declaration of a
12058  //   static member function (although its type and value category are defined
12059  //   within a static member function as they are within a non-static member
12060  //   function). [ Note: this is because declaration matching does not occur
12061  //  until the complete declarator is known. - end note ]
12062  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12063  FindCXXThisExpr Finder(*this);
12064
12065  // If the return type came after the cv-qualifier-seq, check it now.
12066  if (Proto->hasTrailingReturn() &&
12067      !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
12068    return true;
12069
12070  // Check the exception specification.
12071  if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12072    return true;
12073
12074  return checkThisInStaticMemberFunctionAttributes(Method);
12075}
12076
12077bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12078  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12079  if (!TSInfo)
12080    return false;
12081
12082  TypeLoc TL = TSInfo->getTypeLoc();
12083  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12084  if (!ProtoTL)
12085    return false;
12086
12087  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12088  FindCXXThisExpr Finder(*this);
12089
12090  switch (Proto->getExceptionSpecType()) {
12091  case EST_Uninstantiated:
12092  case EST_Unevaluated:
12093  case EST_BasicNoexcept:
12094  case EST_DynamicNone:
12095  case EST_MSAny:
12096  case EST_None:
12097    break;
12098
12099  case EST_ComputedNoexcept:
12100    if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12101      return true;
12102
12103  case EST_Dynamic:
12104    for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
12105         EEnd = Proto->exception_end();
12106         E != EEnd; ++E) {
12107      if (!Finder.TraverseType(*E))
12108        return true;
12109    }
12110    break;
12111  }
12112
12113  return false;
12114}
12115
12116bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12117  FindCXXThisExpr Finder(*this);
12118
12119  // Check attributes.
12120  for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12121       A != AEnd; ++A) {
12122    // FIXME: This should be emitted by tblgen.
12123    Expr *Arg = 0;
12124    ArrayRef<Expr *> Args;
12125    if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12126      Arg = G->getArg();
12127    else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12128      Arg = G->getArg();
12129    else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12130      Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12131    else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12132      Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12133    else if (ExclusiveLockFunctionAttr *ELF
12134               = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12135      Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12136    else if (SharedLockFunctionAttr *SLF
12137               = dyn_cast<SharedLockFunctionAttr>(*A))
12138      Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12139    else if (ExclusiveTrylockFunctionAttr *ETLF
12140               = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12141      Arg = ETLF->getSuccessValue();
12142      Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12143    } else if (SharedTrylockFunctionAttr *STLF
12144                 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12145      Arg = STLF->getSuccessValue();
12146      Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12147    } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12148      Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12149    else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12150      Arg = LR->getArg();
12151    else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12152      Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12153    else if (ExclusiveLocksRequiredAttr *ELR
12154               = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12155      Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12156    else if (SharedLocksRequiredAttr *SLR
12157               = dyn_cast<SharedLocksRequiredAttr>(*A))
12158      Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12159
12160    if (Arg && !Finder.TraverseStmt(Arg))
12161      return true;
12162
12163    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12164      if (!Finder.TraverseStmt(Args[I]))
12165        return true;
12166    }
12167  }
12168
12169  return false;
12170}
12171
12172void
12173Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12174                                  ArrayRef<ParsedType> DynamicExceptions,
12175                                  ArrayRef<SourceRange> DynamicExceptionRanges,
12176                                  Expr *NoexceptExpr,
12177                                  SmallVectorImpl<QualType> &Exceptions,
12178                                  FunctionProtoType::ExtProtoInfo &EPI) {
12179  Exceptions.clear();
12180  EPI.ExceptionSpecType = EST;
12181  if (EST == EST_Dynamic) {
12182    Exceptions.reserve(DynamicExceptions.size());
12183    for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12184      // FIXME: Preserve type source info.
12185      QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12186
12187      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12188      collectUnexpandedParameterPacks(ET, Unexpanded);
12189      if (!Unexpanded.empty()) {
12190        DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12191                                         UPPC_ExceptionType,
12192                                         Unexpanded);
12193        continue;
12194      }
12195
12196      // Check that the type is valid for an exception spec, and
12197      // drop it if not.
12198      if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12199        Exceptions.push_back(ET);
12200    }
12201    EPI.NumExceptions = Exceptions.size();
12202    EPI.Exceptions = Exceptions.data();
12203    return;
12204  }
12205
12206  if (EST == EST_ComputedNoexcept) {
12207    // If an error occurred, there's no expression here.
12208    if (NoexceptExpr) {
12209      assert((NoexceptExpr->isTypeDependent() ||
12210              NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12211              Context.BoolTy) &&
12212             "Parser should have made sure that the expression is boolean");
12213      if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12214        EPI.ExceptionSpecType = EST_BasicNoexcept;
12215        return;
12216      }
12217
12218      if (!NoexceptExpr->isValueDependent())
12219        NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
12220                         diag::err_noexcept_needs_constant_expression,
12221                         /*AllowFold*/ false).take();
12222      EPI.NoexceptExpr = NoexceptExpr;
12223    }
12224    return;
12225  }
12226}
12227
12228/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12229Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12230  // Implicitly declared functions (e.g. copy constructors) are
12231  // __host__ __device__
12232  if (D->isImplicit())
12233    return CFT_HostDevice;
12234
12235  if (D->hasAttr<CUDAGlobalAttr>())
12236    return CFT_Global;
12237
12238  if (D->hasAttr<CUDADeviceAttr>()) {
12239    if (D->hasAttr<CUDAHostAttr>())
12240      return CFT_HostDevice;
12241    else
12242      return CFT_Device;
12243  }
12244
12245  return CFT_Host;
12246}
12247
12248bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12249                           CUDAFunctionTarget CalleeTarget) {
12250  // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12251  // Callable from the device only."
12252  if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12253    return true;
12254
12255  // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12256  // Callable from the host only."
12257  // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12258  // Callable from the host only."
12259  if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12260      (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12261    return true;
12262
12263  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12264    return true;
12265
12266  return false;
12267}
12268
12269/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12270///
12271MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12272                                       SourceLocation DeclStart,
12273                                       Declarator &D, Expr *BitWidth,
12274                                       InClassInitStyle InitStyle,
12275                                       AccessSpecifier AS,
12276                                       AttributeList *MSPropertyAttr) {
12277  IdentifierInfo *II = D.getIdentifier();
12278  if (!II) {
12279    Diag(DeclStart, diag::err_anonymous_property);
12280    return NULL;
12281  }
12282  SourceLocation Loc = D.getIdentifierLoc();
12283
12284  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12285  QualType T = TInfo->getType();
12286  if (getLangOpts().CPlusPlus) {
12287    CheckExtraCXXDefaultArguments(D);
12288
12289    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12290                                        UPPC_DataMemberType)) {
12291      D.setInvalidType();
12292      T = Context.IntTy;
12293      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12294    }
12295  }
12296
12297  DiagnoseFunctionSpecifiers(D.getDeclSpec());
12298
12299  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12300    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12301         diag::err_invalid_thread)
12302      << DeclSpec::getSpecifierName(TSCS);
12303
12304  // Check to see if this name was declared as a member previously
12305  NamedDecl *PrevDecl = 0;
12306  LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12307  LookupName(Previous, S);
12308  switch (Previous.getResultKind()) {
12309  case LookupResult::Found:
12310  case LookupResult::FoundUnresolvedValue:
12311    PrevDecl = Previous.getAsSingle<NamedDecl>();
12312    break;
12313
12314  case LookupResult::FoundOverloaded:
12315    PrevDecl = Previous.getRepresentativeDecl();
12316    break;
12317
12318  case LookupResult::NotFound:
12319  case LookupResult::NotFoundInCurrentInstantiation:
12320  case LookupResult::Ambiguous:
12321    break;
12322  }
12323
12324  if (PrevDecl && PrevDecl->isTemplateParameter()) {
12325    // Maybe we will complain about the shadowed template parameter.
12326    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12327    // Just pretend that we didn't see the previous declaration.
12328    PrevDecl = 0;
12329  }
12330
12331  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12332    PrevDecl = 0;
12333
12334  SourceLocation TSSL = D.getLocStart();
12335  MSPropertyDecl *NewPD;
12336  const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12337  NewPD = new (Context) MSPropertyDecl(Record, Loc,
12338                                       II, T, TInfo, TSSL,
12339                                       Data.GetterId, Data.SetterId);
12340  ProcessDeclAttributes(TUScope, NewPD, D);
12341  NewPD->setAccess(AS);
12342
12343  if (NewPD->isInvalidDecl())
12344    Record->setInvalidDecl();
12345
12346  if (D.getDeclSpec().isModulePrivateSpecified())
12347    NewPD->setModulePrivate();
12348
12349  if (NewPD->isInvalidDecl() && PrevDecl) {
12350    // Don't introduce NewFD into scope; there's already something
12351    // with the same name in the same scope.
12352  } else if (II) {
12353    PushOnScopeChains(NewPD, S);
12354  } else
12355    Record->addDecl(NewPD);
12356
12357  return NewPD;
12358}
12359