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);
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 (!VD->getType()->isDependentType() &&
849            SemaRef.RequireLiteralType(
850              VD->getLocation(), VD->getType(),
851              diag::err_constexpr_local_var_non_literal_type,
852              isa<CXXConstructorDecl>(Dcl)))
853          return false;
854        if (!VD->hasInit()) {
855          SemaRef.Diag(VD->getLocation(),
856                       diag::err_constexpr_local_var_no_init)
857            << isa<CXXConstructorDecl>(Dcl);
858          return false;
859        }
860      }
861      SemaRef.Diag(VD->getLocation(),
862                   SemaRef.getLangOpts().CPlusPlus1y
863                    ? diag::warn_cxx11_compat_constexpr_local_var
864                    : diag::ext_constexpr_local_var)
865        << isa<CXXConstructorDecl>(Dcl);
866      continue;
867    }
868
869    case Decl::NamespaceAlias:
870    case Decl::Function:
871      // These are disallowed in C++11 and permitted in C++1y. Allow them
872      // everywhere as an extension.
873      if (!Cxx1yLoc.isValid())
874        Cxx1yLoc = DS->getLocStart();
875      continue;
876
877    default:
878      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
879        << isa<CXXConstructorDecl>(Dcl);
880      return false;
881    }
882  }
883
884  return true;
885}
886
887/// Check that the given field is initialized within a constexpr constructor.
888///
889/// \param Dcl The constexpr constructor being checked.
890/// \param Field The field being checked. This may be a member of an anonymous
891///        struct or union nested within the class being checked.
892/// \param Inits All declarations, including anonymous struct/union members and
893///        indirect members, for which any initialization was provided.
894/// \param Diagnosed Set to true if an error is produced.
895static void CheckConstexprCtorInitializer(Sema &SemaRef,
896                                          const FunctionDecl *Dcl,
897                                          FieldDecl *Field,
898                                          llvm::SmallSet<Decl*, 16> &Inits,
899                                          bool &Diagnosed) {
900  if (Field->isUnnamedBitfield())
901    return;
902
903  if (Field->isAnonymousStructOrUnion() &&
904      Field->getType()->getAsCXXRecordDecl()->isEmpty())
905    return;
906
907  if (!Inits.count(Field)) {
908    if (!Diagnosed) {
909      SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
910      Diagnosed = true;
911    }
912    SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
913  } else if (Field->isAnonymousStructOrUnion()) {
914    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
915    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
916         I != E; ++I)
917      // If an anonymous union contains an anonymous struct of which any member
918      // is initialized, all members must be initialized.
919      if (!RD->isUnion() || Inits.count(*I))
920        CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
921  }
922}
923
924/// Check the provided statement is allowed in a constexpr function
925/// definition.
926static bool
927CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
928                           llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
929                           SourceLocation &Cxx1yLoc) {
930  // - its function-body shall be [...] a compound-statement that contains only
931  switch (S->getStmtClass()) {
932  case Stmt::NullStmtClass:
933    //   - null statements,
934    return true;
935
936  case Stmt::DeclStmtClass:
937    //   - static_assert-declarations
938    //   - using-declarations,
939    //   - using-directives,
940    //   - typedef declarations and alias-declarations that do not define
941    //     classes or enumerations,
942    if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
943      return false;
944    return true;
945
946  case Stmt::ReturnStmtClass:
947    //   - and exactly one return statement;
948    if (isa<CXXConstructorDecl>(Dcl)) {
949      // C++1y allows return statements in constexpr constructors.
950      if (!Cxx1yLoc.isValid())
951        Cxx1yLoc = S->getLocStart();
952      return true;
953    }
954
955    ReturnStmts.push_back(S->getLocStart());
956    return true;
957
958  case Stmt::CompoundStmtClass: {
959    // C++1y allows compound-statements.
960    if (!Cxx1yLoc.isValid())
961      Cxx1yLoc = S->getLocStart();
962
963    CompoundStmt *CompStmt = cast<CompoundStmt>(S);
964    for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
965           BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
966      if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
967                                      Cxx1yLoc))
968        return false;
969    }
970    return true;
971  }
972
973  case Stmt::AttributedStmtClass:
974    if (!Cxx1yLoc.isValid())
975      Cxx1yLoc = S->getLocStart();
976    return true;
977
978  case Stmt::IfStmtClass: {
979    // C++1y allows if-statements.
980    if (!Cxx1yLoc.isValid())
981      Cxx1yLoc = S->getLocStart();
982
983    IfStmt *If = cast<IfStmt>(S);
984    if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
985                                    Cxx1yLoc))
986      return false;
987    if (If->getElse() &&
988        !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
989                                    Cxx1yLoc))
990      return false;
991    return true;
992  }
993
994  case Stmt::WhileStmtClass:
995  case Stmt::DoStmtClass:
996  case Stmt::ForStmtClass:
997  case Stmt::CXXForRangeStmtClass:
998  case Stmt::ContinueStmtClass:
999    // C++1y allows all of these. We don't allow them as extensions in C++11,
1000    // because they don't make sense without variable mutation.
1001    if (!SemaRef.getLangOpts().CPlusPlus1y)
1002      break;
1003    if (!Cxx1yLoc.isValid())
1004      Cxx1yLoc = S->getLocStart();
1005    for (Stmt::child_range Children = S->children(); Children; ++Children)
1006      if (*Children &&
1007          !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1008                                      Cxx1yLoc))
1009        return false;
1010    return true;
1011
1012  case Stmt::SwitchStmtClass:
1013  case Stmt::CaseStmtClass:
1014  case Stmt::DefaultStmtClass:
1015  case Stmt::BreakStmtClass:
1016    // C++1y allows switch-statements, and since they don't need variable
1017    // mutation, we can reasonably allow them in C++11 as an extension.
1018    if (!Cxx1yLoc.isValid())
1019      Cxx1yLoc = S->getLocStart();
1020    for (Stmt::child_range Children = S->children(); Children; ++Children)
1021      if (*Children &&
1022          !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1023                                      Cxx1yLoc))
1024        return false;
1025    return true;
1026
1027  default:
1028    if (!isa<Expr>(S))
1029      break;
1030
1031    // C++1y allows expression-statements.
1032    if (!Cxx1yLoc.isValid())
1033      Cxx1yLoc = S->getLocStart();
1034    return true;
1035  }
1036
1037  SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1038    << isa<CXXConstructorDecl>(Dcl);
1039  return false;
1040}
1041
1042/// Check the body for the given constexpr function declaration only contains
1043/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1044///
1045/// \return true if the body is OK, false if we have diagnosed a problem.
1046bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1047  if (isa<CXXTryStmt>(Body)) {
1048    // C++11 [dcl.constexpr]p3:
1049    //  The definition of a constexpr function shall satisfy the following
1050    //  constraints: [...]
1051    // - its function-body shall be = delete, = default, or a
1052    //   compound-statement
1053    //
1054    // C++11 [dcl.constexpr]p4:
1055    //  In the definition of a constexpr constructor, [...]
1056    // - its function-body shall not be a function-try-block;
1057    Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1058      << isa<CXXConstructorDecl>(Dcl);
1059    return false;
1060  }
1061
1062  SmallVector<SourceLocation, 4> ReturnStmts;
1063
1064  // - its function-body shall be [...] a compound-statement that contains only
1065  //   [... list of cases ...]
1066  CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1067  SourceLocation Cxx1yLoc;
1068  for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1069         BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
1070    if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1071      return false;
1072  }
1073
1074  if (Cxx1yLoc.isValid())
1075    Diag(Cxx1yLoc,
1076         getLangOpts().CPlusPlus1y
1077           ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1078           : diag::ext_constexpr_body_invalid_stmt)
1079      << isa<CXXConstructorDecl>(Dcl);
1080
1081  if (const CXXConstructorDecl *Constructor
1082        = dyn_cast<CXXConstructorDecl>(Dcl)) {
1083    const CXXRecordDecl *RD = Constructor->getParent();
1084    // DR1359:
1085    // - every non-variant non-static data member and base class sub-object
1086    //   shall be initialized;
1087    // - if the class is a non-empty union, or for each non-empty anonymous
1088    //   union member of a non-union class, exactly one non-static data member
1089    //   shall be initialized;
1090    if (RD->isUnion()) {
1091      if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
1092        Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1093        return false;
1094      }
1095    } else if (!Constructor->isDependentContext() &&
1096               !Constructor->isDelegatingConstructor()) {
1097      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1098
1099      // Skip detailed checking if we have enough initializers, and we would
1100      // allow at most one initializer per member.
1101      bool AnyAnonStructUnionMembers = false;
1102      unsigned Fields = 0;
1103      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1104           E = RD->field_end(); I != E; ++I, ++Fields) {
1105        if (I->isAnonymousStructOrUnion()) {
1106          AnyAnonStructUnionMembers = true;
1107          break;
1108        }
1109      }
1110      if (AnyAnonStructUnionMembers ||
1111          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1112        // Check initialization of non-static data members. Base classes are
1113        // always initialized so do not need to be checked. Dependent bases
1114        // might not have initializers in the member initializer list.
1115        llvm::SmallSet<Decl*, 16> Inits;
1116        for (CXXConstructorDecl::init_const_iterator
1117               I = Constructor->init_begin(), E = Constructor->init_end();
1118             I != E; ++I) {
1119          if (FieldDecl *FD = (*I)->getMember())
1120            Inits.insert(FD);
1121          else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1122            Inits.insert(ID->chain_begin(), ID->chain_end());
1123        }
1124
1125        bool Diagnosed = false;
1126        for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1127             E = RD->field_end(); I != E; ++I)
1128          CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
1129        if (Diagnosed)
1130          return false;
1131      }
1132    }
1133  } else {
1134    if (ReturnStmts.empty()) {
1135      // C++1y doesn't require constexpr functions to contain a 'return'
1136      // statement. We still do, unless the return type is void, because
1137      // otherwise if there's no return statement, the function cannot
1138      // be used in a core constant expression.
1139      bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
1140      Diag(Dcl->getLocation(),
1141           OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1142              : diag::err_constexpr_body_no_return);
1143      return OK;
1144    }
1145    if (ReturnStmts.size() > 1) {
1146      Diag(ReturnStmts.back(),
1147           getLangOpts().CPlusPlus1y
1148             ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1149             : diag::ext_constexpr_body_multiple_return);
1150      for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1151        Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1152    }
1153  }
1154
1155  // C++11 [dcl.constexpr]p5:
1156  //   if no function argument values exist such that the function invocation
1157  //   substitution would produce a constant expression, the program is
1158  //   ill-formed; no diagnostic required.
1159  // C++11 [dcl.constexpr]p3:
1160  //   - every constructor call and implicit conversion used in initializing the
1161  //     return value shall be one of those allowed in a constant expression.
1162  // C++11 [dcl.constexpr]p4:
1163  //   - every constructor involved in initializing non-static data members and
1164  //     base class sub-objects shall be a constexpr constructor.
1165  SmallVector<PartialDiagnosticAt, 8> Diags;
1166  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1167    Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1168      << isa<CXXConstructorDecl>(Dcl);
1169    for (size_t I = 0, N = Diags.size(); I != N; ++I)
1170      Diag(Diags[I].first, Diags[I].second);
1171    // Don't return false here: we allow this for compatibility in
1172    // system headers.
1173  }
1174
1175  return true;
1176}
1177
1178/// isCurrentClassName - Determine whether the identifier II is the
1179/// name of the class type currently being defined. In the case of
1180/// nested classes, this will only return true if II is the name of
1181/// the innermost class.
1182bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1183                              const CXXScopeSpec *SS) {
1184  assert(getLangOpts().CPlusPlus && "No class names in C!");
1185
1186  CXXRecordDecl *CurDecl;
1187  if (SS && SS->isSet() && !SS->isInvalid()) {
1188    DeclContext *DC = computeDeclContext(*SS, true);
1189    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1190  } else
1191    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1192
1193  if (CurDecl && CurDecl->getIdentifier())
1194    return &II == CurDecl->getIdentifier();
1195  else
1196    return false;
1197}
1198
1199/// \brief Determine whether the given class is a base class of the given
1200/// class, including looking at dependent bases.
1201static bool findCircularInheritance(const CXXRecordDecl *Class,
1202                                    const CXXRecordDecl *Current) {
1203  SmallVector<const CXXRecordDecl*, 8> Queue;
1204
1205  Class = Class->getCanonicalDecl();
1206  while (true) {
1207    for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1208                                                  E = Current->bases_end();
1209         I != E; ++I) {
1210      CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1211      if (!Base)
1212        continue;
1213
1214      Base = Base->getDefinition();
1215      if (!Base)
1216        continue;
1217
1218      if (Base->getCanonicalDecl() == Class)
1219        return true;
1220
1221      Queue.push_back(Base);
1222    }
1223
1224    if (Queue.empty())
1225      return false;
1226
1227    Current = Queue.back();
1228    Queue.pop_back();
1229  }
1230
1231  return false;
1232}
1233
1234/// \brief Check the validity of a C++ base class specifier.
1235///
1236/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1237/// and returns NULL otherwise.
1238CXXBaseSpecifier *
1239Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1240                         SourceRange SpecifierRange,
1241                         bool Virtual, AccessSpecifier Access,
1242                         TypeSourceInfo *TInfo,
1243                         SourceLocation EllipsisLoc) {
1244  QualType BaseType = TInfo->getType();
1245
1246  // C++ [class.union]p1:
1247  //   A union shall not have base classes.
1248  if (Class->isUnion()) {
1249    Diag(Class->getLocation(), diag::err_base_clause_on_union)
1250      << SpecifierRange;
1251    return 0;
1252  }
1253
1254  if (EllipsisLoc.isValid() &&
1255      !TInfo->getType()->containsUnexpandedParameterPack()) {
1256    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1257      << TInfo->getTypeLoc().getSourceRange();
1258    EllipsisLoc = SourceLocation();
1259  }
1260
1261  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1262
1263  if (BaseType->isDependentType()) {
1264    // Make sure that we don't have circular inheritance among our dependent
1265    // bases. For non-dependent bases, the check for completeness below handles
1266    // this.
1267    if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1268      if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1269          ((BaseDecl = BaseDecl->getDefinition()) &&
1270           findCircularInheritance(Class, BaseDecl))) {
1271        Diag(BaseLoc, diag::err_circular_inheritance)
1272          << BaseType << Context.getTypeDeclType(Class);
1273
1274        if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1275          Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1276            << BaseType;
1277
1278        return 0;
1279      }
1280    }
1281
1282    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1283                                          Class->getTagKind() == TTK_Class,
1284                                          Access, TInfo, EllipsisLoc);
1285  }
1286
1287  // Base specifiers must be record types.
1288  if (!BaseType->isRecordType()) {
1289    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1290    return 0;
1291  }
1292
1293  // C++ [class.union]p1:
1294  //   A union shall not be used as a base class.
1295  if (BaseType->isUnionType()) {
1296    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1297    return 0;
1298  }
1299
1300  // C++ [class.derived]p2:
1301  //   The class-name in a base-specifier shall not be an incompletely
1302  //   defined class.
1303  if (RequireCompleteType(BaseLoc, BaseType,
1304                          diag::err_incomplete_base_class, SpecifierRange)) {
1305    Class->setInvalidDecl();
1306    return 0;
1307  }
1308
1309  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1310  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1311  assert(BaseDecl && "Record type has no declaration");
1312  BaseDecl = BaseDecl->getDefinition();
1313  assert(BaseDecl && "Base type is not incomplete, but has no definition");
1314  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1315  assert(CXXBaseDecl && "Base type is not a C++ type");
1316
1317  // C++ [class]p3:
1318  //   If a class is marked final and it appears as a base-type-specifier in
1319  //   base-clause, the program is ill-formed.
1320  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1321    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1322      << CXXBaseDecl->getDeclName();
1323    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1324      << CXXBaseDecl->getDeclName();
1325    return 0;
1326  }
1327
1328  if (BaseDecl->isInvalidDecl())
1329    Class->setInvalidDecl();
1330
1331  // Create the base specifier.
1332  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1333                                        Class->getTagKind() == TTK_Class,
1334                                        Access, TInfo, EllipsisLoc);
1335}
1336
1337/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1338/// one entry in the base class list of a class specifier, for
1339/// example:
1340///    class foo : public bar, virtual private baz {
1341/// 'public bar' and 'virtual private baz' are each base-specifiers.
1342BaseResult
1343Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1344                         ParsedAttributes &Attributes,
1345                         bool Virtual, AccessSpecifier Access,
1346                         ParsedType basetype, SourceLocation BaseLoc,
1347                         SourceLocation EllipsisLoc) {
1348  if (!classdecl)
1349    return true;
1350
1351  AdjustDeclIfTemplate(classdecl);
1352  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1353  if (!Class)
1354    return true;
1355
1356  // We do not support any C++11 attributes on base-specifiers yet.
1357  // Diagnose any attributes we see.
1358  if (!Attributes.empty()) {
1359    for (AttributeList *Attr = Attributes.getList(); Attr;
1360         Attr = Attr->getNext()) {
1361      if (Attr->isInvalid() ||
1362          Attr->getKind() == AttributeList::IgnoredAttribute)
1363        continue;
1364      Diag(Attr->getLoc(),
1365           Attr->getKind() == AttributeList::UnknownAttribute
1366             ? diag::warn_unknown_attribute_ignored
1367             : diag::err_base_specifier_attribute)
1368        << Attr->getName();
1369    }
1370  }
1371
1372  TypeSourceInfo *TInfo = 0;
1373  GetTypeFromParser(basetype, &TInfo);
1374
1375  if (EllipsisLoc.isInvalid() &&
1376      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1377                                      UPPC_BaseType))
1378    return true;
1379
1380  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1381                                                      Virtual, Access, TInfo,
1382                                                      EllipsisLoc))
1383    return BaseSpec;
1384  else
1385    Class->setInvalidDecl();
1386
1387  return true;
1388}
1389
1390/// \brief Performs the actual work of attaching the given base class
1391/// specifiers to a C++ class.
1392bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1393                                unsigned NumBases) {
1394 if (NumBases == 0)
1395    return false;
1396
1397  // Used to keep track of which base types we have already seen, so
1398  // that we can properly diagnose redundant direct base types. Note
1399  // that the key is always the unqualified canonical type of the base
1400  // class.
1401  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1402
1403  // Copy non-redundant base specifiers into permanent storage.
1404  unsigned NumGoodBases = 0;
1405  bool Invalid = false;
1406  for (unsigned idx = 0; idx < NumBases; ++idx) {
1407    QualType NewBaseType
1408      = Context.getCanonicalType(Bases[idx]->getType());
1409    NewBaseType = NewBaseType.getLocalUnqualifiedType();
1410
1411    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1412    if (KnownBase) {
1413      // C++ [class.mi]p3:
1414      //   A class shall not be specified as a direct base class of a
1415      //   derived class more than once.
1416      Diag(Bases[idx]->getLocStart(),
1417           diag::err_duplicate_base_class)
1418        << KnownBase->getType()
1419        << Bases[idx]->getSourceRange();
1420
1421      // Delete the duplicate base class specifier; we're going to
1422      // overwrite its pointer later.
1423      Context.Deallocate(Bases[idx]);
1424
1425      Invalid = true;
1426    } else {
1427      // Okay, add this new base class.
1428      KnownBase = Bases[idx];
1429      Bases[NumGoodBases++] = Bases[idx];
1430      if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1431        const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1432        if (Class->isInterface() &&
1433              (!RD->isInterface() ||
1434               KnownBase->getAccessSpecifier() != AS_public)) {
1435          // The Microsoft extension __interface does not permit bases that
1436          // are not themselves public interfaces.
1437          Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1438            << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1439            << RD->getSourceRange();
1440          Invalid = true;
1441        }
1442        if (RD->hasAttr<WeakAttr>())
1443          Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1444      }
1445    }
1446  }
1447
1448  // Attach the remaining base class specifiers to the derived class.
1449  Class->setBases(Bases, NumGoodBases);
1450
1451  // Delete the remaining (good) base class specifiers, since their
1452  // data has been copied into the CXXRecordDecl.
1453  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1454    Context.Deallocate(Bases[idx]);
1455
1456  return Invalid;
1457}
1458
1459/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1460/// class, after checking whether there are any duplicate base
1461/// classes.
1462void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1463                               unsigned NumBases) {
1464  if (!ClassDecl || !Bases || !NumBases)
1465    return;
1466
1467  AdjustDeclIfTemplate(ClassDecl);
1468  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1469                       (CXXBaseSpecifier**)(Bases), NumBases);
1470}
1471
1472/// \brief Determine whether the type \p Derived is a C++ class that is
1473/// derived from the type \p Base.
1474bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1475  if (!getLangOpts().CPlusPlus)
1476    return false;
1477
1478  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1479  if (!DerivedRD)
1480    return false;
1481
1482  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1483  if (!BaseRD)
1484    return false;
1485
1486  // If either the base or the derived type is invalid, don't try to
1487  // check whether one is derived from the other.
1488  if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1489    return false;
1490
1491  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1492  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1493}
1494
1495/// \brief Determine whether the type \p Derived is a C++ class that is
1496/// derived from the type \p Base.
1497bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1498  if (!getLangOpts().CPlusPlus)
1499    return false;
1500
1501  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1502  if (!DerivedRD)
1503    return false;
1504
1505  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1506  if (!BaseRD)
1507    return false;
1508
1509  return DerivedRD->isDerivedFrom(BaseRD, Paths);
1510}
1511
1512void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1513                              CXXCastPath &BasePathArray) {
1514  assert(BasePathArray.empty() && "Base path array must be empty!");
1515  assert(Paths.isRecordingPaths() && "Must record paths!");
1516
1517  const CXXBasePath &Path = Paths.front();
1518
1519  // We first go backward and check if we have a virtual base.
1520  // FIXME: It would be better if CXXBasePath had the base specifier for
1521  // the nearest virtual base.
1522  unsigned Start = 0;
1523  for (unsigned I = Path.size(); I != 0; --I) {
1524    if (Path[I - 1].Base->isVirtual()) {
1525      Start = I - 1;
1526      break;
1527    }
1528  }
1529
1530  // Now add all bases.
1531  for (unsigned I = Start, E = Path.size(); I != E; ++I)
1532    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1533}
1534
1535/// \brief Determine whether the given base path includes a virtual
1536/// base class.
1537bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1538  for (CXXCastPath::const_iterator B = BasePath.begin(),
1539                                BEnd = BasePath.end();
1540       B != BEnd; ++B)
1541    if ((*B)->isVirtual())
1542      return true;
1543
1544  return false;
1545}
1546
1547/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1548/// conversion (where Derived and Base are class types) is
1549/// well-formed, meaning that the conversion is unambiguous (and
1550/// that all of the base classes are accessible). Returns true
1551/// and emits a diagnostic if the code is ill-formed, returns false
1552/// otherwise. Loc is the location where this routine should point to
1553/// if there is an error, and Range is the source range to highlight
1554/// if there is an error.
1555bool
1556Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1557                                   unsigned InaccessibleBaseID,
1558                                   unsigned AmbigiousBaseConvID,
1559                                   SourceLocation Loc, SourceRange Range,
1560                                   DeclarationName Name,
1561                                   CXXCastPath *BasePath) {
1562  // First, determine whether the path from Derived to Base is
1563  // ambiguous. This is slightly more expensive than checking whether
1564  // the Derived to Base conversion exists, because here we need to
1565  // explore multiple paths to determine if there is an ambiguity.
1566  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1567                     /*DetectVirtual=*/false);
1568  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1569  assert(DerivationOkay &&
1570         "Can only be used with a derived-to-base conversion");
1571  (void)DerivationOkay;
1572
1573  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1574    if (InaccessibleBaseID) {
1575      // Check that the base class can be accessed.
1576      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1577                                   InaccessibleBaseID)) {
1578        case AR_inaccessible:
1579          return true;
1580        case AR_accessible:
1581        case AR_dependent:
1582        case AR_delayed:
1583          break;
1584      }
1585    }
1586
1587    // Build a base path if necessary.
1588    if (BasePath)
1589      BuildBasePathArray(Paths, *BasePath);
1590    return false;
1591  }
1592
1593  // We know that the derived-to-base conversion is ambiguous, and
1594  // we're going to produce a diagnostic. Perform the derived-to-base
1595  // search just one more time to compute all of the possible paths so
1596  // that we can print them out. This is more expensive than any of
1597  // the previous derived-to-base checks we've done, but at this point
1598  // performance isn't as much of an issue.
1599  Paths.clear();
1600  Paths.setRecordingPaths(true);
1601  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1602  assert(StillOkay && "Can only be used with a derived-to-base conversion");
1603  (void)StillOkay;
1604
1605  // Build up a textual representation of the ambiguous paths, e.g.,
1606  // D -> B -> A, that will be used to illustrate the ambiguous
1607  // conversions in the diagnostic. We only print one of the paths
1608  // to each base class subobject.
1609  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1610
1611  Diag(Loc, AmbigiousBaseConvID)
1612  << Derived << Base << PathDisplayStr << Range << Name;
1613  return true;
1614}
1615
1616bool
1617Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1618                                   SourceLocation Loc, SourceRange Range,
1619                                   CXXCastPath *BasePath,
1620                                   bool IgnoreAccess) {
1621  return CheckDerivedToBaseConversion(Derived, Base,
1622                                      IgnoreAccess ? 0
1623                                       : diag::err_upcast_to_inaccessible_base,
1624                                      diag::err_ambiguous_derived_to_base_conv,
1625                                      Loc, Range, DeclarationName(),
1626                                      BasePath);
1627}
1628
1629
1630/// @brief Builds a string representing ambiguous paths from a
1631/// specific derived class to different subobjects of the same base
1632/// class.
1633///
1634/// This function builds a string that can be used in error messages
1635/// to show the different paths that one can take through the
1636/// inheritance hierarchy to go from the derived class to different
1637/// subobjects of a base class. The result looks something like this:
1638/// @code
1639/// struct D -> struct B -> struct A
1640/// struct D -> struct C -> struct A
1641/// @endcode
1642std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1643  std::string PathDisplayStr;
1644  std::set<unsigned> DisplayedPaths;
1645  for (CXXBasePaths::paths_iterator Path = Paths.begin();
1646       Path != Paths.end(); ++Path) {
1647    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1648      // We haven't displayed a path to this particular base
1649      // class subobject yet.
1650      PathDisplayStr += "\n    ";
1651      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1652      for (CXXBasePath::const_iterator Element = Path->begin();
1653           Element != Path->end(); ++Element)
1654        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1655    }
1656  }
1657
1658  return PathDisplayStr;
1659}
1660
1661//===----------------------------------------------------------------------===//
1662// C++ class member Handling
1663//===----------------------------------------------------------------------===//
1664
1665/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1666bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1667                                SourceLocation ASLoc,
1668                                SourceLocation ColonLoc,
1669                                AttributeList *Attrs) {
1670  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1671  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1672                                                  ASLoc, ColonLoc);
1673  CurContext->addHiddenDecl(ASDecl);
1674  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1675}
1676
1677/// CheckOverrideControl - Check C++11 override control semantics.
1678void Sema::CheckOverrideControl(Decl *D) {
1679  if (D->isInvalidDecl())
1680    return;
1681
1682  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1683
1684  // Do we know which functions this declaration might be overriding?
1685  bool OverridesAreKnown = !MD ||
1686      (!MD->getParent()->hasAnyDependentBases() &&
1687       !MD->getType()->isDependentType());
1688
1689  if (!MD || !MD->isVirtual()) {
1690    if (OverridesAreKnown) {
1691      if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1692        Diag(OA->getLocation(),
1693             diag::override_keyword_only_allowed_on_virtual_member_functions)
1694          << "override" << FixItHint::CreateRemoval(OA->getLocation());
1695        D->dropAttr<OverrideAttr>();
1696      }
1697      if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1698        Diag(FA->getLocation(),
1699             diag::override_keyword_only_allowed_on_virtual_member_functions)
1700          << "final" << FixItHint::CreateRemoval(FA->getLocation());
1701        D->dropAttr<FinalAttr>();
1702      }
1703    }
1704    return;
1705  }
1706
1707  if (!OverridesAreKnown)
1708    return;
1709
1710  // C++11 [class.virtual]p5:
1711  //   If a virtual function is marked with the virt-specifier override and
1712  //   does not override a member function of a base class, the program is
1713  //   ill-formed.
1714  bool HasOverriddenMethods =
1715    MD->begin_overridden_methods() != MD->end_overridden_methods();
1716  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1717    Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1718      << MD->getDeclName();
1719}
1720
1721/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1722/// function overrides a virtual member function marked 'final', according to
1723/// C++11 [class.virtual]p4.
1724bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1725                                                  const CXXMethodDecl *Old) {
1726  if (!Old->hasAttr<FinalAttr>())
1727    return false;
1728
1729  Diag(New->getLocation(), diag::err_final_function_overridden)
1730    << New->getDeclName();
1731  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1732  return true;
1733}
1734
1735static bool InitializationHasSideEffects(const FieldDecl &FD) {
1736  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1737  // FIXME: Destruction of ObjC lifetime types has side-effects.
1738  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1739    return !RD->isCompleteDefinition() ||
1740           !RD->hasTrivialDefaultConstructor() ||
1741           !RD->hasTrivialDestructor();
1742  return false;
1743}
1744
1745static AttributeList *getMSPropertyAttr(AttributeList *list) {
1746  for (AttributeList* it = list; it != 0; it = it->getNext())
1747    if (it->isDeclspecPropertyAttribute())
1748      return it;
1749  return 0;
1750}
1751
1752/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1753/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1754/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1755/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1756/// present (but parsing it has been deferred).
1757NamedDecl *
1758Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1759                               MultiTemplateParamsArg TemplateParameterLists,
1760                               Expr *BW, const VirtSpecifiers &VS,
1761                               InClassInitStyle InitStyle) {
1762  const DeclSpec &DS = D.getDeclSpec();
1763  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1764  DeclarationName Name = NameInfo.getName();
1765  SourceLocation Loc = NameInfo.getLoc();
1766
1767  // For anonymous bitfields, the location should point to the type.
1768  if (Loc.isInvalid())
1769    Loc = D.getLocStart();
1770
1771  Expr *BitWidth = static_cast<Expr*>(BW);
1772
1773  assert(isa<CXXRecordDecl>(CurContext));
1774  assert(!DS.isFriendSpecified());
1775
1776  bool isFunc = D.isDeclarationOfFunction();
1777
1778  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1779    // The Microsoft extension __interface only permits public member functions
1780    // and prohibits constructors, destructors, operators, non-public member
1781    // functions, static methods and data members.
1782    unsigned InvalidDecl;
1783    bool ShowDeclName = true;
1784    if (!isFunc)
1785      InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1786    else if (AS != AS_public)
1787      InvalidDecl = 2;
1788    else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1789      InvalidDecl = 3;
1790    else switch (Name.getNameKind()) {
1791      case DeclarationName::CXXConstructorName:
1792        InvalidDecl = 4;
1793        ShowDeclName = false;
1794        break;
1795
1796      case DeclarationName::CXXDestructorName:
1797        InvalidDecl = 5;
1798        ShowDeclName = false;
1799        break;
1800
1801      case DeclarationName::CXXOperatorName:
1802      case DeclarationName::CXXConversionFunctionName:
1803        InvalidDecl = 6;
1804        break;
1805
1806      default:
1807        InvalidDecl = 0;
1808        break;
1809    }
1810
1811    if (InvalidDecl) {
1812      if (ShowDeclName)
1813        Diag(Loc, diag::err_invalid_member_in_interface)
1814          << (InvalidDecl-1) << Name;
1815      else
1816        Diag(Loc, diag::err_invalid_member_in_interface)
1817          << (InvalidDecl-1) << "";
1818      return 0;
1819    }
1820  }
1821
1822  // C++ 9.2p6: A member shall not be declared to have automatic storage
1823  // duration (auto, register) or with the extern storage-class-specifier.
1824  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1825  // data members and cannot be applied to names declared const or static,
1826  // and cannot be applied to reference members.
1827  switch (DS.getStorageClassSpec()) {
1828  case DeclSpec::SCS_unspecified:
1829  case DeclSpec::SCS_typedef:
1830  case DeclSpec::SCS_static:
1831    break;
1832  case DeclSpec::SCS_mutable:
1833    if (isFunc) {
1834      Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1835
1836      // FIXME: It would be nicer if the keyword was ignored only for this
1837      // declarator. Otherwise we could get follow-up errors.
1838      D.getMutableDeclSpec().ClearStorageClassSpecs();
1839    }
1840    break;
1841  default:
1842    Diag(DS.getStorageClassSpecLoc(),
1843         diag::err_storageclass_invalid_for_member);
1844    D.getMutableDeclSpec().ClearStorageClassSpecs();
1845    break;
1846  }
1847
1848  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1849                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1850                      !isFunc);
1851
1852  if (DS.isConstexprSpecified() && isInstField) {
1853    SemaDiagnosticBuilder B =
1854        Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1855    SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1856    if (InitStyle == ICIS_NoInit) {
1857      B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1858      D.getMutableDeclSpec().ClearConstexprSpec();
1859      const char *PrevSpec;
1860      unsigned DiagID;
1861      bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1862                                         PrevSpec, DiagID, getLangOpts());
1863      (void)Failed;
1864      assert(!Failed && "Making a constexpr member const shouldn't fail");
1865    } else {
1866      B << 1;
1867      const char *PrevSpec;
1868      unsigned DiagID;
1869      if (D.getMutableDeclSpec().SetStorageClassSpec(
1870          *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
1871        assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
1872               "This is the only DeclSpec that should fail to be applied");
1873        B << 1;
1874      } else {
1875        B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1876        isInstField = false;
1877      }
1878    }
1879  }
1880
1881  NamedDecl *Member;
1882  if (isInstField) {
1883    CXXScopeSpec &SS = D.getCXXScopeSpec();
1884
1885    // Data members must have identifiers for names.
1886    if (!Name.isIdentifier()) {
1887      Diag(Loc, diag::err_bad_variable_name)
1888        << Name;
1889      return 0;
1890    }
1891
1892    IdentifierInfo *II = Name.getAsIdentifierInfo();
1893
1894    // Member field could not be with "template" keyword.
1895    // So TemplateParameterLists should be empty in this case.
1896    if (TemplateParameterLists.size()) {
1897      TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1898      if (TemplateParams->size()) {
1899        // There is no such thing as a member field template.
1900        Diag(D.getIdentifierLoc(), diag::err_template_member)
1901            << II
1902            << SourceRange(TemplateParams->getTemplateLoc(),
1903                TemplateParams->getRAngleLoc());
1904      } else {
1905        // There is an extraneous 'template<>' for this member.
1906        Diag(TemplateParams->getTemplateLoc(),
1907            diag::err_template_member_noparams)
1908            << II
1909            << SourceRange(TemplateParams->getTemplateLoc(),
1910                TemplateParams->getRAngleLoc());
1911      }
1912      return 0;
1913    }
1914
1915    if (SS.isSet() && !SS.isInvalid()) {
1916      // The user provided a superfluous scope specifier inside a class
1917      // definition:
1918      //
1919      // class X {
1920      //   int X::member;
1921      // };
1922      if (DeclContext *DC = computeDeclContext(SS, false))
1923        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1924      else
1925        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1926          << Name << SS.getRange();
1927
1928      SS.clear();
1929    }
1930
1931    AttributeList *MSPropertyAttr =
1932      getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1933    if (MSPropertyAttr) {
1934      Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1935                                BitWidth, InitStyle, AS, MSPropertyAttr);
1936      isInstField = false;
1937    } else {
1938      Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1939                                BitWidth, InitStyle, AS);
1940    }
1941    assert(Member && "HandleField never returns null");
1942  } else {
1943    assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1944
1945    Member = HandleDeclarator(S, D, TemplateParameterLists);
1946    if (!Member) {
1947      return 0;
1948    }
1949
1950    // Non-instance-fields can't have a bitfield.
1951    if (BitWidth) {
1952      if (Member->isInvalidDecl()) {
1953        // don't emit another diagnostic.
1954      } else if (isa<VarDecl>(Member)) {
1955        // C++ 9.6p3: A bit-field shall not be a static member.
1956        // "static member 'A' cannot be a bit-field"
1957        Diag(Loc, diag::err_static_not_bitfield)
1958          << Name << BitWidth->getSourceRange();
1959      } else if (isa<TypedefDecl>(Member)) {
1960        // "typedef member 'x' cannot be a bit-field"
1961        Diag(Loc, diag::err_typedef_not_bitfield)
1962          << Name << BitWidth->getSourceRange();
1963      } else {
1964        // A function typedef ("typedef int f(); f a;").
1965        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1966        Diag(Loc, diag::err_not_integral_type_bitfield)
1967          << Name << cast<ValueDecl>(Member)->getType()
1968          << BitWidth->getSourceRange();
1969      }
1970
1971      BitWidth = 0;
1972      Member->setInvalidDecl();
1973    }
1974
1975    Member->setAccess(AS);
1976
1977    // If we have declared a member function template, set the access of the
1978    // templated declaration as well.
1979    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1980      FunTmpl->getTemplatedDecl()->setAccess(AS);
1981  }
1982
1983  if (VS.isOverrideSpecified())
1984    Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1985  if (VS.isFinalSpecified())
1986    Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1987
1988  if (VS.getLastLocation().isValid()) {
1989    // Update the end location of a method that has a virt-specifiers.
1990    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1991      MD->setRangeEnd(VS.getLastLocation());
1992  }
1993
1994  CheckOverrideControl(Member);
1995
1996  assert((Name || isInstField) && "No identifier for non-field ?");
1997
1998  if (isInstField) {
1999    FieldDecl *FD = cast<FieldDecl>(Member);
2000    FieldCollector->Add(FD);
2001
2002    if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2003                                 FD->getLocation())
2004          != DiagnosticsEngine::Ignored) {
2005      // Remember all explicit private FieldDecls that have a name, no side
2006      // effects and are not part of a dependent type declaration.
2007      if (!FD->isImplicit() && FD->getDeclName() &&
2008          FD->getAccess() == AS_private &&
2009          !FD->hasAttr<UnusedAttr>() &&
2010          !FD->getParent()->isDependentContext() &&
2011          !InitializationHasSideEffects(*FD))
2012        UnusedPrivateFields.insert(FD);
2013    }
2014  }
2015
2016  return Member;
2017}
2018
2019namespace {
2020  class UninitializedFieldVisitor
2021      : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2022    Sema &S;
2023    ValueDecl *VD;
2024  public:
2025    typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2026    UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
2027                                                        S(S) {
2028      if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2029        this->VD = IFD->getAnonField();
2030      else
2031        this->VD = VD;
2032    }
2033
2034    void HandleExpr(Expr *E) {
2035      if (!E) return;
2036
2037      // Expressions like x(x) sometimes lack the surrounding expressions
2038      // but need to be checked anyways.
2039      HandleValue(E);
2040      Visit(E);
2041    }
2042
2043    void HandleValue(Expr *E) {
2044      E = E->IgnoreParens();
2045
2046      if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2047        if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2048          return;
2049
2050        // FieldME is the inner-most MemberExpr that is not an anonymous struct
2051        // or union.
2052        MemberExpr *FieldME = ME;
2053
2054        Expr *Base = E;
2055        while (isa<MemberExpr>(Base)) {
2056          ME = cast<MemberExpr>(Base);
2057
2058          if (isa<VarDecl>(ME->getMemberDecl()))
2059            return;
2060
2061          if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2062            if (!FD->isAnonymousStructOrUnion())
2063              FieldME = ME;
2064
2065          Base = ME->getBase();
2066        }
2067
2068        if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
2069          unsigned diag = VD->getType()->isReferenceType()
2070              ? diag::warn_reference_field_is_uninit
2071              : diag::warn_field_is_uninit;
2072          S.Diag(FieldME->getExprLoc(), diag) << VD;
2073        }
2074        return;
2075      }
2076
2077      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2078        HandleValue(CO->getTrueExpr());
2079        HandleValue(CO->getFalseExpr());
2080        return;
2081      }
2082
2083      if (BinaryConditionalOperator *BCO =
2084              dyn_cast<BinaryConditionalOperator>(E)) {
2085        HandleValue(BCO->getCommon());
2086        HandleValue(BCO->getFalseExpr());
2087        return;
2088      }
2089
2090      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2091        switch (BO->getOpcode()) {
2092        default:
2093          return;
2094        case(BO_PtrMemD):
2095        case(BO_PtrMemI):
2096          HandleValue(BO->getLHS());
2097          return;
2098        case(BO_Comma):
2099          HandleValue(BO->getRHS());
2100          return;
2101        }
2102      }
2103    }
2104
2105    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2106      if (E->getCastKind() == CK_LValueToRValue)
2107        HandleValue(E->getSubExpr());
2108
2109      Inherited::VisitImplicitCastExpr(E);
2110    }
2111
2112    void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2113      Expr *Callee = E->getCallee();
2114      if (isa<MemberExpr>(Callee))
2115        HandleValue(Callee);
2116
2117      Inherited::VisitCXXMemberCallExpr(E);
2118    }
2119  };
2120  static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2121                                                       ValueDecl *VD) {
2122    UninitializedFieldVisitor(S, VD).HandleExpr(E);
2123  }
2124} // namespace
2125
2126/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
2127/// in-class initializer for a non-static C++ class member, and after
2128/// instantiating an in-class initializer in a class template. Such actions
2129/// are deferred until the class is complete.
2130void
2131Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
2132                                       Expr *InitExpr) {
2133  FieldDecl *FD = cast<FieldDecl>(D);
2134  assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2135         "must set init style when field is created");
2136
2137  if (!InitExpr) {
2138    FD->setInvalidDecl();
2139    FD->removeInClassInitializer();
2140    return;
2141  }
2142
2143  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2144    FD->setInvalidDecl();
2145    FD->removeInClassInitializer();
2146    return;
2147  }
2148
2149  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2150      != DiagnosticsEngine::Ignored) {
2151    CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2152  }
2153
2154  ExprResult Init = InitExpr;
2155  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2156    if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
2157      Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
2158        << /*at end of ctor*/1 << InitExpr->getSourceRange();
2159    }
2160    InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2161    InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2162        ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2163        : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2164    InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2165    Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2166    if (Init.isInvalid()) {
2167      FD->setInvalidDecl();
2168      return;
2169    }
2170  }
2171
2172  // C++11 [class.base.init]p7:
2173  //   The initialization of each base and member constitutes a
2174  //   full-expression.
2175  Init = ActOnFinishFullExpr(Init.take(), InitLoc);
2176  if (Init.isInvalid()) {
2177    FD->setInvalidDecl();
2178    return;
2179  }
2180
2181  InitExpr = Init.release();
2182
2183  FD->setInClassInitializer(InitExpr);
2184}
2185
2186/// \brief Find the direct and/or virtual base specifiers that
2187/// correspond to the given base type, for use in base initialization
2188/// within a constructor.
2189static bool FindBaseInitializer(Sema &SemaRef,
2190                                CXXRecordDecl *ClassDecl,
2191                                QualType BaseType,
2192                                const CXXBaseSpecifier *&DirectBaseSpec,
2193                                const CXXBaseSpecifier *&VirtualBaseSpec) {
2194  // First, check for a direct base class.
2195  DirectBaseSpec = 0;
2196  for (CXXRecordDecl::base_class_const_iterator Base
2197         = ClassDecl->bases_begin();
2198       Base != ClassDecl->bases_end(); ++Base) {
2199    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2200      // We found a direct base of this type. That's what we're
2201      // initializing.
2202      DirectBaseSpec = &*Base;
2203      break;
2204    }
2205  }
2206
2207  // Check for a virtual base class.
2208  // FIXME: We might be able to short-circuit this if we know in advance that
2209  // there are no virtual bases.
2210  VirtualBaseSpec = 0;
2211  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2212    // We haven't found a base yet; search the class hierarchy for a
2213    // virtual base class.
2214    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2215                       /*DetectVirtual=*/false);
2216    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2217                              BaseType, Paths)) {
2218      for (CXXBasePaths::paths_iterator Path = Paths.begin();
2219           Path != Paths.end(); ++Path) {
2220        if (Path->back().Base->isVirtual()) {
2221          VirtualBaseSpec = Path->back().Base;
2222          break;
2223        }
2224      }
2225    }
2226  }
2227
2228  return DirectBaseSpec || VirtualBaseSpec;
2229}
2230
2231/// \brief Handle a C++ member initializer using braced-init-list syntax.
2232MemInitResult
2233Sema::ActOnMemInitializer(Decl *ConstructorD,
2234                          Scope *S,
2235                          CXXScopeSpec &SS,
2236                          IdentifierInfo *MemberOrBase,
2237                          ParsedType TemplateTypeTy,
2238                          const DeclSpec &DS,
2239                          SourceLocation IdLoc,
2240                          Expr *InitList,
2241                          SourceLocation EllipsisLoc) {
2242  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2243                             DS, IdLoc, InitList,
2244                             EllipsisLoc);
2245}
2246
2247/// \brief Handle a C++ member initializer using parentheses syntax.
2248MemInitResult
2249Sema::ActOnMemInitializer(Decl *ConstructorD,
2250                          Scope *S,
2251                          CXXScopeSpec &SS,
2252                          IdentifierInfo *MemberOrBase,
2253                          ParsedType TemplateTypeTy,
2254                          const DeclSpec &DS,
2255                          SourceLocation IdLoc,
2256                          SourceLocation LParenLoc,
2257                          Expr **Args, unsigned NumArgs,
2258                          SourceLocation RParenLoc,
2259                          SourceLocation EllipsisLoc) {
2260  Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2261                                           llvm::makeArrayRef(Args, NumArgs),
2262                                           RParenLoc);
2263  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2264                             DS, IdLoc, List, EllipsisLoc);
2265}
2266
2267namespace {
2268
2269// Callback to only accept typo corrections that can be a valid C++ member
2270// intializer: either a non-static field member or a base class.
2271class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2272 public:
2273  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2274      : ClassDecl(ClassDecl) {}
2275
2276  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2277    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2278      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2279        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2280      else
2281        return isa<TypeDecl>(ND);
2282    }
2283    return false;
2284  }
2285
2286 private:
2287  CXXRecordDecl *ClassDecl;
2288};
2289
2290}
2291
2292/// \brief Handle a C++ member initializer.
2293MemInitResult
2294Sema::BuildMemInitializer(Decl *ConstructorD,
2295                          Scope *S,
2296                          CXXScopeSpec &SS,
2297                          IdentifierInfo *MemberOrBase,
2298                          ParsedType TemplateTypeTy,
2299                          const DeclSpec &DS,
2300                          SourceLocation IdLoc,
2301                          Expr *Init,
2302                          SourceLocation EllipsisLoc) {
2303  if (!ConstructorD)
2304    return true;
2305
2306  AdjustDeclIfTemplate(ConstructorD);
2307
2308  CXXConstructorDecl *Constructor
2309    = dyn_cast<CXXConstructorDecl>(ConstructorD);
2310  if (!Constructor) {
2311    // The user wrote a constructor initializer on a function that is
2312    // not a C++ constructor. Ignore the error for now, because we may
2313    // have more member initializers coming; we'll diagnose it just
2314    // once in ActOnMemInitializers.
2315    return true;
2316  }
2317
2318  CXXRecordDecl *ClassDecl = Constructor->getParent();
2319
2320  // C++ [class.base.init]p2:
2321  //   Names in a mem-initializer-id are looked up in the scope of the
2322  //   constructor's class and, if not found in that scope, are looked
2323  //   up in the scope containing the constructor's definition.
2324  //   [Note: if the constructor's class contains a member with the
2325  //   same name as a direct or virtual base class of the class, a
2326  //   mem-initializer-id naming the member or base class and composed
2327  //   of a single identifier refers to the class member. A
2328  //   mem-initializer-id for the hidden base class may be specified
2329  //   using a qualified name. ]
2330  if (!SS.getScopeRep() && !TemplateTypeTy) {
2331    // Look for a member, first.
2332    DeclContext::lookup_result Result
2333      = ClassDecl->lookup(MemberOrBase);
2334    if (!Result.empty()) {
2335      ValueDecl *Member;
2336      if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2337          (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2338        if (EllipsisLoc.isValid())
2339          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2340            << MemberOrBase
2341            << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2342
2343        return BuildMemberInitializer(Member, Init, IdLoc);
2344      }
2345    }
2346  }
2347  // It didn't name a member, so see if it names a class.
2348  QualType BaseType;
2349  TypeSourceInfo *TInfo = 0;
2350
2351  if (TemplateTypeTy) {
2352    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2353  } else if (DS.getTypeSpecType() == TST_decltype) {
2354    BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2355  } else {
2356    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2357    LookupParsedName(R, S, &SS);
2358
2359    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2360    if (!TyD) {
2361      if (R.isAmbiguous()) return true;
2362
2363      // We don't want access-control diagnostics here.
2364      R.suppressDiagnostics();
2365
2366      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2367        bool NotUnknownSpecialization = false;
2368        DeclContext *DC = computeDeclContext(SS, false);
2369        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2370          NotUnknownSpecialization = !Record->hasAnyDependentBases();
2371
2372        if (!NotUnknownSpecialization) {
2373          // When the scope specifier can refer to a member of an unknown
2374          // specialization, we take it as a type name.
2375          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2376                                       SS.getWithLocInContext(Context),
2377                                       *MemberOrBase, IdLoc);
2378          if (BaseType.isNull())
2379            return true;
2380
2381          R.clear();
2382          R.setLookupName(MemberOrBase);
2383        }
2384      }
2385
2386      // If no results were found, try to correct typos.
2387      TypoCorrection Corr;
2388      MemInitializerValidatorCCC Validator(ClassDecl);
2389      if (R.empty() && BaseType.isNull() &&
2390          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2391                              Validator, ClassDecl))) {
2392        std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2393        std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
2394        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2395          // We have found a non-static data member with a similar
2396          // name to what was typed; complain and initialize that
2397          // member.
2398          Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2399            << MemberOrBase << true << CorrectedQuotedStr
2400            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2401          Diag(Member->getLocation(), diag::note_previous_decl)
2402            << CorrectedQuotedStr;
2403
2404          return BuildMemberInitializer(Member, Init, IdLoc);
2405        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2406          const CXXBaseSpecifier *DirectBaseSpec;
2407          const CXXBaseSpecifier *VirtualBaseSpec;
2408          if (FindBaseInitializer(*this, ClassDecl,
2409                                  Context.getTypeDeclType(Type),
2410                                  DirectBaseSpec, VirtualBaseSpec)) {
2411            // We have found a direct or virtual base class with a
2412            // similar name to what was typed; complain and initialize
2413            // that base class.
2414            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2415              << MemberOrBase << false << CorrectedQuotedStr
2416              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2417
2418            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2419                                                             : VirtualBaseSpec;
2420            Diag(BaseSpec->getLocStart(),
2421                 diag::note_base_class_specified_here)
2422              << BaseSpec->getType()
2423              << BaseSpec->getSourceRange();
2424
2425            TyD = Type;
2426          }
2427        }
2428      }
2429
2430      if (!TyD && BaseType.isNull()) {
2431        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2432          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2433        return true;
2434      }
2435    }
2436
2437    if (BaseType.isNull()) {
2438      BaseType = Context.getTypeDeclType(TyD);
2439      if (SS.isSet()) {
2440        NestedNameSpecifier *Qualifier =
2441          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2442
2443        // FIXME: preserve source range information
2444        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
2445      }
2446    }
2447  }
2448
2449  if (!TInfo)
2450    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2451
2452  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2453}
2454
2455/// Checks a member initializer expression for cases where reference (or
2456/// pointer) members are bound to by-value parameters (or their addresses).
2457static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2458                                               Expr *Init,
2459                                               SourceLocation IdLoc) {
2460  QualType MemberTy = Member->getType();
2461
2462  // We only handle pointers and references currently.
2463  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2464  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2465    return;
2466
2467  const bool IsPointer = MemberTy->isPointerType();
2468  if (IsPointer) {
2469    if (const UnaryOperator *Op
2470          = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2471      // The only case we're worried about with pointers requires taking the
2472      // address.
2473      if (Op->getOpcode() != UO_AddrOf)
2474        return;
2475
2476      Init = Op->getSubExpr();
2477    } else {
2478      // We only handle address-of expression initializers for pointers.
2479      return;
2480    }
2481  }
2482
2483  if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2484    // Taking the address of a temporary will be diagnosed as a hard error.
2485    if (IsPointer)
2486      return;
2487
2488    S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2489      << Member << Init->getSourceRange();
2490  } else if (const DeclRefExpr *DRE
2491               = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2492    // We only warn when referring to a non-reference parameter declaration.
2493    const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2494    if (!Parameter || Parameter->getType()->isReferenceType())
2495      return;
2496
2497    S.Diag(Init->getExprLoc(),
2498           IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2499                     : diag::warn_bind_ref_member_to_parameter)
2500      << Member << Parameter << Init->getSourceRange();
2501  } else {
2502    // Other initializers are fine.
2503    return;
2504  }
2505
2506  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2507    << (unsigned)IsPointer;
2508}
2509
2510MemInitResult
2511Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2512                             SourceLocation IdLoc) {
2513  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2514  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2515  assert((DirectMember || IndirectMember) &&
2516         "Member must be a FieldDecl or IndirectFieldDecl");
2517
2518  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2519    return true;
2520
2521  if (Member->isInvalidDecl())
2522    return true;
2523
2524  // Diagnose value-uses of fields to initialize themselves, e.g.
2525  //   foo(foo)
2526  // where foo is not also a parameter to the constructor.
2527  // TODO: implement -Wuninitialized and fold this into that framework.
2528  MultiExprArg Args;
2529  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2530    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2531  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2532    Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2533  } else {
2534    // Template instantiation doesn't reconstruct ParenListExprs for us.
2535    Args = Init;
2536  }
2537
2538  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2539        != DiagnosticsEngine::Ignored)
2540    for (unsigned i = 0, e = Args.size(); i != e; ++i)
2541      // FIXME: Warn about the case when other fields are used before being
2542      // initialized. For example, let this field be the i'th field. When
2543      // initializing the i'th field, throw a warning if any of the >= i'th
2544      // fields are used, as they are not yet initialized.
2545      // Right now we are only handling the case where the i'th field uses
2546      // itself in its initializer.
2547      // Also need to take into account that some fields may be initialized by
2548      // in-class initializers, see C++11 [class.base.init]p9.
2549      CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
2550
2551  SourceRange InitRange = Init->getSourceRange();
2552
2553  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2554    // Can't check initialization for a member of dependent type or when
2555    // any of the arguments are type-dependent expressions.
2556    DiscardCleanupsInEvaluationContext();
2557  } else {
2558    bool InitList = false;
2559    if (isa<InitListExpr>(Init)) {
2560      InitList = true;
2561      Args = Init;
2562
2563      if (isStdInitializerList(Member->getType(), 0)) {
2564        Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2565            << /*at end of ctor*/1 << InitRange;
2566      }
2567    }
2568
2569    // Initialize the member.
2570    InitializedEntity MemberEntity =
2571      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2572                   : InitializedEntity::InitializeMember(IndirectMember, 0);
2573    InitializationKind Kind =
2574      InitList ? InitializationKind::CreateDirectList(IdLoc)
2575               : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2576                                                  InitRange.getEnd());
2577
2578    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2579    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
2580    if (MemberInit.isInvalid())
2581      return true;
2582
2583    // C++11 [class.base.init]p7:
2584    //   The initialization of each base and member constitutes a
2585    //   full-expression.
2586    MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2587    if (MemberInit.isInvalid())
2588      return true;
2589
2590    Init = MemberInit.get();
2591    CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2592  }
2593
2594  if (DirectMember) {
2595    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2596                                            InitRange.getBegin(), Init,
2597                                            InitRange.getEnd());
2598  } else {
2599    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2600                                            InitRange.getBegin(), Init,
2601                                            InitRange.getEnd());
2602  }
2603}
2604
2605MemInitResult
2606Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2607                                 CXXRecordDecl *ClassDecl) {
2608  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2609  if (!LangOpts.CPlusPlus11)
2610    return Diag(NameLoc, diag::err_delegating_ctor)
2611      << TInfo->getTypeLoc().getLocalSourceRange();
2612  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2613
2614  bool InitList = true;
2615  MultiExprArg Args = Init;
2616  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2617    InitList = false;
2618    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2619  }
2620
2621  SourceRange InitRange = Init->getSourceRange();
2622  // Initialize the object.
2623  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2624                                     QualType(ClassDecl->getTypeForDecl(), 0));
2625  InitializationKind Kind =
2626    InitList ? InitializationKind::CreateDirectList(NameLoc)
2627             : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2628                                                InitRange.getEnd());
2629  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
2630  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2631                                              Args, 0);
2632  if (DelegationInit.isInvalid())
2633    return true;
2634
2635  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2636         "Delegating constructor with no target?");
2637
2638  // C++11 [class.base.init]p7:
2639  //   The initialization of each base and member constitutes a
2640  //   full-expression.
2641  DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2642                                       InitRange.getBegin());
2643  if (DelegationInit.isInvalid())
2644    return true;
2645
2646  // If we are in a dependent context, template instantiation will
2647  // perform this type-checking again. Just save the arguments that we
2648  // received in a ParenListExpr.
2649  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2650  // of the information that we have about the base
2651  // initializer. However, deconstructing the ASTs is a dicey process,
2652  // and this approach is far more likely to get the corner cases right.
2653  if (CurContext->isDependentContext())
2654    DelegationInit = Owned(Init);
2655
2656  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2657                                          DelegationInit.takeAs<Expr>(),
2658                                          InitRange.getEnd());
2659}
2660
2661MemInitResult
2662Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2663                           Expr *Init, CXXRecordDecl *ClassDecl,
2664                           SourceLocation EllipsisLoc) {
2665  SourceLocation BaseLoc
2666    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2667
2668  if (!BaseType->isDependentType() && !BaseType->isRecordType())
2669    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2670             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2671
2672  // C++ [class.base.init]p2:
2673  //   [...] Unless the mem-initializer-id names a nonstatic data
2674  //   member of the constructor's class or a direct or virtual base
2675  //   of that class, the mem-initializer is ill-formed. A
2676  //   mem-initializer-list can initialize a base class using any
2677  //   name that denotes that base class type.
2678  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2679
2680  SourceRange InitRange = Init->getSourceRange();
2681  if (EllipsisLoc.isValid()) {
2682    // This is a pack expansion.
2683    if (!BaseType->containsUnexpandedParameterPack())  {
2684      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2685        << SourceRange(BaseLoc, InitRange.getEnd());
2686
2687      EllipsisLoc = SourceLocation();
2688    }
2689  } else {
2690    // Check for any unexpanded parameter packs.
2691    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2692      return true;
2693
2694    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2695      return true;
2696  }
2697
2698  // Check for direct and virtual base classes.
2699  const CXXBaseSpecifier *DirectBaseSpec = 0;
2700  const CXXBaseSpecifier *VirtualBaseSpec = 0;
2701  if (!Dependent) {
2702    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2703                                       BaseType))
2704      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2705
2706    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2707                        VirtualBaseSpec);
2708
2709    // C++ [base.class.init]p2:
2710    // Unless the mem-initializer-id names a nonstatic data member of the
2711    // constructor's class or a direct or virtual base of that class, the
2712    // mem-initializer is ill-formed.
2713    if (!DirectBaseSpec && !VirtualBaseSpec) {
2714      // If the class has any dependent bases, then it's possible that
2715      // one of those types will resolve to the same type as
2716      // BaseType. Therefore, just treat this as a dependent base
2717      // class initialization.  FIXME: Should we try to check the
2718      // initialization anyway? It seems odd.
2719      if (ClassDecl->hasAnyDependentBases())
2720        Dependent = true;
2721      else
2722        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2723          << BaseType << Context.getTypeDeclType(ClassDecl)
2724          << BaseTInfo->getTypeLoc().getLocalSourceRange();
2725    }
2726  }
2727
2728  if (Dependent) {
2729    DiscardCleanupsInEvaluationContext();
2730
2731    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2732                                            /*IsVirtual=*/false,
2733                                            InitRange.getBegin(), Init,
2734                                            InitRange.getEnd(), EllipsisLoc);
2735  }
2736
2737  // C++ [base.class.init]p2:
2738  //   If a mem-initializer-id is ambiguous because it designates both
2739  //   a direct non-virtual base class and an inherited virtual base
2740  //   class, the mem-initializer is ill-formed.
2741  if (DirectBaseSpec && VirtualBaseSpec)
2742    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2743      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2744
2745  CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2746  if (!BaseSpec)
2747    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2748
2749  // Initialize the base.
2750  bool InitList = true;
2751  MultiExprArg Args = Init;
2752  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2753    InitList = false;
2754    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2755  }
2756
2757  InitializedEntity BaseEntity =
2758    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2759  InitializationKind Kind =
2760    InitList ? InitializationKind::CreateDirectList(BaseLoc)
2761             : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2762                                                InitRange.getEnd());
2763  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2764  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
2765  if (BaseInit.isInvalid())
2766    return true;
2767
2768  // C++11 [class.base.init]p7:
2769  //   The initialization of each base and member constitutes a
2770  //   full-expression.
2771  BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
2772  if (BaseInit.isInvalid())
2773    return true;
2774
2775  // If we are in a dependent context, template instantiation will
2776  // perform this type-checking again. Just save the arguments that we
2777  // received in a ParenListExpr.
2778  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2779  // of the information that we have about the base
2780  // initializer. However, deconstructing the ASTs is a dicey process,
2781  // and this approach is far more likely to get the corner cases right.
2782  if (CurContext->isDependentContext())
2783    BaseInit = Owned(Init);
2784
2785  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2786                                          BaseSpec->isVirtual(),
2787                                          InitRange.getBegin(),
2788                                          BaseInit.takeAs<Expr>(),
2789                                          InitRange.getEnd(), EllipsisLoc);
2790}
2791
2792// Create a static_cast\<T&&>(expr).
2793static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2794  if (T.isNull()) T = E->getType();
2795  QualType TargetType = SemaRef.BuildReferenceType(
2796      T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
2797  SourceLocation ExprLoc = E->getLocStart();
2798  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2799      TargetType, ExprLoc);
2800
2801  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2802                                   SourceRange(ExprLoc, ExprLoc),
2803                                   E->getSourceRange()).take();
2804}
2805
2806/// ImplicitInitializerKind - How an implicit base or member initializer should
2807/// initialize its base or member.
2808enum ImplicitInitializerKind {
2809  IIK_Default,
2810  IIK_Copy,
2811  IIK_Move,
2812  IIK_Inherit
2813};
2814
2815static bool
2816BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2817                             ImplicitInitializerKind ImplicitInitKind,
2818                             CXXBaseSpecifier *BaseSpec,
2819                             bool IsInheritedVirtualBase,
2820                             CXXCtorInitializer *&CXXBaseInit) {
2821  InitializedEntity InitEntity
2822    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2823                                        IsInheritedVirtualBase);
2824
2825  ExprResult BaseInit;
2826
2827  switch (ImplicitInitKind) {
2828  case IIK_Inherit: {
2829    const CXXRecordDecl *Inherited =
2830        Constructor->getInheritedConstructor()->getParent();
2831    const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2832    if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2833      // C++11 [class.inhctor]p8:
2834      //   Each expression in the expression-list is of the form
2835      //   static_cast<T&&>(p), where p is the name of the corresponding
2836      //   constructor parameter and T is the declared type of p.
2837      SmallVector<Expr*, 16> Args;
2838      for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2839        ParmVarDecl *PD = Constructor->getParamDecl(I);
2840        ExprResult ArgExpr =
2841            SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2842                                     VK_LValue, SourceLocation());
2843        if (ArgExpr.isInvalid())
2844          return true;
2845        Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2846      }
2847
2848      InitializationKind InitKind = InitializationKind::CreateDirect(
2849          Constructor->getLocation(), SourceLocation(), SourceLocation());
2850      InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
2851      BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2852      break;
2853    }
2854  }
2855  // Fall through.
2856  case IIK_Default: {
2857    InitializationKind InitKind
2858      = InitializationKind::CreateDefault(Constructor->getLocation());
2859    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2860    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
2861    break;
2862  }
2863
2864  case IIK_Move:
2865  case IIK_Copy: {
2866    bool Moving = ImplicitInitKind == IIK_Move;
2867    ParmVarDecl *Param = Constructor->getParamDecl(0);
2868    QualType ParamType = Param->getType().getNonReferenceType();
2869
2870    Expr *CopyCtorArg =
2871      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2872                          SourceLocation(), Param, false,
2873                          Constructor->getLocation(), ParamType,
2874                          VK_LValue, 0);
2875
2876    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2877
2878    // Cast to the base class to avoid ambiguities.
2879    QualType ArgTy =
2880      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2881                                       ParamType.getQualifiers());
2882
2883    if (Moving) {
2884      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2885    }
2886
2887    CXXCastPath BasePath;
2888    BasePath.push_back(BaseSpec);
2889    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2890                                            CK_UncheckedDerivedToBase,
2891                                            Moving ? VK_XValue : VK_LValue,
2892                                            &BasePath).take();
2893
2894    InitializationKind InitKind
2895      = InitializationKind::CreateDirect(Constructor->getLocation(),
2896                                         SourceLocation(), SourceLocation());
2897    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2898    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
2899    break;
2900  }
2901  }
2902
2903  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2904  if (BaseInit.isInvalid())
2905    return true;
2906
2907  CXXBaseInit =
2908    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2909               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2910                                                        SourceLocation()),
2911                                             BaseSpec->isVirtual(),
2912                                             SourceLocation(),
2913                                             BaseInit.takeAs<Expr>(),
2914                                             SourceLocation(),
2915                                             SourceLocation());
2916
2917  return false;
2918}
2919
2920static bool RefersToRValueRef(Expr *MemRef) {
2921  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2922  return Referenced->getType()->isRValueReferenceType();
2923}
2924
2925static bool
2926BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2927                               ImplicitInitializerKind ImplicitInitKind,
2928                               FieldDecl *Field, IndirectFieldDecl *Indirect,
2929                               CXXCtorInitializer *&CXXMemberInit) {
2930  if (Field->isInvalidDecl())
2931    return true;
2932
2933  SourceLocation Loc = Constructor->getLocation();
2934
2935  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2936    bool Moving = ImplicitInitKind == IIK_Move;
2937    ParmVarDecl *Param = Constructor->getParamDecl(0);
2938    QualType ParamType = Param->getType().getNonReferenceType();
2939
2940    // Suppress copying zero-width bitfields.
2941    if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2942      return false;
2943
2944    Expr *MemberExprBase =
2945      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2946                          SourceLocation(), Param, false,
2947                          Loc, ParamType, VK_LValue, 0);
2948
2949    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2950
2951    if (Moving) {
2952      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2953    }
2954
2955    // Build a reference to this field within the parameter.
2956    CXXScopeSpec SS;
2957    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2958                              Sema::LookupMemberName);
2959    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2960                                  : cast<ValueDecl>(Field), AS_public);
2961    MemberLookup.resolveKind();
2962    ExprResult CtorArg
2963      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2964                                         ParamType, Loc,
2965                                         /*IsArrow=*/false,
2966                                         SS,
2967                                         /*TemplateKWLoc=*/SourceLocation(),
2968                                         /*FirstQualifierInScope=*/0,
2969                                         MemberLookup,
2970                                         /*TemplateArgs=*/0);
2971    if (CtorArg.isInvalid())
2972      return true;
2973
2974    // C++11 [class.copy]p15:
2975    //   - if a member m has rvalue reference type T&&, it is direct-initialized
2976    //     with static_cast<T&&>(x.m);
2977    if (RefersToRValueRef(CtorArg.get())) {
2978      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2979    }
2980
2981    // When the field we are copying is an array, create index variables for
2982    // each dimension of the array. We use these index variables to subscript
2983    // the source array, and other clients (e.g., CodeGen) will perform the
2984    // necessary iteration with these index variables.
2985    SmallVector<VarDecl *, 4> IndexVariables;
2986    QualType BaseType = Field->getType();
2987    QualType SizeType = SemaRef.Context.getSizeType();
2988    bool InitializingArray = false;
2989    while (const ConstantArrayType *Array
2990                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2991      InitializingArray = true;
2992      // Create the iteration variable for this array index.
2993      IdentifierInfo *IterationVarName = 0;
2994      {
2995        SmallString<8> Str;
2996        llvm::raw_svector_ostream OS(Str);
2997        OS << "__i" << IndexVariables.size();
2998        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2999      }
3000      VarDecl *IterationVar
3001        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3002                          IterationVarName, SizeType,
3003                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3004                          SC_None);
3005      IndexVariables.push_back(IterationVar);
3006
3007      // Create a reference to the iteration variable.
3008      ExprResult IterationVarRef
3009        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3010      assert(!IterationVarRef.isInvalid() &&
3011             "Reference to invented variable cannot fail!");
3012      IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3013      assert(!IterationVarRef.isInvalid() &&
3014             "Conversion of invented variable cannot fail!");
3015
3016      // Subscript the array with this iteration variable.
3017      CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
3018                                                        IterationVarRef.take(),
3019                                                        Loc);
3020      if (CtorArg.isInvalid())
3021        return true;
3022
3023      BaseType = Array->getElementType();
3024    }
3025
3026    // The array subscript expression is an lvalue, which is wrong for moving.
3027    if (Moving && InitializingArray)
3028      CtorArg = CastForMoving(SemaRef, CtorArg.take());
3029
3030    // Construct the entity that we will be initializing. For an array, this
3031    // will be first element in the array, which may require several levels
3032    // of array-subscript entities.
3033    SmallVector<InitializedEntity, 4> Entities;
3034    Entities.reserve(1 + IndexVariables.size());
3035    if (Indirect)
3036      Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3037    else
3038      Entities.push_back(InitializedEntity::InitializeMember(Field));
3039    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3040      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3041                                                              0,
3042                                                              Entities.back()));
3043
3044    // Direct-initialize to use the copy constructor.
3045    InitializationKind InitKind =
3046      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3047
3048    Expr *CtorArgE = CtorArg.takeAs<Expr>();
3049    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3050
3051    ExprResult MemberInit
3052      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3053                        MultiExprArg(&CtorArgE, 1));
3054    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3055    if (MemberInit.isInvalid())
3056      return true;
3057
3058    if (Indirect) {
3059      assert(IndexVariables.size() == 0 &&
3060             "Indirect field improperly initialized");
3061      CXXMemberInit
3062        = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3063                                                   Loc, Loc,
3064                                                   MemberInit.takeAs<Expr>(),
3065                                                   Loc);
3066    } else
3067      CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3068                                                 Loc, MemberInit.takeAs<Expr>(),
3069                                                 Loc,
3070                                                 IndexVariables.data(),
3071                                                 IndexVariables.size());
3072    return false;
3073  }
3074
3075  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3076         "Unhandled implicit init kind!");
3077
3078  QualType FieldBaseElementType =
3079    SemaRef.Context.getBaseElementType(Field->getType());
3080
3081  if (FieldBaseElementType->isRecordType()) {
3082    InitializedEntity InitEntity
3083      = Indirect? InitializedEntity::InitializeMember(Indirect)
3084                : InitializedEntity::InitializeMember(Field);
3085    InitializationKind InitKind =
3086      InitializationKind::CreateDefault(Loc);
3087
3088    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3089    ExprResult MemberInit =
3090      InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3091
3092    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3093    if (MemberInit.isInvalid())
3094      return true;
3095
3096    if (Indirect)
3097      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3098                                                               Indirect, Loc,
3099                                                               Loc,
3100                                                               MemberInit.get(),
3101                                                               Loc);
3102    else
3103      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3104                                                               Field, Loc, Loc,
3105                                                               MemberInit.get(),
3106                                                               Loc);
3107    return false;
3108  }
3109
3110  if (!Field->getParent()->isUnion()) {
3111    if (FieldBaseElementType->isReferenceType()) {
3112      SemaRef.Diag(Constructor->getLocation(),
3113                   diag::err_uninitialized_member_in_ctor)
3114      << (int)Constructor->isImplicit()
3115      << SemaRef.Context.getTagDeclType(Constructor->getParent())
3116      << 0 << Field->getDeclName();
3117      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3118      return true;
3119    }
3120
3121    if (FieldBaseElementType.isConstQualified()) {
3122      SemaRef.Diag(Constructor->getLocation(),
3123                   diag::err_uninitialized_member_in_ctor)
3124      << (int)Constructor->isImplicit()
3125      << SemaRef.Context.getTagDeclType(Constructor->getParent())
3126      << 1 << Field->getDeclName();
3127      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3128      return true;
3129    }
3130  }
3131
3132  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3133      FieldBaseElementType->isObjCRetainableType() &&
3134      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3135      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3136    // ARC:
3137    //   Default-initialize Objective-C pointers to NULL.
3138    CXXMemberInit
3139      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3140                                                 Loc, Loc,
3141                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3142                                                 Loc);
3143    return false;
3144  }
3145
3146  // Nothing to initialize.
3147  CXXMemberInit = 0;
3148  return false;
3149}
3150
3151namespace {
3152struct BaseAndFieldInfo {
3153  Sema &S;
3154  CXXConstructorDecl *Ctor;
3155  bool AnyErrorsInInits;
3156  ImplicitInitializerKind IIK;
3157  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3158  SmallVector<CXXCtorInitializer*, 8> AllToInit;
3159
3160  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3161    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3162    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3163    if (Generated && Ctor->isCopyConstructor())
3164      IIK = IIK_Copy;
3165    else if (Generated && Ctor->isMoveConstructor())
3166      IIK = IIK_Move;
3167    else if (Ctor->getInheritedConstructor())
3168      IIK = IIK_Inherit;
3169    else
3170      IIK = IIK_Default;
3171  }
3172
3173  bool isImplicitCopyOrMove() const {
3174    switch (IIK) {
3175    case IIK_Copy:
3176    case IIK_Move:
3177      return true;
3178
3179    case IIK_Default:
3180    case IIK_Inherit:
3181      return false;
3182    }
3183
3184    llvm_unreachable("Invalid ImplicitInitializerKind!");
3185  }
3186
3187  bool addFieldInitializer(CXXCtorInitializer *Init) {
3188    AllToInit.push_back(Init);
3189
3190    // Check whether this initializer makes the field "used".
3191    if (Init->getInit()->HasSideEffects(S.Context))
3192      S.UnusedPrivateFields.remove(Init->getAnyMember());
3193
3194    return false;
3195  }
3196};
3197}
3198
3199/// \brief Determine whether the given indirect field declaration is somewhere
3200/// within an anonymous union.
3201static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3202  for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3203                                      CEnd = F->chain_end();
3204       C != CEnd; ++C)
3205    if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3206      if (Record->isUnion())
3207        return true;
3208
3209  return false;
3210}
3211
3212/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3213/// array type.
3214static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3215  if (T->isIncompleteArrayType())
3216    return true;
3217
3218  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3219    if (!ArrayT->getSize())
3220      return true;
3221
3222    T = ArrayT->getElementType();
3223  }
3224
3225  return false;
3226}
3227
3228static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3229                                    FieldDecl *Field,
3230                                    IndirectFieldDecl *Indirect = 0) {
3231
3232  // Overwhelmingly common case: we have a direct initializer for this field.
3233  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3234    return Info.addFieldInitializer(Init);
3235
3236  // C++11 [class.base.init]p8: if the entity is a non-static data member that
3237  // has a brace-or-equal-initializer, the entity is initialized as specified
3238  // in [dcl.init].
3239  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3240    Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3241                                           Info.Ctor->getLocation(), Field);
3242    CXXCtorInitializer *Init;
3243    if (Indirect)
3244      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3245                                                      SourceLocation(),
3246                                                      SourceLocation(), DIE,
3247                                                      SourceLocation());
3248    else
3249      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3250                                                      SourceLocation(),
3251                                                      SourceLocation(), DIE,
3252                                                      SourceLocation());
3253    return Info.addFieldInitializer(Init);
3254  }
3255
3256  // Don't build an implicit initializer for union members if none was
3257  // explicitly specified.
3258  if (Field->getParent()->isUnion() ||
3259      (Indirect && isWithinAnonymousUnion(Indirect)))
3260    return false;
3261
3262  // Don't initialize incomplete or zero-length arrays.
3263  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3264    return false;
3265
3266  // Don't try to build an implicit initializer if there were semantic
3267  // errors in any of the initializers (and therefore we might be
3268  // missing some that the user actually wrote).
3269  if (Info.AnyErrorsInInits || Field->isInvalidDecl())
3270    return false;
3271
3272  CXXCtorInitializer *Init = 0;
3273  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3274                                     Indirect, Init))
3275    return true;
3276
3277  if (!Init)
3278    return false;
3279
3280  return Info.addFieldInitializer(Init);
3281}
3282
3283bool
3284Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3285                               CXXCtorInitializer *Initializer) {
3286  assert(Initializer->isDelegatingInitializer());
3287  Constructor->setNumCtorInitializers(1);
3288  CXXCtorInitializer **initializer =
3289    new (Context) CXXCtorInitializer*[1];
3290  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3291  Constructor->setCtorInitializers(initializer);
3292
3293  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3294    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3295    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3296  }
3297
3298  DelegatingCtorDecls.push_back(Constructor);
3299
3300  return false;
3301}
3302
3303bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3304                               ArrayRef<CXXCtorInitializer *> Initializers) {
3305  if (Constructor->isDependentContext()) {
3306    // Just store the initializers as written, they will be checked during
3307    // instantiation.
3308    if (!Initializers.empty()) {
3309      Constructor->setNumCtorInitializers(Initializers.size());
3310      CXXCtorInitializer **baseOrMemberInitializers =
3311        new (Context) CXXCtorInitializer*[Initializers.size()];
3312      memcpy(baseOrMemberInitializers, Initializers.data(),
3313             Initializers.size() * sizeof(CXXCtorInitializer*));
3314      Constructor->setCtorInitializers(baseOrMemberInitializers);
3315    }
3316
3317    // Let template instantiation know whether we had errors.
3318    if (AnyErrors)
3319      Constructor->setInvalidDecl();
3320
3321    return false;
3322  }
3323
3324  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3325
3326  // We need to build the initializer AST according to order of construction
3327  // and not what user specified in the Initializers list.
3328  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3329  if (!ClassDecl)
3330    return true;
3331
3332  bool HadError = false;
3333
3334  for (unsigned i = 0; i < Initializers.size(); i++) {
3335    CXXCtorInitializer *Member = Initializers[i];
3336
3337    if (Member->isBaseInitializer())
3338      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3339    else
3340      Info.AllBaseFields[Member->getAnyMember()] = Member;
3341  }
3342
3343  // Keep track of the direct virtual bases.
3344  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3345  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3346       E = ClassDecl->bases_end(); I != E; ++I) {
3347    if (I->isVirtual())
3348      DirectVBases.insert(I);
3349  }
3350
3351  // Push virtual bases before others.
3352  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3353       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3354
3355    if (CXXCtorInitializer *Value
3356        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3357      Info.AllToInit.push_back(Value);
3358    } else if (!AnyErrors) {
3359      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3360      CXXCtorInitializer *CXXBaseInit;
3361      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3362                                       VBase, IsInheritedVirtualBase,
3363                                       CXXBaseInit)) {
3364        HadError = true;
3365        continue;
3366      }
3367
3368      Info.AllToInit.push_back(CXXBaseInit);
3369    }
3370  }
3371
3372  // Non-virtual bases.
3373  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3374       E = ClassDecl->bases_end(); Base != E; ++Base) {
3375    // Virtuals are in the virtual base list and already constructed.
3376    if (Base->isVirtual())
3377      continue;
3378
3379    if (CXXCtorInitializer *Value
3380          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3381      Info.AllToInit.push_back(Value);
3382    } else if (!AnyErrors) {
3383      CXXCtorInitializer *CXXBaseInit;
3384      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3385                                       Base, /*IsInheritedVirtualBase=*/false,
3386                                       CXXBaseInit)) {
3387        HadError = true;
3388        continue;
3389      }
3390
3391      Info.AllToInit.push_back(CXXBaseInit);
3392    }
3393  }
3394
3395  // Fields.
3396  for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3397                               MemEnd = ClassDecl->decls_end();
3398       Mem != MemEnd; ++Mem) {
3399    if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3400      // C++ [class.bit]p2:
3401      //   A declaration for a bit-field that omits the identifier declares an
3402      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3403      //   initialized.
3404      if (F->isUnnamedBitfield())
3405        continue;
3406
3407      // If we're not generating the implicit copy/move constructor, then we'll
3408      // handle anonymous struct/union fields based on their individual
3409      // indirect fields.
3410      if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3411        continue;
3412
3413      if (CollectFieldInitializer(*this, Info, F))
3414        HadError = true;
3415      continue;
3416    }
3417
3418    // Beyond this point, we only consider default initialization.
3419    if (Info.isImplicitCopyOrMove())
3420      continue;
3421
3422    if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3423      if (F->getType()->isIncompleteArrayType()) {
3424        assert(ClassDecl->hasFlexibleArrayMember() &&
3425               "Incomplete array type is not valid");
3426        continue;
3427      }
3428
3429      // Initialize each field of an anonymous struct individually.
3430      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3431        HadError = true;
3432
3433      continue;
3434    }
3435  }
3436
3437  unsigned NumInitializers = Info.AllToInit.size();
3438  if (NumInitializers > 0) {
3439    Constructor->setNumCtorInitializers(NumInitializers);
3440    CXXCtorInitializer **baseOrMemberInitializers =
3441      new (Context) CXXCtorInitializer*[NumInitializers];
3442    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3443           NumInitializers * sizeof(CXXCtorInitializer*));
3444    Constructor->setCtorInitializers(baseOrMemberInitializers);
3445
3446    // Constructors implicitly reference the base and member
3447    // destructors.
3448    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3449                                           Constructor->getParent());
3450  }
3451
3452  return HadError;
3453}
3454
3455static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3456  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3457    const RecordDecl *RD = RT->getDecl();
3458    if (RD->isAnonymousStructOrUnion()) {
3459      for (RecordDecl::field_iterator Field = RD->field_begin(),
3460          E = RD->field_end(); Field != E; ++Field)
3461        PopulateKeysForFields(*Field, IdealInits);
3462      return;
3463    }
3464  }
3465  IdealInits.push_back(Field);
3466}
3467
3468static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3469  return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3470}
3471
3472static void *GetKeyForMember(ASTContext &Context,
3473                             CXXCtorInitializer *Member) {
3474  if (!Member->isAnyMemberInitializer())
3475    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3476
3477  return Member->getAnyMember();
3478}
3479
3480static void DiagnoseBaseOrMemInitializerOrder(
3481    Sema &SemaRef, const CXXConstructorDecl *Constructor,
3482    ArrayRef<CXXCtorInitializer *> Inits) {
3483  if (Constructor->getDeclContext()->isDependentContext())
3484    return;
3485
3486  // Don't check initializers order unless the warning is enabled at the
3487  // location of at least one initializer.
3488  bool ShouldCheckOrder = false;
3489  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3490    CXXCtorInitializer *Init = Inits[InitIndex];
3491    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3492                                         Init->getSourceLocation())
3493          != DiagnosticsEngine::Ignored) {
3494      ShouldCheckOrder = true;
3495      break;
3496    }
3497  }
3498  if (!ShouldCheckOrder)
3499    return;
3500
3501  // Build the list of bases and members in the order that they'll
3502  // actually be initialized.  The explicit initializers should be in
3503  // this same order but may be missing things.
3504  SmallVector<const void*, 32> IdealInitKeys;
3505
3506  const CXXRecordDecl *ClassDecl = Constructor->getParent();
3507
3508  // 1. Virtual bases.
3509  for (CXXRecordDecl::base_class_const_iterator VBase =
3510       ClassDecl->vbases_begin(),
3511       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3512    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3513
3514  // 2. Non-virtual bases.
3515  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3516       E = ClassDecl->bases_end(); Base != E; ++Base) {
3517    if (Base->isVirtual())
3518      continue;
3519    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3520  }
3521
3522  // 3. Direct fields.
3523  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3524       E = ClassDecl->field_end(); Field != E; ++Field) {
3525    if (Field->isUnnamedBitfield())
3526      continue;
3527
3528    PopulateKeysForFields(*Field, IdealInitKeys);
3529  }
3530
3531  unsigned NumIdealInits = IdealInitKeys.size();
3532  unsigned IdealIndex = 0;
3533
3534  CXXCtorInitializer *PrevInit = 0;
3535  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3536    CXXCtorInitializer *Init = Inits[InitIndex];
3537    void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3538
3539    // Scan forward to try to find this initializer in the idealized
3540    // initializers list.
3541    for (; IdealIndex != NumIdealInits; ++IdealIndex)
3542      if (InitKey == IdealInitKeys[IdealIndex])
3543        break;
3544
3545    // If we didn't find this initializer, it must be because we
3546    // scanned past it on a previous iteration.  That can only
3547    // happen if we're out of order;  emit a warning.
3548    if (IdealIndex == NumIdealInits && PrevInit) {
3549      Sema::SemaDiagnosticBuilder D =
3550        SemaRef.Diag(PrevInit->getSourceLocation(),
3551                     diag::warn_initializer_out_of_order);
3552
3553      if (PrevInit->isAnyMemberInitializer())
3554        D << 0 << PrevInit->getAnyMember()->getDeclName();
3555      else
3556        D << 1 << PrevInit->getTypeSourceInfo()->getType();
3557
3558      if (Init->isAnyMemberInitializer())
3559        D << 0 << Init->getAnyMember()->getDeclName();
3560      else
3561        D << 1 << Init->getTypeSourceInfo()->getType();
3562
3563      // Move back to the initializer's location in the ideal list.
3564      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3565        if (InitKey == IdealInitKeys[IdealIndex])
3566          break;
3567
3568      assert(IdealIndex != NumIdealInits &&
3569             "initializer not found in initializer list");
3570    }
3571
3572    PrevInit = Init;
3573  }
3574}
3575
3576namespace {
3577bool CheckRedundantInit(Sema &S,
3578                        CXXCtorInitializer *Init,
3579                        CXXCtorInitializer *&PrevInit) {
3580  if (!PrevInit) {
3581    PrevInit = Init;
3582    return false;
3583  }
3584
3585  if (FieldDecl *Field = Init->getAnyMember())
3586    S.Diag(Init->getSourceLocation(),
3587           diag::err_multiple_mem_initialization)
3588      << Field->getDeclName()
3589      << Init->getSourceRange();
3590  else {
3591    const Type *BaseClass = Init->getBaseClass();
3592    assert(BaseClass && "neither field nor base");
3593    S.Diag(Init->getSourceLocation(),
3594           diag::err_multiple_base_initialization)
3595      << QualType(BaseClass, 0)
3596      << Init->getSourceRange();
3597  }
3598  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3599    << 0 << PrevInit->getSourceRange();
3600
3601  return true;
3602}
3603
3604typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3605typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3606
3607bool CheckRedundantUnionInit(Sema &S,
3608                             CXXCtorInitializer *Init,
3609                             RedundantUnionMap &Unions) {
3610  FieldDecl *Field = Init->getAnyMember();
3611  RecordDecl *Parent = Field->getParent();
3612  NamedDecl *Child = Field;
3613
3614  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3615    if (Parent->isUnion()) {
3616      UnionEntry &En = Unions[Parent];
3617      if (En.first && En.first != Child) {
3618        S.Diag(Init->getSourceLocation(),
3619               diag::err_multiple_mem_union_initialization)
3620          << Field->getDeclName()
3621          << Init->getSourceRange();
3622        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3623          << 0 << En.second->getSourceRange();
3624        return true;
3625      }
3626      if (!En.first) {
3627        En.first = Child;
3628        En.second = Init;
3629      }
3630      if (!Parent->isAnonymousStructOrUnion())
3631        return false;
3632    }
3633
3634    Child = Parent;
3635    Parent = cast<RecordDecl>(Parent->getDeclContext());
3636  }
3637
3638  return false;
3639}
3640}
3641
3642/// ActOnMemInitializers - Handle the member initializers for a constructor.
3643void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3644                                SourceLocation ColonLoc,
3645                                ArrayRef<CXXCtorInitializer*> MemInits,
3646                                bool AnyErrors) {
3647  if (!ConstructorDecl)
3648    return;
3649
3650  AdjustDeclIfTemplate(ConstructorDecl);
3651
3652  CXXConstructorDecl *Constructor
3653    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3654
3655  if (!Constructor) {
3656    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3657    return;
3658  }
3659
3660  // Mapping for the duplicate initializers check.
3661  // For member initializers, this is keyed with a FieldDecl*.
3662  // For base initializers, this is keyed with a Type*.
3663  llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3664
3665  // Mapping for the inconsistent anonymous-union initializers check.
3666  RedundantUnionMap MemberUnions;
3667
3668  bool HadError = false;
3669  for (unsigned i = 0; i < MemInits.size(); i++) {
3670    CXXCtorInitializer *Init = MemInits[i];
3671
3672    // Set the source order index.
3673    Init->setSourceOrder(i);
3674
3675    if (Init->isAnyMemberInitializer()) {
3676      FieldDecl *Field = Init->getAnyMember();
3677      if (CheckRedundantInit(*this, Init, Members[Field]) ||
3678          CheckRedundantUnionInit(*this, Init, MemberUnions))
3679        HadError = true;
3680    } else if (Init->isBaseInitializer()) {
3681      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3682      if (CheckRedundantInit(*this, Init, Members[Key]))
3683        HadError = true;
3684    } else {
3685      assert(Init->isDelegatingInitializer());
3686      // This must be the only initializer
3687      if (MemInits.size() != 1) {
3688        Diag(Init->getSourceLocation(),
3689             diag::err_delegating_initializer_alone)
3690          << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3691        // We will treat this as being the only initializer.
3692      }
3693      SetDelegatingInitializer(Constructor, MemInits[i]);
3694      // Return immediately as the initializer is set.
3695      return;
3696    }
3697  }
3698
3699  if (HadError)
3700    return;
3701
3702  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
3703
3704  SetCtorInitializers(Constructor, AnyErrors, MemInits);
3705}
3706
3707void
3708Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3709                                             CXXRecordDecl *ClassDecl) {
3710  // Ignore dependent contexts. Also ignore unions, since their members never
3711  // have destructors implicitly called.
3712  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3713    return;
3714
3715  // FIXME: all the access-control diagnostics are positioned on the
3716  // field/base declaration.  That's probably good; that said, the
3717  // user might reasonably want to know why the destructor is being
3718  // emitted, and we currently don't say.
3719
3720  // Non-static data members.
3721  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3722       E = ClassDecl->field_end(); I != E; ++I) {
3723    FieldDecl *Field = *I;
3724    if (Field->isInvalidDecl())
3725      continue;
3726
3727    // Don't destroy incomplete or zero-length arrays.
3728    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3729      continue;
3730
3731    QualType FieldType = Context.getBaseElementType(Field->getType());
3732
3733    const RecordType* RT = FieldType->getAs<RecordType>();
3734    if (!RT)
3735      continue;
3736
3737    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3738    if (FieldClassDecl->isInvalidDecl())
3739      continue;
3740    if (FieldClassDecl->hasIrrelevantDestructor())
3741      continue;
3742    // The destructor for an implicit anonymous union member is never invoked.
3743    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3744      continue;
3745
3746    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3747    assert(Dtor && "No dtor found for FieldClassDecl!");
3748    CheckDestructorAccess(Field->getLocation(), Dtor,
3749                          PDiag(diag::err_access_dtor_field)
3750                            << Field->getDeclName()
3751                            << FieldType);
3752
3753    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3754    DiagnoseUseOfDecl(Dtor, Location);
3755  }
3756
3757  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3758
3759  // Bases.
3760  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3761       E = ClassDecl->bases_end(); Base != E; ++Base) {
3762    // Bases are always records in a well-formed non-dependent class.
3763    const RecordType *RT = Base->getType()->getAs<RecordType>();
3764
3765    // Remember direct virtual bases.
3766    if (Base->isVirtual())
3767      DirectVirtualBases.insert(RT);
3768
3769    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3770    // If our base class is invalid, we probably can't get its dtor anyway.
3771    if (BaseClassDecl->isInvalidDecl())
3772      continue;
3773    if (BaseClassDecl->hasIrrelevantDestructor())
3774      continue;
3775
3776    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3777    assert(Dtor && "No dtor found for BaseClassDecl!");
3778
3779    // FIXME: caret should be on the start of the class name
3780    CheckDestructorAccess(Base->getLocStart(), Dtor,
3781                          PDiag(diag::err_access_dtor_base)
3782                            << Base->getType()
3783                            << Base->getSourceRange(),
3784                          Context.getTypeDeclType(ClassDecl));
3785
3786    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3787    DiagnoseUseOfDecl(Dtor, Location);
3788  }
3789
3790  // Virtual bases.
3791  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3792       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3793
3794    // Bases are always records in a well-formed non-dependent class.
3795    const RecordType *RT = VBase->getType()->castAs<RecordType>();
3796
3797    // Ignore direct virtual bases.
3798    if (DirectVirtualBases.count(RT))
3799      continue;
3800
3801    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3802    // If our base class is invalid, we probably can't get its dtor anyway.
3803    if (BaseClassDecl->isInvalidDecl())
3804      continue;
3805    if (BaseClassDecl->hasIrrelevantDestructor())
3806      continue;
3807
3808    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3809    assert(Dtor && "No dtor found for BaseClassDecl!");
3810    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3811                          PDiag(diag::err_access_dtor_vbase)
3812                            << VBase->getType(),
3813                          Context.getTypeDeclType(ClassDecl));
3814
3815    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3816    DiagnoseUseOfDecl(Dtor, Location);
3817  }
3818}
3819
3820void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3821  if (!CDtorDecl)
3822    return;
3823
3824  if (CXXConstructorDecl *Constructor
3825      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3826    SetCtorInitializers(Constructor, /*AnyErrors=*/false);
3827}
3828
3829bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3830                                  unsigned DiagID, AbstractDiagSelID SelID) {
3831  class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3832    unsigned DiagID;
3833    AbstractDiagSelID SelID;
3834
3835  public:
3836    NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3837      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3838
3839    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3840      if (Suppressed) return;
3841      if (SelID == -1)
3842        S.Diag(Loc, DiagID) << T;
3843      else
3844        S.Diag(Loc, DiagID) << SelID << T;
3845    }
3846  } Diagnoser(DiagID, SelID);
3847
3848  return RequireNonAbstractType(Loc, T, Diagnoser);
3849}
3850
3851bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3852                                  TypeDiagnoser &Diagnoser) {
3853  if (!getLangOpts().CPlusPlus)
3854    return false;
3855
3856  if (const ArrayType *AT = Context.getAsArrayType(T))
3857    return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3858
3859  if (const PointerType *PT = T->getAs<PointerType>()) {
3860    // Find the innermost pointer type.
3861    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3862      PT = T;
3863
3864    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3865      return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3866  }
3867
3868  const RecordType *RT = T->getAs<RecordType>();
3869  if (!RT)
3870    return false;
3871
3872  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3873
3874  // We can't answer whether something is abstract until it has a
3875  // definition.  If it's currently being defined, we'll walk back
3876  // over all the declarations when we have a full definition.
3877  const CXXRecordDecl *Def = RD->getDefinition();
3878  if (!Def || Def->isBeingDefined())
3879    return false;
3880
3881  if (!RD->isAbstract())
3882    return false;
3883
3884  Diagnoser.diagnose(*this, Loc, T);
3885  DiagnoseAbstractType(RD);
3886
3887  return true;
3888}
3889
3890void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3891  // Check if we've already emitted the list of pure virtual functions
3892  // for this class.
3893  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3894    return;
3895
3896  CXXFinalOverriderMap FinalOverriders;
3897  RD->getFinalOverriders(FinalOverriders);
3898
3899  // Keep a set of seen pure methods so we won't diagnose the same method
3900  // more than once.
3901  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3902
3903  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3904                                   MEnd = FinalOverriders.end();
3905       M != MEnd;
3906       ++M) {
3907    for (OverridingMethods::iterator SO = M->second.begin(),
3908                                  SOEnd = M->second.end();
3909         SO != SOEnd; ++SO) {
3910      // C++ [class.abstract]p4:
3911      //   A class is abstract if it contains or inherits at least one
3912      //   pure virtual function for which the final overrider is pure
3913      //   virtual.
3914
3915      //
3916      if (SO->second.size() != 1)
3917        continue;
3918
3919      if (!SO->second.front().Method->isPure())
3920        continue;
3921
3922      if (!SeenPureMethods.insert(SO->second.front().Method))
3923        continue;
3924
3925      Diag(SO->second.front().Method->getLocation(),
3926           diag::note_pure_virtual_function)
3927        << SO->second.front().Method->getDeclName() << RD->getDeclName();
3928    }
3929  }
3930
3931  if (!PureVirtualClassDiagSet)
3932    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3933  PureVirtualClassDiagSet->insert(RD);
3934}
3935
3936namespace {
3937struct AbstractUsageInfo {
3938  Sema &S;
3939  CXXRecordDecl *Record;
3940  CanQualType AbstractType;
3941  bool Invalid;
3942
3943  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3944    : S(S), Record(Record),
3945      AbstractType(S.Context.getCanonicalType(
3946                   S.Context.getTypeDeclType(Record))),
3947      Invalid(false) {}
3948
3949  void DiagnoseAbstractType() {
3950    if (Invalid) return;
3951    S.DiagnoseAbstractType(Record);
3952    Invalid = true;
3953  }
3954
3955  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3956};
3957
3958struct CheckAbstractUsage {
3959  AbstractUsageInfo &Info;
3960  const NamedDecl *Ctx;
3961
3962  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3963    : Info(Info), Ctx(Ctx) {}
3964
3965  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3966    switch (TL.getTypeLocClass()) {
3967#define ABSTRACT_TYPELOC(CLASS, PARENT)
3968#define TYPELOC(CLASS, PARENT) \
3969    case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
3970#include "clang/AST/TypeLocNodes.def"
3971    }
3972  }
3973
3974  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3975    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3976    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3977      if (!TL.getArg(I))
3978        continue;
3979
3980      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3981      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3982    }
3983  }
3984
3985  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3986    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3987  }
3988
3989  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3990    // Visit the type parameters from a permissive context.
3991    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3992      TemplateArgumentLoc TAL = TL.getArgLoc(I);
3993      if (TAL.getArgument().getKind() == TemplateArgument::Type)
3994        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3995          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3996      // TODO: other template argument types?
3997    }
3998  }
3999
4000  // Visit pointee types from a permissive context.
4001#define CheckPolymorphic(Type) \
4002  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4003    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4004  }
4005  CheckPolymorphic(PointerTypeLoc)
4006  CheckPolymorphic(ReferenceTypeLoc)
4007  CheckPolymorphic(MemberPointerTypeLoc)
4008  CheckPolymorphic(BlockPointerTypeLoc)
4009  CheckPolymorphic(AtomicTypeLoc)
4010
4011  /// Handle all the types we haven't given a more specific
4012  /// implementation for above.
4013  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4014    // Every other kind of type that we haven't called out already
4015    // that has an inner type is either (1) sugar or (2) contains that
4016    // inner type in some way as a subobject.
4017    if (TypeLoc Next = TL.getNextTypeLoc())
4018      return Visit(Next, Sel);
4019
4020    // If there's no inner type and we're in a permissive context,
4021    // don't diagnose.
4022    if (Sel == Sema::AbstractNone) return;
4023
4024    // Check whether the type matches the abstract type.
4025    QualType T = TL.getType();
4026    if (T->isArrayType()) {
4027      Sel = Sema::AbstractArrayType;
4028      T = Info.S.Context.getBaseElementType(T);
4029    }
4030    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4031    if (CT != Info.AbstractType) return;
4032
4033    // It matched; do some magic.
4034    if (Sel == Sema::AbstractArrayType) {
4035      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4036        << T << TL.getSourceRange();
4037    } else {
4038      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4039        << Sel << T << TL.getSourceRange();
4040    }
4041    Info.DiagnoseAbstractType();
4042  }
4043};
4044
4045void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4046                                  Sema::AbstractDiagSelID Sel) {
4047  CheckAbstractUsage(*this, D).Visit(TL, Sel);
4048}
4049
4050}
4051
4052/// Check for invalid uses of an abstract type in a method declaration.
4053static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4054                                    CXXMethodDecl *MD) {
4055  // No need to do the check on definitions, which require that
4056  // the return/param types be complete.
4057  if (MD->doesThisDeclarationHaveABody())
4058    return;
4059
4060  // For safety's sake, just ignore it if we don't have type source
4061  // information.  This should never happen for non-implicit methods,
4062  // but...
4063  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4064    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4065}
4066
4067/// Check for invalid uses of an abstract type within a class definition.
4068static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4069                                    CXXRecordDecl *RD) {
4070  for (CXXRecordDecl::decl_iterator
4071         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4072    Decl *D = *I;
4073    if (D->isImplicit()) continue;
4074
4075    // Methods and method templates.
4076    if (isa<CXXMethodDecl>(D)) {
4077      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4078    } else if (isa<FunctionTemplateDecl>(D)) {
4079      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4080      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4081
4082    // Fields and static variables.
4083    } else if (isa<FieldDecl>(D)) {
4084      FieldDecl *FD = cast<FieldDecl>(D);
4085      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4086        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4087    } else if (isa<VarDecl>(D)) {
4088      VarDecl *VD = cast<VarDecl>(D);
4089      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4090        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4091
4092    // Nested classes and class templates.
4093    } else if (isa<CXXRecordDecl>(D)) {
4094      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4095    } else if (isa<ClassTemplateDecl>(D)) {
4096      CheckAbstractClassUsage(Info,
4097                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4098    }
4099  }
4100}
4101
4102/// \brief Perform semantic checks on a class definition that has been
4103/// completing, introducing implicitly-declared members, checking for
4104/// abstract types, etc.
4105void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4106  if (!Record)
4107    return;
4108
4109  if (Record->isAbstract() && !Record->isInvalidDecl()) {
4110    AbstractUsageInfo Info(*this, Record);
4111    CheckAbstractClassUsage(Info, Record);
4112  }
4113
4114  // If this is not an aggregate type and has no user-declared constructor,
4115  // complain about any non-static data members of reference or const scalar
4116  // type, since they will never get initializers.
4117  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4118      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4119      !Record->isLambda()) {
4120    bool Complained = false;
4121    for (RecordDecl::field_iterator F = Record->field_begin(),
4122                                 FEnd = Record->field_end();
4123         F != FEnd; ++F) {
4124      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4125        continue;
4126
4127      if (F->getType()->isReferenceType() ||
4128          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4129        if (!Complained) {
4130          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4131            << Record->getTagKind() << Record;
4132          Complained = true;
4133        }
4134
4135        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4136          << F->getType()->isReferenceType()
4137          << F->getDeclName();
4138      }
4139    }
4140  }
4141
4142  if (Record->isDynamicClass() && !Record->isDependentType())
4143    DynamicClasses.push_back(Record);
4144
4145  if (Record->getIdentifier()) {
4146    // C++ [class.mem]p13:
4147    //   If T is the name of a class, then each of the following shall have a
4148    //   name different from T:
4149    //     - every member of every anonymous union that is a member of class T.
4150    //
4151    // C++ [class.mem]p14:
4152    //   In addition, if class T has a user-declared constructor (12.1), every
4153    //   non-static data member of class T shall have a name different from T.
4154    DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4155    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4156         ++I) {
4157      NamedDecl *D = *I;
4158      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4159          isa<IndirectFieldDecl>(D)) {
4160        Diag(D->getLocation(), diag::err_member_name_of_class)
4161          << D->getDeclName();
4162        break;
4163      }
4164    }
4165  }
4166
4167  // Warn if the class has virtual methods but non-virtual public destructor.
4168  if (Record->isPolymorphic() && !Record->isDependentType()) {
4169    CXXDestructorDecl *dtor = Record->getDestructor();
4170    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
4171      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4172           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4173  }
4174
4175  if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4176    Diag(Record->getLocation(), diag::warn_abstract_final_class);
4177    DiagnoseAbstractType(Record);
4178  }
4179
4180  if (!Record->isDependentType()) {
4181    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4182                                     MEnd = Record->method_end();
4183         M != MEnd; ++M) {
4184      // See if a method overloads virtual methods in a base
4185      // class without overriding any.
4186      if (!M->isStatic())
4187        DiagnoseHiddenVirtualMethods(Record, *M);
4188
4189      // Check whether the explicitly-defaulted special members are valid.
4190      if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4191        CheckExplicitlyDefaultedSpecialMember(*M);
4192
4193      // For an explicitly defaulted or deleted special member, we defer
4194      // determining triviality until the class is complete. That time is now!
4195      if (!M->isImplicit() && !M->isUserProvided()) {
4196        CXXSpecialMember CSM = getSpecialMember(*M);
4197        if (CSM != CXXInvalid) {
4198          M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4199
4200          // Inform the class that we've finished declaring this member.
4201          Record->finishedDefaultedOrDeletedMember(*M);
4202        }
4203      }
4204    }
4205  }
4206
4207  // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4208  // function that is not a constructor declares that member function to be
4209  // const. [...] The class of which that function is a member shall be
4210  // a literal type.
4211  //
4212  // If the class has virtual bases, any constexpr members will already have
4213  // been diagnosed by the checks performed on the member declaration, so
4214  // suppress this (less useful) diagnostic.
4215  //
4216  // We delay this until we know whether an explicitly-defaulted (or deleted)
4217  // destructor for the class is trivial.
4218  if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4219      !Record->isLiteral() && !Record->getNumVBases()) {
4220    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4221                                     MEnd = Record->method_end();
4222         M != MEnd; ++M) {
4223      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4224        switch (Record->getTemplateSpecializationKind()) {
4225        case TSK_ImplicitInstantiation:
4226        case TSK_ExplicitInstantiationDeclaration:
4227        case TSK_ExplicitInstantiationDefinition:
4228          // If a template instantiates to a non-literal type, but its members
4229          // instantiate to constexpr functions, the template is technically
4230          // ill-formed, but we allow it for sanity.
4231          continue;
4232
4233        case TSK_Undeclared:
4234        case TSK_ExplicitSpecialization:
4235          RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4236                             diag::err_constexpr_method_non_literal);
4237          break;
4238        }
4239
4240        // Only produce one error per class.
4241        break;
4242      }
4243    }
4244  }
4245
4246  // Declare inheriting constructors. We do this eagerly here because:
4247  // - The standard requires an eager diagnostic for conflicting inheriting
4248  //   constructors from different classes.
4249  // - The lazy declaration of the other implicit constructors is so as to not
4250  //   waste space and performance on classes that are not meant to be
4251  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4252  //   have inheriting constructors.
4253  DeclareInheritingConstructors(Record);
4254}
4255
4256/// Is the special member function which would be selected to perform the
4257/// specified operation on the specified class type a constexpr constructor?
4258static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4259                                     Sema::CXXSpecialMember CSM,
4260                                     bool ConstArg) {
4261  Sema::SpecialMemberOverloadResult *SMOR =
4262      S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4263                            false, false, false, false);
4264  if (!SMOR || !SMOR->getMethod())
4265    // A constructor we wouldn't select can't be "involved in initializing"
4266    // anything.
4267    return true;
4268  return SMOR->getMethod()->isConstexpr();
4269}
4270
4271/// Determine whether the specified special member function would be constexpr
4272/// if it were implicitly defined.
4273static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4274                                              Sema::CXXSpecialMember CSM,
4275                                              bool ConstArg) {
4276  if (!S.getLangOpts().CPlusPlus11)
4277    return false;
4278
4279  // C++11 [dcl.constexpr]p4:
4280  // In the definition of a constexpr constructor [...]
4281  switch (CSM) {
4282  case Sema::CXXDefaultConstructor:
4283    // Since default constructor lookup is essentially trivial (and cannot
4284    // involve, for instance, template instantiation), we compute whether a
4285    // defaulted default constructor is constexpr directly within CXXRecordDecl.
4286    //
4287    // This is important for performance; we need to know whether the default
4288    // constructor is constexpr to determine whether the type is a literal type.
4289    return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4290
4291  case Sema::CXXCopyConstructor:
4292  case Sema::CXXMoveConstructor:
4293    // For copy or move constructors, we need to perform overload resolution.
4294    break;
4295
4296  case Sema::CXXCopyAssignment:
4297  case Sema::CXXMoveAssignment:
4298  case Sema::CXXDestructor:
4299  case Sema::CXXInvalid:
4300    return false;
4301  }
4302
4303  //   -- if the class is a non-empty union, or for each non-empty anonymous
4304  //      union member of a non-union class, exactly one non-static data member
4305  //      shall be initialized; [DR1359]
4306  //
4307  // If we squint, this is guaranteed, since exactly one non-static data member
4308  // will be initialized (if the constructor isn't deleted), we just don't know
4309  // which one.
4310  if (ClassDecl->isUnion())
4311    return true;
4312
4313  //   -- the class shall not have any virtual base classes;
4314  if (ClassDecl->getNumVBases())
4315    return false;
4316
4317  //   -- every constructor involved in initializing [...] base class
4318  //      sub-objects shall be a constexpr constructor;
4319  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4320                                       BEnd = ClassDecl->bases_end();
4321       B != BEnd; ++B) {
4322    const RecordType *BaseType = B->getType()->getAs<RecordType>();
4323    if (!BaseType) continue;
4324
4325    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4326    if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4327      return false;
4328  }
4329
4330  //   -- every constructor involved in initializing non-static data members
4331  //      [...] shall be a constexpr constructor;
4332  //   -- every non-static data member and base class sub-object shall be
4333  //      initialized
4334  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4335                               FEnd = ClassDecl->field_end();
4336       F != FEnd; ++F) {
4337    if (F->isInvalidDecl())
4338      continue;
4339    if (const RecordType *RecordTy =
4340            S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4341      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4342      if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4343        return false;
4344    }
4345  }
4346
4347  // All OK, it's constexpr!
4348  return true;
4349}
4350
4351static Sema::ImplicitExceptionSpecification
4352computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4353  switch (S.getSpecialMember(MD)) {
4354  case Sema::CXXDefaultConstructor:
4355    return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4356  case Sema::CXXCopyConstructor:
4357    return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4358  case Sema::CXXCopyAssignment:
4359    return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4360  case Sema::CXXMoveConstructor:
4361    return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4362  case Sema::CXXMoveAssignment:
4363    return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4364  case Sema::CXXDestructor:
4365    return S.ComputeDefaultedDtorExceptionSpec(MD);
4366  case Sema::CXXInvalid:
4367    break;
4368  }
4369  assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4370         "only special members have implicit exception specs");
4371  return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4372}
4373
4374static void
4375updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4376                    const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4377  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4378  ExceptSpec.getEPI(EPI);
4379  FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4380                                        FPT->getArgTypes(), EPI));
4381}
4382
4383void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4384  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4385  if (FPT->getExceptionSpecType() != EST_Unevaluated)
4386    return;
4387
4388  // Evaluate the exception specification.
4389  ImplicitExceptionSpecification ExceptSpec =
4390      computeImplicitExceptionSpec(*this, Loc, MD);
4391
4392  // Update the type of the special member to use it.
4393  updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4394
4395  // A user-provided destructor can be defined outside the class. When that
4396  // happens, be sure to update the exception specification on both
4397  // declarations.
4398  const FunctionProtoType *CanonicalFPT =
4399    MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4400  if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4401    updateExceptionSpec(*this, MD->getCanonicalDecl(),
4402                        CanonicalFPT, ExceptSpec);
4403}
4404
4405void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4406  CXXRecordDecl *RD = MD->getParent();
4407  CXXSpecialMember CSM = getSpecialMember(MD);
4408
4409  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4410         "not an explicitly-defaulted special member");
4411
4412  // Whether this was the first-declared instance of the constructor.
4413  // This affects whether we implicitly add an exception spec and constexpr.
4414  bool First = MD == MD->getCanonicalDecl();
4415
4416  bool HadError = false;
4417
4418  // C++11 [dcl.fct.def.default]p1:
4419  //   A function that is explicitly defaulted shall
4420  //     -- be a special member function (checked elsewhere),
4421  //     -- have the same type (except for ref-qualifiers, and except that a
4422  //        copy operation can take a non-const reference) as an implicit
4423  //        declaration, and
4424  //     -- not have default arguments.
4425  unsigned ExpectedParams = 1;
4426  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4427    ExpectedParams = 0;
4428  if (MD->getNumParams() != ExpectedParams) {
4429    // This also checks for default arguments: a copy or move constructor with a
4430    // default argument is classified as a default constructor, and assignment
4431    // operations and destructors can't have default arguments.
4432    Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4433      << CSM << MD->getSourceRange();
4434    HadError = true;
4435  } else if (MD->isVariadic()) {
4436    Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4437      << CSM << MD->getSourceRange();
4438    HadError = true;
4439  }
4440
4441  const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4442
4443  bool CanHaveConstParam = false;
4444  if (CSM == CXXCopyConstructor)
4445    CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4446  else if (CSM == CXXCopyAssignment)
4447    CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4448
4449  QualType ReturnType = Context.VoidTy;
4450  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4451    // Check for return type matching.
4452    ReturnType = Type->getResultType();
4453    QualType ExpectedReturnType =
4454        Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4455    if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4456      Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4457        << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4458      HadError = true;
4459    }
4460
4461    // A defaulted special member cannot have cv-qualifiers.
4462    if (Type->getTypeQuals()) {
4463      Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4464        << (CSM == CXXMoveAssignment);
4465      HadError = true;
4466    }
4467  }
4468
4469  // Check for parameter type matching.
4470  QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4471  bool HasConstParam = false;
4472  if (ExpectedParams && ArgType->isReferenceType()) {
4473    // Argument must be reference to possibly-const T.
4474    QualType ReferentType = ArgType->getPointeeType();
4475    HasConstParam = ReferentType.isConstQualified();
4476
4477    if (ReferentType.isVolatileQualified()) {
4478      Diag(MD->getLocation(),
4479           diag::err_defaulted_special_member_volatile_param) << CSM;
4480      HadError = true;
4481    }
4482
4483    if (HasConstParam && !CanHaveConstParam) {
4484      if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4485        Diag(MD->getLocation(),
4486             diag::err_defaulted_special_member_copy_const_param)
4487          << (CSM == CXXCopyAssignment);
4488        // FIXME: Explain why this special member can't be const.
4489      } else {
4490        Diag(MD->getLocation(),
4491             diag::err_defaulted_special_member_move_const_param)
4492          << (CSM == CXXMoveAssignment);
4493      }
4494      HadError = true;
4495    }
4496  } else if (ExpectedParams) {
4497    // A copy assignment operator can take its argument by value, but a
4498    // defaulted one cannot.
4499    assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4500    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4501    HadError = true;
4502  }
4503
4504  // C++11 [dcl.fct.def.default]p2:
4505  //   An explicitly-defaulted function may be declared constexpr only if it
4506  //   would have been implicitly declared as constexpr,
4507  // Do not apply this rule to members of class templates, since core issue 1358
4508  // makes such functions always instantiate to constexpr functions. For
4509  // non-constructors, this is checked elsewhere.
4510  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4511                                                     HasConstParam);
4512  if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4513      MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4514    Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4515    // FIXME: Explain why the constructor can't be constexpr.
4516    HadError = true;
4517  }
4518
4519  //   and may have an explicit exception-specification only if it is compatible
4520  //   with the exception-specification on the implicit declaration.
4521  if (Type->hasExceptionSpec()) {
4522    // Delay the check if this is the first declaration of the special member,
4523    // since we may not have parsed some necessary in-class initializers yet.
4524    if (First) {
4525      // If the exception specification needs to be instantiated, do so now,
4526      // before we clobber it with an EST_Unevaluated specification below.
4527      if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4528        InstantiateExceptionSpec(MD->getLocStart(), MD);
4529        Type = MD->getType()->getAs<FunctionProtoType>();
4530      }
4531      DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4532    } else
4533      CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4534  }
4535
4536  //   If a function is explicitly defaulted on its first declaration,
4537  if (First) {
4538    //  -- it is implicitly considered to be constexpr if the implicit
4539    //     definition would be,
4540    MD->setConstexpr(Constexpr);
4541
4542    //  -- it is implicitly considered to have the same exception-specification
4543    //     as if it had been implicitly declared,
4544    FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4545    EPI.ExceptionSpecType = EST_Unevaluated;
4546    EPI.ExceptionSpecDecl = MD;
4547    MD->setType(Context.getFunctionType(ReturnType,
4548                                        ArrayRef<QualType>(&ArgType,
4549                                                           ExpectedParams),
4550                                        EPI));
4551  }
4552
4553  if (ShouldDeleteSpecialMember(MD, CSM)) {
4554    if (First) {
4555      SetDeclDeleted(MD, MD->getLocation());
4556    } else {
4557      // C++11 [dcl.fct.def.default]p4:
4558      //   [For a] user-provided explicitly-defaulted function [...] if such a
4559      //   function is implicitly defined as deleted, the program is ill-formed.
4560      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4561      HadError = true;
4562    }
4563  }
4564
4565  if (HadError)
4566    MD->setInvalidDecl();
4567}
4568
4569/// Check whether the exception specification provided for an
4570/// explicitly-defaulted special member matches the exception specification
4571/// that would have been generated for an implicit special member, per
4572/// C++11 [dcl.fct.def.default]p2.
4573void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4574    CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4575  // Compute the implicit exception specification.
4576  FunctionProtoType::ExtProtoInfo EPI;
4577  computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4578  const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4579    Context.getFunctionType(Context.VoidTy, None, EPI));
4580
4581  // Ensure that it matches.
4582  CheckEquivalentExceptionSpec(
4583    PDiag(diag::err_incorrect_defaulted_exception_spec)
4584      << getSpecialMember(MD), PDiag(),
4585    ImplicitType, SourceLocation(),
4586    SpecifiedType, MD->getLocation());
4587}
4588
4589void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4590  for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4591       I != N; ++I)
4592    CheckExplicitlyDefaultedMemberExceptionSpec(
4593      DelayedDefaultedMemberExceptionSpecs[I].first,
4594      DelayedDefaultedMemberExceptionSpecs[I].second);
4595
4596  DelayedDefaultedMemberExceptionSpecs.clear();
4597}
4598
4599namespace {
4600struct SpecialMemberDeletionInfo {
4601  Sema &S;
4602  CXXMethodDecl *MD;
4603  Sema::CXXSpecialMember CSM;
4604  bool Diagnose;
4605
4606  // Properties of the special member, computed for convenience.
4607  bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4608  SourceLocation Loc;
4609
4610  bool AllFieldsAreConst;
4611
4612  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4613                            Sema::CXXSpecialMember CSM, bool Diagnose)
4614    : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4615      IsConstructor(false), IsAssignment(false), IsMove(false),
4616      ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4617      AllFieldsAreConst(true) {
4618    switch (CSM) {
4619      case Sema::CXXDefaultConstructor:
4620      case Sema::CXXCopyConstructor:
4621        IsConstructor = true;
4622        break;
4623      case Sema::CXXMoveConstructor:
4624        IsConstructor = true;
4625        IsMove = true;
4626        break;
4627      case Sema::CXXCopyAssignment:
4628        IsAssignment = true;
4629        break;
4630      case Sema::CXXMoveAssignment:
4631        IsAssignment = true;
4632        IsMove = true;
4633        break;
4634      case Sema::CXXDestructor:
4635        break;
4636      case Sema::CXXInvalid:
4637        llvm_unreachable("invalid special member kind");
4638    }
4639
4640    if (MD->getNumParams()) {
4641      ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4642      VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4643    }
4644  }
4645
4646  bool inUnion() const { return MD->getParent()->isUnion(); }
4647
4648  /// Look up the corresponding special member in the given class.
4649  Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4650                                              unsigned Quals) {
4651    unsigned TQ = MD->getTypeQualifiers();
4652    // cv-qualifiers on class members don't affect default ctor / dtor calls.
4653    if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4654      Quals = 0;
4655    return S.LookupSpecialMember(Class, CSM,
4656                                 ConstArg || (Quals & Qualifiers::Const),
4657                                 VolatileArg || (Quals & Qualifiers::Volatile),
4658                                 MD->getRefQualifier() == RQ_RValue,
4659                                 TQ & Qualifiers::Const,
4660                                 TQ & Qualifiers::Volatile);
4661  }
4662
4663  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4664
4665  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4666  bool shouldDeleteForField(FieldDecl *FD);
4667  bool shouldDeleteForAllConstMembers();
4668
4669  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4670                                     unsigned Quals);
4671  bool shouldDeleteForSubobjectCall(Subobject Subobj,
4672                                    Sema::SpecialMemberOverloadResult *SMOR,
4673                                    bool IsDtorCallInCtor);
4674
4675  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4676};
4677}
4678
4679/// Is the given special member inaccessible when used on the given
4680/// sub-object.
4681bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4682                                             CXXMethodDecl *target) {
4683  /// If we're operating on a base class, the object type is the
4684  /// type of this special member.
4685  QualType objectTy;
4686  AccessSpecifier access = target->getAccess();
4687  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4688    objectTy = S.Context.getTypeDeclType(MD->getParent());
4689    access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4690
4691  // If we're operating on a field, the object type is the type of the field.
4692  } else {
4693    objectTy = S.Context.getTypeDeclType(target->getParent());
4694  }
4695
4696  return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4697}
4698
4699/// Check whether we should delete a special member due to the implicit
4700/// definition containing a call to a special member of a subobject.
4701bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4702    Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4703    bool IsDtorCallInCtor) {
4704  CXXMethodDecl *Decl = SMOR->getMethod();
4705  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4706
4707  int DiagKind = -1;
4708
4709  if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4710    DiagKind = !Decl ? 0 : 1;
4711  else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4712    DiagKind = 2;
4713  else if (!isAccessible(Subobj, Decl))
4714    DiagKind = 3;
4715  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4716           !Decl->isTrivial()) {
4717    // A member of a union must have a trivial corresponding special member.
4718    // As a weird special case, a destructor call from a union's constructor
4719    // must be accessible and non-deleted, but need not be trivial. Such a
4720    // destructor is never actually called, but is semantically checked as
4721    // if it were.
4722    DiagKind = 4;
4723  }
4724
4725  if (DiagKind == -1)
4726    return false;
4727
4728  if (Diagnose) {
4729    if (Field) {
4730      S.Diag(Field->getLocation(),
4731             diag::note_deleted_special_member_class_subobject)
4732        << CSM << MD->getParent() << /*IsField*/true
4733        << Field << DiagKind << IsDtorCallInCtor;
4734    } else {
4735      CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4736      S.Diag(Base->getLocStart(),
4737             diag::note_deleted_special_member_class_subobject)
4738        << CSM << MD->getParent() << /*IsField*/false
4739        << Base->getType() << DiagKind << IsDtorCallInCtor;
4740    }
4741
4742    if (DiagKind == 1)
4743      S.NoteDeletedFunction(Decl);
4744    // FIXME: Explain inaccessibility if DiagKind == 3.
4745  }
4746
4747  return true;
4748}
4749
4750/// Check whether we should delete a special member function due to having a
4751/// direct or virtual base class or non-static data member of class type M.
4752bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4753    CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
4754  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4755
4756  // C++11 [class.ctor]p5:
4757  // -- any direct or virtual base class, or non-static data member with no
4758  //    brace-or-equal-initializer, has class type M (or array thereof) and
4759  //    either M has no default constructor or overload resolution as applied
4760  //    to M's default constructor results in an ambiguity or in a function
4761  //    that is deleted or inaccessible
4762  // C++11 [class.copy]p11, C++11 [class.copy]p23:
4763  // -- a direct or virtual base class B that cannot be copied/moved because
4764  //    overload resolution, as applied to B's corresponding special member,
4765  //    results in an ambiguity or a function that is deleted or inaccessible
4766  //    from the defaulted special member
4767  // C++11 [class.dtor]p5:
4768  // -- any direct or virtual base class [...] has a type with a destructor
4769  //    that is deleted or inaccessible
4770  if (!(CSM == Sema::CXXDefaultConstructor &&
4771        Field && Field->hasInClassInitializer()) &&
4772      shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
4773    return true;
4774
4775  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4776  // -- any direct or virtual base class or non-static data member has a
4777  //    type with a destructor that is deleted or inaccessible
4778  if (IsConstructor) {
4779    Sema::SpecialMemberOverloadResult *SMOR =
4780        S.LookupSpecialMember(Class, Sema::CXXDestructor,
4781                              false, false, false, false, false);
4782    if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4783      return true;
4784  }
4785
4786  return false;
4787}
4788
4789/// Check whether we should delete a special member function due to the class
4790/// having a particular direct or virtual base class.
4791bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4792  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4793  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
4794}
4795
4796/// Check whether we should delete a special member function due to the class
4797/// having a particular non-static data member.
4798bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4799  QualType FieldType = S.Context.getBaseElementType(FD->getType());
4800  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4801
4802  if (CSM == Sema::CXXDefaultConstructor) {
4803    // For a default constructor, all references must be initialized in-class
4804    // and, if a union, it must have a non-const member.
4805    if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4806      if (Diagnose)
4807        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4808          << MD->getParent() << FD << FieldType << /*Reference*/0;
4809      return true;
4810    }
4811    // C++11 [class.ctor]p5: any non-variant non-static data member of
4812    // const-qualified type (or array thereof) with no
4813    // brace-or-equal-initializer does not have a user-provided default
4814    // constructor.
4815    if (!inUnion() && FieldType.isConstQualified() &&
4816        !FD->hasInClassInitializer() &&
4817        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4818      if (Diagnose)
4819        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4820          << MD->getParent() << FD << FD->getType() << /*Const*/1;
4821      return true;
4822    }
4823
4824    if (inUnion() && !FieldType.isConstQualified())
4825      AllFieldsAreConst = false;
4826  } else if (CSM == Sema::CXXCopyConstructor) {
4827    // For a copy constructor, data members must not be of rvalue reference
4828    // type.
4829    if (FieldType->isRValueReferenceType()) {
4830      if (Diagnose)
4831        S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4832          << MD->getParent() << FD << FieldType;
4833      return true;
4834    }
4835  } else if (IsAssignment) {
4836    // For an assignment operator, data members must not be of reference type.
4837    if (FieldType->isReferenceType()) {
4838      if (Diagnose)
4839        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4840          << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4841      return true;
4842    }
4843    if (!FieldRecord && FieldType.isConstQualified()) {
4844      // C++11 [class.copy]p23:
4845      // -- a non-static data member of const non-class type (or array thereof)
4846      if (Diagnose)
4847        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4848          << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
4849      return true;
4850    }
4851  }
4852
4853  if (FieldRecord) {
4854    // Some additional restrictions exist on the variant members.
4855    if (!inUnion() && FieldRecord->isUnion() &&
4856        FieldRecord->isAnonymousStructOrUnion()) {
4857      bool AllVariantFieldsAreConst = true;
4858
4859      // FIXME: Handle anonymous unions declared within anonymous unions.
4860      for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4861                                         UE = FieldRecord->field_end();
4862           UI != UE; ++UI) {
4863        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4864
4865        if (!UnionFieldType.isConstQualified())
4866          AllVariantFieldsAreConst = false;
4867
4868        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4869        if (UnionFieldRecord &&
4870            shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4871                                          UnionFieldType.getCVRQualifiers()))
4872          return true;
4873      }
4874
4875      // At least one member in each anonymous union must be non-const
4876      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4877          FieldRecord->field_begin() != FieldRecord->field_end()) {
4878        if (Diagnose)
4879          S.Diag(FieldRecord->getLocation(),
4880                 diag::note_deleted_default_ctor_all_const)
4881            << MD->getParent() << /*anonymous union*/1;
4882        return true;
4883      }
4884
4885      // Don't check the implicit member of the anonymous union type.
4886      // This is technically non-conformant, but sanity demands it.
4887      return false;
4888    }
4889
4890    if (shouldDeleteForClassSubobject(FieldRecord, FD,
4891                                      FieldType.getCVRQualifiers()))
4892      return true;
4893  }
4894
4895  return false;
4896}
4897
4898/// C++11 [class.ctor] p5:
4899///   A defaulted default constructor for a class X is defined as deleted if
4900/// X is a union and all of its variant members are of const-qualified type.
4901bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4902  // This is a silly definition, because it gives an empty union a deleted
4903  // default constructor. Don't do that.
4904  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4905      (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4906    if (Diagnose)
4907      S.Diag(MD->getParent()->getLocation(),
4908             diag::note_deleted_default_ctor_all_const)
4909        << MD->getParent() << /*not anonymous union*/0;
4910    return true;
4911  }
4912  return false;
4913}
4914
4915/// Determine whether a defaulted special member function should be defined as
4916/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4917/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
4918bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4919                                     bool Diagnose) {
4920  if (MD->isInvalidDecl())
4921    return false;
4922  CXXRecordDecl *RD = MD->getParent();
4923  assert(!RD->isDependentType() && "do deletion after instantiation");
4924  if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
4925    return false;
4926
4927  // C++11 [expr.lambda.prim]p19:
4928  //   The closure type associated with a lambda-expression has a
4929  //   deleted (8.4.3) default constructor and a deleted copy
4930  //   assignment operator.
4931  if (RD->isLambda() &&
4932      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4933    if (Diagnose)
4934      Diag(RD->getLocation(), diag::note_lambda_decl);
4935    return true;
4936  }
4937
4938  // For an anonymous struct or union, the copy and assignment special members
4939  // will never be used, so skip the check. For an anonymous union declared at
4940  // namespace scope, the constructor and destructor are used.
4941  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4942      RD->isAnonymousStructOrUnion())
4943    return false;
4944
4945  // C++11 [class.copy]p7, p18:
4946  //   If the class definition declares a move constructor or move assignment
4947  //   operator, an implicitly declared copy constructor or copy assignment
4948  //   operator is defined as deleted.
4949  if (MD->isImplicit() &&
4950      (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4951    CXXMethodDecl *UserDeclaredMove = 0;
4952
4953    // In Microsoft mode, a user-declared move only causes the deletion of the
4954    // corresponding copy operation, not both copy operations.
4955    if (RD->hasUserDeclaredMoveConstructor() &&
4956        (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4957      if (!Diagnose) return true;
4958
4959      // Find any user-declared move constructor.
4960      for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4961                                        E = RD->ctor_end(); I != E; ++I) {
4962        if (I->isMoveConstructor()) {
4963          UserDeclaredMove = *I;
4964          break;
4965        }
4966      }
4967      assert(UserDeclaredMove);
4968    } else if (RD->hasUserDeclaredMoveAssignment() &&
4969               (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4970      if (!Diagnose) return true;
4971
4972      // Find any user-declared move assignment operator.
4973      for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4974                                          E = RD->method_end(); I != E; ++I) {
4975        if (I->isMoveAssignmentOperator()) {
4976          UserDeclaredMove = *I;
4977          break;
4978        }
4979      }
4980      assert(UserDeclaredMove);
4981    }
4982
4983    if (UserDeclaredMove) {
4984      Diag(UserDeclaredMove->getLocation(),
4985           diag::note_deleted_copy_user_declared_move)
4986        << (CSM == CXXCopyAssignment) << RD
4987        << UserDeclaredMove->isMoveAssignmentOperator();
4988      return true;
4989    }
4990  }
4991
4992  // Do access control from the special member function
4993  ContextRAII MethodContext(*this, MD);
4994
4995  // C++11 [class.dtor]p5:
4996  // -- for a virtual destructor, lookup of the non-array deallocation function
4997  //    results in an ambiguity or in a function that is deleted or inaccessible
4998  if (CSM == CXXDestructor && MD->isVirtual()) {
4999    FunctionDecl *OperatorDelete = 0;
5000    DeclarationName Name =
5001      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5002    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5003                                 OperatorDelete, false)) {
5004      if (Diagnose)
5005        Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5006      return true;
5007    }
5008  }
5009
5010  SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5011
5012  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5013                                          BE = RD->bases_end(); BI != BE; ++BI)
5014    if (!BI->isVirtual() &&
5015        SMI.shouldDeleteForBase(BI))
5016      return true;
5017
5018  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5019                                          BE = RD->vbases_end(); BI != BE; ++BI)
5020    if (SMI.shouldDeleteForBase(BI))
5021      return true;
5022
5023  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5024                                     FE = RD->field_end(); FI != FE; ++FI)
5025    if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5026        SMI.shouldDeleteForField(*FI))
5027      return true;
5028
5029  if (SMI.shouldDeleteForAllConstMembers())
5030    return true;
5031
5032  return false;
5033}
5034
5035/// Perform lookup for a special member of the specified kind, and determine
5036/// whether it is trivial. If the triviality can be determined without the
5037/// lookup, skip it. This is intended for use when determining whether a
5038/// special member of a containing object is trivial, and thus does not ever
5039/// perform overload resolution for default constructors.
5040///
5041/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5042/// member that was most likely to be intended to be trivial, if any.
5043static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5044                                     Sema::CXXSpecialMember CSM, unsigned Quals,
5045                                     CXXMethodDecl **Selected) {
5046  if (Selected)
5047    *Selected = 0;
5048
5049  switch (CSM) {
5050  case Sema::CXXInvalid:
5051    llvm_unreachable("not a special member");
5052
5053  case Sema::CXXDefaultConstructor:
5054    // C++11 [class.ctor]p5:
5055    //   A default constructor is trivial if:
5056    //    - all the [direct subobjects] have trivial default constructors
5057    //
5058    // Note, no overload resolution is performed in this case.
5059    if (RD->hasTrivialDefaultConstructor())
5060      return true;
5061
5062    if (Selected) {
5063      // If there's a default constructor which could have been trivial, dig it
5064      // out. Otherwise, if there's any user-provided default constructor, point
5065      // to that as an example of why there's not a trivial one.
5066      CXXConstructorDecl *DefCtor = 0;
5067      if (RD->needsImplicitDefaultConstructor())
5068        S.DeclareImplicitDefaultConstructor(RD);
5069      for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5070                                        CE = RD->ctor_end(); CI != CE; ++CI) {
5071        if (!CI->isDefaultConstructor())
5072          continue;
5073        DefCtor = *CI;
5074        if (!DefCtor->isUserProvided())
5075          break;
5076      }
5077
5078      *Selected = DefCtor;
5079    }
5080
5081    return false;
5082
5083  case Sema::CXXDestructor:
5084    // C++11 [class.dtor]p5:
5085    //   A destructor is trivial if:
5086    //    - all the direct [subobjects] have trivial destructors
5087    if (RD->hasTrivialDestructor())
5088      return true;
5089
5090    if (Selected) {
5091      if (RD->needsImplicitDestructor())
5092        S.DeclareImplicitDestructor(RD);
5093      *Selected = RD->getDestructor();
5094    }
5095
5096    return false;
5097
5098  case Sema::CXXCopyConstructor:
5099    // C++11 [class.copy]p12:
5100    //   A copy constructor is trivial if:
5101    //    - the constructor selected to copy each direct [subobject] is trivial
5102    if (RD->hasTrivialCopyConstructor()) {
5103      if (Quals == Qualifiers::Const)
5104        // We must either select the trivial copy constructor or reach an
5105        // ambiguity; no need to actually perform overload resolution.
5106        return true;
5107    } else if (!Selected) {
5108      return false;
5109    }
5110    // In C++98, we are not supposed to perform overload resolution here, but we
5111    // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5112    // cases like B as having a non-trivial copy constructor:
5113    //   struct A { template<typename T> A(T&); };
5114    //   struct B { mutable A a; };
5115    goto NeedOverloadResolution;
5116
5117  case Sema::CXXCopyAssignment:
5118    // C++11 [class.copy]p25:
5119    //   A copy assignment operator is trivial if:
5120    //    - the assignment operator selected to copy each direct [subobject] is
5121    //      trivial
5122    if (RD->hasTrivialCopyAssignment()) {
5123      if (Quals == Qualifiers::Const)
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.
5130    goto NeedOverloadResolution;
5131
5132  case Sema::CXXMoveConstructor:
5133  case Sema::CXXMoveAssignment:
5134  NeedOverloadResolution:
5135    Sema::SpecialMemberOverloadResult *SMOR =
5136      S.LookupSpecialMember(RD, CSM,
5137                            Quals & Qualifiers::Const,
5138                            Quals & Qualifiers::Volatile,
5139                            /*RValueThis*/false, /*ConstThis*/false,
5140                            /*VolatileThis*/false);
5141
5142    // The standard doesn't describe how to behave if the lookup is ambiguous.
5143    // We treat it as not making the member non-trivial, just like the standard
5144    // mandates for the default constructor. This should rarely matter, because
5145    // the member will also be deleted.
5146    if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5147      return true;
5148
5149    if (!SMOR->getMethod()) {
5150      assert(SMOR->getKind() ==
5151             Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5152      return false;
5153    }
5154
5155    // We deliberately don't check if we found a deleted special member. We're
5156    // not supposed to!
5157    if (Selected)
5158      *Selected = SMOR->getMethod();
5159    return SMOR->getMethod()->isTrivial();
5160  }
5161
5162  llvm_unreachable("unknown special method kind");
5163}
5164
5165static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5166  for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5167       CI != CE; ++CI)
5168    if (!CI->isImplicit())
5169      return *CI;
5170
5171  // Look for constructor templates.
5172  typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5173  for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5174    if (CXXConstructorDecl *CD =
5175          dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5176      return CD;
5177  }
5178
5179  return 0;
5180}
5181
5182/// The kind of subobject we are checking for triviality. The values of this
5183/// enumeration are used in diagnostics.
5184enum TrivialSubobjectKind {
5185  /// The subobject is a base class.
5186  TSK_BaseClass,
5187  /// The subobject is a non-static data member.
5188  TSK_Field,
5189  /// The object is actually the complete object.
5190  TSK_CompleteObject
5191};
5192
5193/// Check whether the special member selected for a given type would be trivial.
5194static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5195                                      QualType SubType,
5196                                      Sema::CXXSpecialMember CSM,
5197                                      TrivialSubobjectKind Kind,
5198                                      bool Diagnose) {
5199  CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5200  if (!SubRD)
5201    return true;
5202
5203  CXXMethodDecl *Selected;
5204  if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5205                               Diagnose ? &Selected : 0))
5206    return true;
5207
5208  if (Diagnose) {
5209    if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5210      S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5211        << Kind << SubType.getUnqualifiedType();
5212      if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5213        S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5214    } else if (!Selected)
5215      S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5216        << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5217    else if (Selected->isUserProvided()) {
5218      if (Kind == TSK_CompleteObject)
5219        S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5220          << Kind << SubType.getUnqualifiedType() << CSM;
5221      else {
5222        S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5223          << Kind << SubType.getUnqualifiedType() << CSM;
5224        S.Diag(Selected->getLocation(), diag::note_declared_at);
5225      }
5226    } else {
5227      if (Kind != TSK_CompleteObject)
5228        S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5229          << Kind << SubType.getUnqualifiedType() << CSM;
5230
5231      // Explain why the defaulted or deleted special member isn't trivial.
5232      S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5233    }
5234  }
5235
5236  return false;
5237}
5238
5239/// Check whether the members of a class type allow a special member to be
5240/// trivial.
5241static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5242                                     Sema::CXXSpecialMember CSM,
5243                                     bool ConstArg, bool Diagnose) {
5244  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5245                                     FE = RD->field_end(); FI != FE; ++FI) {
5246    if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5247      continue;
5248
5249    QualType FieldType = S.Context.getBaseElementType(FI->getType());
5250
5251    // Pretend anonymous struct or union members are members of this class.
5252    if (FI->isAnonymousStructOrUnion()) {
5253      if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5254                                    CSM, ConstArg, Diagnose))
5255        return false;
5256      continue;
5257    }
5258
5259    // C++11 [class.ctor]p5:
5260    //   A default constructor is trivial if [...]
5261    //    -- no non-static data member of its class has a
5262    //       brace-or-equal-initializer
5263    if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5264      if (Diagnose)
5265        S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5266      return false;
5267    }
5268
5269    // Objective C ARC 4.3.5:
5270    //   [...] nontrivally ownership-qualified types are [...] not trivially
5271    //   default constructible, copy constructible, move constructible, copy
5272    //   assignable, move assignable, or destructible [...]
5273    if (S.getLangOpts().ObjCAutoRefCount &&
5274        FieldType.hasNonTrivialObjCLifetime()) {
5275      if (Diagnose)
5276        S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5277          << RD << FieldType.getObjCLifetime();
5278      return false;
5279    }
5280
5281    if (ConstArg && !FI->isMutable())
5282      FieldType.addConst();
5283    if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5284                                   TSK_Field, Diagnose))
5285      return false;
5286  }
5287
5288  return true;
5289}
5290
5291/// Diagnose why the specified class does not have a trivial special member of
5292/// the given kind.
5293void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5294  QualType Ty = Context.getRecordType(RD);
5295  if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5296    Ty.addConst();
5297
5298  checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5299                            TSK_CompleteObject, /*Diagnose*/true);
5300}
5301
5302/// Determine whether a defaulted or deleted special member function is trivial,
5303/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5304/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5305bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5306                                  bool Diagnose) {
5307  assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5308
5309  CXXRecordDecl *RD = MD->getParent();
5310
5311  bool ConstArg = false;
5312
5313  // C++11 [class.copy]p12, p25:
5314  //   A [special member] is trivial if its declared parameter type is the same
5315  //   as if it had been implicitly declared [...]
5316  switch (CSM) {
5317  case CXXDefaultConstructor:
5318  case CXXDestructor:
5319    // Trivial default constructors and destructors cannot have parameters.
5320    break;
5321
5322  case CXXCopyConstructor:
5323  case CXXCopyAssignment: {
5324    // Trivial copy operations always have const, non-volatile parameter types.
5325    ConstArg = true;
5326    const ParmVarDecl *Param0 = MD->getParamDecl(0);
5327    const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5328    if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5329      if (Diagnose)
5330        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5331          << Param0->getSourceRange() << Param0->getType()
5332          << Context.getLValueReferenceType(
5333               Context.getRecordType(RD).withConst());
5334      return false;
5335    }
5336    break;
5337  }
5338
5339  case CXXMoveConstructor:
5340  case CXXMoveAssignment: {
5341    // Trivial move operations always have non-cv-qualified parameters.
5342    const ParmVarDecl *Param0 = MD->getParamDecl(0);
5343    const RValueReferenceType *RT =
5344      Param0->getType()->getAs<RValueReferenceType>();
5345    if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5346      if (Diagnose)
5347        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5348          << Param0->getSourceRange() << Param0->getType()
5349          << Context.getRValueReferenceType(Context.getRecordType(RD));
5350      return false;
5351    }
5352    break;
5353  }
5354
5355  case CXXInvalid:
5356    llvm_unreachable("not a special member");
5357  }
5358
5359  // FIXME: We require that the parameter-declaration-clause is equivalent to
5360  // that of an implicit declaration, not just that the declared parameter type
5361  // matches, in order to prevent absuridities like a function simultaneously
5362  // being a trivial copy constructor and a non-trivial default constructor.
5363  // This issue has not yet been assigned a core issue number.
5364  if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5365    if (Diagnose)
5366      Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5367           diag::note_nontrivial_default_arg)
5368        << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5369    return false;
5370  }
5371  if (MD->isVariadic()) {
5372    if (Diagnose)
5373      Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5374    return false;
5375  }
5376
5377  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5378  //   A copy/move [constructor or assignment operator] is trivial if
5379  //    -- the [member] selected to copy/move each direct base class subobject
5380  //       is trivial
5381  //
5382  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5383  //   A [default constructor or destructor] is trivial if
5384  //    -- all the direct base classes have trivial [default constructors or
5385  //       destructors]
5386  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5387                                          BE = RD->bases_end(); BI != BE; ++BI)
5388    if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5389                                   ConstArg ? BI->getType().withConst()
5390                                            : BI->getType(),
5391                                   CSM, TSK_BaseClass, Diagnose))
5392      return false;
5393
5394  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5395  //   A copy/move [constructor or assignment operator] for a class X is
5396  //   trivial if
5397  //    -- for each non-static data member of X that is of class type (or array
5398  //       thereof), the constructor selected to copy/move that member is
5399  //       trivial
5400  //
5401  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5402  //   A [default constructor or destructor] is trivial if
5403  //    -- for all of the non-static data members of its class that are of class
5404  //       type (or array thereof), each such class has a trivial [default
5405  //       constructor or destructor]
5406  if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5407    return false;
5408
5409  // C++11 [class.dtor]p5:
5410  //   A destructor is trivial if [...]
5411  //    -- the destructor is not virtual
5412  if (CSM == CXXDestructor && MD->isVirtual()) {
5413    if (Diagnose)
5414      Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5415    return false;
5416  }
5417
5418  // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5419  //   A [special member] for class X is trivial if [...]
5420  //    -- class X has no virtual functions and no virtual base classes
5421  if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5422    if (!Diagnose)
5423      return false;
5424
5425    if (RD->getNumVBases()) {
5426      // Check for virtual bases. We already know that the corresponding
5427      // member in all bases is trivial, so vbases must all be direct.
5428      CXXBaseSpecifier &BS = *RD->vbases_begin();
5429      assert(BS.isVirtual());
5430      Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5431      return false;
5432    }
5433
5434    // Must have a virtual method.
5435    for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5436                                        ME = RD->method_end(); MI != ME; ++MI) {
5437      if (MI->isVirtual()) {
5438        SourceLocation MLoc = MI->getLocStart();
5439        Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5440        return false;
5441      }
5442    }
5443
5444    llvm_unreachable("dynamic class with no vbases and no virtual functions");
5445  }
5446
5447  // Looks like it's trivial!
5448  return true;
5449}
5450
5451/// \brief Data used with FindHiddenVirtualMethod
5452namespace {
5453  struct FindHiddenVirtualMethodData {
5454    Sema *S;
5455    CXXMethodDecl *Method;
5456    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5457    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5458  };
5459}
5460
5461/// \brief Check whether any most overriden method from MD in Methods
5462static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5463                   const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5464  if (MD->size_overridden_methods() == 0)
5465    return Methods.count(MD->getCanonicalDecl());
5466  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5467                                      E = MD->end_overridden_methods();
5468       I != E; ++I)
5469    if (CheckMostOverridenMethods(*I, Methods))
5470      return true;
5471  return false;
5472}
5473
5474/// \brief Member lookup function that determines whether a given C++
5475/// method overloads virtual methods in a base class without overriding any,
5476/// to be used with CXXRecordDecl::lookupInBases().
5477static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5478                                    CXXBasePath &Path,
5479                                    void *UserData) {
5480  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5481
5482  FindHiddenVirtualMethodData &Data
5483    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5484
5485  DeclarationName Name = Data.Method->getDeclName();
5486  assert(Name.getNameKind() == DeclarationName::Identifier);
5487
5488  bool foundSameNameMethod = false;
5489  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5490  for (Path.Decls = BaseRecord->lookup(Name);
5491       !Path.Decls.empty();
5492       Path.Decls = Path.Decls.slice(1)) {
5493    NamedDecl *D = Path.Decls.front();
5494    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5495      MD = MD->getCanonicalDecl();
5496      foundSameNameMethod = true;
5497      // Interested only in hidden virtual methods.
5498      if (!MD->isVirtual())
5499        continue;
5500      // If the method we are checking overrides a method from its base
5501      // don't warn about the other overloaded methods.
5502      if (!Data.S->IsOverload(Data.Method, MD, false))
5503        return true;
5504      // Collect the overload only if its hidden.
5505      if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5506        overloadedMethods.push_back(MD);
5507    }
5508  }
5509
5510  if (foundSameNameMethod)
5511    Data.OverloadedMethods.append(overloadedMethods.begin(),
5512                                   overloadedMethods.end());
5513  return foundSameNameMethod;
5514}
5515
5516/// \brief Add the most overriden methods from MD to Methods
5517static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5518                         llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5519  if (MD->size_overridden_methods() == 0)
5520    Methods.insert(MD->getCanonicalDecl());
5521  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5522                                      E = MD->end_overridden_methods();
5523       I != E; ++I)
5524    AddMostOverridenMethods(*I, Methods);
5525}
5526
5527/// \brief See if a method overloads virtual methods in a base class without
5528/// overriding any.
5529void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5530  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5531                               MD->getLocation()) == DiagnosticsEngine::Ignored)
5532    return;
5533  if (!MD->getDeclName().isIdentifier())
5534    return;
5535
5536  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5537                     /*bool RecordPaths=*/false,
5538                     /*bool DetectVirtual=*/false);
5539  FindHiddenVirtualMethodData Data;
5540  Data.Method = MD;
5541  Data.S = this;
5542
5543  // Keep the base methods that were overriden or introduced in the subclass
5544  // by 'using' in a set. A base method not in this set is hidden.
5545  DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5546  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5547    NamedDecl *ND = *I;
5548    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5549      ND = shad->getTargetDecl();
5550    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5551      AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5552  }
5553
5554  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5555      !Data.OverloadedMethods.empty()) {
5556    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5557      << MD << (Data.OverloadedMethods.size() > 1);
5558
5559    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5560      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5561      PartialDiagnostic PD = PDiag(
5562           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5563      HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5564      Diag(overloadedMD->getLocation(), PD);
5565    }
5566  }
5567}
5568
5569void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5570                                             Decl *TagDecl,
5571                                             SourceLocation LBrac,
5572                                             SourceLocation RBrac,
5573                                             AttributeList *AttrList) {
5574  if (!TagDecl)
5575    return;
5576
5577  AdjustDeclIfTemplate(TagDecl);
5578
5579  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5580    if (l->getKind() != AttributeList::AT_Visibility)
5581      continue;
5582    l->setInvalid();
5583    Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5584      l->getName();
5585  }
5586
5587  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5588              // strict aliasing violation!
5589              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5590              FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5591
5592  CheckCompletedCXXClass(
5593                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5594}
5595
5596/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5597/// special functions, such as the default constructor, copy
5598/// constructor, or destructor, to the given C++ class (C++
5599/// [special]p1).  This routine can only be executed just before the
5600/// definition of the class is complete.
5601void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
5602  if (!ClassDecl->hasUserDeclaredConstructor())
5603    ++ASTContext::NumImplicitDefaultConstructors;
5604
5605  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
5606    ++ASTContext::NumImplicitCopyConstructors;
5607
5608    // If the properties or semantics of the copy constructor couldn't be
5609    // determined while the class was being declared, force a declaration
5610    // of it now.
5611    if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5612      DeclareImplicitCopyConstructor(ClassDecl);
5613  }
5614
5615  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
5616    ++ASTContext::NumImplicitMoveConstructors;
5617
5618    if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5619      DeclareImplicitMoveConstructor(ClassDecl);
5620  }
5621
5622  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5623    ++ASTContext::NumImplicitCopyAssignmentOperators;
5624
5625    // If we have a dynamic class, then the copy assignment operator may be
5626    // virtual, so we have to declare it immediately. This ensures that, e.g.,
5627    // it shows up in the right place in the vtable and that we diagnose
5628    // problems with the implicit exception specification.
5629    if (ClassDecl->isDynamicClass() ||
5630        ClassDecl->needsOverloadResolutionForCopyAssignment())
5631      DeclareImplicitCopyAssignment(ClassDecl);
5632  }
5633
5634  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
5635    ++ASTContext::NumImplicitMoveAssignmentOperators;
5636
5637    // Likewise for the move assignment operator.
5638    if (ClassDecl->isDynamicClass() ||
5639        ClassDecl->needsOverloadResolutionForMoveAssignment())
5640      DeclareImplicitMoveAssignment(ClassDecl);
5641  }
5642
5643  if (!ClassDecl->hasUserDeclaredDestructor()) {
5644    ++ASTContext::NumImplicitDestructors;
5645
5646    // If we have a dynamic class, then the destructor may be virtual, so we
5647    // have to declare the destructor immediately. This ensures that, e.g., it
5648    // shows up in the right place in the vtable and that we diagnose problems
5649    // with the implicit exception specification.
5650    if (ClassDecl->isDynamicClass() ||
5651        ClassDecl->needsOverloadResolutionForDestructor())
5652      DeclareImplicitDestructor(ClassDecl);
5653  }
5654}
5655
5656void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5657  if (!D)
5658    return;
5659
5660  int NumParamList = D->getNumTemplateParameterLists();
5661  for (int i = 0; i < NumParamList; i++) {
5662    TemplateParameterList* Params = D->getTemplateParameterList(i);
5663    for (TemplateParameterList::iterator Param = Params->begin(),
5664                                      ParamEnd = Params->end();
5665          Param != ParamEnd; ++Param) {
5666      NamedDecl *Named = cast<NamedDecl>(*Param);
5667      if (Named->getDeclName()) {
5668        S->AddDecl(Named);
5669        IdResolver.AddDecl(Named);
5670      }
5671    }
5672  }
5673}
5674
5675void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
5676  if (!D)
5677    return;
5678
5679  TemplateParameterList *Params = 0;
5680  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5681    Params = Template->getTemplateParameters();
5682  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5683           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5684    Params = PartialSpec->getTemplateParameters();
5685  else
5686    return;
5687
5688  for (TemplateParameterList::iterator Param = Params->begin(),
5689                                    ParamEnd = Params->end();
5690       Param != ParamEnd; ++Param) {
5691    NamedDecl *Named = cast<NamedDecl>(*Param);
5692    if (Named->getDeclName()) {
5693      S->AddDecl(Named);
5694      IdResolver.AddDecl(Named);
5695    }
5696  }
5697}
5698
5699void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5700  if (!RecordD) return;
5701  AdjustDeclIfTemplate(RecordD);
5702  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
5703  PushDeclContext(S, Record);
5704}
5705
5706void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5707  if (!RecordD) return;
5708  PopDeclContext();
5709}
5710
5711/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5712/// parsing a top-level (non-nested) C++ class, and we are now
5713/// parsing those parts of the given Method declaration that could
5714/// not be parsed earlier (C++ [class.mem]p2), such as default
5715/// arguments. This action should enter the scope of the given
5716/// Method declaration as if we had just parsed the qualified method
5717/// name. However, it should not bring the parameters into scope;
5718/// that will be performed by ActOnDelayedCXXMethodParameter.
5719void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5720}
5721
5722/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5723/// C++ method declaration. We're (re-)introducing the given
5724/// function parameter into scope for use in parsing later parts of
5725/// the method declaration. For example, we could see an
5726/// ActOnParamDefaultArgument event for this parameter.
5727void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
5728  if (!ParamD)
5729    return;
5730
5731  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
5732
5733  // If this parameter has an unparsed default argument, clear it out
5734  // to make way for the parsed default argument.
5735  if (Param->hasUnparsedDefaultArg())
5736    Param->setDefaultArg(0);
5737
5738  S->AddDecl(Param);
5739  if (Param->getDeclName())
5740    IdResolver.AddDecl(Param);
5741}
5742
5743/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5744/// processing the delayed method declaration for Method. The method
5745/// declaration is now considered finished. There may be a separate
5746/// ActOnStartOfFunctionDef action later (not necessarily
5747/// immediately!) for this method, if it was also defined inside the
5748/// class body.
5749void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5750  if (!MethodD)
5751    return;
5752
5753  AdjustDeclIfTemplate(MethodD);
5754
5755  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
5756
5757  // Now that we have our default arguments, check the constructor
5758  // again. It could produce additional diagnostics or affect whether
5759  // the class has implicitly-declared destructors, among other
5760  // things.
5761  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5762    CheckConstructor(Constructor);
5763
5764  // Check the default arguments, which we may have added.
5765  if (!Method->isInvalidDecl())
5766    CheckCXXDefaultArguments(Method);
5767}
5768
5769/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
5770/// the well-formedness of the constructor declarator @p D with type @p
5771/// R. If there are any errors in the declarator, this routine will
5772/// emit diagnostics and set the invalid bit to true.  In any case, the type
5773/// will be updated to reflect a well-formed type for the constructor and
5774/// returned.
5775QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
5776                                          StorageClass &SC) {
5777  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5778
5779  // C++ [class.ctor]p3:
5780  //   A constructor shall not be virtual (10.3) or static (9.4). A
5781  //   constructor can be invoked for a const, volatile or const
5782  //   volatile object. A constructor shall not be declared const,
5783  //   volatile, or const volatile (9.3.2).
5784  if (isVirtual) {
5785    if (!D.isInvalidType())
5786      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5787        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5788        << SourceRange(D.getIdentifierLoc());
5789    D.setInvalidType();
5790  }
5791  if (SC == SC_Static) {
5792    if (!D.isInvalidType())
5793      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5794        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5795        << SourceRange(D.getIdentifierLoc());
5796    D.setInvalidType();
5797    SC = SC_None;
5798  }
5799
5800  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5801  if (FTI.TypeQuals != 0) {
5802    if (FTI.TypeQuals & Qualifiers::Const)
5803      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5804        << "const" << SourceRange(D.getIdentifierLoc());
5805    if (FTI.TypeQuals & Qualifiers::Volatile)
5806      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5807        << "volatile" << SourceRange(D.getIdentifierLoc());
5808    if (FTI.TypeQuals & Qualifiers::Restrict)
5809      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5810        << "restrict" << SourceRange(D.getIdentifierLoc());
5811    D.setInvalidType();
5812  }
5813
5814  // C++0x [class.ctor]p4:
5815  //   A constructor shall not be declared with a ref-qualifier.
5816  if (FTI.hasRefQualifier()) {
5817    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5818      << FTI.RefQualifierIsLValueRef
5819      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5820    D.setInvalidType();
5821  }
5822
5823  // Rebuild the function type "R" without any type qualifiers (in
5824  // case any of the errors above fired) and with "void" as the
5825  // return type, since constructors don't have return types.
5826  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5827  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5828    return R;
5829
5830  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5831  EPI.TypeQuals = 0;
5832  EPI.RefQualifier = RQ_None;
5833
5834  return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
5835}
5836
5837/// CheckConstructor - Checks a fully-formed constructor for
5838/// well-formedness, issuing any diagnostics required. Returns true if
5839/// the constructor declarator is invalid.
5840void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5841  CXXRecordDecl *ClassDecl
5842    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5843  if (!ClassDecl)
5844    return Constructor->setInvalidDecl();
5845
5846  // C++ [class.copy]p3:
5847  //   A declaration of a constructor for a class X is ill-formed if
5848  //   its first parameter is of type (optionally cv-qualified) X and
5849  //   either there are no other parameters or else all other
5850  //   parameters have default arguments.
5851  if (!Constructor->isInvalidDecl() &&
5852      ((Constructor->getNumParams() == 1) ||
5853       (Constructor->getNumParams() > 1 &&
5854        Constructor->getParamDecl(1)->hasDefaultArg())) &&
5855      Constructor->getTemplateSpecializationKind()
5856                                              != TSK_ImplicitInstantiation) {
5857    QualType ParamType = Constructor->getParamDecl(0)->getType();
5858    QualType ClassTy = Context.getTagDeclType(ClassDecl);
5859    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5860      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5861      const char *ConstRef
5862        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5863                                                        : " const &";
5864      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5865        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5866
5867      // FIXME: Rather that making the constructor invalid, we should endeavor
5868      // to fix the type.
5869      Constructor->setInvalidDecl();
5870    }
5871  }
5872}
5873
5874/// CheckDestructor - Checks a fully-formed destructor definition for
5875/// well-formedness, issuing any diagnostics required.  Returns true
5876/// on error.
5877bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5878  CXXRecordDecl *RD = Destructor->getParent();
5879
5880  if (Destructor->isVirtual()) {
5881    SourceLocation Loc;
5882
5883    if (!Destructor->isImplicit())
5884      Loc = Destructor->getLocation();
5885    else
5886      Loc = RD->getLocation();
5887
5888    // If we have a virtual destructor, look up the deallocation function
5889    FunctionDecl *OperatorDelete = 0;
5890    DeclarationName Name =
5891    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5892    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5893      return true;
5894
5895    MarkFunctionReferenced(Loc, OperatorDelete);
5896
5897    Destructor->setOperatorDelete(OperatorDelete);
5898  }
5899
5900  return false;
5901}
5902
5903static inline bool
5904FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5905  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5906          FTI.ArgInfo[0].Param &&
5907          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5908}
5909
5910/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5911/// the well-formednes of the destructor declarator @p D with type @p
5912/// R. If there are any errors in the declarator, this routine will
5913/// emit diagnostics and set the declarator to invalid.  Even if this happens,
5914/// will be updated to reflect a well-formed type for the destructor and
5915/// returned.
5916QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5917                                         StorageClass& SC) {
5918  // C++ [class.dtor]p1:
5919  //   [...] A typedef-name that names a class is a class-name
5920  //   (7.1.3); however, a typedef-name that names a class shall not
5921  //   be used as the identifier in the declarator for a destructor
5922  //   declaration.
5923  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5924  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5925    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5926      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5927  else if (const TemplateSpecializationType *TST =
5928             DeclaratorType->getAs<TemplateSpecializationType>())
5929    if (TST->isTypeAlias())
5930      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5931        << DeclaratorType << 1;
5932
5933  // C++ [class.dtor]p2:
5934  //   A destructor is used to destroy objects of its class type. A
5935  //   destructor takes no parameters, and no return type can be
5936  //   specified for it (not even void). The address of a destructor
5937  //   shall not be taken. A destructor shall not be static. A
5938  //   destructor can be invoked for a const, volatile or const
5939  //   volatile object. A destructor shall not be declared const,
5940  //   volatile or const volatile (9.3.2).
5941  if (SC == SC_Static) {
5942    if (!D.isInvalidType())
5943      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5944        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5945        << SourceRange(D.getIdentifierLoc())
5946        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5947
5948    SC = SC_None;
5949  }
5950  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5951    // Destructors don't have return types, but the parser will
5952    // happily parse something like:
5953    //
5954    //   class X {
5955    //     float ~X();
5956    //   };
5957    //
5958    // The return type will be eliminated later.
5959    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5960      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5961      << SourceRange(D.getIdentifierLoc());
5962  }
5963
5964  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5965  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5966    if (FTI.TypeQuals & Qualifiers::Const)
5967      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5968        << "const" << SourceRange(D.getIdentifierLoc());
5969    if (FTI.TypeQuals & Qualifiers::Volatile)
5970      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5971        << "volatile" << SourceRange(D.getIdentifierLoc());
5972    if (FTI.TypeQuals & Qualifiers::Restrict)
5973      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5974        << "restrict" << SourceRange(D.getIdentifierLoc());
5975    D.setInvalidType();
5976  }
5977
5978  // C++0x [class.dtor]p2:
5979  //   A destructor shall not be declared with a ref-qualifier.
5980  if (FTI.hasRefQualifier()) {
5981    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5982      << FTI.RefQualifierIsLValueRef
5983      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5984    D.setInvalidType();
5985  }
5986
5987  // Make sure we don't have any parameters.
5988  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5989    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5990
5991    // Delete the parameters.
5992    FTI.freeArgs();
5993    D.setInvalidType();
5994  }
5995
5996  // Make sure the destructor isn't variadic.
5997  if (FTI.isVariadic) {
5998    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5999    D.setInvalidType();
6000  }
6001
6002  // Rebuild the function type "R" without any type qualifiers or
6003  // parameters (in case any of the errors above fired) and with
6004  // "void" as the return type, since destructors don't have return
6005  // types.
6006  if (!D.isInvalidType())
6007    return R;
6008
6009  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6010  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6011  EPI.Variadic = false;
6012  EPI.TypeQuals = 0;
6013  EPI.RefQualifier = RQ_None;
6014  return Context.getFunctionType(Context.VoidTy, None, EPI);
6015}
6016
6017/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6018/// well-formednes of the conversion function declarator @p D with
6019/// type @p R. If there are any errors in the declarator, this routine
6020/// will emit diagnostics and return true. Otherwise, it will return
6021/// false. Either way, the type @p R will be updated to reflect a
6022/// well-formed type for the conversion operator.
6023void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6024                                     StorageClass& SC) {
6025  // C++ [class.conv.fct]p1:
6026  //   Neither parameter types nor return type can be specified. The
6027  //   type of a conversion function (8.3.5) is "function taking no
6028  //   parameter returning conversion-type-id."
6029  if (SC == SC_Static) {
6030    if (!D.isInvalidType())
6031      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6032        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6033        << SourceRange(D.getIdentifierLoc());
6034    D.setInvalidType();
6035    SC = SC_None;
6036  }
6037
6038  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6039
6040  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6041    // Conversion functions don't have return types, but the parser will
6042    // happily parse something like:
6043    //
6044    //   class X {
6045    //     float operator bool();
6046    //   };
6047    //
6048    // The return type will be changed later anyway.
6049    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6050      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6051      << SourceRange(D.getIdentifierLoc());
6052    D.setInvalidType();
6053  }
6054
6055  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6056
6057  // Make sure we don't have any parameters.
6058  if (Proto->getNumArgs() > 0) {
6059    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6060
6061    // Delete the parameters.
6062    D.getFunctionTypeInfo().freeArgs();
6063    D.setInvalidType();
6064  } else if (Proto->isVariadic()) {
6065    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6066    D.setInvalidType();
6067  }
6068
6069  // Diagnose "&operator bool()" and other such nonsense.  This
6070  // is actually a gcc extension which we don't support.
6071  if (Proto->getResultType() != ConvType) {
6072    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6073      << Proto->getResultType();
6074    D.setInvalidType();
6075    ConvType = Proto->getResultType();
6076  }
6077
6078  // C++ [class.conv.fct]p4:
6079  //   The conversion-type-id shall not represent a function type nor
6080  //   an array type.
6081  if (ConvType->isArrayType()) {
6082    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6083    ConvType = Context.getPointerType(ConvType);
6084    D.setInvalidType();
6085  } else if (ConvType->isFunctionType()) {
6086    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6087    ConvType = Context.getPointerType(ConvType);
6088    D.setInvalidType();
6089  }
6090
6091  // Rebuild the function type "R" without any parameters (in case any
6092  // of the errors above fired) and with the conversion type as the
6093  // return type.
6094  if (D.isInvalidType())
6095    R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6096
6097  // C++0x explicit conversion operators.
6098  if (D.getDeclSpec().isExplicitSpecified())
6099    Diag(D.getDeclSpec().getExplicitSpecLoc(),
6100         getLangOpts().CPlusPlus11 ?
6101           diag::warn_cxx98_compat_explicit_conversion_functions :
6102           diag::ext_explicit_conversion_functions)
6103      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6104}
6105
6106/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6107/// the declaration of the given C++ conversion function. This routine
6108/// is responsible for recording the conversion function in the C++
6109/// class, if possible.
6110Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6111  assert(Conversion && "Expected to receive a conversion function declaration");
6112
6113  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6114
6115  // Make sure we aren't redeclaring the conversion function.
6116  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6117
6118  // C++ [class.conv.fct]p1:
6119  //   [...] A conversion function is never used to convert a
6120  //   (possibly cv-qualified) object to the (possibly cv-qualified)
6121  //   same object type (or a reference to it), to a (possibly
6122  //   cv-qualified) base class of that type (or a reference to it),
6123  //   or to (possibly cv-qualified) void.
6124  // FIXME: Suppress this warning if the conversion function ends up being a
6125  // virtual function that overrides a virtual function in a base class.
6126  QualType ClassType
6127    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6128  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6129    ConvType = ConvTypeRef->getPointeeType();
6130  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6131      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6132    /* Suppress diagnostics for instantiations. */;
6133  else if (ConvType->isRecordType()) {
6134    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6135    if (ConvType == ClassType)
6136      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6137        << ClassType;
6138    else if (IsDerivedFrom(ClassType, ConvType))
6139      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6140        <<  ClassType << ConvType;
6141  } else if (ConvType->isVoidType()) {
6142    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6143      << ClassType << ConvType;
6144  }
6145
6146  if (FunctionTemplateDecl *ConversionTemplate
6147                                = Conversion->getDescribedFunctionTemplate())
6148    return ConversionTemplate;
6149
6150  return Conversion;
6151}
6152
6153//===----------------------------------------------------------------------===//
6154// Namespace Handling
6155//===----------------------------------------------------------------------===//
6156
6157/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6158/// reopened.
6159static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6160                                            SourceLocation Loc,
6161                                            IdentifierInfo *II, bool *IsInline,
6162                                            NamespaceDecl *PrevNS) {
6163  assert(*IsInline != PrevNS->isInline());
6164
6165  // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6166  // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6167  // inline namespaces, with the intention of bringing names into namespace std.
6168  //
6169  // We support this just well enough to get that case working; this is not
6170  // sufficient to support reopening namespaces as inline in general.
6171  if (*IsInline && II && II->getName().startswith("__atomic") &&
6172      S.getSourceManager().isInSystemHeader(Loc)) {
6173    // Mark all prior declarations of the namespace as inline.
6174    for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6175         NS = NS->getPreviousDecl())
6176      NS->setInline(*IsInline);
6177    // Patch up the lookup table for the containing namespace. This isn't really
6178    // correct, but it's good enough for this particular case.
6179    for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6180                                    E = PrevNS->decls_end(); I != E; ++I)
6181      if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6182        PrevNS->getParent()->makeDeclVisibleInContext(ND);
6183    return;
6184  }
6185
6186  if (PrevNS->isInline())
6187    // The user probably just forgot the 'inline', so suggest that it
6188    // be added back.
6189    S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6190      << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6191  else
6192    S.Diag(Loc, diag::err_inline_namespace_mismatch)
6193      << IsInline;
6194
6195  S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6196  *IsInline = PrevNS->isInline();
6197}
6198
6199/// ActOnStartNamespaceDef - This is called at the start of a namespace
6200/// definition.
6201Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6202                                   SourceLocation InlineLoc,
6203                                   SourceLocation NamespaceLoc,
6204                                   SourceLocation IdentLoc,
6205                                   IdentifierInfo *II,
6206                                   SourceLocation LBrace,
6207                                   AttributeList *AttrList) {
6208  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6209  // For anonymous namespace, take the location of the left brace.
6210  SourceLocation Loc = II ? IdentLoc : LBrace;
6211  bool IsInline = InlineLoc.isValid();
6212  bool IsInvalid = false;
6213  bool IsStd = false;
6214  bool AddToKnown = false;
6215  Scope *DeclRegionScope = NamespcScope->getParent();
6216
6217  NamespaceDecl *PrevNS = 0;
6218  if (II) {
6219    // C++ [namespace.def]p2:
6220    //   The identifier in an original-namespace-definition shall not
6221    //   have been previously defined in the declarative region in
6222    //   which the original-namespace-definition appears. The
6223    //   identifier in an original-namespace-definition is the name of
6224    //   the namespace. Subsequently in that declarative region, it is
6225    //   treated as an original-namespace-name.
6226    //
6227    // Since namespace names are unique in their scope, and we don't
6228    // look through using directives, just look for any ordinary names.
6229
6230    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6231    Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6232    Decl::IDNS_Namespace;
6233    NamedDecl *PrevDecl = 0;
6234    DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6235    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6236         ++I) {
6237      if ((*I)->getIdentifierNamespace() & IDNS) {
6238        PrevDecl = *I;
6239        break;
6240      }
6241    }
6242
6243    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6244
6245    if (PrevNS) {
6246      // This is an extended namespace definition.
6247      if (IsInline != PrevNS->isInline())
6248        DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6249                                        &IsInline, PrevNS);
6250    } else if (PrevDecl) {
6251      // This is an invalid name redefinition.
6252      Diag(Loc, diag::err_redefinition_different_kind)
6253        << II;
6254      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6255      IsInvalid = true;
6256      // Continue on to push Namespc as current DeclContext and return it.
6257    } else if (II->isStr("std") &&
6258               CurContext->getRedeclContext()->isTranslationUnit()) {
6259      // This is the first "real" definition of the namespace "std", so update
6260      // our cache of the "std" namespace to point at this definition.
6261      PrevNS = getStdNamespace();
6262      IsStd = true;
6263      AddToKnown = !IsInline;
6264    } else {
6265      // We've seen this namespace for the first time.
6266      AddToKnown = !IsInline;
6267    }
6268  } else {
6269    // Anonymous namespaces.
6270
6271    // Determine whether the parent already has an anonymous namespace.
6272    DeclContext *Parent = CurContext->getRedeclContext();
6273    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6274      PrevNS = TU->getAnonymousNamespace();
6275    } else {
6276      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6277      PrevNS = ND->getAnonymousNamespace();
6278    }
6279
6280    if (PrevNS && IsInline != PrevNS->isInline())
6281      DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6282                                      &IsInline, PrevNS);
6283  }
6284
6285  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6286                                                 StartLoc, Loc, II, PrevNS);
6287  if (IsInvalid)
6288    Namespc->setInvalidDecl();
6289
6290  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6291
6292  // FIXME: Should we be merging attributes?
6293  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6294    PushNamespaceVisibilityAttr(Attr, Loc);
6295
6296  if (IsStd)
6297    StdNamespace = Namespc;
6298  if (AddToKnown)
6299    KnownNamespaces[Namespc] = false;
6300
6301  if (II) {
6302    PushOnScopeChains(Namespc, DeclRegionScope);
6303  } else {
6304    // Link the anonymous namespace into its parent.
6305    DeclContext *Parent = CurContext->getRedeclContext();
6306    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6307      TU->setAnonymousNamespace(Namespc);
6308    } else {
6309      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6310    }
6311
6312    CurContext->addDecl(Namespc);
6313
6314    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6315    //   behaves as if it were replaced by
6316    //     namespace unique { /* empty body */ }
6317    //     using namespace unique;
6318    //     namespace unique { namespace-body }
6319    //   where all occurrences of 'unique' in a translation unit are
6320    //   replaced by the same identifier and this identifier differs
6321    //   from all other identifiers in the entire program.
6322
6323    // We just create the namespace with an empty name and then add an
6324    // implicit using declaration, just like the standard suggests.
6325    //
6326    // CodeGen enforces the "universally unique" aspect by giving all
6327    // declarations semantically contained within an anonymous
6328    // namespace internal linkage.
6329
6330    if (!PrevNS) {
6331      UsingDirectiveDecl* UD
6332        = UsingDirectiveDecl::Create(Context, Parent,
6333                                     /* 'using' */ LBrace,
6334                                     /* 'namespace' */ SourceLocation(),
6335                                     /* qualifier */ NestedNameSpecifierLoc(),
6336                                     /* identifier */ SourceLocation(),
6337                                     Namespc,
6338                                     /* Ancestor */ Parent);
6339      UD->setImplicit();
6340      Parent->addDecl(UD);
6341    }
6342  }
6343
6344  ActOnDocumentableDecl(Namespc);
6345
6346  // Although we could have an invalid decl (i.e. the namespace name is a
6347  // redefinition), push it as current DeclContext and try to continue parsing.
6348  // FIXME: We should be able to push Namespc here, so that the each DeclContext
6349  // for the namespace has the declarations that showed up in that particular
6350  // namespace definition.
6351  PushDeclContext(NamespcScope, Namespc);
6352  return Namespc;
6353}
6354
6355/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6356/// is a namespace alias, returns the namespace it points to.
6357static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6358  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6359    return AD->getNamespace();
6360  return dyn_cast_or_null<NamespaceDecl>(D);
6361}
6362
6363/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6364/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6365void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6366  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6367  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6368  Namespc->setRBraceLoc(RBrace);
6369  PopDeclContext();
6370  if (Namespc->hasAttr<VisibilityAttr>())
6371    PopPragmaVisibility(true, RBrace);
6372}
6373
6374CXXRecordDecl *Sema::getStdBadAlloc() const {
6375  return cast_or_null<CXXRecordDecl>(
6376                                  StdBadAlloc.get(Context.getExternalSource()));
6377}
6378
6379NamespaceDecl *Sema::getStdNamespace() const {
6380  return cast_or_null<NamespaceDecl>(
6381                                 StdNamespace.get(Context.getExternalSource()));
6382}
6383
6384/// \brief Retrieve the special "std" namespace, which may require us to
6385/// implicitly define the namespace.
6386NamespaceDecl *Sema::getOrCreateStdNamespace() {
6387  if (!StdNamespace) {
6388    // The "std" namespace has not yet been defined, so build one implicitly.
6389    StdNamespace = NamespaceDecl::Create(Context,
6390                                         Context.getTranslationUnitDecl(),
6391                                         /*Inline=*/false,
6392                                         SourceLocation(), SourceLocation(),
6393                                         &PP.getIdentifierTable().get("std"),
6394                                         /*PrevDecl=*/0);
6395    getStdNamespace()->setImplicit(true);
6396  }
6397
6398  return getStdNamespace();
6399}
6400
6401bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6402  assert(getLangOpts().CPlusPlus &&
6403         "Looking for std::initializer_list outside of C++.");
6404
6405  // We're looking for implicit instantiations of
6406  // template <typename E> class std::initializer_list.
6407
6408  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6409    return false;
6410
6411  ClassTemplateDecl *Template = 0;
6412  const TemplateArgument *Arguments = 0;
6413
6414  if (const RecordType *RT = Ty->getAs<RecordType>()) {
6415
6416    ClassTemplateSpecializationDecl *Specialization =
6417        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6418    if (!Specialization)
6419      return false;
6420
6421    Template = Specialization->getSpecializedTemplate();
6422    Arguments = Specialization->getTemplateArgs().data();
6423  } else if (const TemplateSpecializationType *TST =
6424                 Ty->getAs<TemplateSpecializationType>()) {
6425    Template = dyn_cast_or_null<ClassTemplateDecl>(
6426        TST->getTemplateName().getAsTemplateDecl());
6427    Arguments = TST->getArgs();
6428  }
6429  if (!Template)
6430    return false;
6431
6432  if (!StdInitializerList) {
6433    // Haven't recognized std::initializer_list yet, maybe this is it.
6434    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6435    if (TemplateClass->getIdentifier() !=
6436            &PP.getIdentifierTable().get("initializer_list") ||
6437        !getStdNamespace()->InEnclosingNamespaceSetOf(
6438            TemplateClass->getDeclContext()))
6439      return false;
6440    // This is a template called std::initializer_list, but is it the right
6441    // template?
6442    TemplateParameterList *Params = Template->getTemplateParameters();
6443    if (Params->getMinRequiredArguments() != 1)
6444      return false;
6445    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6446      return false;
6447
6448    // It's the right template.
6449    StdInitializerList = Template;
6450  }
6451
6452  if (Template != StdInitializerList)
6453    return false;
6454
6455  // This is an instance of std::initializer_list. Find the argument type.
6456  if (Element)
6457    *Element = Arguments[0].getAsType();
6458  return true;
6459}
6460
6461static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6462  NamespaceDecl *Std = S.getStdNamespace();
6463  if (!Std) {
6464    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6465    return 0;
6466  }
6467
6468  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6469                      Loc, Sema::LookupOrdinaryName);
6470  if (!S.LookupQualifiedName(Result, Std)) {
6471    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6472    return 0;
6473  }
6474  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6475  if (!Template) {
6476    Result.suppressDiagnostics();
6477    // We found something weird. Complain about the first thing we found.
6478    NamedDecl *Found = *Result.begin();
6479    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6480    return 0;
6481  }
6482
6483  // We found some template called std::initializer_list. Now verify that it's
6484  // correct.
6485  TemplateParameterList *Params = Template->getTemplateParameters();
6486  if (Params->getMinRequiredArguments() != 1 ||
6487      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6488    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6489    return 0;
6490  }
6491
6492  return Template;
6493}
6494
6495QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6496  if (!StdInitializerList) {
6497    StdInitializerList = LookupStdInitializerList(*this, Loc);
6498    if (!StdInitializerList)
6499      return QualType();
6500  }
6501
6502  TemplateArgumentListInfo Args(Loc, Loc);
6503  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6504                                       Context.getTrivialTypeSourceInfo(Element,
6505                                                                        Loc)));
6506  return Context.getCanonicalType(
6507      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6508}
6509
6510bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6511  // C++ [dcl.init.list]p2:
6512  //   A constructor is an initializer-list constructor if its first parameter
6513  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
6514  //   std::initializer_list<E> for some type E, and either there are no other
6515  //   parameters or else all other parameters have default arguments.
6516  if (Ctor->getNumParams() < 1 ||
6517      (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6518    return false;
6519
6520  QualType ArgType = Ctor->getParamDecl(0)->getType();
6521  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6522    ArgType = RT->getPointeeType().getUnqualifiedType();
6523
6524  return isStdInitializerList(ArgType, 0);
6525}
6526
6527/// \brief Determine whether a using statement is in a context where it will be
6528/// apply in all contexts.
6529static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6530  switch (CurContext->getDeclKind()) {
6531    case Decl::TranslationUnit:
6532      return true;
6533    case Decl::LinkageSpec:
6534      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6535    default:
6536      return false;
6537  }
6538}
6539
6540namespace {
6541
6542// Callback to only accept typo corrections that are namespaces.
6543class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6544 public:
6545  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6546    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6547      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6548    }
6549    return false;
6550  }
6551};
6552
6553}
6554
6555static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6556                                       CXXScopeSpec &SS,
6557                                       SourceLocation IdentLoc,
6558                                       IdentifierInfo *Ident) {
6559  NamespaceValidatorCCC Validator;
6560  R.clear();
6561  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6562                                               R.getLookupKind(), Sc, &SS,
6563                                               Validator)) {
6564    std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6565    std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
6566    if (DeclContext *DC = S.computeDeclContext(SS, false))
6567      S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6568        << Ident << DC << CorrectedQuotedStr << SS.getRange()
6569        << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6570                                        CorrectedStr);
6571    else
6572      S.Diag(IdentLoc, diag::err_using_directive_suggest)
6573        << Ident << CorrectedQuotedStr
6574        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
6575
6576    S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6577         diag::note_namespace_defined_here) << CorrectedQuotedStr;
6578
6579    R.addDecl(Corrected.getCorrectionDecl());
6580    return true;
6581  }
6582  return false;
6583}
6584
6585Decl *Sema::ActOnUsingDirective(Scope *S,
6586                                          SourceLocation UsingLoc,
6587                                          SourceLocation NamespcLoc,
6588                                          CXXScopeSpec &SS,
6589                                          SourceLocation IdentLoc,
6590                                          IdentifierInfo *NamespcName,
6591                                          AttributeList *AttrList) {
6592  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6593  assert(NamespcName && "Invalid NamespcName.");
6594  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
6595
6596  // This can only happen along a recovery path.
6597  while (S->getFlags() & Scope::TemplateParamScope)
6598    S = S->getParent();
6599  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6600
6601  UsingDirectiveDecl *UDir = 0;
6602  NestedNameSpecifier *Qualifier = 0;
6603  if (SS.isSet())
6604    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6605
6606  // Lookup namespace name.
6607  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6608  LookupParsedName(R, S, &SS);
6609  if (R.isAmbiguous())
6610    return 0;
6611
6612  if (R.empty()) {
6613    R.clear();
6614    // Allow "using namespace std;" or "using namespace ::std;" even if
6615    // "std" hasn't been defined yet, for GCC compatibility.
6616    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6617        NamespcName->isStr("std")) {
6618      Diag(IdentLoc, diag::ext_using_undefined_std);
6619      R.addDecl(getOrCreateStdNamespace());
6620      R.resolveKind();
6621    }
6622    // Otherwise, attempt typo correction.
6623    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
6624  }
6625
6626  if (!R.empty()) {
6627    NamedDecl *Named = R.getFoundDecl();
6628    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6629        && "expected namespace decl");
6630    // C++ [namespace.udir]p1:
6631    //   A using-directive specifies that the names in the nominated
6632    //   namespace can be used in the scope in which the
6633    //   using-directive appears after the using-directive. During
6634    //   unqualified name lookup (3.4.1), the names appear as if they
6635    //   were declared in the nearest enclosing namespace which
6636    //   contains both the using-directive and the nominated
6637    //   namespace. [Note: in this context, "contains" means "contains
6638    //   directly or indirectly". ]
6639
6640    // Find enclosing context containing both using-directive and
6641    // nominated namespace.
6642    NamespaceDecl *NS = getNamespaceDecl(Named);
6643    DeclContext *CommonAncestor = cast<DeclContext>(NS);
6644    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6645      CommonAncestor = CommonAncestor->getParent();
6646
6647    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
6648                                      SS.getWithLocInContext(Context),
6649                                      IdentLoc, Named, CommonAncestor);
6650
6651    if (IsUsingDirectiveInToplevelContext(CurContext) &&
6652        !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
6653      Diag(IdentLoc, diag::warn_using_directive_in_header);
6654    }
6655
6656    PushUsingDirective(S, UDir);
6657  } else {
6658    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6659  }
6660
6661  if (UDir)
6662    ProcessDeclAttributeList(S, UDir, AttrList);
6663
6664  return UDir;
6665}
6666
6667void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6668  // If the scope has an associated entity and the using directive is at
6669  // namespace or translation unit scope, add the UsingDirectiveDecl into
6670  // its lookup structure so qualified name lookup can find it.
6671  DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6672  if (Ctx && !Ctx->isFunctionOrMethod())
6673    Ctx->addDecl(UDir);
6674  else
6675    // Otherwise, it is at block sope. The using-directives will affect lookup
6676    // only to the end of the scope.
6677    S->PushUsingDirective(UDir);
6678}
6679
6680
6681Decl *Sema::ActOnUsingDeclaration(Scope *S,
6682                                  AccessSpecifier AS,
6683                                  bool HasUsingKeyword,
6684                                  SourceLocation UsingLoc,
6685                                  CXXScopeSpec &SS,
6686                                  UnqualifiedId &Name,
6687                                  AttributeList *AttrList,
6688                                  bool IsTypeName,
6689                                  SourceLocation TypenameLoc) {
6690  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6691
6692  switch (Name.getKind()) {
6693  case UnqualifiedId::IK_ImplicitSelfParam:
6694  case UnqualifiedId::IK_Identifier:
6695  case UnqualifiedId::IK_OperatorFunctionId:
6696  case UnqualifiedId::IK_LiteralOperatorId:
6697  case UnqualifiedId::IK_ConversionFunctionId:
6698    break;
6699
6700  case UnqualifiedId::IK_ConstructorName:
6701  case UnqualifiedId::IK_ConstructorTemplateId:
6702    // C++11 inheriting constructors.
6703    Diag(Name.getLocStart(),
6704         getLangOpts().CPlusPlus11 ?
6705           diag::warn_cxx98_compat_using_decl_constructor :
6706           diag::err_using_decl_constructor)
6707      << SS.getRange();
6708
6709    if (getLangOpts().CPlusPlus11) break;
6710
6711    return 0;
6712
6713  case UnqualifiedId::IK_DestructorName:
6714    Diag(Name.getLocStart(), diag::err_using_decl_destructor)
6715      << SS.getRange();
6716    return 0;
6717
6718  case UnqualifiedId::IK_TemplateId:
6719    Diag(Name.getLocStart(), diag::err_using_decl_template_id)
6720      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
6721    return 0;
6722  }
6723
6724  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6725  DeclarationName TargetName = TargetNameInfo.getName();
6726  if (!TargetName)
6727    return 0;
6728
6729  // Warn about access declarations.
6730  // TODO: store that the declaration was written without 'using' and
6731  // talk about access decls instead of using decls in the
6732  // diagnostics.
6733  if (!HasUsingKeyword) {
6734    UsingLoc = Name.getLocStart();
6735
6736    Diag(UsingLoc, diag::warn_access_decl_deprecated)
6737      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
6738  }
6739
6740  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6741      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6742    return 0;
6743
6744  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
6745                                        TargetNameInfo, AttrList,
6746                                        /* IsInstantiation */ false,
6747                                        IsTypeName, TypenameLoc);
6748  if (UD)
6749    PushOnScopeChains(UD, S, /*AddToContext*/ false);
6750
6751  return UD;
6752}
6753
6754/// \brief Determine whether a using declaration considers the given
6755/// declarations as "equivalent", e.g., if they are redeclarations of
6756/// the same entity or are both typedefs of the same type.
6757static bool
6758IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6759                         bool &SuppressRedeclaration) {
6760  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6761    SuppressRedeclaration = false;
6762    return true;
6763  }
6764
6765  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6766    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
6767      SuppressRedeclaration = true;
6768      return Context.hasSameType(TD1->getUnderlyingType(),
6769                                 TD2->getUnderlyingType());
6770    }
6771
6772  return false;
6773}
6774
6775
6776/// Determines whether to create a using shadow decl for a particular
6777/// decl, given the set of decls existing prior to this using lookup.
6778bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6779                                const LookupResult &Previous) {
6780  // Diagnose finding a decl which is not from a base class of the
6781  // current class.  We do this now because there are cases where this
6782  // function will silently decide not to build a shadow decl, which
6783  // will pre-empt further diagnostics.
6784  //
6785  // We don't need to do this in C++0x because we do the check once on
6786  // the qualifier.
6787  //
6788  // FIXME: diagnose the following if we care enough:
6789  //   struct A { int foo; };
6790  //   struct B : A { using A::foo; };
6791  //   template <class T> struct C : A {};
6792  //   template <class T> struct D : C<T> { using B::foo; } // <---
6793  // This is invalid (during instantiation) in C++03 because B::foo
6794  // resolves to the using decl in B, which is not a base class of D<T>.
6795  // We can't diagnose it immediately because C<T> is an unknown
6796  // specialization.  The UsingShadowDecl in D<T> then points directly
6797  // to A::foo, which will look well-formed when we instantiate.
6798  // The right solution is to not collapse the shadow-decl chain.
6799  if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
6800    DeclContext *OrigDC = Orig->getDeclContext();
6801
6802    // Handle enums and anonymous structs.
6803    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6804    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6805    while (OrigRec->isAnonymousStructOrUnion())
6806      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6807
6808    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6809      if (OrigDC == CurContext) {
6810        Diag(Using->getLocation(),
6811             diag::err_using_decl_nested_name_specifier_is_current_class)
6812          << Using->getQualifierLoc().getSourceRange();
6813        Diag(Orig->getLocation(), diag::note_using_decl_target);
6814        return true;
6815      }
6816
6817      Diag(Using->getQualifierLoc().getBeginLoc(),
6818           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6819        << Using->getQualifier()
6820        << cast<CXXRecordDecl>(CurContext)
6821        << Using->getQualifierLoc().getSourceRange();
6822      Diag(Orig->getLocation(), diag::note_using_decl_target);
6823      return true;
6824    }
6825  }
6826
6827  if (Previous.empty()) return false;
6828
6829  NamedDecl *Target = Orig;
6830  if (isa<UsingShadowDecl>(Target))
6831    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6832
6833  // If the target happens to be one of the previous declarations, we
6834  // don't have a conflict.
6835  //
6836  // FIXME: but we might be increasing its access, in which case we
6837  // should redeclare it.
6838  NamedDecl *NonTag = 0, *Tag = 0;
6839  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6840         I != E; ++I) {
6841    NamedDecl *D = (*I)->getUnderlyingDecl();
6842    bool Result;
6843    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6844      return Result;
6845
6846    (isa<TagDecl>(D) ? Tag : NonTag) = D;
6847  }
6848
6849  if (Target->isFunctionOrFunctionTemplate()) {
6850    FunctionDecl *FD;
6851    if (isa<FunctionTemplateDecl>(Target))
6852      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6853    else
6854      FD = cast<FunctionDecl>(Target);
6855
6856    NamedDecl *OldDecl = 0;
6857    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6858    case Ovl_Overload:
6859      return false;
6860
6861    case Ovl_NonFunction:
6862      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6863      break;
6864
6865    // We found a decl with the exact signature.
6866    case Ovl_Match:
6867      // If we're in a record, we want to hide the target, so we
6868      // return true (without a diagnostic) to tell the caller not to
6869      // build a shadow decl.
6870      if (CurContext->isRecord())
6871        return true;
6872
6873      // If we're not in a record, this is an error.
6874      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6875      break;
6876    }
6877
6878    Diag(Target->getLocation(), diag::note_using_decl_target);
6879    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6880    return true;
6881  }
6882
6883  // Target is not a function.
6884
6885  if (isa<TagDecl>(Target)) {
6886    // No conflict between a tag and a non-tag.
6887    if (!Tag) return false;
6888
6889    Diag(Using->getLocation(), diag::err_using_decl_conflict);
6890    Diag(Target->getLocation(), diag::note_using_decl_target);
6891    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6892    return true;
6893  }
6894
6895  // No conflict between a tag and a non-tag.
6896  if (!NonTag) return false;
6897
6898  Diag(Using->getLocation(), diag::err_using_decl_conflict);
6899  Diag(Target->getLocation(), diag::note_using_decl_target);
6900  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6901  return true;
6902}
6903
6904/// Builds a shadow declaration corresponding to a 'using' declaration.
6905UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6906                                            UsingDecl *UD,
6907                                            NamedDecl *Orig) {
6908
6909  // If we resolved to another shadow declaration, just coalesce them.
6910  NamedDecl *Target = Orig;
6911  if (isa<UsingShadowDecl>(Target)) {
6912    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6913    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6914  }
6915
6916  UsingShadowDecl *Shadow
6917    = UsingShadowDecl::Create(Context, CurContext,
6918                              UD->getLocation(), UD, Target);
6919  UD->addShadowDecl(Shadow);
6920
6921  Shadow->setAccess(UD->getAccess());
6922  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6923    Shadow->setInvalidDecl();
6924
6925  if (S)
6926    PushOnScopeChains(Shadow, S);
6927  else
6928    CurContext->addDecl(Shadow);
6929
6930
6931  return Shadow;
6932}
6933
6934/// Hides a using shadow declaration.  This is required by the current
6935/// using-decl implementation when a resolvable using declaration in a
6936/// class is followed by a declaration which would hide or override
6937/// one or more of the using decl's targets; for example:
6938///
6939///   struct Base { void foo(int); };
6940///   struct Derived : Base {
6941///     using Base::foo;
6942///     void foo(int);
6943///   };
6944///
6945/// The governing language is C++03 [namespace.udecl]p12:
6946///
6947///   When a using-declaration brings names from a base class into a
6948///   derived class scope, member functions in the derived class
6949///   override and/or hide member functions with the same name and
6950///   parameter types in a base class (rather than conflicting).
6951///
6952/// There are two ways to implement this:
6953///   (1) optimistically create shadow decls when they're not hidden
6954///       by existing declarations, or
6955///   (2) don't create any shadow decls (or at least don't make them
6956///       visible) until we've fully parsed/instantiated the class.
6957/// The problem with (1) is that we might have to retroactively remove
6958/// a shadow decl, which requires several O(n) operations because the
6959/// decl structures are (very reasonably) not designed for removal.
6960/// (2) avoids this but is very fiddly and phase-dependent.
6961void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6962  if (Shadow->getDeclName().getNameKind() ==
6963        DeclarationName::CXXConversionFunctionName)
6964    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6965
6966  // Remove it from the DeclContext...
6967  Shadow->getDeclContext()->removeDecl(Shadow);
6968
6969  // ...and the scope, if applicable...
6970  if (S) {
6971    S->RemoveDecl(Shadow);
6972    IdResolver.RemoveDecl(Shadow);
6973  }
6974
6975  // ...and the using decl.
6976  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6977
6978  // TODO: complain somehow if Shadow was used.  It shouldn't
6979  // be possible for this to happen, because...?
6980}
6981
6982/// Builds a using declaration.
6983///
6984/// \param IsInstantiation - Whether this call arises from an
6985///   instantiation of an unresolved using declaration.  We treat
6986///   the lookup differently for these declarations.
6987NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6988                                       SourceLocation UsingLoc,
6989                                       CXXScopeSpec &SS,
6990                                       const DeclarationNameInfo &NameInfo,
6991                                       AttributeList *AttrList,
6992                                       bool IsInstantiation,
6993                                       bool IsTypeName,
6994                                       SourceLocation TypenameLoc) {
6995  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6996  SourceLocation IdentLoc = NameInfo.getLoc();
6997  assert(IdentLoc.isValid() && "Invalid TargetName location.");
6998
6999  // FIXME: We ignore attributes for now.
7000
7001  if (SS.isEmpty()) {
7002    Diag(IdentLoc, diag::err_using_requires_qualname);
7003    return 0;
7004  }
7005
7006  // Do the redeclaration lookup in the current scope.
7007  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7008                        ForRedeclaration);
7009  Previous.setHideTags(false);
7010  if (S) {
7011    LookupName(Previous, S);
7012
7013    // It is really dumb that we have to do this.
7014    LookupResult::Filter F = Previous.makeFilter();
7015    while (F.hasNext()) {
7016      NamedDecl *D = F.next();
7017      if (!isDeclInScope(D, CurContext, S))
7018        F.erase();
7019    }
7020    F.done();
7021  } else {
7022    assert(IsInstantiation && "no scope in non-instantiation");
7023    assert(CurContext->isRecord() && "scope not record in instantiation");
7024    LookupQualifiedName(Previous, CurContext);
7025  }
7026
7027  // Check for invalid redeclarations.
7028  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7029    return 0;
7030
7031  // Check for bad qualifiers.
7032  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7033    return 0;
7034
7035  DeclContext *LookupContext = computeDeclContext(SS);
7036  NamedDecl *D;
7037  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7038  if (!LookupContext) {
7039    if (IsTypeName) {
7040      // FIXME: not all declaration name kinds are legal here
7041      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7042                                              UsingLoc, TypenameLoc,
7043                                              QualifierLoc,
7044                                              IdentLoc, NameInfo.getName());
7045    } else {
7046      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7047                                           QualifierLoc, NameInfo);
7048    }
7049  } else {
7050    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7051                          NameInfo, IsTypeName);
7052  }
7053  D->setAccess(AS);
7054  CurContext->addDecl(D);
7055
7056  if (!LookupContext) return D;
7057  UsingDecl *UD = cast<UsingDecl>(D);
7058
7059  if (RequireCompleteDeclContext(SS, LookupContext)) {
7060    UD->setInvalidDecl();
7061    return UD;
7062  }
7063
7064  // The normal rules do not apply to inheriting constructor declarations.
7065  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7066    if (CheckInheritingConstructorUsingDecl(UD))
7067      UD->setInvalidDecl();
7068    return UD;
7069  }
7070
7071  // Otherwise, look up the target name.
7072
7073  LookupResult R(*this, NameInfo, LookupOrdinaryName);
7074
7075  // Unlike most lookups, we don't always want to hide tag
7076  // declarations: tag names are visible through the using declaration
7077  // even if hidden by ordinary names, *except* in a dependent context
7078  // where it's important for the sanity of two-phase lookup.
7079  if (!IsInstantiation)
7080    R.setHideTags(false);
7081
7082  // For the purposes of this lookup, we have a base object type
7083  // equal to that of the current context.
7084  if (CurContext->isRecord()) {
7085    R.setBaseObjectType(
7086                   Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7087  }
7088
7089  LookupQualifiedName(R, LookupContext);
7090
7091  if (R.empty()) {
7092    Diag(IdentLoc, diag::err_no_member)
7093      << NameInfo.getName() << LookupContext << SS.getRange();
7094    UD->setInvalidDecl();
7095    return UD;
7096  }
7097
7098  if (R.isAmbiguous()) {
7099    UD->setInvalidDecl();
7100    return UD;
7101  }
7102
7103  if (IsTypeName) {
7104    // If we asked for a typename and got a non-type decl, error out.
7105    if (!R.getAsSingle<TypeDecl>()) {
7106      Diag(IdentLoc, diag::err_using_typename_non_type);
7107      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7108        Diag((*I)->getUnderlyingDecl()->getLocation(),
7109             diag::note_using_decl_target);
7110      UD->setInvalidDecl();
7111      return UD;
7112    }
7113  } else {
7114    // If we asked for a non-typename and we got a type, error out,
7115    // but only if this is an instantiation of an unresolved using
7116    // decl.  Otherwise just silently find the type name.
7117    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7118      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7119      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7120      UD->setInvalidDecl();
7121      return UD;
7122    }
7123  }
7124
7125  // C++0x N2914 [namespace.udecl]p6:
7126  // A using-declaration shall not name a namespace.
7127  if (R.getAsSingle<NamespaceDecl>()) {
7128    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7129      << SS.getRange();
7130    UD->setInvalidDecl();
7131    return UD;
7132  }
7133
7134  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7135    if (!CheckUsingShadowDecl(UD, *I, Previous))
7136      BuildUsingShadowDecl(S, UD, *I);
7137  }
7138
7139  return UD;
7140}
7141
7142/// Additional checks for a using declaration referring to a constructor name.
7143bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7144  assert(!UD->isTypeName() && "expecting a constructor name");
7145
7146  const Type *SourceType = UD->getQualifier()->getAsType();
7147  assert(SourceType &&
7148         "Using decl naming constructor doesn't have type in scope spec.");
7149  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7150
7151  // Check whether the named type is a direct base class.
7152  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7153  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7154  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7155       BaseIt != BaseE; ++BaseIt) {
7156    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7157    if (CanonicalSourceType == BaseType)
7158      break;
7159    if (BaseIt->getType()->isDependentType())
7160      break;
7161  }
7162
7163  if (BaseIt == BaseE) {
7164    // Did not find SourceType in the bases.
7165    Diag(UD->getUsingLocation(),
7166         diag::err_using_decl_constructor_not_in_direct_base)
7167      << UD->getNameInfo().getSourceRange()
7168      << QualType(SourceType, 0) << TargetClass;
7169    return true;
7170  }
7171
7172  if (!CurContext->isDependentContext())
7173    BaseIt->setInheritConstructors();
7174
7175  return false;
7176}
7177
7178/// Checks that the given using declaration is not an invalid
7179/// redeclaration.  Note that this is checking only for the using decl
7180/// itself, not for any ill-formedness among the UsingShadowDecls.
7181bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7182                                       bool isTypeName,
7183                                       const CXXScopeSpec &SS,
7184                                       SourceLocation NameLoc,
7185                                       const LookupResult &Prev) {
7186  // C++03 [namespace.udecl]p8:
7187  // C++0x [namespace.udecl]p10:
7188  //   A using-declaration is a declaration and can therefore be used
7189  //   repeatedly where (and only where) multiple declarations are
7190  //   allowed.
7191  //
7192  // That's in non-member contexts.
7193  if (!CurContext->getRedeclContext()->isRecord())
7194    return false;
7195
7196  NestedNameSpecifier *Qual
7197    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7198
7199  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7200    NamedDecl *D = *I;
7201
7202    bool DTypename;
7203    NestedNameSpecifier *DQual;
7204    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7205      DTypename = UD->isTypeName();
7206      DQual = UD->getQualifier();
7207    } else if (UnresolvedUsingValueDecl *UD
7208                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7209      DTypename = false;
7210      DQual = UD->getQualifier();
7211    } else if (UnresolvedUsingTypenameDecl *UD
7212                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7213      DTypename = true;
7214      DQual = UD->getQualifier();
7215    } else continue;
7216
7217    // using decls differ if one says 'typename' and the other doesn't.
7218    // FIXME: non-dependent using decls?
7219    if (isTypeName != DTypename) continue;
7220
7221    // using decls differ if they name different scopes (but note that
7222    // template instantiation can cause this check to trigger when it
7223    // didn't before instantiation).
7224    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7225        Context.getCanonicalNestedNameSpecifier(DQual))
7226      continue;
7227
7228    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7229    Diag(D->getLocation(), diag::note_using_decl) << 1;
7230    return true;
7231  }
7232
7233  return false;
7234}
7235
7236
7237/// Checks that the given nested-name qualifier used in a using decl
7238/// in the current context is appropriately related to the current
7239/// scope.  If an error is found, diagnoses it and returns true.
7240bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7241                                   const CXXScopeSpec &SS,
7242                                   SourceLocation NameLoc) {
7243  DeclContext *NamedContext = computeDeclContext(SS);
7244
7245  if (!CurContext->isRecord()) {
7246    // C++03 [namespace.udecl]p3:
7247    // C++0x [namespace.udecl]p8:
7248    //   A using-declaration for a class member shall be a member-declaration.
7249
7250    // If we weren't able to compute a valid scope, it must be a
7251    // dependent class scope.
7252    if (!NamedContext || NamedContext->isRecord()) {
7253      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7254        << SS.getRange();
7255      return true;
7256    }
7257
7258    // Otherwise, everything is known to be fine.
7259    return false;
7260  }
7261
7262  // The current scope is a record.
7263
7264  // If the named context is dependent, we can't decide much.
7265  if (!NamedContext) {
7266    // FIXME: in C++0x, we can diagnose if we can prove that the
7267    // nested-name-specifier does not refer to a base class, which is
7268    // still possible in some cases.
7269
7270    // Otherwise we have to conservatively report that things might be
7271    // okay.
7272    return false;
7273  }
7274
7275  if (!NamedContext->isRecord()) {
7276    // Ideally this would point at the last name in the specifier,
7277    // but we don't have that level of source info.
7278    Diag(SS.getRange().getBegin(),
7279         diag::err_using_decl_nested_name_specifier_is_not_class)
7280      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7281    return true;
7282  }
7283
7284  if (!NamedContext->isDependentContext() &&
7285      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7286    return true;
7287
7288  if (getLangOpts().CPlusPlus11) {
7289    // C++0x [namespace.udecl]p3:
7290    //   In a using-declaration used as a member-declaration, the
7291    //   nested-name-specifier shall name a base class of the class
7292    //   being defined.
7293
7294    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7295                                 cast<CXXRecordDecl>(NamedContext))) {
7296      if (CurContext == NamedContext) {
7297        Diag(NameLoc,
7298             diag::err_using_decl_nested_name_specifier_is_current_class)
7299          << SS.getRange();
7300        return true;
7301      }
7302
7303      Diag(SS.getRange().getBegin(),
7304           diag::err_using_decl_nested_name_specifier_is_not_base_class)
7305        << (NestedNameSpecifier*) SS.getScopeRep()
7306        << cast<CXXRecordDecl>(CurContext)
7307        << SS.getRange();
7308      return true;
7309    }
7310
7311    return false;
7312  }
7313
7314  // C++03 [namespace.udecl]p4:
7315  //   A using-declaration used as a member-declaration shall refer
7316  //   to a member of a base class of the class being defined [etc.].
7317
7318  // Salient point: SS doesn't have to name a base class as long as
7319  // lookup only finds members from base classes.  Therefore we can
7320  // diagnose here only if we can prove that that can't happen,
7321  // i.e. if the class hierarchies provably don't intersect.
7322
7323  // TODO: it would be nice if "definitely valid" results were cached
7324  // in the UsingDecl and UsingShadowDecl so that these checks didn't
7325  // need to be repeated.
7326
7327  struct UserData {
7328    llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7329
7330    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7331      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7332      Data->Bases.insert(Base);
7333      return true;
7334    }
7335
7336    bool hasDependentBases(const CXXRecordDecl *Class) {
7337      return !Class->forallBases(collect, this);
7338    }
7339
7340    /// Returns true if the base is dependent or is one of the
7341    /// accumulated base classes.
7342    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7343      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7344      return !Data->Bases.count(Base);
7345    }
7346
7347    bool mightShareBases(const CXXRecordDecl *Class) {
7348      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7349    }
7350  };
7351
7352  UserData Data;
7353
7354  // Returns false if we find a dependent base.
7355  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7356    return false;
7357
7358  // Returns false if the class has a dependent base or if it or one
7359  // of its bases is present in the base set of the current context.
7360  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7361    return false;
7362
7363  Diag(SS.getRange().getBegin(),
7364       diag::err_using_decl_nested_name_specifier_is_not_base_class)
7365    << (NestedNameSpecifier*) SS.getScopeRep()
7366    << cast<CXXRecordDecl>(CurContext)
7367    << SS.getRange();
7368
7369  return true;
7370}
7371
7372Decl *Sema::ActOnAliasDeclaration(Scope *S,
7373                                  AccessSpecifier AS,
7374                                  MultiTemplateParamsArg TemplateParamLists,
7375                                  SourceLocation UsingLoc,
7376                                  UnqualifiedId &Name,
7377                                  AttributeList *AttrList,
7378                                  TypeResult Type) {
7379  // Skip up to the relevant declaration scope.
7380  while (S->getFlags() & Scope::TemplateParamScope)
7381    S = S->getParent();
7382  assert((S->getFlags() & Scope::DeclScope) &&
7383         "got alias-declaration outside of declaration scope");
7384
7385  if (Type.isInvalid())
7386    return 0;
7387
7388  bool Invalid = false;
7389  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7390  TypeSourceInfo *TInfo = 0;
7391  GetTypeFromParser(Type.get(), &TInfo);
7392
7393  if (DiagnoseClassNameShadow(CurContext, NameInfo))
7394    return 0;
7395
7396  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7397                                      UPPC_DeclarationType)) {
7398    Invalid = true;
7399    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7400                                             TInfo->getTypeLoc().getBeginLoc());
7401  }
7402
7403  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7404  LookupName(Previous, S);
7405
7406  // Warn about shadowing the name of a template parameter.
7407  if (Previous.isSingleResult() &&
7408      Previous.getFoundDecl()->isTemplateParameter()) {
7409    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
7410    Previous.clear();
7411  }
7412
7413  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7414         "name in alias declaration must be an identifier");
7415  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7416                                               Name.StartLocation,
7417                                               Name.Identifier, TInfo);
7418
7419  NewTD->setAccess(AS);
7420
7421  if (Invalid)
7422    NewTD->setInvalidDecl();
7423
7424  ProcessDeclAttributeList(S, NewTD, AttrList);
7425
7426  CheckTypedefForVariablyModifiedType(S, NewTD);
7427  Invalid |= NewTD->isInvalidDecl();
7428
7429  bool Redeclaration = false;
7430
7431  NamedDecl *NewND;
7432  if (TemplateParamLists.size()) {
7433    TypeAliasTemplateDecl *OldDecl = 0;
7434    TemplateParameterList *OldTemplateParams = 0;
7435
7436    if (TemplateParamLists.size() != 1) {
7437      Diag(UsingLoc, diag::err_alias_template_extra_headers)
7438        << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7439         TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
7440    }
7441    TemplateParameterList *TemplateParams = TemplateParamLists[0];
7442
7443    // Only consider previous declarations in the same scope.
7444    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7445                         /*ExplicitInstantiationOrSpecialization*/false);
7446    if (!Previous.empty()) {
7447      Redeclaration = true;
7448
7449      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7450      if (!OldDecl && !Invalid) {
7451        Diag(UsingLoc, diag::err_redefinition_different_kind)
7452          << Name.Identifier;
7453
7454        NamedDecl *OldD = Previous.getRepresentativeDecl();
7455        if (OldD->getLocation().isValid())
7456          Diag(OldD->getLocation(), diag::note_previous_definition);
7457
7458        Invalid = true;
7459      }
7460
7461      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7462        if (TemplateParameterListsAreEqual(TemplateParams,
7463                                           OldDecl->getTemplateParameters(),
7464                                           /*Complain=*/true,
7465                                           TPL_TemplateMatch))
7466          OldTemplateParams = OldDecl->getTemplateParameters();
7467        else
7468          Invalid = true;
7469
7470        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7471        if (!Invalid &&
7472            !Context.hasSameType(OldTD->getUnderlyingType(),
7473                                 NewTD->getUnderlyingType())) {
7474          // FIXME: The C++0x standard does not clearly say this is ill-formed,
7475          // but we can't reasonably accept it.
7476          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7477            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7478          if (OldTD->getLocation().isValid())
7479            Diag(OldTD->getLocation(), diag::note_previous_definition);
7480          Invalid = true;
7481        }
7482      }
7483    }
7484
7485    // Merge any previous default template arguments into our parameters,
7486    // and check the parameter list.
7487    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7488                                   TPC_TypeAliasTemplate))
7489      return 0;
7490
7491    TypeAliasTemplateDecl *NewDecl =
7492      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7493                                    Name.Identifier, TemplateParams,
7494                                    NewTD);
7495
7496    NewDecl->setAccess(AS);
7497
7498    if (Invalid)
7499      NewDecl->setInvalidDecl();
7500    else if (OldDecl)
7501      NewDecl->setPreviousDeclaration(OldDecl);
7502
7503    NewND = NewDecl;
7504  } else {
7505    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7506    NewND = NewTD;
7507  }
7508
7509  if (!Redeclaration)
7510    PushOnScopeChains(NewND, S);
7511
7512  ActOnDocumentableDecl(NewND);
7513  return NewND;
7514}
7515
7516Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
7517                                             SourceLocation NamespaceLoc,
7518                                             SourceLocation AliasLoc,
7519                                             IdentifierInfo *Alias,
7520                                             CXXScopeSpec &SS,
7521                                             SourceLocation IdentLoc,
7522                                             IdentifierInfo *Ident) {
7523
7524  // Lookup the namespace name.
7525  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7526  LookupParsedName(R, S, &SS);
7527
7528  // Check if we have a previous declaration with the same name.
7529  NamedDecl *PrevDecl
7530    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7531                       ForRedeclaration);
7532  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7533    PrevDecl = 0;
7534
7535  if (PrevDecl) {
7536    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
7537      // We already have an alias with the same name that points to the same
7538      // namespace, so don't create a new one.
7539      // FIXME: At some point, we'll want to create the (redundant)
7540      // declaration to maintain better source information.
7541      if (!R.isAmbiguous() && !R.empty() &&
7542          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
7543        return 0;
7544    }
7545
7546    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7547      diag::err_redefinition_different_kind;
7548    Diag(AliasLoc, DiagID) << Alias;
7549    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7550    return 0;
7551  }
7552
7553  if (R.isAmbiguous())
7554    return 0;
7555
7556  if (R.empty()) {
7557    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
7558      Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7559      return 0;
7560    }
7561  }
7562
7563  NamespaceAliasDecl *AliasDecl =
7564    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
7565                               Alias, SS.getWithLocInContext(Context),
7566                               IdentLoc, R.getFoundDecl());
7567
7568  PushOnScopeChains(AliasDecl, S);
7569  return AliasDecl;
7570}
7571
7572Sema::ImplicitExceptionSpecification
7573Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7574                                               CXXMethodDecl *MD) {
7575  CXXRecordDecl *ClassDecl = MD->getParent();
7576
7577  // C++ [except.spec]p14:
7578  //   An implicitly declared special member function (Clause 12) shall have an
7579  //   exception-specification. [...]
7580  ImplicitExceptionSpecification ExceptSpec(*this);
7581  if (ClassDecl->isInvalidDecl())
7582    return ExceptSpec;
7583
7584  // Direct base-class constructors.
7585  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7586                                       BEnd = ClassDecl->bases_end();
7587       B != BEnd; ++B) {
7588    if (B->isVirtual()) // Handled below.
7589      continue;
7590
7591    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7592      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7593      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7594      // If this is a deleted function, add it anyway. This might be conformant
7595      // with the standard. This might not. I'm not sure. It might not matter.
7596      if (Constructor)
7597        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7598    }
7599  }
7600
7601  // Virtual base-class constructors.
7602  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7603                                       BEnd = ClassDecl->vbases_end();
7604       B != BEnd; ++B) {
7605    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7606      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7607      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7608      // If this is a deleted function, add it anyway. This might be conformant
7609      // with the standard. This might not. I'm not sure. It might not matter.
7610      if (Constructor)
7611        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7612    }
7613  }
7614
7615  // Field constructors.
7616  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7617                               FEnd = ClassDecl->field_end();
7618       F != FEnd; ++F) {
7619    if (F->hasInClassInitializer()) {
7620      if (Expr *E = F->getInClassInitializer())
7621        ExceptSpec.CalledExpr(E);
7622      else if (!F->isInvalidDecl())
7623        // DR1351:
7624        //   If the brace-or-equal-initializer of a non-static data member
7625        //   invokes a defaulted default constructor of its class or of an
7626        //   enclosing class in a potentially evaluated subexpression, the
7627        //   program is ill-formed.
7628        //
7629        // This resolution is unworkable: the exception specification of the
7630        // default constructor can be needed in an unevaluated context, in
7631        // particular, in the operand of a noexcept-expression, and we can be
7632        // unable to compute an exception specification for an enclosed class.
7633        //
7634        // We do not allow an in-class initializer to require the evaluation
7635        // of the exception specification for any in-class initializer whose
7636        // definition is not lexically complete.
7637        Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
7638    } else if (const RecordType *RecordTy
7639              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7640      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7641      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7642      // If this is a deleted function, add it anyway. This might be conformant
7643      // with the standard. This might not. I'm not sure. It might not matter.
7644      // In particular, the problem is that this function never gets called. It
7645      // might just be ill-formed because this function attempts to refer to
7646      // a deleted function here.
7647      if (Constructor)
7648        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7649    }
7650  }
7651
7652  return ExceptSpec;
7653}
7654
7655Sema::ImplicitExceptionSpecification
7656Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7657  CXXRecordDecl *ClassDecl = CD->getParent();
7658
7659  // C++ [except.spec]p14:
7660  //   An inheriting constructor [...] shall have an exception-specification. [...]
7661  ImplicitExceptionSpecification ExceptSpec(*this);
7662  if (ClassDecl->isInvalidDecl())
7663    return ExceptSpec;
7664
7665  // Inherited constructor.
7666  const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7667  const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7668  // FIXME: Copying or moving the parameters could add extra exceptions to the
7669  // set, as could the default arguments for the inherited constructor. This
7670  // will be addressed when we implement the resolution of core issue 1351.
7671  ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7672
7673  // Direct base-class constructors.
7674  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7675                                       BEnd = ClassDecl->bases_end();
7676       B != BEnd; ++B) {
7677    if (B->isVirtual()) // Handled below.
7678      continue;
7679
7680    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7681      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7682      if (BaseClassDecl == InheritedDecl)
7683        continue;
7684      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7685      if (Constructor)
7686        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7687    }
7688  }
7689
7690  // Virtual base-class constructors.
7691  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7692                                       BEnd = ClassDecl->vbases_end();
7693       B != BEnd; ++B) {
7694    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7695      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7696      if (BaseClassDecl == InheritedDecl)
7697        continue;
7698      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7699      if (Constructor)
7700        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7701    }
7702  }
7703
7704  // Field constructors.
7705  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7706                               FEnd = ClassDecl->field_end();
7707       F != FEnd; ++F) {
7708    if (F->hasInClassInitializer()) {
7709      if (Expr *E = F->getInClassInitializer())
7710        ExceptSpec.CalledExpr(E);
7711      else if (!F->isInvalidDecl())
7712        Diag(CD->getLocation(),
7713             diag::err_in_class_initializer_references_def_ctor) << CD;
7714    } else if (const RecordType *RecordTy
7715              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7716      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7717      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7718      if (Constructor)
7719        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7720    }
7721  }
7722
7723  return ExceptSpec;
7724}
7725
7726namespace {
7727/// RAII object to register a special member as being currently declared.
7728struct DeclaringSpecialMember {
7729  Sema &S;
7730  Sema::SpecialMemberDecl D;
7731  bool WasAlreadyBeingDeclared;
7732
7733  DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7734    : S(S), D(RD, CSM) {
7735    WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7736    if (WasAlreadyBeingDeclared)
7737      // This almost never happens, but if it does, ensure that our cache
7738      // doesn't contain a stale result.
7739      S.SpecialMemberCache.clear();
7740
7741    // FIXME: Register a note to be produced if we encounter an error while
7742    // declaring the special member.
7743  }
7744  ~DeclaringSpecialMember() {
7745    if (!WasAlreadyBeingDeclared)
7746      S.SpecialMembersBeingDeclared.erase(D);
7747  }
7748
7749  /// \brief Are we already trying to declare this special member?
7750  bool isAlreadyBeingDeclared() const {
7751    return WasAlreadyBeingDeclared;
7752  }
7753};
7754}
7755
7756CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7757                                                     CXXRecordDecl *ClassDecl) {
7758  // C++ [class.ctor]p5:
7759  //   A default constructor for a class X is a constructor of class X
7760  //   that can be called without an argument. If there is no
7761  //   user-declared constructor for class X, a default constructor is
7762  //   implicitly declared. An implicitly-declared default constructor
7763  //   is an inline public member of its class.
7764  assert(ClassDecl->needsImplicitDefaultConstructor() &&
7765         "Should not build implicit default constructor!");
7766
7767  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7768  if (DSM.isAlreadyBeingDeclared())
7769    return 0;
7770
7771  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7772                                                     CXXDefaultConstructor,
7773                                                     false);
7774
7775  // Create the actual constructor declaration.
7776  CanQualType ClassType
7777    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7778  SourceLocation ClassLoc = ClassDecl->getLocation();
7779  DeclarationName Name
7780    = Context.DeclarationNames.getCXXConstructorName(ClassType);
7781  DeclarationNameInfo NameInfo(Name, ClassLoc);
7782  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7783      Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
7784      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7785      Constexpr);
7786  DefaultCon->setAccess(AS_public);
7787  DefaultCon->setDefaulted();
7788  DefaultCon->setImplicit();
7789
7790  // Build an exception specification pointing back at this constructor.
7791  FunctionProtoType::ExtProtoInfo EPI;
7792  EPI.ExceptionSpecType = EST_Unevaluated;
7793  EPI.ExceptionSpecDecl = DefaultCon;
7794  DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
7795
7796  // We don't need to use SpecialMemberIsTrivial here; triviality for default
7797  // constructors is easy to compute.
7798  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7799
7800  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7801    SetDeclDeleted(DefaultCon, ClassLoc);
7802
7803  // Note that we have declared this constructor.
7804  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7805
7806  if (Scope *S = getScopeForContext(ClassDecl))
7807    PushOnScopeChains(DefaultCon, S, false);
7808  ClassDecl->addDecl(DefaultCon);
7809
7810  return DefaultCon;
7811}
7812
7813void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7814                                            CXXConstructorDecl *Constructor) {
7815  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7816          !Constructor->doesThisDeclarationHaveABody() &&
7817          !Constructor->isDeleted()) &&
7818    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
7819
7820  CXXRecordDecl *ClassDecl = Constructor->getParent();
7821  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
7822
7823  SynthesizedFunctionScope Scope(*this, Constructor);
7824  DiagnosticErrorTrap Trap(Diags);
7825  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
7826      Trap.hasErrorOccurred()) {
7827    Diag(CurrentLocation, diag::note_member_synthesized_at)
7828      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
7829    Constructor->setInvalidDecl();
7830    return;
7831  }
7832
7833  SourceLocation Loc = Constructor->getLocation();
7834  Constructor->setBody(new (Context) CompoundStmt(Loc));
7835
7836  Constructor->setUsed();
7837  MarkVTableUsed(CurrentLocation, ClassDecl);
7838
7839  if (ASTMutationListener *L = getASTMutationListener()) {
7840    L->CompletedImplicitDefinition(Constructor);
7841  }
7842}
7843
7844void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7845  // Check that any explicitly-defaulted methods have exception specifications
7846  // compatible with their implicit exception specifications.
7847  CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
7848}
7849
7850namespace {
7851/// Information on inheriting constructors to declare.
7852class InheritingConstructorInfo {
7853public:
7854  InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7855      : SemaRef(SemaRef), Derived(Derived) {
7856    // Mark the constructors that we already have in the derived class.
7857    //
7858    // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7859    //   unless there is a user-declared constructor with the same signature in
7860    //   the class where the using-declaration appears.
7861    visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7862  }
7863
7864  void inheritAll(CXXRecordDecl *RD) {
7865    visitAll(RD, &InheritingConstructorInfo::inherit);
7866  }
7867
7868private:
7869  /// Information about an inheriting constructor.
7870  struct InheritingConstructor {
7871    InheritingConstructor()
7872      : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7873
7874    /// If \c true, a constructor with this signature is already declared
7875    /// in the derived class.
7876    bool DeclaredInDerived;
7877
7878    /// The constructor which is inherited.
7879    const CXXConstructorDecl *BaseCtor;
7880
7881    /// The derived constructor we declared.
7882    CXXConstructorDecl *DerivedCtor;
7883  };
7884
7885  /// Inheriting constructors with a given canonical type. There can be at
7886  /// most one such non-template constructor, and any number of templated
7887  /// constructors.
7888  struct InheritingConstructorsForType {
7889    InheritingConstructor NonTemplate;
7890    llvm::SmallVector<
7891      std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7892
7893    InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7894      if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7895        TemplateParameterList *ParamList = FTD->getTemplateParameters();
7896        for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7897          if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7898                                               false, S.TPL_TemplateMatch))
7899            return Templates[I].second;
7900        Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7901        return Templates.back().second;
7902      }
7903
7904      return NonTemplate;
7905    }
7906  };
7907
7908  /// Get or create the inheriting constructor record for a constructor.
7909  InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7910                                  QualType CtorType) {
7911    return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7912        .getEntry(SemaRef, Ctor);
7913  }
7914
7915  typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7916
7917  /// Process all constructors for a class.
7918  void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7919    for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7920                                      CtorE = RD->ctor_end();
7921         CtorIt != CtorE; ++CtorIt)
7922      (this->*Callback)(*CtorIt);
7923    for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7924             I(RD->decls_begin()), E(RD->decls_end());
7925         I != E; ++I) {
7926      const FunctionDecl *FD = (*I)->getTemplatedDecl();
7927      if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7928        (this->*Callback)(CD);
7929    }
7930  }
7931
7932  /// Note that a constructor (or constructor template) was declared in Derived.
7933  void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7934    getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7935  }
7936
7937  /// Inherit a single constructor.
7938  void inherit(const CXXConstructorDecl *Ctor) {
7939    const FunctionProtoType *CtorType =
7940        Ctor->getType()->castAs<FunctionProtoType>();
7941    ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7942    FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7943
7944    SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7945
7946    // Core issue (no number yet): the ellipsis is always discarded.
7947    if (EPI.Variadic) {
7948      SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7949      SemaRef.Diag(Ctor->getLocation(),
7950                   diag::note_using_decl_constructor_ellipsis);
7951      EPI.Variadic = false;
7952    }
7953
7954    // Declare a constructor for each number of parameters.
7955    //
7956    // C++11 [class.inhctor]p1:
7957    //   The candidate set of inherited constructors from the class X named in
7958    //   the using-declaration consists of [... modulo defects ...] for each
7959    //   constructor or constructor template of X, the set of constructors or
7960    //   constructor templates that results from omitting any ellipsis parameter
7961    //   specification and successively omitting parameters with a default
7962    //   argument from the end of the parameter-type-list
7963    unsigned MinParams = minParamsToInherit(Ctor);
7964    unsigned Params = Ctor->getNumParams();
7965    if (Params >= MinParams) {
7966      do
7967        declareCtor(UsingLoc, Ctor,
7968                    SemaRef.Context.getFunctionType(
7969                        Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7970      while (Params > MinParams &&
7971             Ctor->getParamDecl(--Params)->hasDefaultArg());
7972    }
7973  }
7974
7975  /// Find the using-declaration which specified that we should inherit the
7976  /// constructors of \p Base.
7977  SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
7978    // No fancy lookup required; just look for the base constructor name
7979    // directly within the derived class.
7980    ASTContext &Context = SemaRef.Context;
7981    DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7982        Context.getCanonicalType(Context.getRecordType(Base)));
7983    DeclContext::lookup_const_result Decls = Derived->lookup(Name);
7984    return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
7985  }
7986
7987  unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
7988    // C++11 [class.inhctor]p3:
7989    //   [F]or each constructor template in the candidate set of inherited
7990    //   constructors, a constructor template is implicitly declared
7991    if (Ctor->getDescribedFunctionTemplate())
7992      return 0;
7993
7994    //   For each non-template constructor in the candidate set of inherited
7995    //   constructors other than a constructor having no parameters or a
7996    //   copy/move constructor having a single parameter, a constructor is
7997    //   implicitly declared [...]
7998    if (Ctor->getNumParams() == 0)
7999      return 1;
8000    if (Ctor->isCopyOrMoveConstructor())
8001      return 2;
8002
8003    // Per discussion on core reflector, never inherit a constructor which
8004    // would become a default, copy, or move constructor of Derived either.
8005    const ParmVarDecl *PD = Ctor->getParamDecl(0);
8006    const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8007    return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8008  }
8009
8010  /// Declare a single inheriting constructor, inheriting the specified
8011  /// constructor, with the given type.
8012  void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8013                   QualType DerivedType) {
8014    InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8015
8016    // C++11 [class.inhctor]p3:
8017    //   ... a constructor is implicitly declared with the same constructor
8018    //   characteristics unless there is a user-declared constructor with
8019    //   the same signature in the class where the using-declaration appears
8020    if (Entry.DeclaredInDerived)
8021      return;
8022
8023    // C++11 [class.inhctor]p7:
8024    //   If two using-declarations declare inheriting constructors with the
8025    //   same signature, the program is ill-formed
8026    if (Entry.DerivedCtor) {
8027      if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8028        // Only diagnose this once per constructor.
8029        if (Entry.DerivedCtor->isInvalidDecl())
8030          return;
8031        Entry.DerivedCtor->setInvalidDecl();
8032
8033        SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8034        SemaRef.Diag(BaseCtor->getLocation(),
8035                     diag::note_using_decl_constructor_conflict_current_ctor);
8036        SemaRef.Diag(Entry.BaseCtor->getLocation(),
8037                     diag::note_using_decl_constructor_conflict_previous_ctor);
8038        SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8039                     diag::note_using_decl_constructor_conflict_previous_using);
8040      } else {
8041        // Core issue (no number): if the same inheriting constructor is
8042        // produced by multiple base class constructors from the same base
8043        // class, the inheriting constructor is defined as deleted.
8044        SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8045      }
8046
8047      return;
8048    }
8049
8050    ASTContext &Context = SemaRef.Context;
8051    DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8052        Context.getCanonicalType(Context.getRecordType(Derived)));
8053    DeclarationNameInfo NameInfo(Name, UsingLoc);
8054
8055    TemplateParameterList *TemplateParams = 0;
8056    if (const FunctionTemplateDecl *FTD =
8057            BaseCtor->getDescribedFunctionTemplate()) {
8058      TemplateParams = FTD->getTemplateParameters();
8059      // We're reusing template parameters from a different DeclContext. This
8060      // is questionable at best, but works out because the template depth in
8061      // both places is guaranteed to be 0.
8062      // FIXME: Rebuild the template parameters in the new context, and
8063      // transform the function type to refer to them.
8064    }
8065
8066    // Build type source info pointing at the using-declaration. This is
8067    // required by template instantiation.
8068    TypeSourceInfo *TInfo =
8069        Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8070    FunctionProtoTypeLoc ProtoLoc =
8071        TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8072
8073    CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8074        Context, Derived, UsingLoc, NameInfo, DerivedType,
8075        TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8076        /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8077
8078    // Build an unevaluated exception specification for this constructor.
8079    const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8080    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8081    EPI.ExceptionSpecType = EST_Unevaluated;
8082    EPI.ExceptionSpecDecl = DerivedCtor;
8083    DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8084                                                 FPT->getArgTypes(), EPI));
8085
8086    // Build the parameter declarations.
8087    SmallVector<ParmVarDecl *, 16> ParamDecls;
8088    for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8089      TypeSourceInfo *TInfo =
8090          Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8091      ParmVarDecl *PD = ParmVarDecl::Create(
8092          Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8093          FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8094      PD->setScopeInfo(0, I);
8095      PD->setImplicit();
8096      ParamDecls.push_back(PD);
8097      ProtoLoc.setArg(I, PD);
8098    }
8099
8100    // Set up the new constructor.
8101    DerivedCtor->setAccess(BaseCtor->getAccess());
8102    DerivedCtor->setParams(ParamDecls);
8103    DerivedCtor->setInheritedConstructor(BaseCtor);
8104    if (BaseCtor->isDeleted())
8105      SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8106
8107    // If this is a constructor template, build the template declaration.
8108    if (TemplateParams) {
8109      FunctionTemplateDecl *DerivedTemplate =
8110          FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8111                                       TemplateParams, DerivedCtor);
8112      DerivedTemplate->setAccess(BaseCtor->getAccess());
8113      DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8114      Derived->addDecl(DerivedTemplate);
8115    } else {
8116      Derived->addDecl(DerivedCtor);
8117    }
8118
8119    Entry.BaseCtor = BaseCtor;
8120    Entry.DerivedCtor = DerivedCtor;
8121  }
8122
8123  Sema &SemaRef;
8124  CXXRecordDecl *Derived;
8125  typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8126  MapType Map;
8127};
8128}
8129
8130void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8131  // Defer declaring the inheriting constructors until the class is
8132  // instantiated.
8133  if (ClassDecl->isDependentContext())
8134    return;
8135
8136  // Find base classes from which we might inherit constructors.
8137  SmallVector<CXXRecordDecl*, 4> InheritedBases;
8138  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8139                                          BaseE = ClassDecl->bases_end();
8140       BaseIt != BaseE; ++BaseIt)
8141    if (BaseIt->getInheritConstructors())
8142      InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
8143
8144  // Go no further if we're not inheriting any constructors.
8145  if (InheritedBases.empty())
8146    return;
8147
8148  // Declare the inherited constructors.
8149  InheritingConstructorInfo ICI(*this, ClassDecl);
8150  for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8151    ICI.inheritAll(InheritedBases[I]);
8152}
8153
8154void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8155                                       CXXConstructorDecl *Constructor) {
8156  CXXRecordDecl *ClassDecl = Constructor->getParent();
8157  assert(Constructor->getInheritedConstructor() &&
8158         !Constructor->doesThisDeclarationHaveABody() &&
8159         !Constructor->isDeleted());
8160
8161  SynthesizedFunctionScope Scope(*this, Constructor);
8162  DiagnosticErrorTrap Trap(Diags);
8163  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8164      Trap.hasErrorOccurred()) {
8165    Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8166      << Context.getTagDeclType(ClassDecl);
8167    Constructor->setInvalidDecl();
8168    return;
8169  }
8170
8171  SourceLocation Loc = Constructor->getLocation();
8172  Constructor->setBody(new (Context) CompoundStmt(Loc));
8173
8174  Constructor->setUsed();
8175  MarkVTableUsed(CurrentLocation, ClassDecl);
8176
8177  if (ASTMutationListener *L = getASTMutationListener()) {
8178    L->CompletedImplicitDefinition(Constructor);
8179  }
8180}
8181
8182
8183Sema::ImplicitExceptionSpecification
8184Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8185  CXXRecordDecl *ClassDecl = MD->getParent();
8186
8187  // C++ [except.spec]p14:
8188  //   An implicitly declared special member function (Clause 12) shall have
8189  //   an exception-specification.
8190  ImplicitExceptionSpecification ExceptSpec(*this);
8191  if (ClassDecl->isInvalidDecl())
8192    return ExceptSpec;
8193
8194  // Direct base-class destructors.
8195  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8196                                       BEnd = ClassDecl->bases_end();
8197       B != BEnd; ++B) {
8198    if (B->isVirtual()) // Handled below.
8199      continue;
8200
8201    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8202      ExceptSpec.CalledDecl(B->getLocStart(),
8203                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8204  }
8205
8206  // Virtual base-class destructors.
8207  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8208                                       BEnd = ClassDecl->vbases_end();
8209       B != BEnd; ++B) {
8210    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8211      ExceptSpec.CalledDecl(B->getLocStart(),
8212                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8213  }
8214
8215  // Field destructors.
8216  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8217                               FEnd = ClassDecl->field_end();
8218       F != FEnd; ++F) {
8219    if (const RecordType *RecordTy
8220        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8221      ExceptSpec.CalledDecl(F->getLocation(),
8222                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8223  }
8224
8225  return ExceptSpec;
8226}
8227
8228CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8229  // C++ [class.dtor]p2:
8230  //   If a class has no user-declared destructor, a destructor is
8231  //   declared implicitly. An implicitly-declared destructor is an
8232  //   inline public member of its class.
8233  assert(ClassDecl->needsImplicitDestructor());
8234
8235  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8236  if (DSM.isAlreadyBeingDeclared())
8237    return 0;
8238
8239  // Create the actual destructor declaration.
8240  CanQualType ClassType
8241    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8242  SourceLocation ClassLoc = ClassDecl->getLocation();
8243  DeclarationName Name
8244    = Context.DeclarationNames.getCXXDestructorName(ClassType);
8245  DeclarationNameInfo NameInfo(Name, ClassLoc);
8246  CXXDestructorDecl *Destructor
8247      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8248                                  QualType(), 0, /*isInline=*/true,
8249                                  /*isImplicitlyDeclared=*/true);
8250  Destructor->setAccess(AS_public);
8251  Destructor->setDefaulted();
8252  Destructor->setImplicit();
8253
8254  // Build an exception specification pointing back at this destructor.
8255  FunctionProtoType::ExtProtoInfo EPI;
8256  EPI.ExceptionSpecType = EST_Unevaluated;
8257  EPI.ExceptionSpecDecl = Destructor;
8258  Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8259
8260  AddOverriddenMethods(ClassDecl, Destructor);
8261
8262  // We don't need to use SpecialMemberIsTrivial here; triviality for
8263  // destructors is easy to compute.
8264  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8265
8266  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8267    SetDeclDeleted(Destructor, ClassLoc);
8268
8269  // Note that we have declared this destructor.
8270  ++ASTContext::NumImplicitDestructorsDeclared;
8271
8272  // Introduce this destructor into its scope.
8273  if (Scope *S = getScopeForContext(ClassDecl))
8274    PushOnScopeChains(Destructor, S, false);
8275  ClassDecl->addDecl(Destructor);
8276
8277  return Destructor;
8278}
8279
8280void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
8281                                    CXXDestructorDecl *Destructor) {
8282  assert((Destructor->isDefaulted() &&
8283          !Destructor->doesThisDeclarationHaveABody() &&
8284          !Destructor->isDeleted()) &&
8285         "DefineImplicitDestructor - call it for implicit default dtor");
8286  CXXRecordDecl *ClassDecl = Destructor->getParent();
8287  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
8288
8289  if (Destructor->isInvalidDecl())
8290    return;
8291
8292  SynthesizedFunctionScope Scope(*this, Destructor);
8293
8294  DiagnosticErrorTrap Trap(Diags);
8295  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8296                                         Destructor->getParent());
8297
8298  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
8299    Diag(CurrentLocation, diag::note_member_synthesized_at)
8300      << CXXDestructor << Context.getTagDeclType(ClassDecl);
8301
8302    Destructor->setInvalidDecl();
8303    return;
8304  }
8305
8306  SourceLocation Loc = Destructor->getLocation();
8307  Destructor->setBody(new (Context) CompoundStmt(Loc));
8308  Destructor->setImplicitlyDefined(true);
8309  Destructor->setUsed();
8310  MarkVTableUsed(CurrentLocation, ClassDecl);
8311
8312  if (ASTMutationListener *L = getASTMutationListener()) {
8313    L->CompletedImplicitDefinition(Destructor);
8314  }
8315}
8316
8317/// \brief Perform any semantic analysis which needs to be delayed until all
8318/// pending class member declarations have been parsed.
8319void Sema::ActOnFinishCXXMemberDecls() {
8320  // If the context is an invalid C++ class, just suppress these checks.
8321  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8322    if (Record->isInvalidDecl()) {
8323      DelayedDestructorExceptionSpecChecks.clear();
8324      return;
8325    }
8326  }
8327
8328  // Perform any deferred checking of exception specifications for virtual
8329  // destructors.
8330  for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8331       i != e; ++i) {
8332    const CXXDestructorDecl *Dtor =
8333        DelayedDestructorExceptionSpecChecks[i].first;
8334    assert(!Dtor->getParent()->isDependentType() &&
8335           "Should not ever add destructors of templates into the list.");
8336    CheckOverridingFunctionExceptionSpec(Dtor,
8337        DelayedDestructorExceptionSpecChecks[i].second);
8338  }
8339  DelayedDestructorExceptionSpecChecks.clear();
8340}
8341
8342void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8343                                         CXXDestructorDecl *Destructor) {
8344  assert(getLangOpts().CPlusPlus11 &&
8345         "adjusting dtor exception specs was introduced in c++11");
8346
8347  // C++11 [class.dtor]p3:
8348  //   A declaration of a destructor that does not have an exception-
8349  //   specification is implicitly considered to have the same exception-
8350  //   specification as an implicit declaration.
8351  const FunctionProtoType *DtorType = Destructor->getType()->
8352                                        getAs<FunctionProtoType>();
8353  if (DtorType->hasExceptionSpec())
8354    return;
8355
8356  // Replace the destructor's type, building off the existing one. Fortunately,
8357  // the only thing of interest in the destructor type is its extended info.
8358  // The return and arguments are fixed.
8359  FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8360  EPI.ExceptionSpecType = EST_Unevaluated;
8361  EPI.ExceptionSpecDecl = Destructor;
8362  Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8363
8364  // FIXME: If the destructor has a body that could throw, and the newly created
8365  // spec doesn't allow exceptions, we should emit a warning, because this
8366  // change in behavior can break conforming C++03 programs at runtime.
8367  // However, we don't have a body or an exception specification yet, so it
8368  // needs to be done somewhere else.
8369}
8370
8371/// When generating a defaulted copy or move assignment operator, if a field
8372/// should be copied with __builtin_memcpy rather than via explicit assignments,
8373/// do so. This optimization only applies for arrays of scalars, and for arrays
8374/// of class type where the selected copy/move-assignment operator is trivial.
8375static StmtResult
8376buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8377                           Expr *To, Expr *From) {
8378  // Compute the size of the memory buffer to be copied.
8379  QualType SizeType = S.Context.getSizeType();
8380  llvm::APInt Size(S.Context.getTypeSize(SizeType),
8381                   S.Context.getTypeSizeInChars(T).getQuantity());
8382
8383  // Take the address of the field references for "from" and "to". We
8384  // directly construct UnaryOperators here because semantic analysis
8385  // does not permit us to take the address of an xvalue.
8386  From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8387                         S.Context.getPointerType(From->getType()),
8388                         VK_RValue, OK_Ordinary, Loc);
8389  To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8390                       S.Context.getPointerType(To->getType()),
8391                       VK_RValue, OK_Ordinary, Loc);
8392
8393  const Type *E = T->getBaseElementTypeUnsafe();
8394  bool NeedsCollectableMemCpy =
8395    E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8396
8397  // Create a reference to the __builtin_objc_memmove_collectable function
8398  StringRef MemCpyName = NeedsCollectableMemCpy ?
8399    "__builtin_objc_memmove_collectable" :
8400    "__builtin_memcpy";
8401  LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8402                 Sema::LookupOrdinaryName);
8403  S.LookupName(R, S.TUScope, true);
8404
8405  FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8406  if (!MemCpy)
8407    // Something went horribly wrong earlier, and we will have complained
8408    // about it.
8409    return StmtError();
8410
8411  ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8412                                            VK_RValue, Loc, 0);
8413  assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8414
8415  Expr *CallArgs[] = {
8416    To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8417  };
8418  ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8419                                    Loc, CallArgs, Loc);
8420
8421  assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8422  return S.Owned(Call.takeAs<Stmt>());
8423}
8424
8425/// \brief Builds a statement that copies/moves the given entity from \p From to
8426/// \c To.
8427///
8428/// This routine is used to copy/move the members of a class with an
8429/// implicitly-declared copy/move assignment operator. When the entities being
8430/// copied are arrays, this routine builds for loops to copy them.
8431///
8432/// \param S The Sema object used for type-checking.
8433///
8434/// \param Loc The location where the implicit copy/move is being generated.
8435///
8436/// \param T The type of the expressions being copied/moved. Both expressions
8437/// must have this type.
8438///
8439/// \param To The expression we are copying/moving to.
8440///
8441/// \param From The expression we are copying/moving from.
8442///
8443/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
8444/// Otherwise, it's a non-static member subobject.
8445///
8446/// \param Copying Whether we're copying or moving.
8447///
8448/// \param Depth Internal parameter recording the depth of the recursion.
8449///
8450/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8451/// if a memcpy should be used instead.
8452static StmtResult
8453buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8454                                 Expr *To, Expr *From,
8455                                 bool CopyingBaseSubobject, bool Copying,
8456                                 unsigned Depth = 0) {
8457  // C++11 [class.copy]p28:
8458  //   Each subobject is assigned in the manner appropriate to its type:
8459  //
8460  //     - if the subobject is of class type, as if by a call to operator= with
8461  //       the subobject as the object expression and the corresponding
8462  //       subobject of x as a single function argument (as if by explicit
8463  //       qualification; that is, ignoring any possible virtual overriding
8464  //       functions in more derived classes);
8465  //
8466  // C++03 [class.copy]p13:
8467  //     - if the subobject is of class type, the copy assignment operator for
8468  //       the class is used (as if by explicit qualification; that is,
8469  //       ignoring any possible virtual overriding functions in more derived
8470  //       classes);
8471  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8472    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8473
8474    // Look for operator=.
8475    DeclarationName Name
8476      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8477    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8478    S.LookupQualifiedName(OpLookup, ClassDecl, false);
8479
8480    // Prior to C++11, filter out any result that isn't a copy/move-assignment
8481    // operator.
8482    if (!S.getLangOpts().CPlusPlus11) {
8483      LookupResult::Filter F = OpLookup.makeFilter();
8484      while (F.hasNext()) {
8485        NamedDecl *D = F.next();
8486        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8487          if (Method->isCopyAssignmentOperator() ||
8488              (!Copying && Method->isMoveAssignmentOperator()))
8489            continue;
8490
8491        F.erase();
8492      }
8493      F.done();
8494    }
8495
8496    // Suppress the protected check (C++ [class.protected]) for each of the
8497    // assignment operators we found. This strange dance is required when
8498    // we're assigning via a base classes's copy-assignment operator. To
8499    // ensure that we're getting the right base class subobject (without
8500    // ambiguities), we need to cast "this" to that subobject type; to
8501    // ensure that we don't go through the virtual call mechanism, we need
8502    // to qualify the operator= name with the base class (see below). However,
8503    // this means that if the base class has a protected copy assignment
8504    // operator, the protected member access check will fail. So, we
8505    // rewrite "protected" access to "public" access in this case, since we
8506    // know by construction that we're calling from a derived class.
8507    if (CopyingBaseSubobject) {
8508      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8509           L != LEnd; ++L) {
8510        if (L.getAccess() == AS_protected)
8511          L.setAccess(AS_public);
8512      }
8513    }
8514
8515    // Create the nested-name-specifier that will be used to qualify the
8516    // reference to operator=; this is required to suppress the virtual
8517    // call mechanism.
8518    CXXScopeSpec SS;
8519    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
8520    SS.MakeTrivial(S.Context,
8521                   NestedNameSpecifier::Create(S.Context, 0, false,
8522                                               CanonicalT),
8523                   Loc);
8524
8525    // Create the reference to operator=.
8526    ExprResult OpEqualRef
8527      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
8528                                   /*TemplateKWLoc=*/SourceLocation(),
8529                                   /*FirstQualifierInScope=*/0,
8530                                   OpLookup,
8531                                   /*TemplateArgs=*/0,
8532                                   /*SuppressQualifierCheck=*/true);
8533    if (OpEqualRef.isInvalid())
8534      return StmtError();
8535
8536    // Build the call to the assignment operator.
8537
8538    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
8539                                                  OpEqualRef.takeAs<Expr>(),
8540                                                  Loc, &From, 1, Loc);
8541    if (Call.isInvalid())
8542      return StmtError();
8543
8544    // If we built a call to a trivial 'operator=' while copying an array,
8545    // bail out. We'll replace the whole shebang with a memcpy.
8546    CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8547    if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8548      return StmtResult((Stmt*)0);
8549
8550    // Convert to an expression-statement, and clean up any produced
8551    // temporaries.
8552    return S.ActOnExprStmt(Call);
8553  }
8554
8555  //     - if the subobject is of scalar type, the built-in assignment
8556  //       operator is used.
8557  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
8558  if (!ArrayTy) {
8559    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
8560    if (Assignment.isInvalid())
8561      return StmtError();
8562    return S.ActOnExprStmt(Assignment);
8563  }
8564
8565  //     - if the subobject is an array, each element is assigned, in the
8566  //       manner appropriate to the element type;
8567
8568  // Construct a loop over the array bounds, e.g.,
8569  //
8570  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8571  //
8572  // that will copy each of the array elements.
8573  QualType SizeType = S.Context.getSizeType();
8574
8575  // Create the iteration variable.
8576  IdentifierInfo *IterationVarName = 0;
8577  {
8578    SmallString<8> Str;
8579    llvm::raw_svector_ostream OS(Str);
8580    OS << "__i" << Depth;
8581    IterationVarName = &S.Context.Idents.get(OS.str());
8582  }
8583  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
8584                                          IterationVarName, SizeType,
8585                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
8586                                          SC_None);
8587
8588  // Initialize the iteration variable to zero.
8589  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8590  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8591
8592  // Create a reference to the iteration variable; we'll use this several
8593  // times throughout.
8594  Expr *IterationVarRef
8595    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
8596  assert(IterationVarRef && "Reference to invented variable cannot fail!");
8597  Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8598  assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8599
8600  // Create the DeclStmt that holds the iteration variable.
8601  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
8602
8603  // Subscript the "from" and "to" expressions with the iteration variable.
8604  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
8605                                                         IterationVarRefRVal,
8606                                                         Loc));
8607  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
8608                                                       IterationVarRefRVal,
8609                                                       Loc));
8610  if (!Copying) // Cast to rvalue
8611    From = CastForMoving(S, From);
8612
8613  // Build the copy/move for an individual element of the array.
8614  StmtResult Copy =
8615    buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8616                                     To, From, CopyingBaseSubobject,
8617                                     Copying, Depth + 1);
8618  // Bail out if copying fails or if we determined that we should use memcpy.
8619  if (Copy.isInvalid() || !Copy.get())
8620    return Copy;
8621
8622  // Create the comparison against the array bound.
8623  llvm::APInt Upper
8624    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8625  Expr *Comparison
8626    = new (S.Context) BinaryOperator(IterationVarRefRVal,
8627                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8628                                     BO_NE, S.Context.BoolTy,
8629                                     VK_RValue, OK_Ordinary, Loc, false);
8630
8631  // Create the pre-increment of the iteration variable.
8632  Expr *Increment
8633    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8634                                    VK_LValue, OK_Ordinary, Loc);
8635
8636  // Construct the loop that copies all elements of this array.
8637  return S.ActOnForStmt(Loc, Loc, InitStmt,
8638                        S.MakeFullExpr(Comparison),
8639                        0, S.MakeFullDiscardedValueExpr(Increment),
8640                        Loc, Copy.take());
8641}
8642
8643static StmtResult
8644buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8645                      Expr *To, Expr *From,
8646                      bool CopyingBaseSubobject, bool Copying) {
8647  // Maybe we should use a memcpy?
8648  if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8649      T.isTriviallyCopyableType(S.Context))
8650    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8651
8652  StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8653                                                     CopyingBaseSubobject,
8654                                                     Copying, 0));
8655
8656  // If we ended up picking a trivial assignment operator for an array of a
8657  // non-trivially-copyable class type, just emit a memcpy.
8658  if (!Result.isInvalid() && !Result.get())
8659    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8660
8661  return Result;
8662}
8663
8664Sema::ImplicitExceptionSpecification
8665Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8666  CXXRecordDecl *ClassDecl = MD->getParent();
8667
8668  ImplicitExceptionSpecification ExceptSpec(*this);
8669  if (ClassDecl->isInvalidDecl())
8670    return ExceptSpec;
8671
8672  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8673  assert(T->getNumArgs() == 1 && "not a copy assignment op");
8674  unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8675
8676  // C++ [except.spec]p14:
8677  //   An implicitly declared special member function (Clause 12) shall have an
8678  //   exception-specification. [...]
8679
8680  // It is unspecified whether or not an implicit copy assignment operator
8681  // attempts to deduplicate calls to assignment operators of virtual bases are
8682  // made. As such, this exception specification is effectively unspecified.
8683  // Based on a similar decision made for constness in C++0x, we're erring on
8684  // the side of assuming such calls to be made regardless of whether they
8685  // actually happen.
8686  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8687                                       BaseEnd = ClassDecl->bases_end();
8688       Base != BaseEnd; ++Base) {
8689    if (Base->isVirtual())
8690      continue;
8691
8692    CXXRecordDecl *BaseClassDecl
8693      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8694    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8695                                                            ArgQuals, false, 0))
8696      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8697  }
8698
8699  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8700                                       BaseEnd = ClassDecl->vbases_end();
8701       Base != BaseEnd; ++Base) {
8702    CXXRecordDecl *BaseClassDecl
8703      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8704    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8705                                                            ArgQuals, false, 0))
8706      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8707  }
8708
8709  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8710                                  FieldEnd = ClassDecl->field_end();
8711       Field != FieldEnd;
8712       ++Field) {
8713    QualType FieldType = Context.getBaseElementType(Field->getType());
8714    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8715      if (CXXMethodDecl *CopyAssign =
8716          LookupCopyingAssignment(FieldClassDecl,
8717                                  ArgQuals | FieldType.getCVRQualifiers(),
8718                                  false, 0))
8719        ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
8720    }
8721  }
8722
8723  return ExceptSpec;
8724}
8725
8726CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8727  // Note: The following rules are largely analoguous to the copy
8728  // constructor rules. Note that virtual bases are not taken into account
8729  // for determining the argument type of the operator. Note also that
8730  // operators taking an object instead of a reference are allowed.
8731  assert(ClassDecl->needsImplicitCopyAssignment());
8732
8733  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8734  if (DSM.isAlreadyBeingDeclared())
8735    return 0;
8736
8737  QualType ArgType = Context.getTypeDeclType(ClassDecl);
8738  QualType RetType = Context.getLValueReferenceType(ArgType);
8739  if (ClassDecl->implicitCopyAssignmentHasConstParam())
8740    ArgType = ArgType.withConst();
8741  ArgType = Context.getLValueReferenceType(ArgType);
8742
8743  //   An implicitly-declared copy assignment operator is an inline public
8744  //   member of its class.
8745  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8746  SourceLocation ClassLoc = ClassDecl->getLocation();
8747  DeclarationNameInfo NameInfo(Name, ClassLoc);
8748  CXXMethodDecl *CopyAssignment
8749    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8750                            /*TInfo=*/0,
8751                            /*StorageClass=*/SC_None,
8752                            /*isInline=*/true, /*isConstexpr=*/false,
8753                            SourceLocation());
8754  CopyAssignment->setAccess(AS_public);
8755  CopyAssignment->setDefaulted();
8756  CopyAssignment->setImplicit();
8757
8758  // Build an exception specification pointing back at this member.
8759  FunctionProtoType::ExtProtoInfo EPI;
8760  EPI.ExceptionSpecType = EST_Unevaluated;
8761  EPI.ExceptionSpecDecl = CopyAssignment;
8762  CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
8763
8764  // Add the parameter to the operator.
8765  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
8766                                               ClassLoc, ClassLoc, /*Id=*/0,
8767                                               ArgType, /*TInfo=*/0,
8768                                               SC_None, 0);
8769  CopyAssignment->setParams(FromParam);
8770
8771  AddOverriddenMethods(ClassDecl, CopyAssignment);
8772
8773  CopyAssignment->setTrivial(
8774    ClassDecl->needsOverloadResolutionForCopyAssignment()
8775      ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8776      : ClassDecl->hasTrivialCopyAssignment());
8777
8778  // C++0x [class.copy]p19:
8779  //   ....  If the class definition does not explicitly declare a copy
8780  //   assignment operator, there is no user-declared move constructor, and
8781  //   there is no user-declared move assignment operator, a copy assignment
8782  //   operator is implicitly declared as defaulted.
8783  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
8784    SetDeclDeleted(CopyAssignment, ClassLoc);
8785
8786  // Note that we have added this copy-assignment operator.
8787  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8788
8789  if (Scope *S = getScopeForContext(ClassDecl))
8790    PushOnScopeChains(CopyAssignment, S, false);
8791  ClassDecl->addDecl(CopyAssignment);
8792
8793  return CopyAssignment;
8794}
8795
8796void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8797                                        CXXMethodDecl *CopyAssignOperator) {
8798  assert((CopyAssignOperator->isDefaulted() &&
8799          CopyAssignOperator->isOverloadedOperator() &&
8800          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
8801          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8802          !CopyAssignOperator->isDeleted()) &&
8803         "DefineImplicitCopyAssignment called for wrong function");
8804
8805  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8806
8807  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8808    CopyAssignOperator->setInvalidDecl();
8809    return;
8810  }
8811
8812  CopyAssignOperator->setUsed();
8813
8814  SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
8815  DiagnosticErrorTrap Trap(Diags);
8816
8817  // C++0x [class.copy]p30:
8818  //   The implicitly-defined or explicitly-defaulted copy assignment operator
8819  //   for a non-union class X performs memberwise copy assignment of its
8820  //   subobjects. The direct base classes of X are assigned first, in the
8821  //   order of their declaration in the base-specifier-list, and then the
8822  //   immediate non-static data members of X are assigned, in the order in
8823  //   which they were declared in the class definition.
8824
8825  // The statements that form the synthesized function body.
8826  SmallVector<Stmt*, 8> Statements;
8827
8828  // The parameter for the "other" object, which we are copying from.
8829  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8830  Qualifiers OtherQuals = Other->getType().getQualifiers();
8831  QualType OtherRefType = Other->getType();
8832  if (const LValueReferenceType *OtherRef
8833                                = OtherRefType->getAs<LValueReferenceType>()) {
8834    OtherRefType = OtherRef->getPointeeType();
8835    OtherQuals = OtherRefType.getQualifiers();
8836  }
8837
8838  // Our location for everything implicitly-generated.
8839  SourceLocation Loc = CopyAssignOperator->getLocation();
8840
8841  // Construct a reference to the "other" object. We'll be using this
8842  // throughout the generated ASTs.
8843  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8844  assert(OtherRef && "Reference to parameter cannot fail!");
8845
8846  // Construct the "this" pointer. We'll be using this throughout the generated
8847  // ASTs.
8848  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8849  assert(This && "Reference to this cannot fail!");
8850
8851  // Assign base classes.
8852  bool Invalid = false;
8853  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8854       E = ClassDecl->bases_end(); Base != E; ++Base) {
8855    // Form the assignment:
8856    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8857    QualType BaseType = Base->getType().getUnqualifiedType();
8858    if (!BaseType->isRecordType()) {
8859      Invalid = true;
8860      continue;
8861    }
8862
8863    CXXCastPath BasePath;
8864    BasePath.push_back(Base);
8865
8866    // Construct the "from" expression, which is an implicit cast to the
8867    // appropriately-qualified base type.
8868    Expr *From = OtherRef;
8869    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8870                             CK_UncheckedDerivedToBase,
8871                             VK_LValue, &BasePath).take();
8872
8873    // Dereference "this".
8874    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8875
8876    // Implicitly cast "this" to the appropriately-qualified base type.
8877    To = ImpCastExprToType(To.take(),
8878                           Context.getCVRQualifiedType(BaseType,
8879                                     CopyAssignOperator->getTypeQualifiers()),
8880                           CK_UncheckedDerivedToBase,
8881                           VK_LValue, &BasePath);
8882
8883    // Build the copy.
8884    StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
8885                                            To.get(), From,
8886                                            /*CopyingBaseSubobject=*/true,
8887                                            /*Copying=*/true);
8888    if (Copy.isInvalid()) {
8889      Diag(CurrentLocation, diag::note_member_synthesized_at)
8890        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8891      CopyAssignOperator->setInvalidDecl();
8892      return;
8893    }
8894
8895    // Success! Record the copy.
8896    Statements.push_back(Copy.takeAs<Expr>());
8897  }
8898
8899  // Assign non-static members.
8900  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8901                                  FieldEnd = ClassDecl->field_end();
8902       Field != FieldEnd; ++Field) {
8903    if (Field->isUnnamedBitfield())
8904      continue;
8905
8906    // Check for members of reference type; we can't copy those.
8907    if (Field->getType()->isReferenceType()) {
8908      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8909        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8910      Diag(Field->getLocation(), diag::note_declared_at);
8911      Diag(CurrentLocation, diag::note_member_synthesized_at)
8912        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8913      Invalid = true;
8914      continue;
8915    }
8916
8917    // Check for members of const-qualified, non-class type.
8918    QualType BaseType = Context.getBaseElementType(Field->getType());
8919    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8920      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8921        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8922      Diag(Field->getLocation(), diag::note_declared_at);
8923      Diag(CurrentLocation, diag::note_member_synthesized_at)
8924        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8925      Invalid = true;
8926      continue;
8927    }
8928
8929    // Suppress assigning zero-width bitfields.
8930    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8931      continue;
8932
8933    QualType FieldType = Field->getType().getNonReferenceType();
8934    if (FieldType->isIncompleteArrayType()) {
8935      assert(ClassDecl->hasFlexibleArrayMember() &&
8936             "Incomplete array type is not valid");
8937      continue;
8938    }
8939
8940    // Build references to the field in the object we're copying from and to.
8941    CXXScopeSpec SS; // Intentionally empty
8942    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8943                              LookupMemberName);
8944    MemberLookup.addDecl(*Field);
8945    MemberLookup.resolveKind();
8946    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8947                                               Loc, /*IsArrow=*/false,
8948                                               SS, SourceLocation(), 0,
8949                                               MemberLookup, 0);
8950    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8951                                             Loc, /*IsArrow=*/true,
8952                                             SS, SourceLocation(), 0,
8953                                             MemberLookup, 0);
8954    assert(!From.isInvalid() && "Implicit field reference cannot fail");
8955    assert(!To.isInvalid() && "Implicit field reference cannot fail");
8956
8957    // Build the copy of this field.
8958    StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
8959                                            To.get(), From.get(),
8960                                            /*CopyingBaseSubobject=*/false,
8961                                            /*Copying=*/true);
8962    if (Copy.isInvalid()) {
8963      Diag(CurrentLocation, diag::note_member_synthesized_at)
8964        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8965      CopyAssignOperator->setInvalidDecl();
8966      return;
8967    }
8968
8969    // Success! Record the copy.
8970    Statements.push_back(Copy.takeAs<Stmt>());
8971  }
8972
8973  if (!Invalid) {
8974    // Add a "return *this;"
8975    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8976
8977    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8978    if (Return.isInvalid())
8979      Invalid = true;
8980    else {
8981      Statements.push_back(Return.takeAs<Stmt>());
8982
8983      if (Trap.hasErrorOccurred()) {
8984        Diag(CurrentLocation, diag::note_member_synthesized_at)
8985          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8986        Invalid = true;
8987      }
8988    }
8989  }
8990
8991  if (Invalid) {
8992    CopyAssignOperator->setInvalidDecl();
8993    return;
8994  }
8995
8996  StmtResult Body;
8997  {
8998    CompoundScopeRAII CompoundScope(*this);
8999    Body = ActOnCompoundStmt(Loc, Loc, Statements,
9000                             /*isStmtExpr=*/false);
9001    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9002  }
9003  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
9004
9005  if (ASTMutationListener *L = getASTMutationListener()) {
9006    L->CompletedImplicitDefinition(CopyAssignOperator);
9007  }
9008}
9009
9010Sema::ImplicitExceptionSpecification
9011Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9012  CXXRecordDecl *ClassDecl = MD->getParent();
9013
9014  ImplicitExceptionSpecification ExceptSpec(*this);
9015  if (ClassDecl->isInvalidDecl())
9016    return ExceptSpec;
9017
9018  // C++0x [except.spec]p14:
9019  //   An implicitly declared special member function (Clause 12) shall have an
9020  //   exception-specification. [...]
9021
9022  // It is unspecified whether or not an implicit move assignment operator
9023  // attempts to deduplicate calls to assignment operators of virtual bases are
9024  // made. As such, this exception specification is effectively unspecified.
9025  // Based on a similar decision made for constness in C++0x, we're erring on
9026  // the side of assuming such calls to be made regardless of whether they
9027  // actually happen.
9028  // Note that a move constructor is not implicitly declared when there are
9029  // virtual bases, but it can still be user-declared and explicitly defaulted.
9030  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9031                                       BaseEnd = ClassDecl->bases_end();
9032       Base != BaseEnd; ++Base) {
9033    if (Base->isVirtual())
9034      continue;
9035
9036    CXXRecordDecl *BaseClassDecl
9037      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9038    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9039                                                           0, false, 0))
9040      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9041  }
9042
9043  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9044                                       BaseEnd = ClassDecl->vbases_end();
9045       Base != BaseEnd; ++Base) {
9046    CXXRecordDecl *BaseClassDecl
9047      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9048    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9049                                                           0, false, 0))
9050      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9051  }
9052
9053  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9054                                  FieldEnd = ClassDecl->field_end();
9055       Field != FieldEnd;
9056       ++Field) {
9057    QualType FieldType = Context.getBaseElementType(Field->getType());
9058    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9059      if (CXXMethodDecl *MoveAssign =
9060              LookupMovingAssignment(FieldClassDecl,
9061                                     FieldType.getCVRQualifiers(),
9062                                     false, 0))
9063        ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
9064    }
9065  }
9066
9067  return ExceptSpec;
9068}
9069
9070/// Determine whether the class type has any direct or indirect virtual base
9071/// classes which have a non-trivial move assignment operator.
9072static bool
9073hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9074  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9075                                          BaseEnd = ClassDecl->vbases_end();
9076       Base != BaseEnd; ++Base) {
9077    CXXRecordDecl *BaseClass =
9078        cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9079
9080    // Try to declare the move assignment. If it would be deleted, then the
9081    // class does not have a non-trivial move assignment.
9082    if (BaseClass->needsImplicitMoveAssignment())
9083      S.DeclareImplicitMoveAssignment(BaseClass);
9084
9085    if (BaseClass->hasNonTrivialMoveAssignment())
9086      return true;
9087  }
9088
9089  return false;
9090}
9091
9092/// Determine whether the given type either has a move constructor or is
9093/// trivially copyable.
9094static bool
9095hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9096  Type = S.Context.getBaseElementType(Type);
9097
9098  // FIXME: Technically, non-trivially-copyable non-class types, such as
9099  // reference types, are supposed to return false here, but that appears
9100  // to be a standard defect.
9101  CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
9102  if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
9103    return true;
9104
9105  if (Type.isTriviallyCopyableType(S.Context))
9106    return true;
9107
9108  if (IsConstructor) {
9109    // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9110    // give the right answer.
9111    if (ClassDecl->needsImplicitMoveConstructor())
9112      S.DeclareImplicitMoveConstructor(ClassDecl);
9113    return ClassDecl->hasMoveConstructor();
9114  }
9115
9116  // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9117  // give the right answer.
9118  if (ClassDecl->needsImplicitMoveAssignment())
9119    S.DeclareImplicitMoveAssignment(ClassDecl);
9120  return ClassDecl->hasMoveAssignment();
9121}
9122
9123/// Determine whether all non-static data members and direct or virtual bases
9124/// of class \p ClassDecl have either a move operation, or are trivially
9125/// copyable.
9126static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9127                                            bool IsConstructor) {
9128  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9129                                          BaseEnd = ClassDecl->bases_end();
9130       Base != BaseEnd; ++Base) {
9131    if (Base->isVirtual())
9132      continue;
9133
9134    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9135      return false;
9136  }
9137
9138  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9139                                          BaseEnd = ClassDecl->vbases_end();
9140       Base != BaseEnd; ++Base) {
9141    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9142      return false;
9143  }
9144
9145  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9146                                     FieldEnd = ClassDecl->field_end();
9147       Field != FieldEnd; ++Field) {
9148    if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
9149      return false;
9150  }
9151
9152  return true;
9153}
9154
9155CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9156  // C++11 [class.copy]p20:
9157  //   If the definition of a class X does not explicitly declare a move
9158  //   assignment operator, one will be implicitly declared as defaulted
9159  //   if and only if:
9160  //
9161  //   - [first 4 bullets]
9162  assert(ClassDecl->needsImplicitMoveAssignment());
9163
9164  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9165  if (DSM.isAlreadyBeingDeclared())
9166    return 0;
9167
9168  // [Checked after we build the declaration]
9169  //   - the move assignment operator would not be implicitly defined as
9170  //     deleted,
9171
9172  // [DR1402]:
9173  //   - X has no direct or indirect virtual base class with a non-trivial
9174  //     move assignment operator, and
9175  //   - each of X's non-static data members and direct or virtual base classes
9176  //     has a type that either has a move assignment operator or is trivially
9177  //     copyable.
9178  if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9179      !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9180    ClassDecl->setFailedImplicitMoveAssignment();
9181    return 0;
9182  }
9183
9184  // Note: The following rules are largely analoguous to the move
9185  // constructor rules.
9186
9187  QualType ArgType = Context.getTypeDeclType(ClassDecl);
9188  QualType RetType = Context.getLValueReferenceType(ArgType);
9189  ArgType = Context.getRValueReferenceType(ArgType);
9190
9191  //   An implicitly-declared move assignment operator is an inline public
9192  //   member of its class.
9193  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9194  SourceLocation ClassLoc = ClassDecl->getLocation();
9195  DeclarationNameInfo NameInfo(Name, ClassLoc);
9196  CXXMethodDecl *MoveAssignment
9197    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9198                            /*TInfo=*/0,
9199                            /*StorageClass=*/SC_None,
9200                            /*isInline=*/true,
9201                            /*isConstexpr=*/false,
9202                            SourceLocation());
9203  MoveAssignment->setAccess(AS_public);
9204  MoveAssignment->setDefaulted();
9205  MoveAssignment->setImplicit();
9206
9207  // Build an exception specification pointing back at this member.
9208  FunctionProtoType::ExtProtoInfo EPI;
9209  EPI.ExceptionSpecType = EST_Unevaluated;
9210  EPI.ExceptionSpecDecl = MoveAssignment;
9211  MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9212
9213  // Add the parameter to the operator.
9214  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9215                                               ClassLoc, ClassLoc, /*Id=*/0,
9216                                               ArgType, /*TInfo=*/0,
9217                                               SC_None, 0);
9218  MoveAssignment->setParams(FromParam);
9219
9220  AddOverriddenMethods(ClassDecl, MoveAssignment);
9221
9222  MoveAssignment->setTrivial(
9223    ClassDecl->needsOverloadResolutionForMoveAssignment()
9224      ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9225      : ClassDecl->hasTrivialMoveAssignment());
9226
9227  // C++0x [class.copy]p9:
9228  //   If the definition of a class X does not explicitly declare a move
9229  //   assignment operator, one will be implicitly declared as defaulted if and
9230  //   only if:
9231  //   [...]
9232  //   - the move assignment operator would not be implicitly defined as
9233  //     deleted.
9234  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
9235    // Cache this result so that we don't try to generate this over and over
9236    // on every lookup, leaking memory and wasting time.
9237    ClassDecl->setFailedImplicitMoveAssignment();
9238    return 0;
9239  }
9240
9241  // Note that we have added this copy-assignment operator.
9242  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9243
9244  if (Scope *S = getScopeForContext(ClassDecl))
9245    PushOnScopeChains(MoveAssignment, S, false);
9246  ClassDecl->addDecl(MoveAssignment);
9247
9248  return MoveAssignment;
9249}
9250
9251void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9252                                        CXXMethodDecl *MoveAssignOperator) {
9253  assert((MoveAssignOperator->isDefaulted() &&
9254          MoveAssignOperator->isOverloadedOperator() &&
9255          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
9256          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9257          !MoveAssignOperator->isDeleted()) &&
9258         "DefineImplicitMoveAssignment called for wrong function");
9259
9260  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9261
9262  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9263    MoveAssignOperator->setInvalidDecl();
9264    return;
9265  }
9266
9267  MoveAssignOperator->setUsed();
9268
9269  SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
9270  DiagnosticErrorTrap Trap(Diags);
9271
9272  // C++0x [class.copy]p28:
9273  //   The implicitly-defined or move assignment operator for a non-union class
9274  //   X performs memberwise move assignment of its subobjects. The direct base
9275  //   classes of X are assigned first, in the order of their declaration in the
9276  //   base-specifier-list, and then the immediate non-static data members of X
9277  //   are assigned, in the order in which they were declared in the class
9278  //   definition.
9279
9280  // The statements that form the synthesized function body.
9281  SmallVector<Stmt*, 8> Statements;
9282
9283  // The parameter for the "other" object, which we are move from.
9284  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9285  QualType OtherRefType = Other->getType()->
9286      getAs<RValueReferenceType>()->getPointeeType();
9287  assert(OtherRefType.getQualifiers() == 0 &&
9288         "Bad argument type of defaulted move assignment");
9289
9290  // Our location for everything implicitly-generated.
9291  SourceLocation Loc = MoveAssignOperator->getLocation();
9292
9293  // Construct a reference to the "other" object. We'll be using this
9294  // throughout the generated ASTs.
9295  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9296  assert(OtherRef && "Reference to parameter cannot fail!");
9297  // Cast to rvalue.
9298  OtherRef = CastForMoving(*this, OtherRef);
9299
9300  // Construct the "this" pointer. We'll be using this throughout the generated
9301  // ASTs.
9302  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9303  assert(This && "Reference to this cannot fail!");
9304
9305  // Assign base classes.
9306  bool Invalid = false;
9307  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9308       E = ClassDecl->bases_end(); Base != E; ++Base) {
9309    // Form the assignment:
9310    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9311    QualType BaseType = Base->getType().getUnqualifiedType();
9312    if (!BaseType->isRecordType()) {
9313      Invalid = true;
9314      continue;
9315    }
9316
9317    CXXCastPath BasePath;
9318    BasePath.push_back(Base);
9319
9320    // Construct the "from" expression, which is an implicit cast to the
9321    // appropriately-qualified base type.
9322    Expr *From = OtherRef;
9323    From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
9324                             VK_XValue, &BasePath).take();
9325
9326    // Dereference "this".
9327    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9328
9329    // Implicitly cast "this" to the appropriately-qualified base type.
9330    To = ImpCastExprToType(To.take(),
9331                           Context.getCVRQualifiedType(BaseType,
9332                                     MoveAssignOperator->getTypeQualifiers()),
9333                           CK_UncheckedDerivedToBase,
9334                           VK_LValue, &BasePath);
9335
9336    // Build the move.
9337    StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
9338                                            To.get(), From,
9339                                            /*CopyingBaseSubobject=*/true,
9340                                            /*Copying=*/false);
9341    if (Move.isInvalid()) {
9342      Diag(CurrentLocation, diag::note_member_synthesized_at)
9343        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9344      MoveAssignOperator->setInvalidDecl();
9345      return;
9346    }
9347
9348    // Success! Record the move.
9349    Statements.push_back(Move.takeAs<Expr>());
9350  }
9351
9352  // Assign non-static members.
9353  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9354                                  FieldEnd = ClassDecl->field_end();
9355       Field != FieldEnd; ++Field) {
9356    if (Field->isUnnamedBitfield())
9357      continue;
9358
9359    // Check for members of reference type; we can't move those.
9360    if (Field->getType()->isReferenceType()) {
9361      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9362        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9363      Diag(Field->getLocation(), diag::note_declared_at);
9364      Diag(CurrentLocation, diag::note_member_synthesized_at)
9365        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9366      Invalid = true;
9367      continue;
9368    }
9369
9370    // Check for members of const-qualified, non-class type.
9371    QualType BaseType = Context.getBaseElementType(Field->getType());
9372    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9373      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9374        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9375      Diag(Field->getLocation(), diag::note_declared_at);
9376      Diag(CurrentLocation, diag::note_member_synthesized_at)
9377        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9378      Invalid = true;
9379      continue;
9380    }
9381
9382    // Suppress assigning zero-width bitfields.
9383    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9384      continue;
9385
9386    QualType FieldType = Field->getType().getNonReferenceType();
9387    if (FieldType->isIncompleteArrayType()) {
9388      assert(ClassDecl->hasFlexibleArrayMember() &&
9389             "Incomplete array type is not valid");
9390      continue;
9391    }
9392
9393    // Build references to the field in the object we're copying from and to.
9394    CXXScopeSpec SS; // Intentionally empty
9395    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9396                              LookupMemberName);
9397    MemberLookup.addDecl(*Field);
9398    MemberLookup.resolveKind();
9399    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9400                                               Loc, /*IsArrow=*/false,
9401                                               SS, SourceLocation(), 0,
9402                                               MemberLookup, 0);
9403    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9404                                             Loc, /*IsArrow=*/true,
9405                                             SS, SourceLocation(), 0,
9406                                             MemberLookup, 0);
9407    assert(!From.isInvalid() && "Implicit field reference cannot fail");
9408    assert(!To.isInvalid() && "Implicit field reference cannot fail");
9409
9410    assert(!From.get()->isLValue() && // could be xvalue or prvalue
9411        "Member reference with rvalue base must be rvalue except for reference "
9412        "members, which aren't allowed for move assignment.");
9413
9414    // Build the move of this field.
9415    StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
9416                                            To.get(), From.get(),
9417                                            /*CopyingBaseSubobject=*/false,
9418                                            /*Copying=*/false);
9419    if (Move.isInvalid()) {
9420      Diag(CurrentLocation, diag::note_member_synthesized_at)
9421        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9422      MoveAssignOperator->setInvalidDecl();
9423      return;
9424    }
9425
9426    // Success! Record the copy.
9427    Statements.push_back(Move.takeAs<Stmt>());
9428  }
9429
9430  if (!Invalid) {
9431    // Add a "return *this;"
9432    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9433
9434    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9435    if (Return.isInvalid())
9436      Invalid = true;
9437    else {
9438      Statements.push_back(Return.takeAs<Stmt>());
9439
9440      if (Trap.hasErrorOccurred()) {
9441        Diag(CurrentLocation, diag::note_member_synthesized_at)
9442          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9443        Invalid = true;
9444      }
9445    }
9446  }
9447
9448  if (Invalid) {
9449    MoveAssignOperator->setInvalidDecl();
9450    return;
9451  }
9452
9453  StmtResult Body;
9454  {
9455    CompoundScopeRAII CompoundScope(*this);
9456    Body = ActOnCompoundStmt(Loc, Loc, Statements,
9457                             /*isStmtExpr=*/false);
9458    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9459  }
9460  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9461
9462  if (ASTMutationListener *L = getASTMutationListener()) {
9463    L->CompletedImplicitDefinition(MoveAssignOperator);
9464  }
9465}
9466
9467Sema::ImplicitExceptionSpecification
9468Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9469  CXXRecordDecl *ClassDecl = MD->getParent();
9470
9471  ImplicitExceptionSpecification ExceptSpec(*this);
9472  if (ClassDecl->isInvalidDecl())
9473    return ExceptSpec;
9474
9475  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9476  assert(T->getNumArgs() >= 1 && "not a copy ctor");
9477  unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9478
9479  // C++ [except.spec]p14:
9480  //   An implicitly declared special member function (Clause 12) shall have an
9481  //   exception-specification. [...]
9482  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9483                                       BaseEnd = ClassDecl->bases_end();
9484       Base != BaseEnd;
9485       ++Base) {
9486    // Virtual bases are handled below.
9487    if (Base->isVirtual())
9488      continue;
9489
9490    CXXRecordDecl *BaseClassDecl
9491      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9492    if (CXXConstructorDecl *CopyConstructor =
9493          LookupCopyingConstructor(BaseClassDecl, Quals))
9494      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9495  }
9496  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9497                                       BaseEnd = ClassDecl->vbases_end();
9498       Base != BaseEnd;
9499       ++Base) {
9500    CXXRecordDecl *BaseClassDecl
9501      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9502    if (CXXConstructorDecl *CopyConstructor =
9503          LookupCopyingConstructor(BaseClassDecl, Quals))
9504      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9505  }
9506  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9507                                  FieldEnd = ClassDecl->field_end();
9508       Field != FieldEnd;
9509       ++Field) {
9510    QualType FieldType = Context.getBaseElementType(Field->getType());
9511    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9512      if (CXXConstructorDecl *CopyConstructor =
9513              LookupCopyingConstructor(FieldClassDecl,
9514                                       Quals | FieldType.getCVRQualifiers()))
9515      ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
9516    }
9517  }
9518
9519  return ExceptSpec;
9520}
9521
9522CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9523                                                    CXXRecordDecl *ClassDecl) {
9524  // C++ [class.copy]p4:
9525  //   If the class definition does not explicitly declare a copy
9526  //   constructor, one is declared implicitly.
9527  assert(ClassDecl->needsImplicitCopyConstructor());
9528
9529  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9530  if (DSM.isAlreadyBeingDeclared())
9531    return 0;
9532
9533  QualType ClassType = Context.getTypeDeclType(ClassDecl);
9534  QualType ArgType = ClassType;
9535  bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
9536  if (Const)
9537    ArgType = ArgType.withConst();
9538  ArgType = Context.getLValueReferenceType(ArgType);
9539
9540  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9541                                                     CXXCopyConstructor,
9542                                                     Const);
9543
9544  DeclarationName Name
9545    = Context.DeclarationNames.getCXXConstructorName(
9546                                           Context.getCanonicalType(ClassType));
9547  SourceLocation ClassLoc = ClassDecl->getLocation();
9548  DeclarationNameInfo NameInfo(Name, ClassLoc);
9549
9550  //   An implicitly-declared copy constructor is an inline public
9551  //   member of its class.
9552  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
9553      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9554      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9555      Constexpr);
9556  CopyConstructor->setAccess(AS_public);
9557  CopyConstructor->setDefaulted();
9558
9559  // Build an exception specification pointing back at this member.
9560  FunctionProtoType::ExtProtoInfo EPI;
9561  EPI.ExceptionSpecType = EST_Unevaluated;
9562  EPI.ExceptionSpecDecl = CopyConstructor;
9563  CopyConstructor->setType(
9564      Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9565
9566  // Add the parameter to the constructor.
9567  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
9568                                               ClassLoc, ClassLoc,
9569                                               /*IdentifierInfo=*/0,
9570                                               ArgType, /*TInfo=*/0,
9571                                               SC_None, 0);
9572  CopyConstructor->setParams(FromParam);
9573
9574  CopyConstructor->setTrivial(
9575    ClassDecl->needsOverloadResolutionForCopyConstructor()
9576      ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9577      : ClassDecl->hasTrivialCopyConstructor());
9578
9579  // C++11 [class.copy]p8:
9580  //   ... If the class definition does not explicitly declare a copy
9581  //   constructor, there is no user-declared move constructor, and there is no
9582  //   user-declared move assignment operator, a copy constructor is implicitly
9583  //   declared as defaulted.
9584  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
9585    SetDeclDeleted(CopyConstructor, ClassLoc);
9586
9587  // Note that we have declared this constructor.
9588  ++ASTContext::NumImplicitCopyConstructorsDeclared;
9589
9590  if (Scope *S = getScopeForContext(ClassDecl))
9591    PushOnScopeChains(CopyConstructor, S, false);
9592  ClassDecl->addDecl(CopyConstructor);
9593
9594  return CopyConstructor;
9595}
9596
9597void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
9598                                   CXXConstructorDecl *CopyConstructor) {
9599  assert((CopyConstructor->isDefaulted() &&
9600          CopyConstructor->isCopyConstructor() &&
9601          !CopyConstructor->doesThisDeclarationHaveABody() &&
9602          !CopyConstructor->isDeleted()) &&
9603         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
9604
9605  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
9606  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
9607
9608  SynthesizedFunctionScope Scope(*this, CopyConstructor);
9609  DiagnosticErrorTrap Trap(Diags);
9610
9611  if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
9612      Trap.hasErrorOccurred()) {
9613    Diag(CurrentLocation, diag::note_member_synthesized_at)
9614      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
9615    CopyConstructor->setInvalidDecl();
9616  }  else {
9617    Sema::CompoundScopeRAII CompoundScope(*this);
9618    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9619                                               CopyConstructor->getLocation(),
9620                                               MultiStmtArg(),
9621                                               /*isStmtExpr=*/false)
9622                                                              .takeAs<Stmt>());
9623    CopyConstructor->setImplicitlyDefined(true);
9624  }
9625
9626  CopyConstructor->setUsed();
9627  if (ASTMutationListener *L = getASTMutationListener()) {
9628    L->CompletedImplicitDefinition(CopyConstructor);
9629  }
9630}
9631
9632Sema::ImplicitExceptionSpecification
9633Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9634  CXXRecordDecl *ClassDecl = MD->getParent();
9635
9636  // C++ [except.spec]p14:
9637  //   An implicitly declared special member function (Clause 12) shall have an
9638  //   exception-specification. [...]
9639  ImplicitExceptionSpecification ExceptSpec(*this);
9640  if (ClassDecl->isInvalidDecl())
9641    return ExceptSpec;
9642
9643  // Direct base-class constructors.
9644  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9645                                       BEnd = ClassDecl->bases_end();
9646       B != BEnd; ++B) {
9647    if (B->isVirtual()) // Handled below.
9648      continue;
9649
9650    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9651      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9652      CXXConstructorDecl *Constructor =
9653          LookupMovingConstructor(BaseClassDecl, 0);
9654      // If this is a deleted function, add it anyway. This might be conformant
9655      // with the standard. This might not. I'm not sure. It might not matter.
9656      if (Constructor)
9657        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9658    }
9659  }
9660
9661  // Virtual base-class constructors.
9662  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9663                                       BEnd = ClassDecl->vbases_end();
9664       B != BEnd; ++B) {
9665    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9666      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9667      CXXConstructorDecl *Constructor =
9668          LookupMovingConstructor(BaseClassDecl, 0);
9669      // If this is a deleted function, add it anyway. This might be conformant
9670      // with the standard. This might not. I'm not sure. It might not matter.
9671      if (Constructor)
9672        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9673    }
9674  }
9675
9676  // Field constructors.
9677  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9678                               FEnd = ClassDecl->field_end();
9679       F != FEnd; ++F) {
9680    QualType FieldType = Context.getBaseElementType(F->getType());
9681    if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9682      CXXConstructorDecl *Constructor =
9683          LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
9684      // If this is a deleted function, add it anyway. This might be conformant
9685      // with the standard. This might not. I'm not sure. It might not matter.
9686      // In particular, the problem is that this function never gets called. It
9687      // might just be ill-formed because this function attempts to refer to
9688      // a deleted function here.
9689      if (Constructor)
9690        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9691    }
9692  }
9693
9694  return ExceptSpec;
9695}
9696
9697CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9698                                                    CXXRecordDecl *ClassDecl) {
9699  // C++11 [class.copy]p9:
9700  //   If the definition of a class X does not explicitly declare a move
9701  //   constructor, one will be implicitly declared as defaulted if and only if:
9702  //
9703  //   - [first 4 bullets]
9704  assert(ClassDecl->needsImplicitMoveConstructor());
9705
9706  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9707  if (DSM.isAlreadyBeingDeclared())
9708    return 0;
9709
9710  // [Checked after we build the declaration]
9711  //   - the move assignment operator would not be implicitly defined as
9712  //     deleted,
9713
9714  // [DR1402]:
9715  //   - each of X's non-static data members and direct or virtual base classes
9716  //     has a type that either has a move constructor or is trivially copyable.
9717  if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9718    ClassDecl->setFailedImplicitMoveConstructor();
9719    return 0;
9720  }
9721
9722  QualType ClassType = Context.getTypeDeclType(ClassDecl);
9723  QualType ArgType = Context.getRValueReferenceType(ClassType);
9724
9725  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9726                                                     CXXMoveConstructor,
9727                                                     false);
9728
9729  DeclarationName Name
9730    = Context.DeclarationNames.getCXXConstructorName(
9731                                           Context.getCanonicalType(ClassType));
9732  SourceLocation ClassLoc = ClassDecl->getLocation();
9733  DeclarationNameInfo NameInfo(Name, ClassLoc);
9734
9735  // C++0x [class.copy]p11:
9736  //   An implicitly-declared copy/move constructor is an inline public
9737  //   member of its class.
9738  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
9739      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9740      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9741      Constexpr);
9742  MoveConstructor->setAccess(AS_public);
9743  MoveConstructor->setDefaulted();
9744
9745  // Build an exception specification pointing back at this member.
9746  FunctionProtoType::ExtProtoInfo EPI;
9747  EPI.ExceptionSpecType = EST_Unevaluated;
9748  EPI.ExceptionSpecDecl = MoveConstructor;
9749  MoveConstructor->setType(
9750      Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9751
9752  // Add the parameter to the constructor.
9753  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9754                                               ClassLoc, ClassLoc,
9755                                               /*IdentifierInfo=*/0,
9756                                               ArgType, /*TInfo=*/0,
9757                                               SC_None, 0);
9758  MoveConstructor->setParams(FromParam);
9759
9760  MoveConstructor->setTrivial(
9761    ClassDecl->needsOverloadResolutionForMoveConstructor()
9762      ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9763      : ClassDecl->hasTrivialMoveConstructor());
9764
9765  // C++0x [class.copy]p9:
9766  //   If the definition of a class X does not explicitly declare a move
9767  //   constructor, one will be implicitly declared as defaulted if and only if:
9768  //   [...]
9769  //   - the move constructor would not be implicitly defined as deleted.
9770  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
9771    // Cache this result so that we don't try to generate this over and over
9772    // on every lookup, leaking memory and wasting time.
9773    ClassDecl->setFailedImplicitMoveConstructor();
9774    return 0;
9775  }
9776
9777  // Note that we have declared this constructor.
9778  ++ASTContext::NumImplicitMoveConstructorsDeclared;
9779
9780  if (Scope *S = getScopeForContext(ClassDecl))
9781    PushOnScopeChains(MoveConstructor, S, false);
9782  ClassDecl->addDecl(MoveConstructor);
9783
9784  return MoveConstructor;
9785}
9786
9787void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9788                                   CXXConstructorDecl *MoveConstructor) {
9789  assert((MoveConstructor->isDefaulted() &&
9790          MoveConstructor->isMoveConstructor() &&
9791          !MoveConstructor->doesThisDeclarationHaveABody() &&
9792          !MoveConstructor->isDeleted()) &&
9793         "DefineImplicitMoveConstructor - call it for implicit move ctor");
9794
9795  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9796  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9797
9798  SynthesizedFunctionScope Scope(*this, MoveConstructor);
9799  DiagnosticErrorTrap Trap(Diags);
9800
9801  if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
9802      Trap.hasErrorOccurred()) {
9803    Diag(CurrentLocation, diag::note_member_synthesized_at)
9804      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9805    MoveConstructor->setInvalidDecl();
9806  }  else {
9807    Sema::CompoundScopeRAII CompoundScope(*this);
9808    MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9809                                               MoveConstructor->getLocation(),
9810                                               MultiStmtArg(),
9811                                               /*isStmtExpr=*/false)
9812                                                              .takeAs<Stmt>());
9813    MoveConstructor->setImplicitlyDefined(true);
9814  }
9815
9816  MoveConstructor->setUsed();
9817
9818  if (ASTMutationListener *L = getASTMutationListener()) {
9819    L->CompletedImplicitDefinition(MoveConstructor);
9820  }
9821}
9822
9823bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9824  return FD->isDeleted() &&
9825         (FD->isDefaulted() || FD->isImplicit()) &&
9826         isa<CXXMethodDecl>(FD);
9827}
9828
9829/// \brief Mark the call operator of the given lambda closure type as "used".
9830static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9831  CXXMethodDecl *CallOperator
9832    = cast<CXXMethodDecl>(
9833        Lambda->lookup(
9834          S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
9835  CallOperator->setReferenced();
9836  CallOperator->setUsed();
9837}
9838
9839void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9840       SourceLocation CurrentLocation,
9841       CXXConversionDecl *Conv)
9842{
9843  CXXRecordDecl *Lambda = Conv->getParent();
9844
9845  // Make sure that the lambda call operator is marked used.
9846  markLambdaCallOperatorUsed(*this, Lambda);
9847
9848  Conv->setUsed();
9849
9850  SynthesizedFunctionScope Scope(*this, Conv);
9851  DiagnosticErrorTrap Trap(Diags);
9852
9853  // Return the address of the __invoke function.
9854  DeclarationName InvokeName = &Context.Idents.get("__invoke");
9855  CXXMethodDecl *Invoke
9856    = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
9857  Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9858                                       VK_LValue, Conv->getLocation()).take();
9859  assert(FunctionRef && "Can't refer to __invoke function?");
9860  Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
9861  Conv->setBody(new (Context) CompoundStmt(Context, Return,
9862                                           Conv->getLocation(),
9863                                           Conv->getLocation()));
9864
9865  // Fill in the __invoke function with a dummy implementation. IR generation
9866  // will fill in the actual details.
9867  Invoke->setUsed();
9868  Invoke->setReferenced();
9869  Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
9870
9871  if (ASTMutationListener *L = getASTMutationListener()) {
9872    L->CompletedImplicitDefinition(Conv);
9873    L->CompletedImplicitDefinition(Invoke);
9874  }
9875}
9876
9877void Sema::DefineImplicitLambdaToBlockPointerConversion(
9878       SourceLocation CurrentLocation,
9879       CXXConversionDecl *Conv)
9880{
9881  Conv->setUsed();
9882
9883  SynthesizedFunctionScope Scope(*this, Conv);
9884  DiagnosticErrorTrap Trap(Diags);
9885
9886  // Copy-initialize the lambda object as needed to capture it.
9887  Expr *This = ActOnCXXThis(CurrentLocation).take();
9888  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
9889
9890  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9891                                                        Conv->getLocation(),
9892                                                        Conv, DerefThis);
9893
9894  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9895  // behavior.  Note that only the general conversion function does this
9896  // (since it's unusable otherwise); in the case where we inline the
9897  // block literal, it has block literal lifetime semantics.
9898  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
9899    BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9900                                          CK_CopyAndAutoreleaseBlockObject,
9901                                          BuildBlock.get(), 0, VK_RValue);
9902
9903  if (BuildBlock.isInvalid()) {
9904    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9905    Conv->setInvalidDecl();
9906    return;
9907  }
9908
9909  // Create the return statement that returns the block from the conversion
9910  // function.
9911  StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
9912  if (Return.isInvalid()) {
9913    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9914    Conv->setInvalidDecl();
9915    return;
9916  }
9917
9918  // Set the body of the conversion function.
9919  Stmt *ReturnS = Return.take();
9920  Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
9921                                           Conv->getLocation(),
9922                                           Conv->getLocation()));
9923
9924  // We're done; notify the mutation listener, if any.
9925  if (ASTMutationListener *L = getASTMutationListener()) {
9926    L->CompletedImplicitDefinition(Conv);
9927  }
9928}
9929
9930/// \brief Determine whether the given list arguments contains exactly one
9931/// "real" (non-default) argument.
9932static bool hasOneRealArgument(MultiExprArg Args) {
9933  switch (Args.size()) {
9934  case 0:
9935    return false;
9936
9937  default:
9938    if (!Args[1]->isDefaultArgument())
9939      return false;
9940
9941    // fall through
9942  case 1:
9943    return !Args[0]->isDefaultArgument();
9944  }
9945
9946  return false;
9947}
9948
9949ExprResult
9950Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9951                            CXXConstructorDecl *Constructor,
9952                            MultiExprArg ExprArgs,
9953                            bool HadMultipleCandidates,
9954                            bool IsListInitialization,
9955                            bool RequiresZeroInit,
9956                            unsigned ConstructKind,
9957                            SourceRange ParenRange) {
9958  bool Elidable = false;
9959
9960  // C++0x [class.copy]p34:
9961  //   When certain criteria are met, an implementation is allowed to
9962  //   omit the copy/move construction of a class object, even if the
9963  //   copy/move constructor and/or destructor for the object have
9964  //   side effects. [...]
9965  //     - when a temporary class object that has not been bound to a
9966  //       reference (12.2) would be copied/moved to a class object
9967  //       with the same cv-unqualified type, the copy/move operation
9968  //       can be omitted by constructing the temporary object
9969  //       directly into the target of the omitted copy/move
9970  if (ConstructKind == CXXConstructExpr::CK_Complete &&
9971      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
9972    Expr *SubExpr = ExprArgs[0];
9973    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
9974  }
9975
9976  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
9977                               Elidable, ExprArgs, HadMultipleCandidates,
9978                               IsListInitialization, RequiresZeroInit,
9979                               ConstructKind, ParenRange);
9980}
9981
9982/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9983/// including handling of its default argument expressions.
9984ExprResult
9985Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9986                            CXXConstructorDecl *Constructor, bool Elidable,
9987                            MultiExprArg ExprArgs,
9988                            bool HadMultipleCandidates,
9989                            bool IsListInitialization,
9990                            bool RequiresZeroInit,
9991                            unsigned ConstructKind,
9992                            SourceRange ParenRange) {
9993  MarkFunctionReferenced(ConstructLoc, Constructor);
9994  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
9995                                        Constructor, Elidable, ExprArgs,
9996                                        HadMultipleCandidates,
9997                                        IsListInitialization, RequiresZeroInit,
9998              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9999                                        ParenRange));
10000}
10001
10002void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
10003  if (VD->isInvalidDecl()) return;
10004
10005  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
10006  if (ClassDecl->isInvalidDecl()) return;
10007  if (ClassDecl->hasIrrelevantDestructor()) return;
10008  if (ClassDecl->isDependentContext()) return;
10009
10010  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10011  MarkFunctionReferenced(VD->getLocation(), Destructor);
10012  CheckDestructorAccess(VD->getLocation(), Destructor,
10013                        PDiag(diag::err_access_dtor_var)
10014                        << VD->getDeclName()
10015                        << VD->getType());
10016  DiagnoseUseOfDecl(Destructor, VD->getLocation());
10017
10018  if (!VD->hasGlobalStorage()) return;
10019
10020  // Emit warning for non-trivial dtor in global scope (a real global,
10021  // class-static, function-static).
10022  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10023
10024  // TODO: this should be re-enabled for static locals by !CXAAtExit
10025  if (!VD->isStaticLocal())
10026    Diag(VD->getLocation(), diag::warn_global_destructor);
10027}
10028
10029/// \brief Given a constructor and the set of arguments provided for the
10030/// constructor, convert the arguments and add any required default arguments
10031/// to form a proper call to this constructor.
10032///
10033/// \returns true if an error occurred, false otherwise.
10034bool
10035Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10036                              MultiExprArg ArgsPtr,
10037                              SourceLocation Loc,
10038                              SmallVectorImpl<Expr*> &ConvertedArgs,
10039                              bool AllowExplicit,
10040                              bool IsListInitialization) {
10041  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10042  unsigned NumArgs = ArgsPtr.size();
10043  Expr **Args = ArgsPtr.data();
10044
10045  const FunctionProtoType *Proto
10046    = Constructor->getType()->getAs<FunctionProtoType>();
10047  assert(Proto && "Constructor without a prototype?");
10048  unsigned NumArgsInProto = Proto->getNumArgs();
10049
10050  // If too few arguments are available, we'll fill in the rest with defaults.
10051  if (NumArgs < NumArgsInProto)
10052    ConvertedArgs.reserve(NumArgsInProto);
10053  else
10054    ConvertedArgs.reserve(NumArgs);
10055
10056  VariadicCallType CallType =
10057    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
10058  SmallVector<Expr *, 8> AllArgs;
10059  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10060                                        Proto, 0, Args, NumArgs, AllArgs,
10061                                        CallType, AllowExplicit,
10062                                        IsListInitialization);
10063  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
10064
10065  DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
10066
10067  CheckConstructorCall(Constructor,
10068                       llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10069                                                        AllArgs.size()),
10070                       Proto, Loc);
10071
10072  return Invalid;
10073}
10074
10075static inline bool
10076CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10077                                       const FunctionDecl *FnDecl) {
10078  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
10079  if (isa<NamespaceDecl>(DC)) {
10080    return SemaRef.Diag(FnDecl->getLocation(),
10081                        diag::err_operator_new_delete_declared_in_namespace)
10082      << FnDecl->getDeclName();
10083  }
10084
10085  if (isa<TranslationUnitDecl>(DC) &&
10086      FnDecl->getStorageClass() == SC_Static) {
10087    return SemaRef.Diag(FnDecl->getLocation(),
10088                        diag::err_operator_new_delete_declared_static)
10089      << FnDecl->getDeclName();
10090  }
10091
10092  return false;
10093}
10094
10095static inline bool
10096CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10097                            CanQualType ExpectedResultType,
10098                            CanQualType ExpectedFirstParamType,
10099                            unsigned DependentParamTypeDiag,
10100                            unsigned InvalidParamTypeDiag) {
10101  QualType ResultType =
10102    FnDecl->getType()->getAs<FunctionType>()->getResultType();
10103
10104  // Check that the result type is not dependent.
10105  if (ResultType->isDependentType())
10106    return SemaRef.Diag(FnDecl->getLocation(),
10107                        diag::err_operator_new_delete_dependent_result_type)
10108    << FnDecl->getDeclName() << ExpectedResultType;
10109
10110  // Check that the result type is what we expect.
10111  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10112    return SemaRef.Diag(FnDecl->getLocation(),
10113                        diag::err_operator_new_delete_invalid_result_type)
10114    << FnDecl->getDeclName() << ExpectedResultType;
10115
10116  // A function template must have at least 2 parameters.
10117  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10118    return SemaRef.Diag(FnDecl->getLocation(),
10119                      diag::err_operator_new_delete_template_too_few_parameters)
10120        << FnDecl->getDeclName();
10121
10122  // The function decl must have at least 1 parameter.
10123  if (FnDecl->getNumParams() == 0)
10124    return SemaRef.Diag(FnDecl->getLocation(),
10125                        diag::err_operator_new_delete_too_few_parameters)
10126      << FnDecl->getDeclName();
10127
10128  // Check the first parameter type is not dependent.
10129  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10130  if (FirstParamType->isDependentType())
10131    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10132      << FnDecl->getDeclName() << ExpectedFirstParamType;
10133
10134  // Check that the first parameter type is what we expect.
10135  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10136      ExpectedFirstParamType)
10137    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10138    << FnDecl->getDeclName() << ExpectedFirstParamType;
10139
10140  return false;
10141}
10142
10143static bool
10144CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10145  // C++ [basic.stc.dynamic.allocation]p1:
10146  //   A program is ill-formed if an allocation function is declared in a
10147  //   namespace scope other than global scope or declared static in global
10148  //   scope.
10149  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10150    return true;
10151
10152  CanQualType SizeTy =
10153    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10154
10155  // C++ [basic.stc.dynamic.allocation]p1:
10156  //  The return type shall be void*. The first parameter shall have type
10157  //  std::size_t.
10158  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10159                                  SizeTy,
10160                                  diag::err_operator_new_dependent_param_type,
10161                                  diag::err_operator_new_param_type))
10162    return true;
10163
10164  // C++ [basic.stc.dynamic.allocation]p1:
10165  //  The first parameter shall not have an associated default argument.
10166  if (FnDecl->getParamDecl(0)->hasDefaultArg())
10167    return SemaRef.Diag(FnDecl->getLocation(),
10168                        diag::err_operator_new_default_arg)
10169      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10170
10171  return false;
10172}
10173
10174static bool
10175CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
10176  // C++ [basic.stc.dynamic.deallocation]p1:
10177  //   A program is ill-formed if deallocation functions are declared in a
10178  //   namespace scope other than global scope or declared static in global
10179  //   scope.
10180  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10181    return true;
10182
10183  // C++ [basic.stc.dynamic.deallocation]p2:
10184  //   Each deallocation function shall return void and its first parameter
10185  //   shall be void*.
10186  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10187                                  SemaRef.Context.VoidPtrTy,
10188                                 diag::err_operator_delete_dependent_param_type,
10189                                 diag::err_operator_delete_param_type))
10190    return true;
10191
10192  return false;
10193}
10194
10195/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10196/// of this overloaded operator is well-formed. If so, returns false;
10197/// otherwise, emits appropriate diagnostics and returns true.
10198bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
10199  assert(FnDecl && FnDecl->isOverloadedOperator() &&
10200         "Expected an overloaded operator declaration");
10201
10202  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10203
10204  // C++ [over.oper]p5:
10205  //   The allocation and deallocation functions, operator new,
10206  //   operator new[], operator delete and operator delete[], are
10207  //   described completely in 3.7.3. The attributes and restrictions
10208  //   found in the rest of this subclause do not apply to them unless
10209  //   explicitly stated in 3.7.3.
10210  if (Op == OO_Delete || Op == OO_Array_Delete)
10211    return CheckOperatorDeleteDeclaration(*this, FnDecl);
10212
10213  if (Op == OO_New || Op == OO_Array_New)
10214    return CheckOperatorNewDeclaration(*this, FnDecl);
10215
10216  // C++ [over.oper]p6:
10217  //   An operator function shall either be a non-static member
10218  //   function or be a non-member function and have at least one
10219  //   parameter whose type is a class, a reference to a class, an
10220  //   enumeration, or a reference to an enumeration.
10221  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10222    if (MethodDecl->isStatic())
10223      return Diag(FnDecl->getLocation(),
10224                  diag::err_operator_overload_static) << FnDecl->getDeclName();
10225  } else {
10226    bool ClassOrEnumParam = false;
10227    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10228                                   ParamEnd = FnDecl->param_end();
10229         Param != ParamEnd; ++Param) {
10230      QualType ParamType = (*Param)->getType().getNonReferenceType();
10231      if (ParamType->isDependentType() || ParamType->isRecordType() ||
10232          ParamType->isEnumeralType()) {
10233        ClassOrEnumParam = true;
10234        break;
10235      }
10236    }
10237
10238    if (!ClassOrEnumParam)
10239      return Diag(FnDecl->getLocation(),
10240                  diag::err_operator_overload_needs_class_or_enum)
10241        << FnDecl->getDeclName();
10242  }
10243
10244  // C++ [over.oper]p8:
10245  //   An operator function cannot have default arguments (8.3.6),
10246  //   except where explicitly stated below.
10247  //
10248  // Only the function-call operator allows default arguments
10249  // (C++ [over.call]p1).
10250  if (Op != OO_Call) {
10251    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10252         Param != FnDecl->param_end(); ++Param) {
10253      if ((*Param)->hasDefaultArg())
10254        return Diag((*Param)->getLocation(),
10255                    diag::err_operator_overload_default_arg)
10256          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
10257    }
10258  }
10259
10260  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10261    { false, false, false }
10262#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10263    , { Unary, Binary, MemberOnly }
10264#include "clang/Basic/OperatorKinds.def"
10265  };
10266
10267  bool CanBeUnaryOperator = OperatorUses[Op][0];
10268  bool CanBeBinaryOperator = OperatorUses[Op][1];
10269  bool MustBeMemberOperator = OperatorUses[Op][2];
10270
10271  // C++ [over.oper]p8:
10272  //   [...] Operator functions cannot have more or fewer parameters
10273  //   than the number required for the corresponding operator, as
10274  //   described in the rest of this subclause.
10275  unsigned NumParams = FnDecl->getNumParams()
10276                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
10277  if (Op != OO_Call &&
10278      ((NumParams == 1 && !CanBeUnaryOperator) ||
10279       (NumParams == 2 && !CanBeBinaryOperator) ||
10280       (NumParams < 1) || (NumParams > 2))) {
10281    // We have the wrong number of parameters.
10282    unsigned ErrorKind;
10283    if (CanBeUnaryOperator && CanBeBinaryOperator) {
10284      ErrorKind = 2;  // 2 -> unary or binary.
10285    } else if (CanBeUnaryOperator) {
10286      ErrorKind = 0;  // 0 -> unary
10287    } else {
10288      assert(CanBeBinaryOperator &&
10289             "All non-call overloaded operators are unary or binary!");
10290      ErrorKind = 1;  // 1 -> binary
10291    }
10292
10293    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
10294      << FnDecl->getDeclName() << NumParams << ErrorKind;
10295  }
10296
10297  // Overloaded operators other than operator() cannot be variadic.
10298  if (Op != OO_Call &&
10299      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
10300    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
10301      << FnDecl->getDeclName();
10302  }
10303
10304  // Some operators must be non-static member functions.
10305  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10306    return Diag(FnDecl->getLocation(),
10307                diag::err_operator_overload_must_be_member)
10308      << FnDecl->getDeclName();
10309  }
10310
10311  // C++ [over.inc]p1:
10312  //   The user-defined function called operator++ implements the
10313  //   prefix and postfix ++ operator. If this function is a member
10314  //   function with no parameters, or a non-member function with one
10315  //   parameter of class or enumeration type, it defines the prefix
10316  //   increment operator ++ for objects of that type. If the function
10317  //   is a member function with one parameter (which shall be of type
10318  //   int) or a non-member function with two parameters (the second
10319  //   of which shall be of type int), it defines the postfix
10320  //   increment operator ++ for objects of that type.
10321  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10322    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10323    bool ParamIsInt = false;
10324    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
10325      ParamIsInt = BT->getKind() == BuiltinType::Int;
10326
10327    if (!ParamIsInt)
10328      return Diag(LastParam->getLocation(),
10329                  diag::err_operator_overload_post_incdec_must_be_int)
10330        << LastParam->getType() << (Op == OO_MinusMinus);
10331  }
10332
10333  return false;
10334}
10335
10336/// CheckLiteralOperatorDeclaration - Check whether the declaration
10337/// of this literal operator function is well-formed. If so, returns
10338/// false; otherwise, emits appropriate diagnostics and returns true.
10339bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
10340  if (isa<CXXMethodDecl>(FnDecl)) {
10341    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10342      << FnDecl->getDeclName();
10343    return true;
10344  }
10345
10346  if (FnDecl->isExternC()) {
10347    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10348    return true;
10349  }
10350
10351  bool Valid = false;
10352
10353  // This might be the definition of a literal operator template.
10354  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10355  // This might be a specialization of a literal operator template.
10356  if (!TpDecl)
10357    TpDecl = FnDecl->getPrimaryTemplate();
10358
10359  // template <char...> type operator "" name() is the only valid template
10360  // signature, and the only valid signature with no parameters.
10361  if (TpDecl) {
10362    if (FnDecl->param_size() == 0) {
10363      // Must have only one template parameter
10364      TemplateParameterList *Params = TpDecl->getTemplateParameters();
10365      if (Params->size() == 1) {
10366        NonTypeTemplateParmDecl *PmDecl =
10367          dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
10368
10369        // The template parameter must be a char parameter pack.
10370        if (PmDecl && PmDecl->isTemplateParameterPack() &&
10371            Context.hasSameType(PmDecl->getType(), Context.CharTy))
10372          Valid = true;
10373      }
10374    }
10375  } else if (FnDecl->param_size()) {
10376    // Check the first parameter
10377    FunctionDecl::param_iterator Param = FnDecl->param_begin();
10378
10379    QualType T = (*Param)->getType().getUnqualifiedType();
10380
10381    // unsigned long long int, long double, and any character type are allowed
10382    // as the only parameters.
10383    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10384        Context.hasSameType(T, Context.LongDoubleTy) ||
10385        Context.hasSameType(T, Context.CharTy) ||
10386        Context.hasSameType(T, Context.WCharTy) ||
10387        Context.hasSameType(T, Context.Char16Ty) ||
10388        Context.hasSameType(T, Context.Char32Ty)) {
10389      if (++Param == FnDecl->param_end())
10390        Valid = true;
10391      goto FinishedParams;
10392    }
10393
10394    // Otherwise it must be a pointer to const; let's strip those qualifiers.
10395    const PointerType *PT = T->getAs<PointerType>();
10396    if (!PT)
10397      goto FinishedParams;
10398    T = PT->getPointeeType();
10399    if (!T.isConstQualified() || T.isVolatileQualified())
10400      goto FinishedParams;
10401    T = T.getUnqualifiedType();
10402
10403    // Move on to the second parameter;
10404    ++Param;
10405
10406    // If there is no second parameter, the first must be a const char *
10407    if (Param == FnDecl->param_end()) {
10408      if (Context.hasSameType(T, Context.CharTy))
10409        Valid = true;
10410      goto FinishedParams;
10411    }
10412
10413    // const char *, const wchar_t*, const char16_t*, and const char32_t*
10414    // are allowed as the first parameter to a two-parameter function
10415    if (!(Context.hasSameType(T, Context.CharTy) ||
10416          Context.hasSameType(T, Context.WCharTy) ||
10417          Context.hasSameType(T, Context.Char16Ty) ||
10418          Context.hasSameType(T, Context.Char32Ty)))
10419      goto FinishedParams;
10420
10421    // The second and final parameter must be an std::size_t
10422    T = (*Param)->getType().getUnqualifiedType();
10423    if (Context.hasSameType(T, Context.getSizeType()) &&
10424        ++Param == FnDecl->param_end())
10425      Valid = true;
10426  }
10427
10428  // FIXME: This diagnostic is absolutely terrible.
10429FinishedParams:
10430  if (!Valid) {
10431    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10432      << FnDecl->getDeclName();
10433    return true;
10434  }
10435
10436  // A parameter-declaration-clause containing a default argument is not
10437  // equivalent to any of the permitted forms.
10438  for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10439                                    ParamEnd = FnDecl->param_end();
10440       Param != ParamEnd; ++Param) {
10441    if ((*Param)->hasDefaultArg()) {
10442      Diag((*Param)->getDefaultArgRange().getBegin(),
10443           diag::err_literal_operator_default_argument)
10444        << (*Param)->getDefaultArgRange();
10445      break;
10446    }
10447  }
10448
10449  StringRef LiteralName
10450    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10451  if (LiteralName[0] != '_') {
10452    // C++11 [usrlit.suffix]p1:
10453    //   Literal suffix identifiers that do not start with an underscore
10454    //   are reserved for future standardization.
10455    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
10456  }
10457
10458  return false;
10459}
10460
10461/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10462/// linkage specification, including the language and (if present)
10463/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10464/// the location of the language string literal, which is provided
10465/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10466/// the '{' brace. Otherwise, this linkage specification does not
10467/// have any braces.
10468Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10469                                           SourceLocation LangLoc,
10470                                           StringRef Lang,
10471                                           SourceLocation LBraceLoc) {
10472  LinkageSpecDecl::LanguageIDs Language;
10473  if (Lang == "\"C\"")
10474    Language = LinkageSpecDecl::lang_c;
10475  else if (Lang == "\"C++\"")
10476    Language = LinkageSpecDecl::lang_cxx;
10477  else {
10478    Diag(LangLoc, diag::err_bad_language);
10479    return 0;
10480  }
10481
10482  // FIXME: Add all the various semantics of linkage specifications
10483
10484  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
10485                                               ExternLoc, LangLoc, Language,
10486                                               LBraceLoc.isValid());
10487  CurContext->addDecl(D);
10488  PushDeclContext(S, D);
10489  return D;
10490}
10491
10492/// ActOnFinishLinkageSpecification - Complete the definition of
10493/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10494/// valid, it's the position of the closing '}' brace in a linkage
10495/// specification that uses braces.
10496Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
10497                                            Decl *LinkageSpec,
10498                                            SourceLocation RBraceLoc) {
10499  if (LinkageSpec) {
10500    if (RBraceLoc.isValid()) {
10501      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10502      LSDecl->setRBraceLoc(RBraceLoc);
10503    }
10504    PopDeclContext();
10505  }
10506  return LinkageSpec;
10507}
10508
10509Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10510                                  AttributeList *AttrList,
10511                                  SourceLocation SemiLoc) {
10512  Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10513  // Attribute declarations appertain to empty declaration so we handle
10514  // them here.
10515  if (AttrList)
10516    ProcessDeclAttributeList(S, ED, AttrList);
10517
10518  CurContext->addDecl(ED);
10519  return ED;
10520}
10521
10522/// \brief Perform semantic analysis for the variable declaration that
10523/// occurs within a C++ catch clause, returning the newly-created
10524/// variable.
10525VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
10526                                         TypeSourceInfo *TInfo,
10527                                         SourceLocation StartLoc,
10528                                         SourceLocation Loc,
10529                                         IdentifierInfo *Name) {
10530  bool Invalid = false;
10531  QualType ExDeclType = TInfo->getType();
10532
10533  // Arrays and functions decay.
10534  if (ExDeclType->isArrayType())
10535    ExDeclType = Context.getArrayDecayedType(ExDeclType);
10536  else if (ExDeclType->isFunctionType())
10537    ExDeclType = Context.getPointerType(ExDeclType);
10538
10539  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10540  // The exception-declaration shall not denote a pointer or reference to an
10541  // incomplete type, other than [cv] void*.
10542  // N2844 forbids rvalue references.
10543  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
10544    Diag(Loc, diag::err_catch_rvalue_ref);
10545    Invalid = true;
10546  }
10547
10548  QualType BaseType = ExDeclType;
10549  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
10550  unsigned DK = diag::err_catch_incomplete;
10551  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
10552    BaseType = Ptr->getPointeeType();
10553    Mode = 1;
10554    DK = diag::err_catch_incomplete_ptr;
10555  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
10556    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
10557    BaseType = Ref->getPointeeType();
10558    Mode = 2;
10559    DK = diag::err_catch_incomplete_ref;
10560  }
10561  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
10562      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
10563    Invalid = true;
10564
10565  if (!Invalid && !ExDeclType->isDependentType() &&
10566      RequireNonAbstractType(Loc, ExDeclType,
10567                             diag::err_abstract_type_in_decl,
10568                             AbstractVariableType))
10569    Invalid = true;
10570
10571  // Only the non-fragile NeXT runtime currently supports C++ catches
10572  // of ObjC types, and no runtime supports catching ObjC types by value.
10573  if (!Invalid && getLangOpts().ObjC1) {
10574    QualType T = ExDeclType;
10575    if (const ReferenceType *RT = T->getAs<ReferenceType>())
10576      T = RT->getPointeeType();
10577
10578    if (T->isObjCObjectType()) {
10579      Diag(Loc, diag::err_objc_object_catch);
10580      Invalid = true;
10581    } else if (T->isObjCObjectPointerType()) {
10582      // FIXME: should this be a test for macosx-fragile specifically?
10583      if (getLangOpts().ObjCRuntime.isFragile())
10584        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
10585    }
10586  }
10587
10588  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10589                                    ExDeclType, TInfo, SC_None);
10590  ExDecl->setExceptionVariable(true);
10591
10592  // In ARC, infer 'retaining' for variables of retainable type.
10593  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
10594    Invalid = true;
10595
10596  if (!Invalid && !ExDeclType->isDependentType()) {
10597    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
10598      // Insulate this from anything else we might currently be parsing.
10599      EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10600
10601      // C++ [except.handle]p16:
10602      //   The object declared in an exception-declaration or, if the
10603      //   exception-declaration does not specify a name, a temporary (12.2) is
10604      //   copy-initialized (8.5) from the exception object. [...]
10605      //   The object is destroyed when the handler exits, after the destruction
10606      //   of any automatic objects initialized within the handler.
10607      //
10608      // We just pretend to initialize the object with itself, then make sure
10609      // it can be destroyed later.
10610      QualType initType = ExDeclType;
10611
10612      InitializedEntity entity =
10613        InitializedEntity::InitializeVariable(ExDecl);
10614      InitializationKind initKind =
10615        InitializationKind::CreateCopy(Loc, SourceLocation());
10616
10617      Expr *opaqueValue =
10618        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10619      InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10620      ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
10621      if (result.isInvalid())
10622        Invalid = true;
10623      else {
10624        // If the constructor used was non-trivial, set this as the
10625        // "initializer".
10626        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10627        if (!construct->getConstructor()->isTrivial()) {
10628          Expr *init = MaybeCreateExprWithCleanups(construct);
10629          ExDecl->setInit(init);
10630        }
10631
10632        // And make sure it's destructable.
10633        FinalizeVarWithDestructor(ExDecl, recordType);
10634      }
10635    }
10636  }
10637
10638  if (Invalid)
10639    ExDecl->setInvalidDecl();
10640
10641  return ExDecl;
10642}
10643
10644/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10645/// handler.
10646Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
10647  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10648  bool Invalid = D.isInvalidType();
10649
10650  // Check for unexpanded parameter packs.
10651  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10652                                      UPPC_ExceptionType)) {
10653    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10654                                             D.getIdentifierLoc());
10655    Invalid = true;
10656  }
10657
10658  IdentifierInfo *II = D.getIdentifier();
10659  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
10660                                             LookupOrdinaryName,
10661                                             ForRedeclaration)) {
10662    // The scope should be freshly made just for us. There is just no way
10663    // it contains any previous declaration.
10664    assert(!S->isDeclScope(PrevDecl));
10665    if (PrevDecl->isTemplateParameter()) {
10666      // Maybe we will complain about the shadowed template parameter.
10667      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10668      PrevDecl = 0;
10669    }
10670  }
10671
10672  if (D.getCXXScopeSpec().isSet() && !Invalid) {
10673    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10674      << D.getCXXScopeSpec().getRange();
10675    Invalid = true;
10676  }
10677
10678  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
10679                                              D.getLocStart(),
10680                                              D.getIdentifierLoc(),
10681                                              D.getIdentifier());
10682  if (Invalid)
10683    ExDecl->setInvalidDecl();
10684
10685  // Add the exception declaration into this scope.
10686  if (II)
10687    PushOnScopeChains(ExDecl, S);
10688  else
10689    CurContext->addDecl(ExDecl);
10690
10691  ProcessDeclAttributes(S, ExDecl, D);
10692  return ExDecl;
10693}
10694
10695Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10696                                         Expr *AssertExpr,
10697                                         Expr *AssertMessageExpr,
10698                                         SourceLocation RParenLoc) {
10699  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
10700
10701  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10702    return 0;
10703
10704  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10705                                      AssertMessage, RParenLoc, false);
10706}
10707
10708Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10709                                         Expr *AssertExpr,
10710                                         StringLiteral *AssertMessage,
10711                                         SourceLocation RParenLoc,
10712                                         bool Failed) {
10713  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10714      !Failed) {
10715    // In a static_assert-declaration, the constant-expression shall be a
10716    // constant expression that can be contextually converted to bool.
10717    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10718    if (Converted.isInvalid())
10719      Failed = true;
10720
10721    llvm::APSInt Cond;
10722    if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
10723          diag::err_static_assert_expression_is_not_constant,
10724          /*AllowFold=*/false).isInvalid())
10725      Failed = true;
10726
10727    if (!Failed && !Cond) {
10728      SmallString<256> MsgBuffer;
10729      llvm::raw_svector_ostream Msg(MsgBuffer);
10730      AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
10731      Diag(StaticAssertLoc, diag::err_static_assert_failed)
10732        << Msg.str() << AssertExpr->getSourceRange();
10733      Failed = true;
10734    }
10735  }
10736
10737  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
10738                                        AssertExpr, AssertMessage, RParenLoc,
10739                                        Failed);
10740
10741  CurContext->addDecl(Decl);
10742  return Decl;
10743}
10744
10745/// \brief Perform semantic analysis of the given friend type declaration.
10746///
10747/// \returns A friend declaration that.
10748FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
10749                                      SourceLocation FriendLoc,
10750                                      TypeSourceInfo *TSInfo) {
10751  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10752
10753  QualType T = TSInfo->getType();
10754  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
10755
10756  // C++03 [class.friend]p2:
10757  //   An elaborated-type-specifier shall be used in a friend declaration
10758  //   for a class.*
10759  //
10760  //   * The class-key of the elaborated-type-specifier is required.
10761  if (!ActiveTemplateInstantiations.empty()) {
10762    // Do not complain about the form of friend template types during
10763    // template instantiation; we will already have complained when the
10764    // template was declared.
10765  } else {
10766    if (!T->isElaboratedTypeSpecifier()) {
10767      // If we evaluated the type to a record type, suggest putting
10768      // a tag in front.
10769      if (const RecordType *RT = T->getAs<RecordType>()) {
10770        RecordDecl *RD = RT->getDecl();
10771
10772        std::string InsertionText = std::string(" ") + RD->getKindName();
10773
10774        Diag(TypeRange.getBegin(),
10775             getLangOpts().CPlusPlus11 ?
10776               diag::warn_cxx98_compat_unelaborated_friend_type :
10777               diag::ext_unelaborated_friend_type)
10778          << (unsigned) RD->getTagKind()
10779          << T
10780          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10781                                        InsertionText);
10782      } else {
10783        Diag(FriendLoc,
10784             getLangOpts().CPlusPlus11 ?
10785               diag::warn_cxx98_compat_nonclass_type_friend :
10786               diag::ext_nonclass_type_friend)
10787          << T
10788          << TypeRange;
10789      }
10790    } else if (T->getAs<EnumType>()) {
10791      Diag(FriendLoc,
10792           getLangOpts().CPlusPlus11 ?
10793             diag::warn_cxx98_compat_enum_friend :
10794             diag::ext_enum_friend)
10795        << T
10796        << TypeRange;
10797    }
10798
10799    // C++11 [class.friend]p3:
10800    //   A friend declaration that does not declare a function shall have one
10801    //   of the following forms:
10802    //     friend elaborated-type-specifier ;
10803    //     friend simple-type-specifier ;
10804    //     friend typename-specifier ;
10805    if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10806      Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10807  }
10808
10809  //   If the type specifier in a friend declaration designates a (possibly
10810  //   cv-qualified) class type, that class is declared as a friend; otherwise,
10811  //   the friend declaration is ignored.
10812  return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
10813}
10814
10815/// Handle a friend tag declaration where the scope specifier was
10816/// templated.
10817Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10818                                    unsigned TagSpec, SourceLocation TagLoc,
10819                                    CXXScopeSpec &SS,
10820                                    IdentifierInfo *Name,
10821                                    SourceLocation NameLoc,
10822                                    AttributeList *Attr,
10823                                    MultiTemplateParamsArg TempParamLists) {
10824  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10825
10826  bool isExplicitSpecialization = false;
10827  bool Invalid = false;
10828
10829  if (TemplateParameterList *TemplateParams
10830        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
10831                                                  TempParamLists.data(),
10832                                                  TempParamLists.size(),
10833                                                  /*friend*/ true,
10834                                                  isExplicitSpecialization,
10835                                                  Invalid)) {
10836    if (TemplateParams->size() > 0) {
10837      // This is a declaration of a class template.
10838      if (Invalid)
10839        return 0;
10840
10841      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10842                                SS, Name, NameLoc, Attr,
10843                                TemplateParams, AS_public,
10844                                /*ModulePrivateLoc=*/SourceLocation(),
10845                                TempParamLists.size() - 1,
10846                                TempParamLists.data()).take();
10847    } else {
10848      // The "template<>" header is extraneous.
10849      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10850        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10851      isExplicitSpecialization = true;
10852    }
10853  }
10854
10855  if (Invalid) return 0;
10856
10857  bool isAllExplicitSpecializations = true;
10858  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
10859    if (TempParamLists[I]->size()) {
10860      isAllExplicitSpecializations = false;
10861      break;
10862    }
10863  }
10864
10865  // FIXME: don't ignore attributes.
10866
10867  // If it's explicit specializations all the way down, just forget
10868  // about the template header and build an appropriate non-templated
10869  // friend.  TODO: for source fidelity, remember the headers.
10870  if (isAllExplicitSpecializations) {
10871    if (SS.isEmpty()) {
10872      bool Owned = false;
10873      bool IsDependent = false;
10874      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10875                      Attr, AS_public,
10876                      /*ModulePrivateLoc=*/SourceLocation(),
10877                      MultiTemplateParamsArg(), Owned, IsDependent,
10878                      /*ScopedEnumKWLoc=*/SourceLocation(),
10879                      /*ScopedEnumUsesClassTag=*/false,
10880                      /*UnderlyingType=*/TypeResult());
10881    }
10882
10883    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10884    ElaboratedTypeKeyword Keyword
10885      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10886    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
10887                                   *Name, NameLoc);
10888    if (T.isNull())
10889      return 0;
10890
10891    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10892    if (isa<DependentNameType>(T)) {
10893      DependentNameTypeLoc TL =
10894          TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
10895      TL.setElaboratedKeywordLoc(TagLoc);
10896      TL.setQualifierLoc(QualifierLoc);
10897      TL.setNameLoc(NameLoc);
10898    } else {
10899      ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
10900      TL.setElaboratedKeywordLoc(TagLoc);
10901      TL.setQualifierLoc(QualifierLoc);
10902      TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
10903    }
10904
10905    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10906                                            TSI, FriendLoc, TempParamLists);
10907    Friend->setAccess(AS_public);
10908    CurContext->addDecl(Friend);
10909    return Friend;
10910  }
10911
10912  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10913
10914
10915
10916  // Handle the case of a templated-scope friend class.  e.g.
10917  //   template <class T> class A<T>::B;
10918  // FIXME: we don't support these right now.
10919  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10920  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10921  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10922  DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
10923  TL.setElaboratedKeywordLoc(TagLoc);
10924  TL.setQualifierLoc(SS.getWithLocInContext(Context));
10925  TL.setNameLoc(NameLoc);
10926
10927  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10928                                          TSI, FriendLoc, TempParamLists);
10929  Friend->setAccess(AS_public);
10930  Friend->setUnsupportedFriend(true);
10931  CurContext->addDecl(Friend);
10932  return Friend;
10933}
10934
10935
10936/// Handle a friend type declaration.  This works in tandem with
10937/// ActOnTag.
10938///
10939/// Notes on friend class templates:
10940///
10941/// We generally treat friend class declarations as if they were
10942/// declaring a class.  So, for example, the elaborated type specifier
10943/// in a friend declaration is required to obey the restrictions of a
10944/// class-head (i.e. no typedefs in the scope chain), template
10945/// parameters are required to match up with simple template-ids, &c.
10946/// However, unlike when declaring a template specialization, it's
10947/// okay to refer to a template specialization without an empty
10948/// template parameter declaration, e.g.
10949///   friend class A<T>::B<unsigned>;
10950/// We permit this as a special case; if there are any template
10951/// parameters present at all, require proper matching, i.e.
10952///   template <> template \<class T> friend class A<int>::B;
10953Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
10954                                MultiTemplateParamsArg TempParams) {
10955  SourceLocation Loc = DS.getLocStart();
10956
10957  assert(DS.isFriendSpecified());
10958  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10959
10960  // Try to convert the decl specifier to a type.  This works for
10961  // friend templates because ActOnTag never produces a ClassTemplateDecl
10962  // for a TUK_Friend.
10963  Declarator TheDeclarator(DS, Declarator::MemberContext);
10964  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10965  QualType T = TSI->getType();
10966  if (TheDeclarator.isInvalidType())
10967    return 0;
10968
10969  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10970    return 0;
10971
10972  // This is definitely an error in C++98.  It's probably meant to
10973  // be forbidden in C++0x, too, but the specification is just
10974  // poorly written.
10975  //
10976  // The problem is with declarations like the following:
10977  //   template <T> friend A<T>::foo;
10978  // where deciding whether a class C is a friend or not now hinges
10979  // on whether there exists an instantiation of A that causes
10980  // 'foo' to equal C.  There are restrictions on class-heads
10981  // (which we declare (by fiat) elaborated friend declarations to
10982  // be) that makes this tractable.
10983  //
10984  // FIXME: handle "template <> friend class A<T>;", which
10985  // is possibly well-formed?  Who even knows?
10986  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
10987    Diag(Loc, diag::err_tagless_friend_type_template)
10988      << DS.getSourceRange();
10989    return 0;
10990  }
10991
10992  // C++98 [class.friend]p1: A friend of a class is a function
10993  //   or class that is not a member of the class . . .
10994  // This is fixed in DR77, which just barely didn't make the C++03
10995  // deadline.  It's also a very silly restriction that seriously
10996  // affects inner classes and which nobody else seems to implement;
10997  // thus we never diagnose it, not even in -pedantic.
10998  //
10999  // But note that we could warn about it: it's always useless to
11000  // friend one of your own members (it's not, however, worthless to
11001  // friend a member of an arbitrary specialization of your template).
11002
11003  Decl *D;
11004  if (unsigned NumTempParamLists = TempParams.size())
11005    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
11006                                   NumTempParamLists,
11007                                   TempParams.data(),
11008                                   TSI,
11009                                   DS.getFriendSpecLoc());
11010  else
11011    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
11012
11013  if (!D)
11014    return 0;
11015
11016  D->setAccess(AS_public);
11017  CurContext->addDecl(D);
11018
11019  return D;
11020}
11021
11022NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11023                                        MultiTemplateParamsArg TemplateParams) {
11024  const DeclSpec &DS = D.getDeclSpec();
11025
11026  assert(DS.isFriendSpecified());
11027  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11028
11029  SourceLocation Loc = D.getIdentifierLoc();
11030  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11031
11032  // C++ [class.friend]p1
11033  //   A friend of a class is a function or class....
11034  // Note that this sees through typedefs, which is intended.
11035  // It *doesn't* see through dependent types, which is correct
11036  // according to [temp.arg.type]p3:
11037  //   If a declaration acquires a function type through a
11038  //   type dependent on a template-parameter and this causes
11039  //   a declaration that does not use the syntactic form of a
11040  //   function declarator to have a function type, the program
11041  //   is ill-formed.
11042  if (!TInfo->getType()->isFunctionType()) {
11043    Diag(Loc, diag::err_unexpected_friend);
11044
11045    // It might be worthwhile to try to recover by creating an
11046    // appropriate declaration.
11047    return 0;
11048  }
11049
11050  // C++ [namespace.memdef]p3
11051  //  - If a friend declaration in a non-local class first declares a
11052  //    class or function, the friend class or function is a member
11053  //    of the innermost enclosing namespace.
11054  //  - The name of the friend is not found by simple name lookup
11055  //    until a matching declaration is provided in that namespace
11056  //    scope (either before or after the class declaration granting
11057  //    friendship).
11058  //  - If a friend function is called, its name may be found by the
11059  //    name lookup that considers functions from namespaces and
11060  //    classes associated with the types of the function arguments.
11061  //  - When looking for a prior declaration of a class or a function
11062  //    declared as a friend, scopes outside the innermost enclosing
11063  //    namespace scope are not considered.
11064
11065  CXXScopeSpec &SS = D.getCXXScopeSpec();
11066  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11067  DeclarationName Name = NameInfo.getName();
11068  assert(Name);
11069
11070  // Check for unexpanded parameter packs.
11071  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11072      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11073      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11074    return 0;
11075
11076  // The context we found the declaration in, or in which we should
11077  // create the declaration.
11078  DeclContext *DC;
11079  Scope *DCScope = S;
11080  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
11081                        ForRedeclaration);
11082
11083  // FIXME: there are different rules in local classes
11084
11085  // There are four cases here.
11086  //   - There's no scope specifier, in which case we just go to the
11087  //     appropriate scope and look for a function or function template
11088  //     there as appropriate.
11089  // Recover from invalid scope qualifiers as if they just weren't there.
11090  if (SS.isInvalid() || !SS.isSet()) {
11091    // C++0x [namespace.memdef]p3:
11092    //   If the name in a friend declaration is neither qualified nor
11093    //   a template-id and the declaration is a function or an
11094    //   elaborated-type-specifier, the lookup to determine whether
11095    //   the entity has been previously declared shall not consider
11096    //   any scopes outside the innermost enclosing namespace.
11097    // C++0x [class.friend]p11:
11098    //   If a friend declaration appears in a local class and the name
11099    //   specified is an unqualified name, a prior declaration is
11100    //   looked up without considering scopes that are outside the
11101    //   innermost enclosing non-class scope. For a friend function
11102    //   declaration, if there is no prior declaration, the program is
11103    //   ill-formed.
11104    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
11105    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
11106
11107    // Find the appropriate context according to the above.
11108    DC = CurContext;
11109
11110    // Skip class contexts.  If someone can cite chapter and verse
11111    // for this behavior, that would be nice --- it's what GCC and
11112    // EDG do, and it seems like a reasonable intent, but the spec
11113    // really only says that checks for unqualified existing
11114    // declarations should stop at the nearest enclosing namespace,
11115    // not that they should only consider the nearest enclosing
11116    // namespace.
11117    while (DC->isRecord())
11118      DC = DC->getParent();
11119
11120    DeclContext *LookupDC = DC;
11121    while (LookupDC->isTransparentContext())
11122      LookupDC = LookupDC->getParent();
11123
11124    while (true) {
11125      LookupQualifiedName(Previous, LookupDC);
11126
11127      // TODO: decide what we think about using declarations.
11128      if (isLocal)
11129        break;
11130
11131      if (!Previous.empty()) {
11132        DC = LookupDC;
11133        break;
11134      }
11135
11136      if (isTemplateId) {
11137        if (isa<TranslationUnitDecl>(LookupDC)) break;
11138      } else {
11139        if (LookupDC->isFileContext()) break;
11140      }
11141      LookupDC = LookupDC->getParent();
11142    }
11143
11144    DCScope = getScopeForDeclContext(S, DC);
11145
11146    // C++ [class.friend]p6:
11147    //   A function can be defined in a friend declaration of a class if and
11148    //   only if the class is a non-local class (9.8), the function name is
11149    //   unqualified, and the function has namespace scope.
11150    if (isLocal && D.isFunctionDefinition()) {
11151      Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11152    }
11153
11154  //   - There's a non-dependent scope specifier, in which case we
11155  //     compute it and do a previous lookup there for a function
11156  //     or function template.
11157  } else if (!SS.getScopeRep()->isDependent()) {
11158    DC = computeDeclContext(SS);
11159    if (!DC) return 0;
11160
11161    if (RequireCompleteDeclContext(SS, DC)) return 0;
11162
11163    LookupQualifiedName(Previous, DC);
11164
11165    // Ignore things found implicitly in the wrong scope.
11166    // TODO: better diagnostics for this case.  Suggesting the right
11167    // qualified scope would be nice...
11168    LookupResult::Filter F = Previous.makeFilter();
11169    while (F.hasNext()) {
11170      NamedDecl *D = F.next();
11171      if (!DC->InEnclosingNamespaceSetOf(
11172              D->getDeclContext()->getRedeclContext()))
11173        F.erase();
11174    }
11175    F.done();
11176
11177    if (Previous.empty()) {
11178      D.setInvalidType();
11179      Diag(Loc, diag::err_qualified_friend_not_found)
11180          << Name << TInfo->getType();
11181      return 0;
11182    }
11183
11184    // C++ [class.friend]p1: A friend of a class is a function or
11185    //   class that is not a member of the class . . .
11186    if (DC->Equals(CurContext))
11187      Diag(DS.getFriendSpecLoc(),
11188           getLangOpts().CPlusPlus11 ?
11189             diag::warn_cxx98_compat_friend_is_member :
11190             diag::err_friend_is_member);
11191
11192    if (D.isFunctionDefinition()) {
11193      // C++ [class.friend]p6:
11194      //   A function can be defined in a friend declaration of a class if and
11195      //   only if the class is a non-local class (9.8), the function name is
11196      //   unqualified, and the function has namespace scope.
11197      SemaDiagnosticBuilder DB
11198        = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11199
11200      DB << SS.getScopeRep();
11201      if (DC->isFileContext())
11202        DB << FixItHint::CreateRemoval(SS.getRange());
11203      SS.clear();
11204    }
11205
11206  //   - There's a scope specifier that does not match any template
11207  //     parameter lists, in which case we use some arbitrary context,
11208  //     create a method or method template, and wait for instantiation.
11209  //   - There's a scope specifier that does match some template
11210  //     parameter lists, which we don't handle right now.
11211  } else {
11212    if (D.isFunctionDefinition()) {
11213      // C++ [class.friend]p6:
11214      //   A function can be defined in a friend declaration of a class if and
11215      //   only if the class is a non-local class (9.8), the function name is
11216      //   unqualified, and the function has namespace scope.
11217      Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11218        << SS.getScopeRep();
11219    }
11220
11221    DC = CurContext;
11222    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
11223  }
11224
11225  if (!DC->isRecord()) {
11226    // This implies that it has to be an operator or function.
11227    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11228        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11229        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
11230      Diag(Loc, diag::err_introducing_special_friend) <<
11231        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11232         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
11233      return 0;
11234    }
11235  }
11236
11237  // FIXME: This is an egregious hack to cope with cases where the scope stack
11238  // does not contain the declaration context, i.e., in an out-of-line
11239  // definition of a class.
11240  Scope FakeDCScope(S, Scope::DeclScope, Diags);
11241  if (!DCScope) {
11242    FakeDCScope.setEntity(DC);
11243    DCScope = &FakeDCScope;
11244  }
11245
11246  bool AddToScope = true;
11247  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
11248                                          TemplateParams, AddToScope);
11249  if (!ND) return 0;
11250
11251  assert(ND->getDeclContext() == DC);
11252  assert(ND->getLexicalDeclContext() == CurContext);
11253
11254  // Add the function declaration to the appropriate lookup tables,
11255  // adjusting the redeclarations list as necessary.  We don't
11256  // want to do this yet if the friending class is dependent.
11257  //
11258  // Also update the scope-based lookup if the target context's
11259  // lookup context is in lexical scope.
11260  if (!CurContext->isDependentContext()) {
11261    DC = DC->getRedeclContext();
11262    DC->makeDeclVisibleInContext(ND);
11263    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11264      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
11265  }
11266
11267  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
11268                                       D.getIdentifierLoc(), ND,
11269                                       DS.getFriendSpecLoc());
11270  FrD->setAccess(AS_public);
11271  CurContext->addDecl(FrD);
11272
11273  if (ND->isInvalidDecl()) {
11274    FrD->setInvalidDecl();
11275  } else {
11276    if (DC->isRecord()) CheckFriendAccess(ND);
11277
11278    FunctionDecl *FD;
11279    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11280      FD = FTD->getTemplatedDecl();
11281    else
11282      FD = cast<FunctionDecl>(ND);
11283
11284    // Mark templated-scope function declarations as unsupported.
11285    if (FD->getNumTemplateParameterLists())
11286      FrD->setUnsupportedFriend(true);
11287  }
11288
11289  return ND;
11290}
11291
11292void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11293  AdjustDeclIfTemplate(Dcl);
11294
11295  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
11296  if (!Fn) {
11297    Diag(DelLoc, diag::err_deleted_non_function);
11298    return;
11299  }
11300
11301  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
11302    // Don't consider the implicit declaration we generate for explicit
11303    // specializations. FIXME: Do not generate these implicit declarations.
11304    if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11305        || Prev->getPreviousDecl()) && !Prev->isDefined()) {
11306      Diag(DelLoc, diag::err_deleted_decl_not_first);
11307      Diag(Prev->getLocation(), diag::note_previous_declaration);
11308    }
11309    // If the declaration wasn't the first, we delete the function anyway for
11310    // recovery.
11311    Fn = Fn->getCanonicalDecl();
11312  }
11313
11314  if (Fn->isDeleted())
11315    return;
11316
11317  // See if we're deleting a function which is already known to override a
11318  // non-deleted virtual function.
11319  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11320    bool IssuedDiagnostic = false;
11321    for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11322                                        E = MD->end_overridden_methods();
11323         I != E; ++I) {
11324      if (!(*MD->begin_overridden_methods())->isDeleted()) {
11325        if (!IssuedDiagnostic) {
11326          Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11327          IssuedDiagnostic = true;
11328        }
11329        Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11330      }
11331    }
11332  }
11333
11334  Fn->setDeletedAsWritten();
11335}
11336
11337void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
11338  CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
11339
11340  if (MD) {
11341    if (MD->getParent()->isDependentType()) {
11342      MD->setDefaulted();
11343      MD->setExplicitlyDefaulted();
11344      return;
11345    }
11346
11347    CXXSpecialMember Member = getSpecialMember(MD);
11348    if (Member == CXXInvalid) {
11349      Diag(DefaultLoc, diag::err_default_special_members);
11350      return;
11351    }
11352
11353    MD->setDefaulted();
11354    MD->setExplicitlyDefaulted();
11355
11356    // If this definition appears within the record, do the checking when
11357    // the record is complete.
11358    const FunctionDecl *Primary = MD;
11359    if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
11360      // Find the uninstantiated declaration that actually had the '= default'
11361      // on it.
11362      Pattern->isDefined(Primary);
11363
11364    // If the method was defaulted on its first declaration, we will have
11365    // already performed the checking in CheckCompletedCXXClass. Such a
11366    // declaration doesn't trigger an implicit definition.
11367    if (Primary == Primary->getCanonicalDecl())
11368      return;
11369
11370    CheckExplicitlyDefaultedSpecialMember(MD);
11371
11372    // The exception specification is needed because we are defining the
11373    // function.
11374    ResolveExceptionSpec(DefaultLoc,
11375                         MD->getType()->castAs<FunctionProtoType>());
11376
11377    switch (Member) {
11378    case CXXDefaultConstructor: {
11379      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11380      if (!CD->isInvalidDecl())
11381        DefineImplicitDefaultConstructor(DefaultLoc, CD);
11382      break;
11383    }
11384
11385    case CXXCopyConstructor: {
11386      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11387      if (!CD->isInvalidDecl())
11388        DefineImplicitCopyConstructor(DefaultLoc, CD);
11389      break;
11390    }
11391
11392    case CXXCopyAssignment: {
11393      if (!MD->isInvalidDecl())
11394        DefineImplicitCopyAssignment(DefaultLoc, MD);
11395      break;
11396    }
11397
11398    case CXXDestructor: {
11399      CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
11400      if (!DD->isInvalidDecl())
11401        DefineImplicitDestructor(DefaultLoc, DD);
11402      break;
11403    }
11404
11405    case CXXMoveConstructor: {
11406      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11407      if (!CD->isInvalidDecl())
11408        DefineImplicitMoveConstructor(DefaultLoc, CD);
11409      break;
11410    }
11411
11412    case CXXMoveAssignment: {
11413      if (!MD->isInvalidDecl())
11414        DefineImplicitMoveAssignment(DefaultLoc, MD);
11415      break;
11416    }
11417
11418    case CXXInvalid:
11419      llvm_unreachable("Invalid special member.");
11420    }
11421  } else {
11422    Diag(DefaultLoc, diag::err_default_special_members);
11423  }
11424}
11425
11426static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
11427  for (Stmt::child_range CI = S->children(); CI; ++CI) {
11428    Stmt *SubStmt = *CI;
11429    if (!SubStmt)
11430      continue;
11431    if (isa<ReturnStmt>(SubStmt))
11432      Self.Diag(SubStmt->getLocStart(),
11433           diag::err_return_in_constructor_handler);
11434    if (!isa<Expr>(SubStmt))
11435      SearchForReturnInStmt(Self, SubStmt);
11436  }
11437}
11438
11439void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11440  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11441    CXXCatchStmt *Handler = TryBlock->getHandler(I);
11442    SearchForReturnInStmt(*this, Handler);
11443  }
11444}
11445
11446bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
11447                                             const CXXMethodDecl *Old) {
11448  const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11449  const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11450
11451  CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11452
11453  // If the calling conventions match, everything is fine
11454  if (NewCC == OldCC)
11455    return false;
11456
11457  // If either of the calling conventions are set to "default", we need to pick
11458  // something more sensible based on the target. This supports code where the
11459  // one method explicitly sets thiscall, and another has no explicit calling
11460  // convention.
11461  CallingConv Default =
11462    Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11463  if (NewCC == CC_Default)
11464    NewCC = Default;
11465  if (OldCC == CC_Default)
11466    OldCC = Default;
11467
11468  // If the calling conventions still don't match, then report the error
11469  if (NewCC != OldCC) {
11470    Diag(New->getLocation(),
11471         diag::err_conflicting_overriding_cc_attributes)
11472      << New->getDeclName() << New->getType() << Old->getType();
11473    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11474    return true;
11475  }
11476
11477  return false;
11478}
11479
11480bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
11481                                             const CXXMethodDecl *Old) {
11482  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11483  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
11484
11485  if (Context.hasSameType(NewTy, OldTy) ||
11486      NewTy->isDependentType() || OldTy->isDependentType())
11487    return false;
11488
11489  // Check if the return types are covariant
11490  QualType NewClassTy, OldClassTy;
11491
11492  /// Both types must be pointers or references to classes.
11493  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11494    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
11495      NewClassTy = NewPT->getPointeeType();
11496      OldClassTy = OldPT->getPointeeType();
11497    }
11498  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11499    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11500      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11501        NewClassTy = NewRT->getPointeeType();
11502        OldClassTy = OldRT->getPointeeType();
11503      }
11504    }
11505  }
11506
11507  // The return types aren't either both pointers or references to a class type.
11508  if (NewClassTy.isNull()) {
11509    Diag(New->getLocation(),
11510         diag::err_different_return_type_for_overriding_virtual_function)
11511      << New->getDeclName() << NewTy << OldTy;
11512    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11513
11514    return true;
11515  }
11516
11517  // C++ [class.virtual]p6:
11518  //   If the return type of D::f differs from the return type of B::f, the
11519  //   class type in the return type of D::f shall be complete at the point of
11520  //   declaration of D::f or shall be the class type D.
11521  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11522    if (!RT->isBeingDefined() &&
11523        RequireCompleteType(New->getLocation(), NewClassTy,
11524                            diag::err_covariant_return_incomplete,
11525                            New->getDeclName()))
11526    return true;
11527  }
11528
11529  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
11530    // Check if the new class derives from the old class.
11531    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11532      Diag(New->getLocation(),
11533           diag::err_covariant_return_not_derived)
11534      << New->getDeclName() << NewTy << OldTy;
11535      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11536      return true;
11537    }
11538
11539    // Check if we the conversion from derived to base is valid.
11540    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
11541                    diag::err_covariant_return_inaccessible_base,
11542                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
11543                    // FIXME: Should this point to the return type?
11544                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
11545      // FIXME: this note won't trigger for delayed access control
11546      // diagnostics, and it's impossible to get an undelayed error
11547      // here from access control during the original parse because
11548      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
11549      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11550      return true;
11551    }
11552  }
11553
11554  // The qualifiers of the return types must be the same.
11555  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
11556    Diag(New->getLocation(),
11557         diag::err_covariant_return_type_different_qualifications)
11558    << New->getDeclName() << NewTy << OldTy;
11559    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11560    return true;
11561  };
11562
11563
11564  // The new class type must have the same or less qualifiers as the old type.
11565  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11566    Diag(New->getLocation(),
11567         diag::err_covariant_return_type_class_type_more_qualified)
11568    << New->getDeclName() << NewTy << OldTy;
11569    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11570    return true;
11571  };
11572
11573  return false;
11574}
11575
11576/// \brief Mark the given method pure.
11577///
11578/// \param Method the method to be marked pure.
11579///
11580/// \param InitRange the source range that covers the "0" initializer.
11581bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
11582  SourceLocation EndLoc = InitRange.getEnd();
11583  if (EndLoc.isValid())
11584    Method->setRangeEnd(EndLoc);
11585
11586  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11587    Method->setPure();
11588    return false;
11589  }
11590
11591  if (!Method->isInvalidDecl())
11592    Diag(Method->getLocation(), diag::err_non_virtual_pure)
11593      << Method->getDeclName() << InitRange;
11594  return true;
11595}
11596
11597/// \brief Determine whether the given declaration is a static data member.
11598static bool isStaticDataMember(Decl *D) {
11599  VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11600  if (!Var)
11601    return false;
11602
11603  return Var->isStaticDataMember();
11604}
11605/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11606/// an initializer for the out-of-line declaration 'Dcl'.  The scope
11607/// is a fresh scope pushed for just this purpose.
11608///
11609/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11610/// static data member of class X, names should be looked up in the scope of
11611/// class X.
11612void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
11613  // If there is no declaration, there was an error parsing it.
11614  if (D == 0 || D->isInvalidDecl()) return;
11615
11616  // We should only get called for declarations with scope specifiers, like:
11617  //   int foo::bar;
11618  assert(D->isOutOfLine());
11619  EnterDeclaratorContext(S, D->getDeclContext());
11620
11621  // If we are parsing the initializer for a static data member, push a
11622  // new expression evaluation context that is associated with this static
11623  // data member.
11624  if (isStaticDataMember(D))
11625    PushExpressionEvaluationContext(PotentiallyEvaluated, D);
11626}
11627
11628/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
11629/// initializer for the out-of-line declaration 'D'.
11630void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
11631  // If there is no declaration, there was an error parsing it.
11632  if (D == 0 || D->isInvalidDecl()) return;
11633
11634  if (isStaticDataMember(D))
11635    PopExpressionEvaluationContext();
11636
11637  assert(D->isOutOfLine());
11638  ExitDeclaratorContext(S);
11639}
11640
11641/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11642/// C++ if/switch/while/for statement.
11643/// e.g: "if (int x = f()) {...}"
11644DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
11645  // C++ 6.4p2:
11646  // The declarator shall not specify a function or an array.
11647  // The type-specifier-seq shall not contain typedef and shall not declare a
11648  // new class or enumeration.
11649  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11650         "Parser allowed 'typedef' as storage class of condition decl.");
11651
11652  Decl *Dcl = ActOnDeclarator(S, D);
11653  if (!Dcl)
11654    return true;
11655
11656  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11657    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
11658      << D.getSourceRange();
11659    return true;
11660  }
11661
11662  return Dcl;
11663}
11664
11665void Sema::LoadExternalVTableUses() {
11666  if (!ExternalSource)
11667    return;
11668
11669  SmallVector<ExternalVTableUse, 4> VTables;
11670  ExternalSource->ReadUsedVTables(VTables);
11671  SmallVector<VTableUse, 4> NewUses;
11672  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11673    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11674      = VTablesUsed.find(VTables[I].Record);
11675    // Even if a definition wasn't required before, it may be required now.
11676    if (Pos != VTablesUsed.end()) {
11677      if (!Pos->second && VTables[I].DefinitionRequired)
11678        Pos->second = true;
11679      continue;
11680    }
11681
11682    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11683    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11684  }
11685
11686  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11687}
11688
11689void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11690                          bool DefinitionRequired) {
11691  // Ignore any vtable uses in unevaluated operands or for classes that do
11692  // not have a vtable.
11693  if (!Class->isDynamicClass() || Class->isDependentContext() ||
11694      CurContext->isDependentContext() || isUnevaluatedContext())
11695    return;
11696
11697  // Try to insert this class into the map.
11698  LoadExternalVTableUses();
11699  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11700  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11701    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11702  if (!Pos.second) {
11703    // If we already had an entry, check to see if we are promoting this vtable
11704    // to required a definition. If so, we need to reappend to the VTableUses
11705    // list, since we may have already processed the first entry.
11706    if (DefinitionRequired && !Pos.first->second) {
11707      Pos.first->second = true;
11708    } else {
11709      // Otherwise, we can early exit.
11710      return;
11711    }
11712  }
11713
11714  // Local classes need to have their virtual members marked
11715  // immediately. For all other classes, we mark their virtual members
11716  // at the end of the translation unit.
11717  if (Class->isLocalClass())
11718    MarkVirtualMembersReferenced(Loc, Class);
11719  else
11720    VTableUses.push_back(std::make_pair(Class, Loc));
11721}
11722
11723bool Sema::DefineUsedVTables() {
11724  LoadExternalVTableUses();
11725  if (VTableUses.empty())
11726    return false;
11727
11728  // Note: The VTableUses vector could grow as a result of marking
11729  // the members of a class as "used", so we check the size each
11730  // time through the loop and prefer indices (which are stable) to
11731  // iterators (which are not).
11732  bool DefinedAnything = false;
11733  for (unsigned I = 0; I != VTableUses.size(); ++I) {
11734    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
11735    if (!Class)
11736      continue;
11737
11738    SourceLocation Loc = VTableUses[I].second;
11739
11740    bool DefineVTable = true;
11741
11742    // If this class has a key function, but that key function is
11743    // defined in another translation unit, we don't need to emit the
11744    // vtable even though we're using it.
11745    const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
11746    if (KeyFunction && !KeyFunction->hasBody()) {
11747      switch (KeyFunction->getTemplateSpecializationKind()) {
11748      case TSK_Undeclared:
11749      case TSK_ExplicitSpecialization:
11750      case TSK_ExplicitInstantiationDeclaration:
11751        // The key function is in another translation unit.
11752        DefineVTable = false;
11753        break;
11754
11755      case TSK_ExplicitInstantiationDefinition:
11756      case TSK_ImplicitInstantiation:
11757        // We will be instantiating the key function.
11758        break;
11759      }
11760    } else if (!KeyFunction) {
11761      // If we have a class with no key function that is the subject
11762      // of an explicit instantiation declaration, suppress the
11763      // vtable; it will live with the explicit instantiation
11764      // definition.
11765      bool IsExplicitInstantiationDeclaration
11766        = Class->getTemplateSpecializationKind()
11767                                      == TSK_ExplicitInstantiationDeclaration;
11768      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11769                                 REnd = Class->redecls_end();
11770           R != REnd; ++R) {
11771        TemplateSpecializationKind TSK
11772          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11773        if (TSK == TSK_ExplicitInstantiationDeclaration)
11774          IsExplicitInstantiationDeclaration = true;
11775        else if (TSK == TSK_ExplicitInstantiationDefinition) {
11776          IsExplicitInstantiationDeclaration = false;
11777          break;
11778        }
11779      }
11780
11781      if (IsExplicitInstantiationDeclaration)
11782        DefineVTable = false;
11783    }
11784
11785    // The exception specifications for all virtual members may be needed even
11786    // if we are not providing an authoritative form of the vtable in this TU.
11787    // We may choose to emit it available_externally anyway.
11788    if (!DefineVTable) {
11789      MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11790      continue;
11791    }
11792
11793    // Mark all of the virtual members of this class as referenced, so
11794    // that we can build a vtable. Then, tell the AST consumer that a
11795    // vtable for this class is required.
11796    DefinedAnything = true;
11797    MarkVirtualMembersReferenced(Loc, Class);
11798    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11799    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11800
11801    // Optionally warn if we're emitting a weak vtable.
11802    if (Class->hasExternalLinkage() &&
11803        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
11804      const FunctionDecl *KeyFunctionDef = 0;
11805      if (!KeyFunction ||
11806          (KeyFunction->hasBody(KeyFunctionDef) &&
11807           KeyFunctionDef->isInlined()))
11808        Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11809             TSK_ExplicitInstantiationDefinition
11810             ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11811          << Class;
11812    }
11813  }
11814  VTableUses.clear();
11815
11816  return DefinedAnything;
11817}
11818
11819void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11820                                                 const CXXRecordDecl *RD) {
11821  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11822                                      E = RD->method_end(); I != E; ++I)
11823    if ((*I)->isVirtual() && !(*I)->isPure())
11824      ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11825}
11826
11827void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11828                                        const CXXRecordDecl *RD) {
11829  // Mark all functions which will appear in RD's vtable as used.
11830  CXXFinalOverriderMap FinalOverriders;
11831  RD->getFinalOverriders(FinalOverriders);
11832  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11833                                            E = FinalOverriders.end();
11834       I != E; ++I) {
11835    for (OverridingMethods::const_iterator OI = I->second.begin(),
11836                                           OE = I->second.end();
11837         OI != OE; ++OI) {
11838      assert(OI->second.size() > 0 && "no final overrider");
11839      CXXMethodDecl *Overrider = OI->second.front().Method;
11840
11841      // C++ [basic.def.odr]p2:
11842      //   [...] A virtual member function is used if it is not pure. [...]
11843      if (!Overrider->isPure())
11844        MarkFunctionReferenced(Loc, Overrider);
11845    }
11846  }
11847
11848  // Only classes that have virtual bases need a VTT.
11849  if (RD->getNumVBases() == 0)
11850    return;
11851
11852  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11853           e = RD->bases_end(); i != e; ++i) {
11854    const CXXRecordDecl *Base =
11855        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
11856    if (Base->getNumVBases() == 0)
11857      continue;
11858    MarkVirtualMembersReferenced(Loc, Base);
11859  }
11860}
11861
11862/// SetIvarInitializers - This routine builds initialization ASTs for the
11863/// Objective-C implementation whose ivars need be initialized.
11864void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
11865  if (!getLangOpts().CPlusPlus)
11866    return;
11867  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
11868    SmallVector<ObjCIvarDecl*, 8> ivars;
11869    CollectIvarsToConstructOrDestruct(OID, ivars);
11870    if (ivars.empty())
11871      return;
11872    SmallVector<CXXCtorInitializer*, 32> AllToInit;
11873    for (unsigned i = 0; i < ivars.size(); i++) {
11874      FieldDecl *Field = ivars[i];
11875      if (Field->isInvalidDecl())
11876        continue;
11877
11878      CXXCtorInitializer *Member;
11879      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11880      InitializationKind InitKind =
11881        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11882
11883      InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
11884      ExprResult MemberInit =
11885        InitSeq.Perform(*this, InitEntity, InitKind, None);
11886      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
11887      // Note, MemberInit could actually come back empty if no initialization
11888      // is required (e.g., because it would call a trivial default constructor)
11889      if (!MemberInit.get() || MemberInit.isInvalid())
11890        continue;
11891
11892      Member =
11893        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11894                                         SourceLocation(),
11895                                         MemberInit.takeAs<Expr>(),
11896                                         SourceLocation());
11897      AllToInit.push_back(Member);
11898
11899      // Be sure that the destructor is accessible and is marked as referenced.
11900      if (const RecordType *RecordTy
11901                  = Context.getBaseElementType(Field->getType())
11902                                                        ->getAs<RecordType>()) {
11903                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
11904        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
11905          MarkFunctionReferenced(Field->getLocation(), Destructor);
11906          CheckDestructorAccess(Field->getLocation(), Destructor,
11907                            PDiag(diag::err_access_dtor_ivar)
11908                              << Context.getBaseElementType(Field->getType()));
11909        }
11910      }
11911    }
11912    ObjCImplementation->setIvarInitializers(Context,
11913                                            AllToInit.data(), AllToInit.size());
11914  }
11915}
11916
11917static
11918void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11919                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11920                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11921                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11922                           Sema &S) {
11923  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11924                                                   CE = Current.end();
11925  if (Ctor->isInvalidDecl())
11926    return;
11927
11928  CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11929
11930  // Target may not be determinable yet, for instance if this is a dependent
11931  // call in an uninstantiated template.
11932  if (Target) {
11933    const FunctionDecl *FNTarget = 0;
11934    (void)Target->hasBody(FNTarget);
11935    Target = const_cast<CXXConstructorDecl*>(
11936      cast_or_null<CXXConstructorDecl>(FNTarget));
11937  }
11938
11939  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11940                     // Avoid dereferencing a null pointer here.
11941                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11942
11943  if (!Current.insert(Canonical))
11944    return;
11945
11946  // We know that beyond here, we aren't chaining into a cycle.
11947  if (!Target || !Target->isDelegatingConstructor() ||
11948      Target->isInvalidDecl() || Valid.count(TCanonical)) {
11949    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11950      Valid.insert(*CI);
11951    Current.clear();
11952  // We've hit a cycle.
11953  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11954             Current.count(TCanonical)) {
11955    // If we haven't diagnosed this cycle yet, do so now.
11956    if (!Invalid.count(TCanonical)) {
11957      S.Diag((*Ctor->init_begin())->getSourceLocation(),
11958             diag::warn_delegating_ctor_cycle)
11959        << Ctor;
11960
11961      // Don't add a note for a function delegating directly to itself.
11962      if (TCanonical != Canonical)
11963        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11964
11965      CXXConstructorDecl *C = Target;
11966      while (C->getCanonicalDecl() != Canonical) {
11967        const FunctionDecl *FNTarget = 0;
11968        (void)C->getTargetConstructor()->hasBody(FNTarget);
11969        assert(FNTarget && "Ctor cycle through bodiless function");
11970
11971        C = const_cast<CXXConstructorDecl*>(
11972          cast<CXXConstructorDecl>(FNTarget));
11973        S.Diag(C->getLocation(), diag::note_which_delegates_to);
11974      }
11975    }
11976
11977    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11978      Invalid.insert(*CI);
11979    Current.clear();
11980  } else {
11981    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11982  }
11983}
11984
11985
11986void Sema::CheckDelegatingCtorCycles() {
11987  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11988
11989  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11990                                                   CE = Current.end();
11991
11992  for (DelegatingCtorDeclsType::iterator
11993         I = DelegatingCtorDecls.begin(ExternalSource),
11994         E = DelegatingCtorDecls.end();
11995       I != E; ++I)
11996    DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
11997
11998  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11999    (*CI)->setInvalidDecl();
12000}
12001
12002namespace {
12003  /// \brief AST visitor that finds references to the 'this' expression.
12004  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12005    Sema &S;
12006
12007  public:
12008    explicit FindCXXThisExpr(Sema &S) : S(S) { }
12009
12010    bool VisitCXXThisExpr(CXXThisExpr *E) {
12011      S.Diag(E->getLocation(), diag::err_this_static_member_func)
12012        << E->isImplicit();
12013      return false;
12014    }
12015  };
12016}
12017
12018bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12019  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12020  if (!TSInfo)
12021    return false;
12022
12023  TypeLoc TL = TSInfo->getTypeLoc();
12024  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12025  if (!ProtoTL)
12026    return false;
12027
12028  // C++11 [expr.prim.general]p3:
12029  //   [The expression this] shall not appear before the optional
12030  //   cv-qualifier-seq and it shall not appear within the declaration of a
12031  //   static member function (although its type and value category are defined
12032  //   within a static member function as they are within a non-static member
12033  //   function). [ Note: this is because declaration matching does not occur
12034  //  until the complete declarator is known. - end note ]
12035  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12036  FindCXXThisExpr Finder(*this);
12037
12038  // If the return type came after the cv-qualifier-seq, check it now.
12039  if (Proto->hasTrailingReturn() &&
12040      !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
12041    return true;
12042
12043  // Check the exception specification.
12044  if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12045    return true;
12046
12047  return checkThisInStaticMemberFunctionAttributes(Method);
12048}
12049
12050bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12051  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12052  if (!TSInfo)
12053    return false;
12054
12055  TypeLoc TL = TSInfo->getTypeLoc();
12056  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12057  if (!ProtoTL)
12058    return false;
12059
12060  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12061  FindCXXThisExpr Finder(*this);
12062
12063  switch (Proto->getExceptionSpecType()) {
12064  case EST_Uninstantiated:
12065  case EST_Unevaluated:
12066  case EST_BasicNoexcept:
12067  case EST_DynamicNone:
12068  case EST_MSAny:
12069  case EST_None:
12070    break;
12071
12072  case EST_ComputedNoexcept:
12073    if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12074      return true;
12075
12076  case EST_Dynamic:
12077    for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
12078         EEnd = Proto->exception_end();
12079         E != EEnd; ++E) {
12080      if (!Finder.TraverseType(*E))
12081        return true;
12082    }
12083    break;
12084  }
12085
12086  return false;
12087}
12088
12089bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12090  FindCXXThisExpr Finder(*this);
12091
12092  // Check attributes.
12093  for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12094       A != AEnd; ++A) {
12095    // FIXME: This should be emitted by tblgen.
12096    Expr *Arg = 0;
12097    ArrayRef<Expr *> Args;
12098    if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12099      Arg = G->getArg();
12100    else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12101      Arg = G->getArg();
12102    else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12103      Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12104    else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12105      Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12106    else if (ExclusiveLockFunctionAttr *ELF
12107               = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12108      Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12109    else if (SharedLockFunctionAttr *SLF
12110               = dyn_cast<SharedLockFunctionAttr>(*A))
12111      Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12112    else if (ExclusiveTrylockFunctionAttr *ETLF
12113               = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12114      Arg = ETLF->getSuccessValue();
12115      Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12116    } else if (SharedTrylockFunctionAttr *STLF
12117                 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12118      Arg = STLF->getSuccessValue();
12119      Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12120    } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12121      Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12122    else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12123      Arg = LR->getArg();
12124    else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12125      Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12126    else if (ExclusiveLocksRequiredAttr *ELR
12127               = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12128      Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12129    else if (SharedLocksRequiredAttr *SLR
12130               = dyn_cast<SharedLocksRequiredAttr>(*A))
12131      Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12132
12133    if (Arg && !Finder.TraverseStmt(Arg))
12134      return true;
12135
12136    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12137      if (!Finder.TraverseStmt(Args[I]))
12138        return true;
12139    }
12140  }
12141
12142  return false;
12143}
12144
12145void
12146Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12147                                  ArrayRef<ParsedType> DynamicExceptions,
12148                                  ArrayRef<SourceRange> DynamicExceptionRanges,
12149                                  Expr *NoexceptExpr,
12150                                  SmallVectorImpl<QualType> &Exceptions,
12151                                  FunctionProtoType::ExtProtoInfo &EPI) {
12152  Exceptions.clear();
12153  EPI.ExceptionSpecType = EST;
12154  if (EST == EST_Dynamic) {
12155    Exceptions.reserve(DynamicExceptions.size());
12156    for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12157      // FIXME: Preserve type source info.
12158      QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12159
12160      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12161      collectUnexpandedParameterPacks(ET, Unexpanded);
12162      if (!Unexpanded.empty()) {
12163        DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12164                                         UPPC_ExceptionType,
12165                                         Unexpanded);
12166        continue;
12167      }
12168
12169      // Check that the type is valid for an exception spec, and
12170      // drop it if not.
12171      if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12172        Exceptions.push_back(ET);
12173    }
12174    EPI.NumExceptions = Exceptions.size();
12175    EPI.Exceptions = Exceptions.data();
12176    return;
12177  }
12178
12179  if (EST == EST_ComputedNoexcept) {
12180    // If an error occurred, there's no expression here.
12181    if (NoexceptExpr) {
12182      assert((NoexceptExpr->isTypeDependent() ||
12183              NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12184              Context.BoolTy) &&
12185             "Parser should have made sure that the expression is boolean");
12186      if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12187        EPI.ExceptionSpecType = EST_BasicNoexcept;
12188        return;
12189      }
12190
12191      if (!NoexceptExpr->isValueDependent())
12192        NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
12193                         diag::err_noexcept_needs_constant_expression,
12194                         /*AllowFold*/ false).take();
12195      EPI.NoexceptExpr = NoexceptExpr;
12196    }
12197    return;
12198  }
12199}
12200
12201/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12202Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12203  // Implicitly declared functions (e.g. copy constructors) are
12204  // __host__ __device__
12205  if (D->isImplicit())
12206    return CFT_HostDevice;
12207
12208  if (D->hasAttr<CUDAGlobalAttr>())
12209    return CFT_Global;
12210
12211  if (D->hasAttr<CUDADeviceAttr>()) {
12212    if (D->hasAttr<CUDAHostAttr>())
12213      return CFT_HostDevice;
12214    else
12215      return CFT_Device;
12216  }
12217
12218  return CFT_Host;
12219}
12220
12221bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12222                           CUDAFunctionTarget CalleeTarget) {
12223  // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12224  // Callable from the device only."
12225  if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12226    return true;
12227
12228  // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12229  // Callable from the host only."
12230  // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12231  // Callable from the host only."
12232  if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12233      (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12234    return true;
12235
12236  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12237    return true;
12238
12239  return false;
12240}
12241
12242/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12243///
12244MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12245                                       SourceLocation DeclStart,
12246                                       Declarator &D, Expr *BitWidth,
12247                                       InClassInitStyle InitStyle,
12248                                       AccessSpecifier AS,
12249                                       AttributeList *MSPropertyAttr) {
12250  IdentifierInfo *II = D.getIdentifier();
12251  if (!II) {
12252    Diag(DeclStart, diag::err_anonymous_property);
12253    return NULL;
12254  }
12255  SourceLocation Loc = D.getIdentifierLoc();
12256
12257  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12258  QualType T = TInfo->getType();
12259  if (getLangOpts().CPlusPlus) {
12260    CheckExtraCXXDefaultArguments(D);
12261
12262    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12263                                        UPPC_DataMemberType)) {
12264      D.setInvalidType();
12265      T = Context.IntTy;
12266      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12267    }
12268  }
12269
12270  DiagnoseFunctionSpecifiers(D.getDeclSpec());
12271
12272  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12273    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12274         diag::err_invalid_thread)
12275      << DeclSpec::getSpecifierName(TSCS);
12276
12277  // Check to see if this name was declared as a member previously
12278  NamedDecl *PrevDecl = 0;
12279  LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12280  LookupName(Previous, S);
12281  switch (Previous.getResultKind()) {
12282  case LookupResult::Found:
12283  case LookupResult::FoundUnresolvedValue:
12284    PrevDecl = Previous.getAsSingle<NamedDecl>();
12285    break;
12286
12287  case LookupResult::FoundOverloaded:
12288    PrevDecl = Previous.getRepresentativeDecl();
12289    break;
12290
12291  case LookupResult::NotFound:
12292  case LookupResult::NotFoundInCurrentInstantiation:
12293  case LookupResult::Ambiguous:
12294    break;
12295  }
12296
12297  if (PrevDecl && PrevDecl->isTemplateParameter()) {
12298    // Maybe we will complain about the shadowed template parameter.
12299    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12300    // Just pretend that we didn't see the previous declaration.
12301    PrevDecl = 0;
12302  }
12303
12304  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12305    PrevDecl = 0;
12306
12307  SourceLocation TSSL = D.getLocStart();
12308  MSPropertyDecl *NewPD;
12309  const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12310  NewPD = new (Context) MSPropertyDecl(Record, Loc,
12311                                       II, T, TInfo, TSSL,
12312                                       Data.GetterId, Data.SetterId);
12313  ProcessDeclAttributes(TUScope, NewPD, D);
12314  NewPD->setAccess(AS);
12315
12316  if (NewPD->isInvalidDecl())
12317    Record->setInvalidDecl();
12318
12319  if (D.getDeclSpec().isModulePrivateSpecified())
12320    NewPD->setModulePrivate();
12321
12322  if (NewPD->isInvalidDecl() && PrevDecl) {
12323    // Don't introduce NewFD into scope; there's already something
12324    // with the same name in the same scope.
12325  } else if (II) {
12326    PushOnScopeChains(NewPD, S);
12327  } else
12328    Record->addDecl(NewPD);
12329
12330  return NewPD;
12331}
12332