SemaDeclCXX.cpp revision fbb08b5ec01fbdeb6219fbba0f5edfd95c752233
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/LiteralSupport.h"
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/SmallString.h"
41#include <map>
42#include <set>
43
44using namespace clang;
45
46//===----------------------------------------------------------------------===//
47// CheckDefaultArgumentVisitor
48//===----------------------------------------------------------------------===//
49
50namespace {
51  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
52  /// the default argument of a parameter to determine whether it
53  /// contains any ill-formed subexpressions. For example, this will
54  /// diagnose the use of local variables or parameters within the
55  /// default argument expression.
56  class CheckDefaultArgumentVisitor
57    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
58    Expr *DefaultArg;
59    Sema *S;
60
61  public:
62    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
63      : DefaultArg(defarg), S(s) {}
64
65    bool VisitExpr(Expr *Node);
66    bool VisitDeclRefExpr(DeclRefExpr *DRE);
67    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
68    bool VisitLambdaExpr(LambdaExpr *Lambda);
69    bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
70  };
71
72  /// VisitExpr - Visit all of the children of this expression.
73  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
74    bool IsInvalid = false;
75    for (Stmt::child_range I = Node->children(); I; ++I)
76      IsInvalid |= Visit(*I);
77    return IsInvalid;
78  }
79
80  /// VisitDeclRefExpr - Visit a reference to a declaration, to
81  /// determine whether this declaration can be used in the default
82  /// argument expression.
83  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
84    NamedDecl *Decl = DRE->getDecl();
85    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
86      // C++ [dcl.fct.default]p9
87      //   Default arguments are evaluated each time the function is
88      //   called. The order of evaluation of function arguments is
89      //   unspecified. Consequently, parameters of a function shall not
90      //   be used in default argument expressions, even if they are not
91      //   evaluated. Parameters of a function declared before a default
92      //   argument expression are in scope and can hide namespace and
93      //   class member names.
94      return S->Diag(DRE->getLocStart(),
95                     diag::err_param_default_argument_references_param)
96         << Param->getDeclName() << DefaultArg->getSourceRange();
97    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
98      // C++ [dcl.fct.default]p7
99      //   Local variables shall not be used in default argument
100      //   expressions.
101      if (VDecl->isLocalVarDecl())
102        return S->Diag(DRE->getLocStart(),
103                       diag::err_param_default_argument_references_local)
104          << VDecl->getDeclName() << DefaultArg->getSourceRange();
105    }
106
107    return false;
108  }
109
110  /// VisitCXXThisExpr - Visit a C++ "this" expression.
111  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
112    // C++ [dcl.fct.default]p8:
113    //   The keyword this shall not be used in a default argument of a
114    //   member function.
115    return S->Diag(ThisE->getLocStart(),
116                   diag::err_param_default_argument_references_this)
117               << ThisE->getSourceRange();
118  }
119
120  bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
121    bool Invalid = false;
122    for (PseudoObjectExpr::semantics_iterator
123           i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
124      Expr *E = *i;
125
126      // Look through bindings.
127      if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
128        E = OVE->getSourceExpr();
129        assert(E && "pseudo-object binding without source expression?");
130      }
131
132      Invalid |= Visit(E);
133    }
134    return Invalid;
135  }
136
137  bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
138    // C++11 [expr.lambda.prim]p13:
139    //   A lambda-expression appearing in a default argument shall not
140    //   implicitly or explicitly capture any entity.
141    if (Lambda->capture_begin() == Lambda->capture_end())
142      return false;
143
144    return S->Diag(Lambda->getLocStart(),
145                   diag::err_lambda_capture_default_arg);
146  }
147}
148
149void
150Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
151                                                 const CXXMethodDecl *Method) {
152  // If we have an MSAny spec already, don't bother.
153  if (!Method || ComputedEST == EST_MSAny)
154    return;
155
156  const FunctionProtoType *Proto
157    = Method->getType()->getAs<FunctionProtoType>();
158  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
159  if (!Proto)
160    return;
161
162  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
163
164  // If this function can throw any exceptions, make a note of that.
165  if (EST == EST_MSAny || EST == EST_None) {
166    ClearExceptions();
167    ComputedEST = EST;
168    return;
169  }
170
171  // FIXME: If the call to this decl is using any of its default arguments, we
172  // need to search them for potentially-throwing calls.
173
174  // If this function has a basic noexcept, it doesn't affect the outcome.
175  if (EST == EST_BasicNoexcept)
176    return;
177
178  // If we have a throw-all spec at this point, ignore the function.
179  if (ComputedEST == EST_None)
180    return;
181
182  // If we're still at noexcept(true) and there's a nothrow() callee,
183  // change to that specification.
184  if (EST == EST_DynamicNone) {
185    if (ComputedEST == EST_BasicNoexcept)
186      ComputedEST = EST_DynamicNone;
187    return;
188  }
189
190  // Check out noexcept specs.
191  if (EST == EST_ComputedNoexcept) {
192    FunctionProtoType::NoexceptResult NR =
193        Proto->getNoexceptSpec(Self->Context);
194    assert(NR != FunctionProtoType::NR_NoNoexcept &&
195           "Must have noexcept result for EST_ComputedNoexcept.");
196    assert(NR != FunctionProtoType::NR_Dependent &&
197           "Should not generate implicit declarations for dependent cases, "
198           "and don't know how to handle them anyway.");
199
200    // noexcept(false) -> no spec on the new function
201    if (NR == FunctionProtoType::NR_Throw) {
202      ClearExceptions();
203      ComputedEST = EST_None;
204    }
205    // noexcept(true) won't change anything either.
206    return;
207  }
208
209  assert(EST == EST_Dynamic && "EST case not considered earlier.");
210  assert(ComputedEST != EST_None &&
211         "Shouldn't collect exceptions when throw-all is guaranteed.");
212  ComputedEST = EST_Dynamic;
213  // Record the exceptions in this function's exception specification.
214  for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
215                                          EEnd = Proto->exception_end();
216       E != EEnd; ++E)
217    if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
218      Exceptions.push_back(*E);
219}
220
221void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
222  if (!E || ComputedEST == EST_MSAny)
223    return;
224
225  // FIXME:
226  //
227  // C++0x [except.spec]p14:
228  //   [An] implicit exception-specification specifies the type-id T if and
229  // only if T is allowed by the exception-specification of a function directly
230  // invoked by f's implicit definition; f shall allow all exceptions if any
231  // function it directly invokes allows all exceptions, and f shall allow no
232  // exceptions if every function it directly invokes allows no exceptions.
233  //
234  // Note in particular that if an implicit exception-specification is generated
235  // for a function containing a throw-expression, that specification can still
236  // be noexcept(true).
237  //
238  // Note also that 'directly invoked' is not defined in the standard, and there
239  // is no indication that we should only consider potentially-evaluated calls.
240  //
241  // Ultimately we should implement the intent of the standard: the exception
242  // specification should be the set of exceptions which can be thrown by the
243  // implicit definition. For now, we assume that any non-nothrow expression can
244  // throw any exception.
245
246  if (Self->canThrow(E))
247    ComputedEST = EST_None;
248}
249
250bool
251Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
252                              SourceLocation EqualLoc) {
253  if (RequireCompleteType(Param->getLocation(), Param->getType(),
254                          diag::err_typecheck_decl_incomplete_type)) {
255    Param->setInvalidDecl();
256    return true;
257  }
258
259  // C++ [dcl.fct.default]p5
260  //   A default argument expression is implicitly converted (clause
261  //   4) to the parameter type. The default argument expression has
262  //   the same semantic constraints as the initializer expression in
263  //   a declaration of a variable of the parameter type, using the
264  //   copy-initialization semantics (8.5).
265  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
266                                                                    Param);
267  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
268                                                           EqualLoc);
269  InitializationSequence InitSeq(*this, Entity, Kind, Arg);
270  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
271  if (Result.isInvalid())
272    return true;
273  Arg = Result.takeAs<Expr>();
274
275  CheckCompletedExpr(Arg, EqualLoc);
276  Arg = MaybeCreateExprWithCleanups(Arg);
277
278  // Okay: add the default argument to the parameter
279  Param->setDefaultArg(Arg);
280
281  // We have already instantiated this parameter; provide each of the
282  // instantiations with the uninstantiated default argument.
283  UnparsedDefaultArgInstantiationsMap::iterator InstPos
284    = UnparsedDefaultArgInstantiations.find(Param);
285  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
286    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
287      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
288
289    // We're done tracking this parameter's instantiations.
290    UnparsedDefaultArgInstantiations.erase(InstPos);
291  }
292
293  return false;
294}
295
296/// ActOnParamDefaultArgument - Check whether the default argument
297/// provided for a function parameter is well-formed. If so, attach it
298/// to the parameter declaration.
299void
300Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
301                                Expr *DefaultArg) {
302  if (!param || !DefaultArg)
303    return;
304
305  ParmVarDecl *Param = cast<ParmVarDecl>(param);
306  UnparsedDefaultArgLocs.erase(Param);
307
308  // Default arguments are only permitted in C++
309  if (!getLangOpts().CPlusPlus) {
310    Diag(EqualLoc, diag::err_param_default_argument)
311      << DefaultArg->getSourceRange();
312    Param->setInvalidDecl();
313    return;
314  }
315
316  // Check for unexpanded parameter packs.
317  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
318    Param->setInvalidDecl();
319    return;
320  }
321
322  // Check that the default argument is well-formed
323  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
324  if (DefaultArgChecker.Visit(DefaultArg)) {
325    Param->setInvalidDecl();
326    return;
327  }
328
329  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
330}
331
332/// ActOnParamUnparsedDefaultArgument - We've seen a default
333/// argument for a function parameter, but we can't parse it yet
334/// because we're inside a class definition. Note that this default
335/// argument will be parsed later.
336void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
337                                             SourceLocation EqualLoc,
338                                             SourceLocation ArgLoc) {
339  if (!param)
340    return;
341
342  ParmVarDecl *Param = cast<ParmVarDecl>(param);
343  if (Param)
344    Param->setUnparsedDefaultArg();
345
346  UnparsedDefaultArgLocs[Param] = ArgLoc;
347}
348
349/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
350/// the default argument for the parameter param failed.
351void Sema::ActOnParamDefaultArgumentError(Decl *param) {
352  if (!param)
353    return;
354
355  ParmVarDecl *Param = cast<ParmVarDecl>(param);
356
357  Param->setInvalidDecl();
358
359  UnparsedDefaultArgLocs.erase(Param);
360}
361
362/// CheckExtraCXXDefaultArguments - Check for any extra default
363/// arguments in the declarator, which is not a function declaration
364/// or definition and therefore is not permitted to have default
365/// arguments. This routine should be invoked for every declarator
366/// that is not a function declaration or definition.
367void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
368  // C++ [dcl.fct.default]p3
369  //   A default argument expression shall be specified only in the
370  //   parameter-declaration-clause of a function declaration or in a
371  //   template-parameter (14.1). It shall not be specified for a
372  //   parameter pack. If it is specified in a
373  //   parameter-declaration-clause, it shall not occur within a
374  //   declarator or abstract-declarator of a parameter-declaration.
375  bool MightBeFunction = D.isFunctionDeclarationContext();
376  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
377    DeclaratorChunk &chunk = D.getTypeObject(i);
378    if (chunk.Kind == DeclaratorChunk::Function) {
379      if (MightBeFunction) {
380        // This is a function declaration. It can have default arguments, but
381        // keep looking in case its return type is a function type with default
382        // arguments.
383        MightBeFunction = false;
384        continue;
385      }
386      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
387        ParmVarDecl *Param =
388          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
389        if (Param->hasUnparsedDefaultArg()) {
390          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
391          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
392            << SourceRange((*Toks)[1].getLocation(),
393                           Toks->back().getLocation());
394          delete Toks;
395          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
396        } else if (Param->getDefaultArg()) {
397          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
398            << Param->getDefaultArg()->getSourceRange();
399          Param->setDefaultArg(0);
400        }
401      }
402    } else if (chunk.Kind != DeclaratorChunk::Paren) {
403      MightBeFunction = false;
404    }
405  }
406}
407
408static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
409  for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
410    const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
411    if (!PVD->hasDefaultArg())
412      return false;
413    if (!PVD->hasInheritedDefaultArg())
414      return true;
415  }
416  return false;
417}
418
419/// MergeCXXFunctionDecl - Merge two declarations of the same C++
420/// function, once we already know that they have the same
421/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
422/// error, false otherwise.
423bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
424                                Scope *S) {
425  bool Invalid = false;
426
427  // C++ [dcl.fct.default]p4:
428  //   For non-template functions, default arguments can be added in
429  //   later declarations of a function in the same
430  //   scope. Declarations in different scopes have completely
431  //   distinct sets of default arguments. That is, declarations in
432  //   inner scopes do not acquire default arguments from
433  //   declarations in outer scopes, and vice versa. In a given
434  //   function declaration, all parameters subsequent to a
435  //   parameter with a default argument shall have default
436  //   arguments supplied in this or previous declarations. A
437  //   default argument shall not be redefined by a later
438  //   declaration (not even to the same value).
439  //
440  // C++ [dcl.fct.default]p6:
441  //   Except for member functions of class templates, the default arguments
442  //   in a member function definition that appears outside of the class
443  //   definition are added to the set of default arguments provided by the
444  //   member function declaration in the class definition.
445  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
446    ParmVarDecl *OldParam = Old->getParamDecl(p);
447    ParmVarDecl *NewParam = New->getParamDecl(p);
448
449    bool OldParamHasDfl = OldParam->hasDefaultArg();
450    bool NewParamHasDfl = NewParam->hasDefaultArg();
451
452    NamedDecl *ND = Old;
453    if (S && !isDeclInScope(ND, New->getDeclContext(), S))
454      // Ignore default parameters of old decl if they are not in
455      // the same scope.
456      OldParamHasDfl = false;
457
458    if (OldParamHasDfl && NewParamHasDfl) {
459
460      unsigned DiagDefaultParamID =
461        diag::err_param_default_argument_redefinition;
462
463      // MSVC accepts that default parameters be redefined for member functions
464      // of template class. The new default parameter's value is ignored.
465      Invalid = true;
466      if (getLangOpts().MicrosoftExt) {
467        CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
468        if (MD && MD->getParent()->getDescribedClassTemplate()) {
469          // Merge the old default argument into the new parameter.
470          NewParam->setHasInheritedDefaultArg();
471          if (OldParam->hasUninstantiatedDefaultArg())
472            NewParam->setUninstantiatedDefaultArg(
473                                      OldParam->getUninstantiatedDefaultArg());
474          else
475            NewParam->setDefaultArg(OldParam->getInit());
476          DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
477          Invalid = false;
478        }
479      }
480
481      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
482      // hint here. Alternatively, we could walk the type-source information
483      // for NewParam to find the last source location in the type... but it
484      // isn't worth the effort right now. This is the kind of test case that
485      // is hard to get right:
486      //   int f(int);
487      //   void g(int (*fp)(int) = f);
488      //   void g(int (*fp)(int) = &f);
489      Diag(NewParam->getLocation(), DiagDefaultParamID)
490        << NewParam->getDefaultArgRange();
491
492      // Look for the function declaration where the default argument was
493      // actually written, which may be a declaration prior to Old.
494      for (FunctionDecl *Older = Old->getPreviousDecl();
495           Older; Older = Older->getPreviousDecl()) {
496        if (!Older->getParamDecl(p)->hasDefaultArg())
497          break;
498
499        OldParam = Older->getParamDecl(p);
500      }
501
502      Diag(OldParam->getLocation(), diag::note_previous_definition)
503        << OldParam->getDefaultArgRange();
504    } else if (OldParamHasDfl) {
505      // Merge the old default argument into the new parameter.
506      // It's important to use getInit() here;  getDefaultArg()
507      // strips off any top-level ExprWithCleanups.
508      NewParam->setHasInheritedDefaultArg();
509      if (OldParam->hasUninstantiatedDefaultArg())
510        NewParam->setUninstantiatedDefaultArg(
511                                      OldParam->getUninstantiatedDefaultArg());
512      else
513        NewParam->setDefaultArg(OldParam->getInit());
514    } else if (NewParamHasDfl) {
515      if (New->getDescribedFunctionTemplate()) {
516        // Paragraph 4, quoted above, only applies to non-template functions.
517        Diag(NewParam->getLocation(),
518             diag::err_param_default_argument_template_redecl)
519          << NewParam->getDefaultArgRange();
520        Diag(Old->getLocation(), diag::note_template_prev_declaration)
521          << false;
522      } else if (New->getTemplateSpecializationKind()
523                   != TSK_ImplicitInstantiation &&
524                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
525        // C++ [temp.expr.spec]p21:
526        //   Default function arguments shall not be specified in a declaration
527        //   or a definition for one of the following explicit specializations:
528        //     - the explicit specialization of a function template;
529        //     - the explicit specialization of a member function template;
530        //     - the explicit specialization of a member function of a class
531        //       template where the class template specialization to which the
532        //       member function specialization belongs is implicitly
533        //       instantiated.
534        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
535          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
536          << New->getDeclName()
537          << NewParam->getDefaultArgRange();
538      } else if (New->getDeclContext()->isDependentContext()) {
539        // C++ [dcl.fct.default]p6 (DR217):
540        //   Default arguments for a member function of a class template shall
541        //   be specified on the initial declaration of the member function
542        //   within the class template.
543        //
544        // Reading the tea leaves a bit in DR217 and its reference to DR205
545        // leads me to the conclusion that one cannot add default function
546        // arguments for an out-of-line definition of a member function of a
547        // dependent type.
548        int WhichKind = 2;
549        if (CXXRecordDecl *Record
550              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
551          if (Record->getDescribedClassTemplate())
552            WhichKind = 0;
553          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
554            WhichKind = 1;
555          else
556            WhichKind = 2;
557        }
558
559        Diag(NewParam->getLocation(),
560             diag::err_param_default_argument_member_template_redecl)
561          << WhichKind
562          << NewParam->getDefaultArgRange();
563      }
564    }
565  }
566
567  // DR1344: If a default argument is added outside a class definition and that
568  // default argument makes the function a special member function, the program
569  // is ill-formed. This can only happen for constructors.
570  if (isa<CXXConstructorDecl>(New) &&
571      New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
572    CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
573                     OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
574    if (NewSM != OldSM) {
575      ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
576      assert(NewParam->hasDefaultArg());
577      Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
578        << NewParam->getDefaultArgRange() << NewSM;
579      Diag(Old->getLocation(), diag::note_previous_declaration);
580    }
581  }
582
583  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
584  // template has a constexpr specifier then all its declarations shall
585  // contain the constexpr specifier.
586  if (New->isConstexpr() != Old->isConstexpr()) {
587    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
588      << New << New->isConstexpr();
589    Diag(Old->getLocation(), diag::note_previous_declaration);
590    Invalid = true;
591  }
592
593  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
594  // argument expression, that declaration shall be a definition and shall be
595  // the only declaration of the function or function template in the
596  // translation unit.
597  if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
598      functionDeclHasDefaultArgument(Old)) {
599    Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
600    Diag(Old->getLocation(), diag::note_previous_declaration);
601    Invalid = true;
602  }
603
604  if (CheckEquivalentExceptionSpec(Old, New))
605    Invalid = true;
606
607  return Invalid;
608}
609
610/// \brief Merge the exception specifications of two variable declarations.
611///
612/// This is called when there's a redeclaration of a VarDecl. The function
613/// checks if the redeclaration might have an exception specification and
614/// validates compatibility and merges the specs if necessary.
615void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
616  // Shortcut if exceptions are disabled.
617  if (!getLangOpts().CXXExceptions)
618    return;
619
620  assert(Context.hasSameType(New->getType(), Old->getType()) &&
621         "Should only be called if types are otherwise the same.");
622
623  QualType NewType = New->getType();
624  QualType OldType = Old->getType();
625
626  // We're only interested in pointers and references to functions, as well
627  // as pointers to member functions.
628  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
629    NewType = R->getPointeeType();
630    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
631  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
632    NewType = P->getPointeeType();
633    OldType = OldType->getAs<PointerType>()->getPointeeType();
634  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
635    NewType = M->getPointeeType();
636    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
637  }
638
639  if (!NewType->isFunctionProtoType())
640    return;
641
642  // There's lots of special cases for functions. For function pointers, system
643  // libraries are hopefully not as broken so that we don't need these
644  // workarounds.
645  if (CheckEquivalentExceptionSpec(
646        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
647        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
648    New->setInvalidDecl();
649  }
650}
651
652/// CheckCXXDefaultArguments - Verify that the default arguments for a
653/// function declaration are well-formed according to C++
654/// [dcl.fct.default].
655void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
656  unsigned NumParams = FD->getNumParams();
657  unsigned p;
658
659  // Find first parameter with a default argument
660  for (p = 0; p < NumParams; ++p) {
661    ParmVarDecl *Param = FD->getParamDecl(p);
662    if (Param->hasDefaultArg())
663      break;
664  }
665
666  // C++ [dcl.fct.default]p4:
667  //   In a given function declaration, all parameters
668  //   subsequent to a parameter with a default argument shall
669  //   have default arguments supplied in this or previous
670  //   declarations. A default argument shall not be redefined
671  //   by a later declaration (not even to the same value).
672  unsigned LastMissingDefaultArg = 0;
673  for (; p < NumParams; ++p) {
674    ParmVarDecl *Param = FD->getParamDecl(p);
675    if (!Param->hasDefaultArg()) {
676      if (Param->isInvalidDecl())
677        /* We already complained about this parameter. */;
678      else if (Param->getIdentifier())
679        Diag(Param->getLocation(),
680             diag::err_param_default_argument_missing_name)
681          << Param->getIdentifier();
682      else
683        Diag(Param->getLocation(),
684             diag::err_param_default_argument_missing);
685
686      LastMissingDefaultArg = p;
687    }
688  }
689
690  if (LastMissingDefaultArg > 0) {
691    // Some default arguments were missing. Clear out all of the
692    // default arguments up to (and including) the last missing
693    // default argument, so that we leave the function parameters
694    // in a semantically valid state.
695    for (p = 0; p <= LastMissingDefaultArg; ++p) {
696      ParmVarDecl *Param = FD->getParamDecl(p);
697      if (Param->hasDefaultArg()) {
698        Param->setDefaultArg(0);
699      }
700    }
701  }
702}
703
704// CheckConstexprParameterTypes - Check whether a function's parameter types
705// are all literal types. If so, return true. If not, produce a suitable
706// diagnostic and return false.
707static bool CheckConstexprParameterTypes(Sema &SemaRef,
708                                         const FunctionDecl *FD) {
709  unsigned ArgIndex = 0;
710  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
711  for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
712       e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
713    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
714    SourceLocation ParamLoc = PD->getLocation();
715    if (!(*i)->isDependentType() &&
716        SemaRef.RequireLiteralType(ParamLoc, *i,
717                                   diag::err_constexpr_non_literal_param,
718                                   ArgIndex+1, PD->getSourceRange(),
719                                   isa<CXXConstructorDecl>(FD)))
720      return false;
721  }
722  return true;
723}
724
725/// \brief Get diagnostic %select index for tag kind for
726/// record diagnostic message.
727/// WARNING: Indexes apply to particular diagnostics only!
728///
729/// \returns diagnostic %select index.
730static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
731  switch (Tag) {
732  case TTK_Struct: return 0;
733  case TTK_Interface: return 1;
734  case TTK_Class:  return 2;
735  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
736  }
737}
738
739// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
740// the requirements of a constexpr function definition or a constexpr
741// constructor definition. If so, return true. If not, produce appropriate
742// diagnostics and return false.
743//
744// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
745bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
746  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
747  if (MD && MD->isInstance()) {
748    // C++11 [dcl.constexpr]p4:
749    //  The definition of a constexpr constructor shall satisfy the following
750    //  constraints:
751    //  - the class shall not have any virtual base classes;
752    const CXXRecordDecl *RD = MD->getParent();
753    if (RD->getNumVBases()) {
754      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
755        << isa<CXXConstructorDecl>(NewFD)
756        << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
757      for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
758             E = RD->vbases_end(); I != E; ++I)
759        Diag(I->getLocStart(),
760             diag::note_constexpr_virtual_base_here) << I->getSourceRange();
761      return false;
762    }
763  }
764
765  if (!isa<CXXConstructorDecl>(NewFD)) {
766    // C++11 [dcl.constexpr]p3:
767    //  The definition of a constexpr function shall satisfy the following
768    //  constraints:
769    // - it shall not be virtual;
770    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
771    if (Method && Method->isVirtual()) {
772      Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
773
774      // If it's not obvious why this function is virtual, find an overridden
775      // function which uses the 'virtual' keyword.
776      const CXXMethodDecl *WrittenVirtual = Method;
777      while (!WrittenVirtual->isVirtualAsWritten())
778        WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
779      if (WrittenVirtual != Method)
780        Diag(WrittenVirtual->getLocation(),
781             diag::note_overridden_virtual_function);
782      return false;
783    }
784
785    // - its return type shall be a literal type;
786    QualType RT = NewFD->getResultType();
787    if (!RT->isDependentType() &&
788        RequireLiteralType(NewFD->getLocation(), RT,
789                           diag::err_constexpr_non_literal_return))
790      return false;
791  }
792
793  // - each of its parameter types shall be a literal type;
794  if (!CheckConstexprParameterTypes(*this, NewFD))
795    return false;
796
797  return true;
798}
799
800/// Check the given declaration statement is legal within a constexpr function
801/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
802///
803/// \return true if the body is OK (maybe only as an extension), false if we
804///         have diagnosed a problem.
805static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
806                                   DeclStmt *DS, SourceLocation &Cxx1yLoc) {
807  // C++11 [dcl.constexpr]p3 and p4:
808  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
809  //  contain only
810  for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
811         DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
812    switch ((*DclIt)->getKind()) {
813    case Decl::StaticAssert:
814    case Decl::Using:
815    case Decl::UsingShadow:
816    case Decl::UsingDirective:
817    case Decl::UnresolvedUsingTypename:
818    case Decl::UnresolvedUsingValue:
819      //   - static_assert-declarations
820      //   - using-declarations,
821      //   - using-directives,
822      continue;
823
824    case Decl::Typedef:
825    case Decl::TypeAlias: {
826      //   - typedef declarations and alias-declarations that do not define
827      //     classes or enumerations,
828      TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
829      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
830        // Don't allow variably-modified types in constexpr functions.
831        TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
832        SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
833          << TL.getSourceRange() << TL.getType()
834          << isa<CXXConstructorDecl>(Dcl);
835        return false;
836      }
837      continue;
838    }
839
840    case Decl::Enum:
841    case Decl::CXXRecord:
842      // C++1y allows types to be defined, not just declared.
843      if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
844        SemaRef.Diag(DS->getLocStart(),
845                     SemaRef.getLangOpts().CPlusPlus1y
846                       ? diag::warn_cxx11_compat_constexpr_type_definition
847                       : diag::ext_constexpr_type_definition)
848          << isa<CXXConstructorDecl>(Dcl);
849      continue;
850
851    case Decl::EnumConstant:
852    case Decl::IndirectField:
853    case Decl::ParmVar:
854      // These can only appear with other declarations which are banned in
855      // C++11 and permitted in C++1y, so ignore them.
856      continue;
857
858    case Decl::Var: {
859      // C++1y [dcl.constexpr]p3 allows anything except:
860      //   a definition of a variable of non-literal type or of static or
861      //   thread storage duration or for which no initialization is performed.
862      VarDecl *VD = cast<VarDecl>(*DclIt);
863      if (VD->isThisDeclarationADefinition()) {
864        if (VD->isStaticLocal()) {
865          SemaRef.Diag(VD->getLocation(),
866                       diag::err_constexpr_local_var_static)
867            << isa<CXXConstructorDecl>(Dcl)
868            << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
869          return false;
870        }
871        if (!VD->getType()->isDependentType() &&
872            SemaRef.RequireLiteralType(
873              VD->getLocation(), VD->getType(),
874              diag::err_constexpr_local_var_non_literal_type,
875              isa<CXXConstructorDecl>(Dcl)))
876          return false;
877        if (!VD->hasInit()) {
878          SemaRef.Diag(VD->getLocation(),
879                       diag::err_constexpr_local_var_no_init)
880            << isa<CXXConstructorDecl>(Dcl);
881          return false;
882        }
883      }
884      SemaRef.Diag(VD->getLocation(),
885                   SemaRef.getLangOpts().CPlusPlus1y
886                    ? diag::warn_cxx11_compat_constexpr_local_var
887                    : diag::ext_constexpr_local_var)
888        << isa<CXXConstructorDecl>(Dcl);
889      continue;
890    }
891
892    case Decl::NamespaceAlias:
893    case Decl::Function:
894      // These are disallowed in C++11 and permitted in C++1y. Allow them
895      // everywhere as an extension.
896      if (!Cxx1yLoc.isValid())
897        Cxx1yLoc = DS->getLocStart();
898      continue;
899
900    default:
901      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
902        << isa<CXXConstructorDecl>(Dcl);
903      return false;
904    }
905  }
906
907  return true;
908}
909
910/// Check that the given field is initialized within a constexpr constructor.
911///
912/// \param Dcl The constexpr constructor being checked.
913/// \param Field The field being checked. This may be a member of an anonymous
914///        struct or union nested within the class being checked.
915/// \param Inits All declarations, including anonymous struct/union members and
916///        indirect members, for which any initialization was provided.
917/// \param Diagnosed Set to true if an error is produced.
918static void CheckConstexprCtorInitializer(Sema &SemaRef,
919                                          const FunctionDecl *Dcl,
920                                          FieldDecl *Field,
921                                          llvm::SmallSet<Decl*, 16> &Inits,
922                                          bool &Diagnosed) {
923  if (Field->isInvalidDecl())
924    return;
925
926  if (Field->isUnnamedBitfield())
927    return;
928
929  if (Field->isAnonymousStructOrUnion() &&
930      Field->getType()->getAsCXXRecordDecl()->isEmpty())
931    return;
932
933  if (!Inits.count(Field)) {
934    if (!Diagnosed) {
935      SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
936      Diagnosed = true;
937    }
938    SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
939  } else if (Field->isAnonymousStructOrUnion()) {
940    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
941    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
942         I != E; ++I)
943      // If an anonymous union contains an anonymous struct of which any member
944      // is initialized, all members must be initialized.
945      if (!RD->isUnion() || Inits.count(*I))
946        CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
947  }
948}
949
950/// Check the provided statement is allowed in a constexpr function
951/// definition.
952static bool
953CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
954                           SmallVectorImpl<SourceLocation> &ReturnStmts,
955                           SourceLocation &Cxx1yLoc) {
956  // - its function-body shall be [...] a compound-statement that contains only
957  switch (S->getStmtClass()) {
958  case Stmt::NullStmtClass:
959    //   - null statements,
960    return true;
961
962  case Stmt::DeclStmtClass:
963    //   - static_assert-declarations
964    //   - using-declarations,
965    //   - using-directives,
966    //   - typedef declarations and alias-declarations that do not define
967    //     classes or enumerations,
968    if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
969      return false;
970    return true;
971
972  case Stmt::ReturnStmtClass:
973    //   - and exactly one return statement;
974    if (isa<CXXConstructorDecl>(Dcl)) {
975      // C++1y allows return statements in constexpr constructors.
976      if (!Cxx1yLoc.isValid())
977        Cxx1yLoc = S->getLocStart();
978      return true;
979    }
980
981    ReturnStmts.push_back(S->getLocStart());
982    return true;
983
984  case Stmt::CompoundStmtClass: {
985    // C++1y allows compound-statements.
986    if (!Cxx1yLoc.isValid())
987      Cxx1yLoc = S->getLocStart();
988
989    CompoundStmt *CompStmt = cast<CompoundStmt>(S);
990    for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
991           BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
992      if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
993                                      Cxx1yLoc))
994        return false;
995    }
996    return true;
997  }
998
999  case Stmt::AttributedStmtClass:
1000    if (!Cxx1yLoc.isValid())
1001      Cxx1yLoc = S->getLocStart();
1002    return true;
1003
1004  case Stmt::IfStmtClass: {
1005    // C++1y allows if-statements.
1006    if (!Cxx1yLoc.isValid())
1007      Cxx1yLoc = S->getLocStart();
1008
1009    IfStmt *If = cast<IfStmt>(S);
1010    if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1011                                    Cxx1yLoc))
1012      return false;
1013    if (If->getElse() &&
1014        !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1015                                    Cxx1yLoc))
1016      return false;
1017    return true;
1018  }
1019
1020  case Stmt::WhileStmtClass:
1021  case Stmt::DoStmtClass:
1022  case Stmt::ForStmtClass:
1023  case Stmt::CXXForRangeStmtClass:
1024  case Stmt::ContinueStmtClass:
1025    // C++1y allows all of these. We don't allow them as extensions in C++11,
1026    // because they don't make sense without variable mutation.
1027    if (!SemaRef.getLangOpts().CPlusPlus1y)
1028      break;
1029    if (!Cxx1yLoc.isValid())
1030      Cxx1yLoc = S->getLocStart();
1031    for (Stmt::child_range Children = S->children(); Children; ++Children)
1032      if (*Children &&
1033          !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1034                                      Cxx1yLoc))
1035        return false;
1036    return true;
1037
1038  case Stmt::SwitchStmtClass:
1039  case Stmt::CaseStmtClass:
1040  case Stmt::DefaultStmtClass:
1041  case Stmt::BreakStmtClass:
1042    // C++1y allows switch-statements, and since they don't need variable
1043    // mutation, we can reasonably allow them in C++11 as an extension.
1044    if (!Cxx1yLoc.isValid())
1045      Cxx1yLoc = S->getLocStart();
1046    for (Stmt::child_range Children = S->children(); Children; ++Children)
1047      if (*Children &&
1048          !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1049                                      Cxx1yLoc))
1050        return false;
1051    return true;
1052
1053  default:
1054    if (!isa<Expr>(S))
1055      break;
1056
1057    // C++1y allows expression-statements.
1058    if (!Cxx1yLoc.isValid())
1059      Cxx1yLoc = S->getLocStart();
1060    return true;
1061  }
1062
1063  SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1064    << isa<CXXConstructorDecl>(Dcl);
1065  return false;
1066}
1067
1068/// Check the body for the given constexpr function declaration only contains
1069/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1070///
1071/// \return true if the body is OK, false if we have diagnosed a problem.
1072bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1073  if (isa<CXXTryStmt>(Body)) {
1074    // C++11 [dcl.constexpr]p3:
1075    //  The definition of a constexpr function shall satisfy the following
1076    //  constraints: [...]
1077    // - its function-body shall be = delete, = default, or a
1078    //   compound-statement
1079    //
1080    // C++11 [dcl.constexpr]p4:
1081    //  In the definition of a constexpr constructor, [...]
1082    // - its function-body shall not be a function-try-block;
1083    Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1084      << isa<CXXConstructorDecl>(Dcl);
1085    return false;
1086  }
1087
1088  SmallVector<SourceLocation, 4> ReturnStmts;
1089
1090  // - its function-body shall be [...] a compound-statement that contains only
1091  //   [... list of cases ...]
1092  CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1093  SourceLocation Cxx1yLoc;
1094  for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1095         BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
1096    if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1097      return false;
1098  }
1099
1100  if (Cxx1yLoc.isValid())
1101    Diag(Cxx1yLoc,
1102         getLangOpts().CPlusPlus1y
1103           ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1104           : diag::ext_constexpr_body_invalid_stmt)
1105      << isa<CXXConstructorDecl>(Dcl);
1106
1107  if (const CXXConstructorDecl *Constructor
1108        = dyn_cast<CXXConstructorDecl>(Dcl)) {
1109    const CXXRecordDecl *RD = Constructor->getParent();
1110    // DR1359:
1111    // - every non-variant non-static data member and base class sub-object
1112    //   shall be initialized;
1113    // - if the class is a non-empty union, or for each non-empty anonymous
1114    //   union member of a non-union class, exactly one non-static data member
1115    //   shall be initialized;
1116    if (RD->isUnion()) {
1117      if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
1118        Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1119        return false;
1120      }
1121    } else if (!Constructor->isDependentContext() &&
1122               !Constructor->isDelegatingConstructor()) {
1123      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1124
1125      // Skip detailed checking if we have enough initializers, and we would
1126      // allow at most one initializer per member.
1127      bool AnyAnonStructUnionMembers = false;
1128      unsigned Fields = 0;
1129      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1130           E = RD->field_end(); I != E; ++I, ++Fields) {
1131        if (I->isAnonymousStructOrUnion()) {
1132          AnyAnonStructUnionMembers = true;
1133          break;
1134        }
1135      }
1136      if (AnyAnonStructUnionMembers ||
1137          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1138        // Check initialization of non-static data members. Base classes are
1139        // always initialized so do not need to be checked. Dependent bases
1140        // might not have initializers in the member initializer list.
1141        llvm::SmallSet<Decl*, 16> Inits;
1142        for (CXXConstructorDecl::init_const_iterator
1143               I = Constructor->init_begin(), E = Constructor->init_end();
1144             I != E; ++I) {
1145          if (FieldDecl *FD = (*I)->getMember())
1146            Inits.insert(FD);
1147          else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1148            Inits.insert(ID->chain_begin(), ID->chain_end());
1149        }
1150
1151        bool Diagnosed = false;
1152        for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1153             E = RD->field_end(); I != E; ++I)
1154          CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
1155        if (Diagnosed)
1156          return false;
1157      }
1158    }
1159  } else {
1160    if (ReturnStmts.empty()) {
1161      // C++1y doesn't require constexpr functions to contain a 'return'
1162      // statement. We still do, unless the return type is void, because
1163      // otherwise if there's no return statement, the function cannot
1164      // be used in a core constant expression.
1165      bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
1166      Diag(Dcl->getLocation(),
1167           OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1168              : diag::err_constexpr_body_no_return);
1169      return OK;
1170    }
1171    if (ReturnStmts.size() > 1) {
1172      Diag(ReturnStmts.back(),
1173           getLangOpts().CPlusPlus1y
1174             ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1175             : diag::ext_constexpr_body_multiple_return);
1176      for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1177        Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1178    }
1179  }
1180
1181  // C++11 [dcl.constexpr]p5:
1182  //   if no function argument values exist such that the function invocation
1183  //   substitution would produce a constant expression, the program is
1184  //   ill-formed; no diagnostic required.
1185  // C++11 [dcl.constexpr]p3:
1186  //   - every constructor call and implicit conversion used in initializing the
1187  //     return value shall be one of those allowed in a constant expression.
1188  // C++11 [dcl.constexpr]p4:
1189  //   - every constructor involved in initializing non-static data members and
1190  //     base class sub-objects shall be a constexpr constructor.
1191  SmallVector<PartialDiagnosticAt, 8> Diags;
1192  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1193    Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1194      << isa<CXXConstructorDecl>(Dcl);
1195    for (size_t I = 0, N = Diags.size(); I != N; ++I)
1196      Diag(Diags[I].first, Diags[I].second);
1197    // Don't return false here: we allow this for compatibility in
1198    // system headers.
1199  }
1200
1201  return true;
1202}
1203
1204/// isCurrentClassName - Determine whether the identifier II is the
1205/// name of the class type currently being defined. In the case of
1206/// nested classes, this will only return true if II is the name of
1207/// the innermost class.
1208bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1209                              const CXXScopeSpec *SS) {
1210  assert(getLangOpts().CPlusPlus && "No class names in C!");
1211
1212  CXXRecordDecl *CurDecl;
1213  if (SS && SS->isSet() && !SS->isInvalid()) {
1214    DeclContext *DC = computeDeclContext(*SS, true);
1215    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1216  } else
1217    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1218
1219  if (CurDecl && CurDecl->getIdentifier())
1220    return &II == CurDecl->getIdentifier();
1221  return false;
1222}
1223
1224/// \brief Determine whether the given class is a base class of the given
1225/// class, including looking at dependent bases.
1226static bool findCircularInheritance(const CXXRecordDecl *Class,
1227                                    const CXXRecordDecl *Current) {
1228  SmallVector<const CXXRecordDecl*, 8> Queue;
1229
1230  Class = Class->getCanonicalDecl();
1231  while (true) {
1232    for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1233                                                  E = Current->bases_end();
1234         I != E; ++I) {
1235      CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1236      if (!Base)
1237        continue;
1238
1239      Base = Base->getDefinition();
1240      if (!Base)
1241        continue;
1242
1243      if (Base->getCanonicalDecl() == Class)
1244        return true;
1245
1246      Queue.push_back(Base);
1247    }
1248
1249    if (Queue.empty())
1250      return false;
1251
1252    Current = Queue.pop_back_val();
1253  }
1254
1255  return false;
1256}
1257
1258/// \brief Check the validity of a C++ base class specifier.
1259///
1260/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1261/// and returns NULL otherwise.
1262CXXBaseSpecifier *
1263Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1264                         SourceRange SpecifierRange,
1265                         bool Virtual, AccessSpecifier Access,
1266                         TypeSourceInfo *TInfo,
1267                         SourceLocation EllipsisLoc) {
1268  QualType BaseType = TInfo->getType();
1269
1270  // C++ [class.union]p1:
1271  //   A union shall not have base classes.
1272  if (Class->isUnion()) {
1273    Diag(Class->getLocation(), diag::err_base_clause_on_union)
1274      << SpecifierRange;
1275    return 0;
1276  }
1277
1278  if (EllipsisLoc.isValid() &&
1279      !TInfo->getType()->containsUnexpandedParameterPack()) {
1280    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1281      << TInfo->getTypeLoc().getSourceRange();
1282    EllipsisLoc = SourceLocation();
1283  }
1284
1285  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1286
1287  if (BaseType->isDependentType()) {
1288    // Make sure that we don't have circular inheritance among our dependent
1289    // bases. For non-dependent bases, the check for completeness below handles
1290    // this.
1291    if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1292      if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1293          ((BaseDecl = BaseDecl->getDefinition()) &&
1294           findCircularInheritance(Class, BaseDecl))) {
1295        Diag(BaseLoc, diag::err_circular_inheritance)
1296          << BaseType << Context.getTypeDeclType(Class);
1297
1298        if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1299          Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1300            << BaseType;
1301
1302        return 0;
1303      }
1304    }
1305
1306    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1307                                          Class->getTagKind() == TTK_Class,
1308                                          Access, TInfo, EllipsisLoc);
1309  }
1310
1311  // Base specifiers must be record types.
1312  if (!BaseType->isRecordType()) {
1313    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1314    return 0;
1315  }
1316
1317  // C++ [class.union]p1:
1318  //   A union shall not be used as a base class.
1319  if (BaseType->isUnionType()) {
1320    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1321    return 0;
1322  }
1323
1324  // C++ [class.derived]p2:
1325  //   The class-name in a base-specifier shall not be an incompletely
1326  //   defined class.
1327  if (RequireCompleteType(BaseLoc, BaseType,
1328                          diag::err_incomplete_base_class, SpecifierRange)) {
1329    Class->setInvalidDecl();
1330    return 0;
1331  }
1332
1333  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1334  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1335  assert(BaseDecl && "Record type has no declaration");
1336  BaseDecl = BaseDecl->getDefinition();
1337  assert(BaseDecl && "Base type is not incomplete, but has no definition");
1338  CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1339  assert(CXXBaseDecl && "Base type is not a C++ type");
1340
1341  // C++ [class]p3:
1342  //   If a class is marked final and it appears as a base-type-specifier in
1343  //   base-clause, the program is ill-formed.
1344  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1345    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1346      << CXXBaseDecl->getDeclName();
1347    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1348      << CXXBaseDecl->getDeclName();
1349    return 0;
1350  }
1351
1352  if (BaseDecl->isInvalidDecl())
1353    Class->setInvalidDecl();
1354
1355  // Create the base specifier.
1356  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1357                                        Class->getTagKind() == TTK_Class,
1358                                        Access, TInfo, EllipsisLoc);
1359}
1360
1361/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1362/// one entry in the base class list of a class specifier, for
1363/// example:
1364///    class foo : public bar, virtual private baz {
1365/// 'public bar' and 'virtual private baz' are each base-specifiers.
1366BaseResult
1367Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1368                         ParsedAttributes &Attributes,
1369                         bool Virtual, AccessSpecifier Access,
1370                         ParsedType basetype, SourceLocation BaseLoc,
1371                         SourceLocation EllipsisLoc) {
1372  if (!classdecl)
1373    return true;
1374
1375  AdjustDeclIfTemplate(classdecl);
1376  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1377  if (!Class)
1378    return true;
1379
1380  // We do not support any C++11 attributes on base-specifiers yet.
1381  // Diagnose any attributes we see.
1382  if (!Attributes.empty()) {
1383    for (AttributeList *Attr = Attributes.getList(); Attr;
1384         Attr = Attr->getNext()) {
1385      if (Attr->isInvalid() ||
1386          Attr->getKind() == AttributeList::IgnoredAttribute)
1387        continue;
1388      Diag(Attr->getLoc(),
1389           Attr->getKind() == AttributeList::UnknownAttribute
1390             ? diag::warn_unknown_attribute_ignored
1391             : diag::err_base_specifier_attribute)
1392        << Attr->getName();
1393    }
1394  }
1395
1396  TypeSourceInfo *TInfo = 0;
1397  GetTypeFromParser(basetype, &TInfo);
1398
1399  if (EllipsisLoc.isInvalid() &&
1400      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1401                                      UPPC_BaseType))
1402    return true;
1403
1404  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1405                                                      Virtual, Access, TInfo,
1406                                                      EllipsisLoc))
1407    return BaseSpec;
1408  else
1409    Class->setInvalidDecl();
1410
1411  return true;
1412}
1413
1414/// \brief Performs the actual work of attaching the given base class
1415/// specifiers to a C++ class.
1416bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1417                                unsigned NumBases) {
1418 if (NumBases == 0)
1419    return false;
1420
1421  // Used to keep track of which base types we have already seen, so
1422  // that we can properly diagnose redundant direct base types. Note
1423  // that the key is always the unqualified canonical type of the base
1424  // class.
1425  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1426
1427  // Copy non-redundant base specifiers into permanent storage.
1428  unsigned NumGoodBases = 0;
1429  bool Invalid = false;
1430  for (unsigned idx = 0; idx < NumBases; ++idx) {
1431    QualType NewBaseType
1432      = Context.getCanonicalType(Bases[idx]->getType());
1433    NewBaseType = NewBaseType.getLocalUnqualifiedType();
1434
1435    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1436    if (KnownBase) {
1437      // C++ [class.mi]p3:
1438      //   A class shall not be specified as a direct base class of a
1439      //   derived class more than once.
1440      Diag(Bases[idx]->getLocStart(),
1441           diag::err_duplicate_base_class)
1442        << KnownBase->getType()
1443        << Bases[idx]->getSourceRange();
1444
1445      // Delete the duplicate base class specifier; we're going to
1446      // overwrite its pointer later.
1447      Context.Deallocate(Bases[idx]);
1448
1449      Invalid = true;
1450    } else {
1451      // Okay, add this new base class.
1452      KnownBase = Bases[idx];
1453      Bases[NumGoodBases++] = Bases[idx];
1454      if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1455        const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1456        if (Class->isInterface() &&
1457              (!RD->isInterface() ||
1458               KnownBase->getAccessSpecifier() != AS_public)) {
1459          // The Microsoft extension __interface does not permit bases that
1460          // are not themselves public interfaces.
1461          Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1462            << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1463            << RD->getSourceRange();
1464          Invalid = true;
1465        }
1466        if (RD->hasAttr<WeakAttr>())
1467          Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1468      }
1469    }
1470  }
1471
1472  // Attach the remaining base class specifiers to the derived class.
1473  Class->setBases(Bases, NumGoodBases);
1474
1475  // Delete the remaining (good) base class specifiers, since their
1476  // data has been copied into the CXXRecordDecl.
1477  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1478    Context.Deallocate(Bases[idx]);
1479
1480  return Invalid;
1481}
1482
1483/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1484/// class, after checking whether there are any duplicate base
1485/// classes.
1486void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1487                               unsigned NumBases) {
1488  if (!ClassDecl || !Bases || !NumBases)
1489    return;
1490
1491  AdjustDeclIfTemplate(ClassDecl);
1492  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
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) {
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  // If either the base or the derived type is invalid, don't try to
1510  // check whether one is derived from the other.
1511  if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1512    return false;
1513
1514  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1515  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1516}
1517
1518/// \brief Determine whether the type \p Derived is a C++ class that is
1519/// derived from the type \p Base.
1520bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1521  if (!getLangOpts().CPlusPlus)
1522    return false;
1523
1524  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1525  if (!DerivedRD)
1526    return false;
1527
1528  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1529  if (!BaseRD)
1530    return false;
1531
1532  return DerivedRD->isDerivedFrom(BaseRD, Paths);
1533}
1534
1535void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1536                              CXXCastPath &BasePathArray) {
1537  assert(BasePathArray.empty() && "Base path array must be empty!");
1538  assert(Paths.isRecordingPaths() && "Must record paths!");
1539
1540  const CXXBasePath &Path = Paths.front();
1541
1542  // We first go backward and check if we have a virtual base.
1543  // FIXME: It would be better if CXXBasePath had the base specifier for
1544  // the nearest virtual base.
1545  unsigned Start = 0;
1546  for (unsigned I = Path.size(); I != 0; --I) {
1547    if (Path[I - 1].Base->isVirtual()) {
1548      Start = I - 1;
1549      break;
1550    }
1551  }
1552
1553  // Now add all bases.
1554  for (unsigned I = Start, E = Path.size(); I != E; ++I)
1555    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1556}
1557
1558/// \brief Determine whether the given base path includes a virtual
1559/// base class.
1560bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1561  for (CXXCastPath::const_iterator B = BasePath.begin(),
1562                                BEnd = BasePath.end();
1563       B != BEnd; ++B)
1564    if ((*B)->isVirtual())
1565      return true;
1566
1567  return false;
1568}
1569
1570/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1571/// conversion (where Derived and Base are class types) is
1572/// well-formed, meaning that the conversion is unambiguous (and
1573/// that all of the base classes are accessible). Returns true
1574/// and emits a diagnostic if the code is ill-formed, returns false
1575/// otherwise. Loc is the location where this routine should point to
1576/// if there is an error, and Range is the source range to highlight
1577/// if there is an error.
1578bool
1579Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1580                                   unsigned InaccessibleBaseID,
1581                                   unsigned AmbigiousBaseConvID,
1582                                   SourceLocation Loc, SourceRange Range,
1583                                   DeclarationName Name,
1584                                   CXXCastPath *BasePath) {
1585  // First, determine whether the path from Derived to Base is
1586  // ambiguous. This is slightly more expensive than checking whether
1587  // the Derived to Base conversion exists, because here we need to
1588  // explore multiple paths to determine if there is an ambiguity.
1589  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1590                     /*DetectVirtual=*/false);
1591  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1592  assert(DerivationOkay &&
1593         "Can only be used with a derived-to-base conversion");
1594  (void)DerivationOkay;
1595
1596  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1597    if (InaccessibleBaseID) {
1598      // Check that the base class can be accessed.
1599      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1600                                   InaccessibleBaseID)) {
1601        case AR_inaccessible:
1602          return true;
1603        case AR_accessible:
1604        case AR_dependent:
1605        case AR_delayed:
1606          break;
1607      }
1608    }
1609
1610    // Build a base path if necessary.
1611    if (BasePath)
1612      BuildBasePathArray(Paths, *BasePath);
1613    return false;
1614  }
1615
1616  if (AmbigiousBaseConvID) {
1617    // We know that the derived-to-base conversion is ambiguous, and
1618    // we're going to produce a diagnostic. Perform the derived-to-base
1619    // search just one more time to compute all of the possible paths so
1620    // that we can print them out. This is more expensive than any of
1621    // the previous derived-to-base checks we've done, but at this point
1622    // performance isn't as much of an issue.
1623    Paths.clear();
1624    Paths.setRecordingPaths(true);
1625    bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1626    assert(StillOkay && "Can only be used with a derived-to-base conversion");
1627    (void)StillOkay;
1628
1629    // Build up a textual representation of the ambiguous paths, e.g.,
1630    // D -> B -> A, that will be used to illustrate the ambiguous
1631    // conversions in the diagnostic. We only print one of the paths
1632    // to each base class subobject.
1633    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1634
1635    Diag(Loc, AmbigiousBaseConvID)
1636    << Derived << Base << PathDisplayStr << Range << Name;
1637  }
1638  return true;
1639}
1640
1641bool
1642Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1643                                   SourceLocation Loc, SourceRange Range,
1644                                   CXXCastPath *BasePath,
1645                                   bool IgnoreAccess) {
1646  return CheckDerivedToBaseConversion(Derived, Base,
1647                                      IgnoreAccess ? 0
1648                                       : diag::err_upcast_to_inaccessible_base,
1649                                      diag::err_ambiguous_derived_to_base_conv,
1650                                      Loc, Range, DeclarationName(),
1651                                      BasePath);
1652}
1653
1654
1655/// @brief Builds a string representing ambiguous paths from a
1656/// specific derived class to different subobjects of the same base
1657/// class.
1658///
1659/// This function builds a string that can be used in error messages
1660/// to show the different paths that one can take through the
1661/// inheritance hierarchy to go from the derived class to different
1662/// subobjects of a base class. The result looks something like this:
1663/// @code
1664/// struct D -> struct B -> struct A
1665/// struct D -> struct C -> struct A
1666/// @endcode
1667std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1668  std::string PathDisplayStr;
1669  std::set<unsigned> DisplayedPaths;
1670  for (CXXBasePaths::paths_iterator Path = Paths.begin();
1671       Path != Paths.end(); ++Path) {
1672    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1673      // We haven't displayed a path to this particular base
1674      // class subobject yet.
1675      PathDisplayStr += "\n    ";
1676      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1677      for (CXXBasePath::const_iterator Element = Path->begin();
1678           Element != Path->end(); ++Element)
1679        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1680    }
1681  }
1682
1683  return PathDisplayStr;
1684}
1685
1686//===----------------------------------------------------------------------===//
1687// C++ class member Handling
1688//===----------------------------------------------------------------------===//
1689
1690/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1691bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1692                                SourceLocation ASLoc,
1693                                SourceLocation ColonLoc,
1694                                AttributeList *Attrs) {
1695  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1696  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1697                                                  ASLoc, ColonLoc);
1698  CurContext->addHiddenDecl(ASDecl);
1699  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1700}
1701
1702/// CheckOverrideControl - Check C++11 override control semantics.
1703void Sema::CheckOverrideControl(NamedDecl *D) {
1704  if (D->isInvalidDecl())
1705    return;
1706
1707  // We only care about "override" and "final" declarations.
1708  if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1709    return;
1710
1711  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1712
1713  // We can't check dependent instance methods.
1714  if (MD && MD->isInstance() &&
1715      (MD->getParent()->hasAnyDependentBases() ||
1716       MD->getType()->isDependentType()))
1717    return;
1718
1719  if (MD && !MD->isVirtual()) {
1720    // If we have a non-virtual method, check if if hides a virtual method.
1721    // (In that case, it's most likely the method has the wrong type.)
1722    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1723    FindHiddenVirtualMethods(MD, OverloadedMethods);
1724
1725    if (!OverloadedMethods.empty()) {
1726      if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1727        Diag(OA->getLocation(),
1728             diag::override_keyword_hides_virtual_member_function)
1729          << "override" << (OverloadedMethods.size() > 1);
1730      } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1731        Diag(FA->getLocation(),
1732             diag::override_keyword_hides_virtual_member_function)
1733            << "final" << (OverloadedMethods.size() > 1);
1734      }
1735      NoteHiddenVirtualMethods(MD, OverloadedMethods);
1736      MD->setInvalidDecl();
1737      return;
1738    }
1739    // Fall through into the general case diagnostic.
1740    // FIXME: We might want to attempt typo correction here.
1741  }
1742
1743  if (!MD || !MD->isVirtual()) {
1744    if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1745      Diag(OA->getLocation(),
1746           diag::override_keyword_only_allowed_on_virtual_member_functions)
1747        << "override" << FixItHint::CreateRemoval(OA->getLocation());
1748      D->dropAttr<OverrideAttr>();
1749    }
1750    if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1751      Diag(FA->getLocation(),
1752           diag::override_keyword_only_allowed_on_virtual_member_functions)
1753        << "final" << FixItHint::CreateRemoval(FA->getLocation());
1754      D->dropAttr<FinalAttr>();
1755    }
1756    return;
1757  }
1758
1759  // C++11 [class.virtual]p5:
1760  //   If a virtual function is marked with the virt-specifier override and
1761  //   does not override a member function of a base class, the program is
1762  //   ill-formed.
1763  bool HasOverriddenMethods =
1764    MD->begin_overridden_methods() != MD->end_overridden_methods();
1765  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1766    Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1767      << MD->getDeclName();
1768}
1769
1770/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1771/// function overrides a virtual member function marked 'final', according to
1772/// C++11 [class.virtual]p4.
1773bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1774                                                  const CXXMethodDecl *Old) {
1775  if (!Old->hasAttr<FinalAttr>())
1776    return false;
1777
1778  Diag(New->getLocation(), diag::err_final_function_overridden)
1779    << New->getDeclName();
1780  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1781  return true;
1782}
1783
1784static bool InitializationHasSideEffects(const FieldDecl &FD) {
1785  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1786  // FIXME: Destruction of ObjC lifetime types has side-effects.
1787  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1788    return !RD->isCompleteDefinition() ||
1789           !RD->hasTrivialDefaultConstructor() ||
1790           !RD->hasTrivialDestructor();
1791  return false;
1792}
1793
1794static AttributeList *getMSPropertyAttr(AttributeList *list) {
1795  for (AttributeList* it = list; it != 0; it = it->getNext())
1796    if (it->isDeclspecPropertyAttribute())
1797      return it;
1798  return 0;
1799}
1800
1801/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1802/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1803/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1804/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1805/// present (but parsing it has been deferred).
1806NamedDecl *
1807Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1808                               MultiTemplateParamsArg TemplateParameterLists,
1809                               Expr *BW, const VirtSpecifiers &VS,
1810                               InClassInitStyle InitStyle) {
1811  const DeclSpec &DS = D.getDeclSpec();
1812  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1813  DeclarationName Name = NameInfo.getName();
1814  SourceLocation Loc = NameInfo.getLoc();
1815
1816  // For anonymous bitfields, the location should point to the type.
1817  if (Loc.isInvalid())
1818    Loc = D.getLocStart();
1819
1820  Expr *BitWidth = static_cast<Expr*>(BW);
1821
1822  assert(isa<CXXRecordDecl>(CurContext));
1823  assert(!DS.isFriendSpecified());
1824
1825  bool isFunc = D.isDeclarationOfFunction();
1826
1827  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1828    // The Microsoft extension __interface only permits public member functions
1829    // and prohibits constructors, destructors, operators, non-public member
1830    // functions, static methods and data members.
1831    unsigned InvalidDecl;
1832    bool ShowDeclName = true;
1833    if (!isFunc)
1834      InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1835    else if (AS != AS_public)
1836      InvalidDecl = 2;
1837    else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1838      InvalidDecl = 3;
1839    else switch (Name.getNameKind()) {
1840      case DeclarationName::CXXConstructorName:
1841        InvalidDecl = 4;
1842        ShowDeclName = false;
1843        break;
1844
1845      case DeclarationName::CXXDestructorName:
1846        InvalidDecl = 5;
1847        ShowDeclName = false;
1848        break;
1849
1850      case DeclarationName::CXXOperatorName:
1851      case DeclarationName::CXXConversionFunctionName:
1852        InvalidDecl = 6;
1853        break;
1854
1855      default:
1856        InvalidDecl = 0;
1857        break;
1858    }
1859
1860    if (InvalidDecl) {
1861      if (ShowDeclName)
1862        Diag(Loc, diag::err_invalid_member_in_interface)
1863          << (InvalidDecl-1) << Name;
1864      else
1865        Diag(Loc, diag::err_invalid_member_in_interface)
1866          << (InvalidDecl-1) << "";
1867      return 0;
1868    }
1869  }
1870
1871  // C++ 9.2p6: A member shall not be declared to have automatic storage
1872  // duration (auto, register) or with the extern storage-class-specifier.
1873  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1874  // data members and cannot be applied to names declared const or static,
1875  // and cannot be applied to reference members.
1876  switch (DS.getStorageClassSpec()) {
1877  case DeclSpec::SCS_unspecified:
1878  case DeclSpec::SCS_typedef:
1879  case DeclSpec::SCS_static:
1880    break;
1881  case DeclSpec::SCS_mutable:
1882    if (isFunc) {
1883      Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1884
1885      // FIXME: It would be nicer if the keyword was ignored only for this
1886      // declarator. Otherwise we could get follow-up errors.
1887      D.getMutableDeclSpec().ClearStorageClassSpecs();
1888    }
1889    break;
1890  default:
1891    Diag(DS.getStorageClassSpecLoc(),
1892         diag::err_storageclass_invalid_for_member);
1893    D.getMutableDeclSpec().ClearStorageClassSpecs();
1894    break;
1895  }
1896
1897  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1898                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1899                      !isFunc);
1900
1901  if (DS.isConstexprSpecified() && isInstField) {
1902    SemaDiagnosticBuilder B =
1903        Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1904    SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1905    if (InitStyle == ICIS_NoInit) {
1906      B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1907      D.getMutableDeclSpec().ClearConstexprSpec();
1908      const char *PrevSpec;
1909      unsigned DiagID;
1910      bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1911                                         PrevSpec, DiagID, getLangOpts());
1912      (void)Failed;
1913      assert(!Failed && "Making a constexpr member const shouldn't fail");
1914    } else {
1915      B << 1;
1916      const char *PrevSpec;
1917      unsigned DiagID;
1918      if (D.getMutableDeclSpec().SetStorageClassSpec(
1919          *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
1920        assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
1921               "This is the only DeclSpec that should fail to be applied");
1922        B << 1;
1923      } else {
1924        B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1925        isInstField = false;
1926      }
1927    }
1928  }
1929
1930  NamedDecl *Member;
1931  if (isInstField) {
1932    CXXScopeSpec &SS = D.getCXXScopeSpec();
1933
1934    // Data members must have identifiers for names.
1935    if (!Name.isIdentifier()) {
1936      Diag(Loc, diag::err_bad_variable_name)
1937        << Name;
1938      return 0;
1939    }
1940
1941    IdentifierInfo *II = Name.getAsIdentifierInfo();
1942
1943    // Member field could not be with "template" keyword.
1944    // So TemplateParameterLists should be empty in this case.
1945    if (TemplateParameterLists.size()) {
1946      TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1947      if (TemplateParams->size()) {
1948        // There is no such thing as a member field template.
1949        Diag(D.getIdentifierLoc(), diag::err_template_member)
1950            << II
1951            << SourceRange(TemplateParams->getTemplateLoc(),
1952                TemplateParams->getRAngleLoc());
1953      } else {
1954        // There is an extraneous 'template<>' for this member.
1955        Diag(TemplateParams->getTemplateLoc(),
1956            diag::err_template_member_noparams)
1957            << II
1958            << SourceRange(TemplateParams->getTemplateLoc(),
1959                TemplateParams->getRAngleLoc());
1960      }
1961      return 0;
1962    }
1963
1964    if (SS.isSet() && !SS.isInvalid()) {
1965      // The user provided a superfluous scope specifier inside a class
1966      // definition:
1967      //
1968      // class X {
1969      //   int X::member;
1970      // };
1971      if (DeclContext *DC = computeDeclContext(SS, false))
1972        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1973      else
1974        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1975          << Name << SS.getRange();
1976
1977      SS.clear();
1978    }
1979
1980    AttributeList *MSPropertyAttr =
1981      getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1982    if (MSPropertyAttr) {
1983      Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1984                                BitWidth, InitStyle, AS, MSPropertyAttr);
1985      if (!Member)
1986        return 0;
1987      isInstField = false;
1988    } else {
1989      Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1990                                BitWidth, InitStyle, AS);
1991      assert(Member && "HandleField never returns null");
1992    }
1993  } else {
1994    assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1995
1996    Member = HandleDeclarator(S, D, TemplateParameterLists);
1997    if (!Member)
1998      return 0;
1999
2000    // Non-instance-fields can't have a bitfield.
2001    if (BitWidth) {
2002      if (Member->isInvalidDecl()) {
2003        // don't emit another diagnostic.
2004      } else if (isa<VarDecl>(Member)) {
2005        // C++ 9.6p3: A bit-field shall not be a static member.
2006        // "static member 'A' cannot be a bit-field"
2007        Diag(Loc, diag::err_static_not_bitfield)
2008          << Name << BitWidth->getSourceRange();
2009      } else if (isa<TypedefDecl>(Member)) {
2010        // "typedef member 'x' cannot be a bit-field"
2011        Diag(Loc, diag::err_typedef_not_bitfield)
2012          << Name << BitWidth->getSourceRange();
2013      } else {
2014        // A function typedef ("typedef int f(); f a;").
2015        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2016        Diag(Loc, diag::err_not_integral_type_bitfield)
2017          << Name << cast<ValueDecl>(Member)->getType()
2018          << BitWidth->getSourceRange();
2019      }
2020
2021      BitWidth = 0;
2022      Member->setInvalidDecl();
2023    }
2024
2025    Member->setAccess(AS);
2026
2027    // If we have declared a member function template or static data member
2028    // template, set the access of the templated declaration as well.
2029    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2030      FunTmpl->getTemplatedDecl()->setAccess(AS);
2031    else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2032      VarTmpl->getTemplatedDecl()->setAccess(AS);
2033  }
2034
2035  if (VS.isOverrideSpecified())
2036    Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2037  if (VS.isFinalSpecified())
2038    Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
2039
2040  if (VS.getLastLocation().isValid()) {
2041    // Update the end location of a method that has a virt-specifiers.
2042    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2043      MD->setRangeEnd(VS.getLastLocation());
2044  }
2045
2046  CheckOverrideControl(Member);
2047
2048  assert((Name || isInstField) && "No identifier for non-field ?");
2049
2050  if (isInstField) {
2051    FieldDecl *FD = cast<FieldDecl>(Member);
2052    FieldCollector->Add(FD);
2053
2054    if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2055                                 FD->getLocation())
2056          != DiagnosticsEngine::Ignored) {
2057      // Remember all explicit private FieldDecls that have a name, no side
2058      // effects and are not part of a dependent type declaration.
2059      if (!FD->isImplicit() && FD->getDeclName() &&
2060          FD->getAccess() == AS_private &&
2061          !FD->hasAttr<UnusedAttr>() &&
2062          !FD->getParent()->isDependentContext() &&
2063          !InitializationHasSideEffects(*FD))
2064        UnusedPrivateFields.insert(FD);
2065    }
2066  }
2067
2068  return Member;
2069}
2070
2071namespace {
2072  class UninitializedFieldVisitor
2073      : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2074    Sema &S;
2075    ValueDecl *VD;
2076    bool isReferenceType;
2077  public:
2078    typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2079    UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
2080                                                        S(S) {
2081      if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2082        this->VD = IFD->getAnonField();
2083      else
2084        this->VD = VD;
2085      isReferenceType = this->VD->getType()->isReferenceType();
2086    }
2087
2088    void HandleMemberExpr(MemberExpr *ME) {
2089      if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2090        return;
2091
2092      // FieldME is the inner-most MemberExpr that is not an anonymous struct
2093      // or union.
2094      MemberExpr *FieldME = ME;
2095
2096      Expr *Base = ME;
2097      while (isa<MemberExpr>(Base)) {
2098        ME = cast<MemberExpr>(Base);
2099
2100        if (isa<VarDecl>(ME->getMemberDecl()))
2101          return;
2102
2103        if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2104          if (!FD->isAnonymousStructOrUnion())
2105            FieldME = ME;
2106
2107        Base = ME->getBase();
2108      }
2109
2110      if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
2111        unsigned diag = VD->getType()->isReferenceType()
2112            ? diag::warn_reference_field_is_uninit
2113            : diag::warn_field_is_uninit;
2114        S.Diag(FieldME->getExprLoc(), diag) << VD;
2115      }
2116    }
2117
2118    void HandleValue(Expr *E) {
2119      E = E->IgnoreParens();
2120
2121      if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2122        HandleMemberExpr(ME);
2123        return;
2124      }
2125
2126      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2127        HandleValue(CO->getTrueExpr());
2128        HandleValue(CO->getFalseExpr());
2129        return;
2130      }
2131
2132      if (BinaryConditionalOperator *BCO =
2133              dyn_cast<BinaryConditionalOperator>(E)) {
2134        HandleValue(BCO->getCommon());
2135        HandleValue(BCO->getFalseExpr());
2136        return;
2137      }
2138
2139      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2140        switch (BO->getOpcode()) {
2141        default:
2142          return;
2143        case(BO_PtrMemD):
2144        case(BO_PtrMemI):
2145          HandleValue(BO->getLHS());
2146          return;
2147        case(BO_Comma):
2148          HandleValue(BO->getRHS());
2149          return;
2150        }
2151      }
2152    }
2153
2154    void VisitMemberExpr(MemberExpr *ME) {
2155      if (isReferenceType)
2156        HandleMemberExpr(ME);
2157
2158      Inherited::VisitMemberExpr(ME);
2159    }
2160
2161    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2162      if (E->getCastKind() == CK_LValueToRValue)
2163        HandleValue(E->getSubExpr());
2164
2165      Inherited::VisitImplicitCastExpr(E);
2166    }
2167
2168    void VisitCXXConstructExpr(CXXConstructExpr *E) {
2169      if (E->getNumArgs() == 1)
2170        if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2171          if (ICE->getCastKind() == CK_NoOp)
2172            if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
2173              HandleMemberExpr(ME);
2174
2175      Inherited::VisitCXXConstructExpr(E);
2176    }
2177
2178    void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2179      Expr *Callee = E->getCallee();
2180      if (isa<MemberExpr>(Callee))
2181        HandleValue(Callee);
2182
2183      Inherited::VisitCXXMemberCallExpr(E);
2184    }
2185  };
2186  static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2187                                                       ValueDecl *VD) {
2188    if (E)
2189      UninitializedFieldVisitor(S, VD).Visit(E);
2190  }
2191} // namespace
2192
2193/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
2194/// in-class initializer for a non-static C++ class member, and after
2195/// instantiating an in-class initializer in a class template. Such actions
2196/// are deferred until the class is complete.
2197void
2198Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
2199                                       Expr *InitExpr) {
2200  FieldDecl *FD = cast<FieldDecl>(D);
2201  assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2202         "must set init style when field is created");
2203
2204  if (!InitExpr) {
2205    FD->setInvalidDecl();
2206    FD->removeInClassInitializer();
2207    return;
2208  }
2209
2210  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2211    FD->setInvalidDecl();
2212    FD->removeInClassInitializer();
2213    return;
2214  }
2215
2216  ExprResult Init = InitExpr;
2217  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2218    InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2219    InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2220        ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2221        : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2222    InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2223    Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2224    if (Init.isInvalid()) {
2225      FD->setInvalidDecl();
2226      return;
2227    }
2228  }
2229
2230  // C++11 [class.base.init]p7:
2231  //   The initialization of each base and member constitutes a
2232  //   full-expression.
2233  Init = ActOnFinishFullExpr(Init.take(), InitLoc);
2234  if (Init.isInvalid()) {
2235    FD->setInvalidDecl();
2236    return;
2237  }
2238
2239  InitExpr = Init.release();
2240
2241  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2242      != DiagnosticsEngine::Ignored) {
2243    CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2244  }
2245
2246  FD->setInClassInitializer(InitExpr);
2247}
2248
2249/// \brief Find the direct and/or virtual base specifiers that
2250/// correspond to the given base type, for use in base initialization
2251/// within a constructor.
2252static bool FindBaseInitializer(Sema &SemaRef,
2253                                CXXRecordDecl *ClassDecl,
2254                                QualType BaseType,
2255                                const CXXBaseSpecifier *&DirectBaseSpec,
2256                                const CXXBaseSpecifier *&VirtualBaseSpec) {
2257  // First, check for a direct base class.
2258  DirectBaseSpec = 0;
2259  for (CXXRecordDecl::base_class_const_iterator Base
2260         = ClassDecl->bases_begin();
2261       Base != ClassDecl->bases_end(); ++Base) {
2262    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2263      // We found a direct base of this type. That's what we're
2264      // initializing.
2265      DirectBaseSpec = &*Base;
2266      break;
2267    }
2268  }
2269
2270  // Check for a virtual base class.
2271  // FIXME: We might be able to short-circuit this if we know in advance that
2272  // there are no virtual bases.
2273  VirtualBaseSpec = 0;
2274  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2275    // We haven't found a base yet; search the class hierarchy for a
2276    // virtual base class.
2277    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2278                       /*DetectVirtual=*/false);
2279    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2280                              BaseType, Paths)) {
2281      for (CXXBasePaths::paths_iterator Path = Paths.begin();
2282           Path != Paths.end(); ++Path) {
2283        if (Path->back().Base->isVirtual()) {
2284          VirtualBaseSpec = Path->back().Base;
2285          break;
2286        }
2287      }
2288    }
2289  }
2290
2291  return DirectBaseSpec || VirtualBaseSpec;
2292}
2293
2294/// \brief Handle a C++ member initializer using braced-init-list syntax.
2295MemInitResult
2296Sema::ActOnMemInitializer(Decl *ConstructorD,
2297                          Scope *S,
2298                          CXXScopeSpec &SS,
2299                          IdentifierInfo *MemberOrBase,
2300                          ParsedType TemplateTypeTy,
2301                          const DeclSpec &DS,
2302                          SourceLocation IdLoc,
2303                          Expr *InitList,
2304                          SourceLocation EllipsisLoc) {
2305  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2306                             DS, IdLoc, InitList,
2307                             EllipsisLoc);
2308}
2309
2310/// \brief Handle a C++ member initializer using parentheses syntax.
2311MemInitResult
2312Sema::ActOnMemInitializer(Decl *ConstructorD,
2313                          Scope *S,
2314                          CXXScopeSpec &SS,
2315                          IdentifierInfo *MemberOrBase,
2316                          ParsedType TemplateTypeTy,
2317                          const DeclSpec &DS,
2318                          SourceLocation IdLoc,
2319                          SourceLocation LParenLoc,
2320                          ArrayRef<Expr *> Args,
2321                          SourceLocation RParenLoc,
2322                          SourceLocation EllipsisLoc) {
2323  Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2324                                           Args, RParenLoc);
2325  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2326                             DS, IdLoc, List, EllipsisLoc);
2327}
2328
2329namespace {
2330
2331// Callback to only accept typo corrections that can be a valid C++ member
2332// intializer: either a non-static field member or a base class.
2333class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2334public:
2335  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2336      : ClassDecl(ClassDecl) {}
2337
2338  bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
2339    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2340      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2341        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2342      return isa<TypeDecl>(ND);
2343    }
2344    return false;
2345  }
2346
2347private:
2348  CXXRecordDecl *ClassDecl;
2349};
2350
2351}
2352
2353/// \brief Handle a C++ member initializer.
2354MemInitResult
2355Sema::BuildMemInitializer(Decl *ConstructorD,
2356                          Scope *S,
2357                          CXXScopeSpec &SS,
2358                          IdentifierInfo *MemberOrBase,
2359                          ParsedType TemplateTypeTy,
2360                          const DeclSpec &DS,
2361                          SourceLocation IdLoc,
2362                          Expr *Init,
2363                          SourceLocation EllipsisLoc) {
2364  if (!ConstructorD)
2365    return true;
2366
2367  AdjustDeclIfTemplate(ConstructorD);
2368
2369  CXXConstructorDecl *Constructor
2370    = dyn_cast<CXXConstructorDecl>(ConstructorD);
2371  if (!Constructor) {
2372    // The user wrote a constructor initializer on a function that is
2373    // not a C++ constructor. Ignore the error for now, because we may
2374    // have more member initializers coming; we'll diagnose it just
2375    // once in ActOnMemInitializers.
2376    return true;
2377  }
2378
2379  CXXRecordDecl *ClassDecl = Constructor->getParent();
2380
2381  // C++ [class.base.init]p2:
2382  //   Names in a mem-initializer-id are looked up in the scope of the
2383  //   constructor's class and, if not found in that scope, are looked
2384  //   up in the scope containing the constructor's definition.
2385  //   [Note: if the constructor's class contains a member with the
2386  //   same name as a direct or virtual base class of the class, a
2387  //   mem-initializer-id naming the member or base class and composed
2388  //   of a single identifier refers to the class member. A
2389  //   mem-initializer-id for the hidden base class may be specified
2390  //   using a qualified name. ]
2391  if (!SS.getScopeRep() && !TemplateTypeTy) {
2392    // Look for a member, first.
2393    DeclContext::lookup_result Result
2394      = ClassDecl->lookup(MemberOrBase);
2395    if (!Result.empty()) {
2396      ValueDecl *Member;
2397      if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2398          (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2399        if (EllipsisLoc.isValid())
2400          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2401            << MemberOrBase
2402            << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2403
2404        return BuildMemberInitializer(Member, Init, IdLoc);
2405      }
2406    }
2407  }
2408  // It didn't name a member, so see if it names a class.
2409  QualType BaseType;
2410  TypeSourceInfo *TInfo = 0;
2411
2412  if (TemplateTypeTy) {
2413    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2414  } else if (DS.getTypeSpecType() == TST_decltype) {
2415    BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2416  } else {
2417    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2418    LookupParsedName(R, S, &SS);
2419
2420    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2421    if (!TyD) {
2422      if (R.isAmbiguous()) return true;
2423
2424      // We don't want access-control diagnostics here.
2425      R.suppressDiagnostics();
2426
2427      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2428        bool NotUnknownSpecialization = false;
2429        DeclContext *DC = computeDeclContext(SS, false);
2430        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2431          NotUnknownSpecialization = !Record->hasAnyDependentBases();
2432
2433        if (!NotUnknownSpecialization) {
2434          // When the scope specifier can refer to a member of an unknown
2435          // specialization, we take it as a type name.
2436          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2437                                       SS.getWithLocInContext(Context),
2438                                       *MemberOrBase, IdLoc);
2439          if (BaseType.isNull())
2440            return true;
2441
2442          R.clear();
2443          R.setLookupName(MemberOrBase);
2444        }
2445      }
2446
2447      // If no results were found, try to correct typos.
2448      TypoCorrection Corr;
2449      MemInitializerValidatorCCC Validator(ClassDecl);
2450      if (R.empty() && BaseType.isNull() &&
2451          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2452                              Validator, ClassDecl))) {
2453        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2454          // We have found a non-static data member with a similar
2455          // name to what was typed; complain and initialize that
2456          // member.
2457          diagnoseTypo(Corr,
2458                       PDiag(diag::err_mem_init_not_member_or_class_suggest)
2459                         << MemberOrBase << true);
2460          return BuildMemberInitializer(Member, Init, IdLoc);
2461        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2462          const CXXBaseSpecifier *DirectBaseSpec;
2463          const CXXBaseSpecifier *VirtualBaseSpec;
2464          if (FindBaseInitializer(*this, ClassDecl,
2465                                  Context.getTypeDeclType(Type),
2466                                  DirectBaseSpec, VirtualBaseSpec)) {
2467            // We have found a direct or virtual base class with a
2468            // similar name to what was typed; complain and initialize
2469            // that base class.
2470            diagnoseTypo(Corr,
2471                         PDiag(diag::err_mem_init_not_member_or_class_suggest)
2472                           << MemberOrBase << false,
2473                         PDiag() /*Suppress note, we provide our own.*/);
2474
2475            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2476                                                              : VirtualBaseSpec;
2477            Diag(BaseSpec->getLocStart(),
2478                 diag::note_base_class_specified_here)
2479              << BaseSpec->getType()
2480              << BaseSpec->getSourceRange();
2481
2482            TyD = Type;
2483          }
2484        }
2485      }
2486
2487      if (!TyD && BaseType.isNull()) {
2488        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2489          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2490        return true;
2491      }
2492    }
2493
2494    if (BaseType.isNull()) {
2495      BaseType = Context.getTypeDeclType(TyD);
2496      if (SS.isSet()) {
2497        NestedNameSpecifier *Qualifier =
2498          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2499
2500        // FIXME: preserve source range information
2501        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
2502      }
2503    }
2504  }
2505
2506  if (!TInfo)
2507    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2508
2509  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2510}
2511
2512/// Checks a member initializer expression for cases where reference (or
2513/// pointer) members are bound to by-value parameters (or their addresses).
2514static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2515                                               Expr *Init,
2516                                               SourceLocation IdLoc) {
2517  QualType MemberTy = Member->getType();
2518
2519  // We only handle pointers and references currently.
2520  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2521  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2522    return;
2523
2524  const bool IsPointer = MemberTy->isPointerType();
2525  if (IsPointer) {
2526    if (const UnaryOperator *Op
2527          = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2528      // The only case we're worried about with pointers requires taking the
2529      // address.
2530      if (Op->getOpcode() != UO_AddrOf)
2531        return;
2532
2533      Init = Op->getSubExpr();
2534    } else {
2535      // We only handle address-of expression initializers for pointers.
2536      return;
2537    }
2538  }
2539
2540  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2541    // We only warn when referring to a non-reference parameter declaration.
2542    const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2543    if (!Parameter || Parameter->getType()->isReferenceType())
2544      return;
2545
2546    S.Diag(Init->getExprLoc(),
2547           IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2548                     : diag::warn_bind_ref_member_to_parameter)
2549      << Member << Parameter << Init->getSourceRange();
2550  } else {
2551    // Other initializers are fine.
2552    return;
2553  }
2554
2555  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2556    << (unsigned)IsPointer;
2557}
2558
2559MemInitResult
2560Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2561                             SourceLocation IdLoc) {
2562  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2563  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2564  assert((DirectMember || IndirectMember) &&
2565         "Member must be a FieldDecl or IndirectFieldDecl");
2566
2567  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2568    return true;
2569
2570  if (Member->isInvalidDecl())
2571    return true;
2572
2573  MultiExprArg Args;
2574  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2575    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2576  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2577    Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2578  } else {
2579    // Template instantiation doesn't reconstruct ParenListExprs for us.
2580    Args = Init;
2581  }
2582
2583  SourceRange InitRange = Init->getSourceRange();
2584
2585  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2586    // Can't check initialization for a member of dependent type or when
2587    // any of the arguments are type-dependent expressions.
2588    DiscardCleanupsInEvaluationContext();
2589  } else {
2590    bool InitList = false;
2591    if (isa<InitListExpr>(Init)) {
2592      InitList = true;
2593      Args = Init;
2594    }
2595
2596    // Initialize the member.
2597    InitializedEntity MemberEntity =
2598      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2599                   : InitializedEntity::InitializeMember(IndirectMember, 0);
2600    InitializationKind Kind =
2601      InitList ? InitializationKind::CreateDirectList(IdLoc)
2602               : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2603                                                  InitRange.getEnd());
2604
2605    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2606    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
2607    if (MemberInit.isInvalid())
2608      return true;
2609
2610    CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2611
2612    // C++11 [class.base.init]p7:
2613    //   The initialization of each base and member constitutes a
2614    //   full-expression.
2615    MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2616    if (MemberInit.isInvalid())
2617      return true;
2618
2619    Init = MemberInit.get();
2620  }
2621
2622  // Diagnose value-uses of fields to initialize themselves, e.g.
2623  //   foo(foo)
2624  // where foo is not also a parameter to the constructor.
2625  // TODO: implement -Wuninitialized and fold this into that framework.
2626  // FIXME: Warn about the case when other fields are used before being
2627  // initialized. For example, let this field be the i'th field. When
2628  // initializing the i'th field, throw a warning if any of the >= i'th
2629  // fields are used, as they are not yet initialized.
2630  // Right now we are only handling the case where the i'th field uses
2631  // itself in its initializer.
2632  // Also need to take into account that some fields may be initialized by
2633  // in-class initializers, see C++11 [class.base.init]p9.
2634  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2635      != DiagnosticsEngine::Ignored) {
2636    CheckInitExprContainsUninitializedFields(*this, Init, Member);
2637  }
2638
2639  if (DirectMember) {
2640    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2641                                            InitRange.getBegin(), Init,
2642                                            InitRange.getEnd());
2643  } else {
2644    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2645                                            InitRange.getBegin(), Init,
2646                                            InitRange.getEnd());
2647  }
2648}
2649
2650MemInitResult
2651Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2652                                 CXXRecordDecl *ClassDecl) {
2653  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2654  if (!LangOpts.CPlusPlus11)
2655    return Diag(NameLoc, diag::err_delegating_ctor)
2656      << TInfo->getTypeLoc().getLocalSourceRange();
2657  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2658
2659  bool InitList = true;
2660  MultiExprArg Args = Init;
2661  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2662    InitList = false;
2663    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2664  }
2665
2666  SourceRange InitRange = Init->getSourceRange();
2667  // Initialize the object.
2668  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2669                                     QualType(ClassDecl->getTypeForDecl(), 0));
2670  InitializationKind Kind =
2671    InitList ? InitializationKind::CreateDirectList(NameLoc)
2672             : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2673                                                InitRange.getEnd());
2674  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
2675  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2676                                              Args, 0);
2677  if (DelegationInit.isInvalid())
2678    return true;
2679
2680  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2681         "Delegating constructor with no target?");
2682
2683  // C++11 [class.base.init]p7:
2684  //   The initialization of each base and member constitutes a
2685  //   full-expression.
2686  DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2687                                       InitRange.getBegin());
2688  if (DelegationInit.isInvalid())
2689    return true;
2690
2691  // If we are in a dependent context, template instantiation will
2692  // perform this type-checking again. Just save the arguments that we
2693  // received in a ParenListExpr.
2694  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2695  // of the information that we have about the base
2696  // initializer. However, deconstructing the ASTs is a dicey process,
2697  // and this approach is far more likely to get the corner cases right.
2698  if (CurContext->isDependentContext())
2699    DelegationInit = Owned(Init);
2700
2701  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2702                                          DelegationInit.takeAs<Expr>(),
2703                                          InitRange.getEnd());
2704}
2705
2706MemInitResult
2707Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2708                           Expr *Init, CXXRecordDecl *ClassDecl,
2709                           SourceLocation EllipsisLoc) {
2710  SourceLocation BaseLoc
2711    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2712
2713  if (!BaseType->isDependentType() && !BaseType->isRecordType())
2714    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2715             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2716
2717  // C++ [class.base.init]p2:
2718  //   [...] Unless the mem-initializer-id names a nonstatic data
2719  //   member of the constructor's class or a direct or virtual base
2720  //   of that class, the mem-initializer is ill-formed. A
2721  //   mem-initializer-list can initialize a base class using any
2722  //   name that denotes that base class type.
2723  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2724
2725  SourceRange InitRange = Init->getSourceRange();
2726  if (EllipsisLoc.isValid()) {
2727    // This is a pack expansion.
2728    if (!BaseType->containsUnexpandedParameterPack())  {
2729      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2730        << SourceRange(BaseLoc, InitRange.getEnd());
2731
2732      EllipsisLoc = SourceLocation();
2733    }
2734  } else {
2735    // Check for any unexpanded parameter packs.
2736    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2737      return true;
2738
2739    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2740      return true;
2741  }
2742
2743  // Check for direct and virtual base classes.
2744  const CXXBaseSpecifier *DirectBaseSpec = 0;
2745  const CXXBaseSpecifier *VirtualBaseSpec = 0;
2746  if (!Dependent) {
2747    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2748                                       BaseType))
2749      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2750
2751    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2752                        VirtualBaseSpec);
2753
2754    // C++ [base.class.init]p2:
2755    // Unless the mem-initializer-id names a nonstatic data member of the
2756    // constructor's class or a direct or virtual base of that class, the
2757    // mem-initializer is ill-formed.
2758    if (!DirectBaseSpec && !VirtualBaseSpec) {
2759      // If the class has any dependent bases, then it's possible that
2760      // one of those types will resolve to the same type as
2761      // BaseType. Therefore, just treat this as a dependent base
2762      // class initialization.  FIXME: Should we try to check the
2763      // initialization anyway? It seems odd.
2764      if (ClassDecl->hasAnyDependentBases())
2765        Dependent = true;
2766      else
2767        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2768          << BaseType << Context.getTypeDeclType(ClassDecl)
2769          << BaseTInfo->getTypeLoc().getLocalSourceRange();
2770    }
2771  }
2772
2773  if (Dependent) {
2774    DiscardCleanupsInEvaluationContext();
2775
2776    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2777                                            /*IsVirtual=*/false,
2778                                            InitRange.getBegin(), Init,
2779                                            InitRange.getEnd(), EllipsisLoc);
2780  }
2781
2782  // C++ [base.class.init]p2:
2783  //   If a mem-initializer-id is ambiguous because it designates both
2784  //   a direct non-virtual base class and an inherited virtual base
2785  //   class, the mem-initializer is ill-formed.
2786  if (DirectBaseSpec && VirtualBaseSpec)
2787    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2788      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2789
2790  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
2791  if (!BaseSpec)
2792    BaseSpec = VirtualBaseSpec;
2793
2794  // Initialize the base.
2795  bool InitList = true;
2796  MultiExprArg Args = Init;
2797  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2798    InitList = false;
2799    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2800  }
2801
2802  InitializedEntity BaseEntity =
2803    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2804  InitializationKind Kind =
2805    InitList ? InitializationKind::CreateDirectList(BaseLoc)
2806             : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2807                                                InitRange.getEnd());
2808  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2809  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
2810  if (BaseInit.isInvalid())
2811    return true;
2812
2813  // C++11 [class.base.init]p7:
2814  //   The initialization of each base and member constitutes a
2815  //   full-expression.
2816  BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
2817  if (BaseInit.isInvalid())
2818    return true;
2819
2820  // If we are in a dependent context, template instantiation will
2821  // perform this type-checking again. Just save the arguments that we
2822  // received in a ParenListExpr.
2823  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2824  // of the information that we have about the base
2825  // initializer. However, deconstructing the ASTs is a dicey process,
2826  // and this approach is far more likely to get the corner cases right.
2827  if (CurContext->isDependentContext())
2828    BaseInit = Owned(Init);
2829
2830  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2831                                          BaseSpec->isVirtual(),
2832                                          InitRange.getBegin(),
2833                                          BaseInit.takeAs<Expr>(),
2834                                          InitRange.getEnd(), EllipsisLoc);
2835}
2836
2837// Create a static_cast\<T&&>(expr).
2838static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2839  if (T.isNull()) T = E->getType();
2840  QualType TargetType = SemaRef.BuildReferenceType(
2841      T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
2842  SourceLocation ExprLoc = E->getLocStart();
2843  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2844      TargetType, ExprLoc);
2845
2846  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2847                                   SourceRange(ExprLoc, ExprLoc),
2848                                   E->getSourceRange()).take();
2849}
2850
2851/// ImplicitInitializerKind - How an implicit base or member initializer should
2852/// initialize its base or member.
2853enum ImplicitInitializerKind {
2854  IIK_Default,
2855  IIK_Copy,
2856  IIK_Move,
2857  IIK_Inherit
2858};
2859
2860static bool
2861BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2862                             ImplicitInitializerKind ImplicitInitKind,
2863                             CXXBaseSpecifier *BaseSpec,
2864                             bool IsInheritedVirtualBase,
2865                             CXXCtorInitializer *&CXXBaseInit) {
2866  InitializedEntity InitEntity
2867    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2868                                        IsInheritedVirtualBase);
2869
2870  ExprResult BaseInit;
2871
2872  switch (ImplicitInitKind) {
2873  case IIK_Inherit: {
2874    const CXXRecordDecl *Inherited =
2875        Constructor->getInheritedConstructor()->getParent();
2876    const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2877    if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2878      // C++11 [class.inhctor]p8:
2879      //   Each expression in the expression-list is of the form
2880      //   static_cast<T&&>(p), where p is the name of the corresponding
2881      //   constructor parameter and T is the declared type of p.
2882      SmallVector<Expr*, 16> Args;
2883      for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2884        ParmVarDecl *PD = Constructor->getParamDecl(I);
2885        ExprResult ArgExpr =
2886            SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2887                                     VK_LValue, SourceLocation());
2888        if (ArgExpr.isInvalid())
2889          return true;
2890        Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2891      }
2892
2893      InitializationKind InitKind = InitializationKind::CreateDirect(
2894          Constructor->getLocation(), SourceLocation(), SourceLocation());
2895      InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
2896      BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2897      break;
2898    }
2899  }
2900  // Fall through.
2901  case IIK_Default: {
2902    InitializationKind InitKind
2903      = InitializationKind::CreateDefault(Constructor->getLocation());
2904    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2905    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
2906    break;
2907  }
2908
2909  case IIK_Move:
2910  case IIK_Copy: {
2911    bool Moving = ImplicitInitKind == IIK_Move;
2912    ParmVarDecl *Param = Constructor->getParamDecl(0);
2913    QualType ParamType = Param->getType().getNonReferenceType();
2914
2915    Expr *CopyCtorArg =
2916      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2917                          SourceLocation(), Param, false,
2918                          Constructor->getLocation(), ParamType,
2919                          VK_LValue, 0);
2920
2921    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2922
2923    // Cast to the base class to avoid ambiguities.
2924    QualType ArgTy =
2925      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2926                                       ParamType.getQualifiers());
2927
2928    if (Moving) {
2929      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2930    }
2931
2932    CXXCastPath BasePath;
2933    BasePath.push_back(BaseSpec);
2934    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2935                                            CK_UncheckedDerivedToBase,
2936                                            Moving ? VK_XValue : VK_LValue,
2937                                            &BasePath).take();
2938
2939    InitializationKind InitKind
2940      = InitializationKind::CreateDirect(Constructor->getLocation(),
2941                                         SourceLocation(), SourceLocation());
2942    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2943    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
2944    break;
2945  }
2946  }
2947
2948  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2949  if (BaseInit.isInvalid())
2950    return true;
2951
2952  CXXBaseInit =
2953    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2954               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2955                                                        SourceLocation()),
2956                                             BaseSpec->isVirtual(),
2957                                             SourceLocation(),
2958                                             BaseInit.takeAs<Expr>(),
2959                                             SourceLocation(),
2960                                             SourceLocation());
2961
2962  return false;
2963}
2964
2965static bool RefersToRValueRef(Expr *MemRef) {
2966  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2967  return Referenced->getType()->isRValueReferenceType();
2968}
2969
2970static bool
2971BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2972                               ImplicitInitializerKind ImplicitInitKind,
2973                               FieldDecl *Field, IndirectFieldDecl *Indirect,
2974                               CXXCtorInitializer *&CXXMemberInit) {
2975  if (Field->isInvalidDecl())
2976    return true;
2977
2978  SourceLocation Loc = Constructor->getLocation();
2979
2980  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2981    bool Moving = ImplicitInitKind == IIK_Move;
2982    ParmVarDecl *Param = Constructor->getParamDecl(0);
2983    QualType ParamType = Param->getType().getNonReferenceType();
2984
2985    // Suppress copying zero-width bitfields.
2986    if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2987      return false;
2988
2989    Expr *MemberExprBase =
2990      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2991                          SourceLocation(), Param, false,
2992                          Loc, ParamType, VK_LValue, 0);
2993
2994    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2995
2996    if (Moving) {
2997      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2998    }
2999
3000    // Build a reference to this field within the parameter.
3001    CXXScopeSpec SS;
3002    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3003                              Sema::LookupMemberName);
3004    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3005                                  : cast<ValueDecl>(Field), AS_public);
3006    MemberLookup.resolveKind();
3007    ExprResult CtorArg
3008      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3009                                         ParamType, Loc,
3010                                         /*IsArrow=*/false,
3011                                         SS,
3012                                         /*TemplateKWLoc=*/SourceLocation(),
3013                                         /*FirstQualifierInScope=*/0,
3014                                         MemberLookup,
3015                                         /*TemplateArgs=*/0);
3016    if (CtorArg.isInvalid())
3017      return true;
3018
3019    // C++11 [class.copy]p15:
3020    //   - if a member m has rvalue reference type T&&, it is direct-initialized
3021    //     with static_cast<T&&>(x.m);
3022    if (RefersToRValueRef(CtorArg.get())) {
3023      CtorArg = CastForMoving(SemaRef, CtorArg.take());
3024    }
3025
3026    // When the field we are copying is an array, create index variables for
3027    // each dimension of the array. We use these index variables to subscript
3028    // the source array, and other clients (e.g., CodeGen) will perform the
3029    // necessary iteration with these index variables.
3030    SmallVector<VarDecl *, 4> IndexVariables;
3031    QualType BaseType = Field->getType();
3032    QualType SizeType = SemaRef.Context.getSizeType();
3033    bool InitializingArray = false;
3034    while (const ConstantArrayType *Array
3035                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3036      InitializingArray = true;
3037      // Create the iteration variable for this array index.
3038      IdentifierInfo *IterationVarName = 0;
3039      {
3040        SmallString<8> Str;
3041        llvm::raw_svector_ostream OS(Str);
3042        OS << "__i" << IndexVariables.size();
3043        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3044      }
3045      VarDecl *IterationVar
3046        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3047                          IterationVarName, SizeType,
3048                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3049                          SC_None);
3050      IndexVariables.push_back(IterationVar);
3051
3052      // Create a reference to the iteration variable.
3053      ExprResult IterationVarRef
3054        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3055      assert(!IterationVarRef.isInvalid() &&
3056             "Reference to invented variable cannot fail!");
3057      IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3058      assert(!IterationVarRef.isInvalid() &&
3059             "Conversion of invented variable cannot fail!");
3060
3061      // Subscript the array with this iteration variable.
3062      CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
3063                                                        IterationVarRef.take(),
3064                                                        Loc);
3065      if (CtorArg.isInvalid())
3066        return true;
3067
3068      BaseType = Array->getElementType();
3069    }
3070
3071    // The array subscript expression is an lvalue, which is wrong for moving.
3072    if (Moving && InitializingArray)
3073      CtorArg = CastForMoving(SemaRef, CtorArg.take());
3074
3075    // Construct the entity that we will be initializing. For an array, this
3076    // will be first element in the array, which may require several levels
3077    // of array-subscript entities.
3078    SmallVector<InitializedEntity, 4> Entities;
3079    Entities.reserve(1 + IndexVariables.size());
3080    if (Indirect)
3081      Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3082    else
3083      Entities.push_back(InitializedEntity::InitializeMember(Field));
3084    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3085      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3086                                                              0,
3087                                                              Entities.back()));
3088
3089    // Direct-initialize to use the copy constructor.
3090    InitializationKind InitKind =
3091      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3092
3093    Expr *CtorArgE = CtorArg.takeAs<Expr>();
3094    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3095
3096    ExprResult MemberInit
3097      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3098                        MultiExprArg(&CtorArgE, 1));
3099    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3100    if (MemberInit.isInvalid())
3101      return true;
3102
3103    if (Indirect) {
3104      assert(IndexVariables.size() == 0 &&
3105             "Indirect field improperly initialized");
3106      CXXMemberInit
3107        = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3108                                                   Loc, Loc,
3109                                                   MemberInit.takeAs<Expr>(),
3110                                                   Loc);
3111    } else
3112      CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3113                                                 Loc, MemberInit.takeAs<Expr>(),
3114                                                 Loc,
3115                                                 IndexVariables.data(),
3116                                                 IndexVariables.size());
3117    return false;
3118  }
3119
3120  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3121         "Unhandled implicit init kind!");
3122
3123  QualType FieldBaseElementType =
3124    SemaRef.Context.getBaseElementType(Field->getType());
3125
3126  if (FieldBaseElementType->isRecordType()) {
3127    InitializedEntity InitEntity
3128      = Indirect? InitializedEntity::InitializeMember(Indirect)
3129                : InitializedEntity::InitializeMember(Field);
3130    InitializationKind InitKind =
3131      InitializationKind::CreateDefault(Loc);
3132
3133    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3134    ExprResult MemberInit =
3135      InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3136
3137    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3138    if (MemberInit.isInvalid())
3139      return true;
3140
3141    if (Indirect)
3142      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3143                                                               Indirect, Loc,
3144                                                               Loc,
3145                                                               MemberInit.get(),
3146                                                               Loc);
3147    else
3148      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3149                                                               Field, Loc, Loc,
3150                                                               MemberInit.get(),
3151                                                               Loc);
3152    return false;
3153  }
3154
3155  if (!Field->getParent()->isUnion()) {
3156    if (FieldBaseElementType->isReferenceType()) {
3157      SemaRef.Diag(Constructor->getLocation(),
3158                   diag::err_uninitialized_member_in_ctor)
3159      << (int)Constructor->isImplicit()
3160      << SemaRef.Context.getTagDeclType(Constructor->getParent())
3161      << 0 << Field->getDeclName();
3162      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3163      return true;
3164    }
3165
3166    if (FieldBaseElementType.isConstQualified()) {
3167      SemaRef.Diag(Constructor->getLocation(),
3168                   diag::err_uninitialized_member_in_ctor)
3169      << (int)Constructor->isImplicit()
3170      << SemaRef.Context.getTagDeclType(Constructor->getParent())
3171      << 1 << Field->getDeclName();
3172      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3173      return true;
3174    }
3175  }
3176
3177  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3178      FieldBaseElementType->isObjCRetainableType() &&
3179      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3180      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3181    // ARC:
3182    //   Default-initialize Objective-C pointers to NULL.
3183    CXXMemberInit
3184      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3185                                                 Loc, Loc,
3186                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3187                                                 Loc);
3188    return false;
3189  }
3190
3191  // Nothing to initialize.
3192  CXXMemberInit = 0;
3193  return false;
3194}
3195
3196namespace {
3197struct BaseAndFieldInfo {
3198  Sema &S;
3199  CXXConstructorDecl *Ctor;
3200  bool AnyErrorsInInits;
3201  ImplicitInitializerKind IIK;
3202  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3203  SmallVector<CXXCtorInitializer*, 8> AllToInit;
3204
3205  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3206    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3207    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3208    if (Generated && Ctor->isCopyConstructor())
3209      IIK = IIK_Copy;
3210    else if (Generated && Ctor->isMoveConstructor())
3211      IIK = IIK_Move;
3212    else if (Ctor->getInheritedConstructor())
3213      IIK = IIK_Inherit;
3214    else
3215      IIK = IIK_Default;
3216  }
3217
3218  bool isImplicitCopyOrMove() const {
3219    switch (IIK) {
3220    case IIK_Copy:
3221    case IIK_Move:
3222      return true;
3223
3224    case IIK_Default:
3225    case IIK_Inherit:
3226      return false;
3227    }
3228
3229    llvm_unreachable("Invalid ImplicitInitializerKind!");
3230  }
3231
3232  bool addFieldInitializer(CXXCtorInitializer *Init) {
3233    AllToInit.push_back(Init);
3234
3235    // Check whether this initializer makes the field "used".
3236    if (Init->getInit()->HasSideEffects(S.Context))
3237      S.UnusedPrivateFields.remove(Init->getAnyMember());
3238
3239    return false;
3240  }
3241};
3242}
3243
3244/// \brief Determine whether the given indirect field declaration is somewhere
3245/// within an anonymous union.
3246static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3247  for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3248                                      CEnd = F->chain_end();
3249       C != CEnd; ++C)
3250    if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3251      if (Record->isUnion())
3252        return true;
3253
3254  return false;
3255}
3256
3257/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3258/// array type.
3259static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3260  if (T->isIncompleteArrayType())
3261    return true;
3262
3263  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3264    if (!ArrayT->getSize())
3265      return true;
3266
3267    T = ArrayT->getElementType();
3268  }
3269
3270  return false;
3271}
3272
3273static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3274                                    FieldDecl *Field,
3275                                    IndirectFieldDecl *Indirect = 0) {
3276  if (Field->isInvalidDecl())
3277    return false;
3278
3279  // Overwhelmingly common case: we have a direct initializer for this field.
3280  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3281    return Info.addFieldInitializer(Init);
3282
3283  // C++11 [class.base.init]p8: if the entity is a non-static data member that
3284  // has a brace-or-equal-initializer, the entity is initialized as specified
3285  // in [dcl.init].
3286  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3287    Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3288                                           Info.Ctor->getLocation(), Field);
3289    CXXCtorInitializer *Init;
3290    if (Indirect)
3291      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3292                                                      SourceLocation(),
3293                                                      SourceLocation(), DIE,
3294                                                      SourceLocation());
3295    else
3296      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3297                                                      SourceLocation(),
3298                                                      SourceLocation(), DIE,
3299                                                      SourceLocation());
3300    return Info.addFieldInitializer(Init);
3301  }
3302
3303  // Don't build an implicit initializer for union members if none was
3304  // explicitly specified.
3305  if (Field->getParent()->isUnion() ||
3306      (Indirect && isWithinAnonymousUnion(Indirect)))
3307    return false;
3308
3309  // Don't initialize incomplete or zero-length arrays.
3310  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3311    return false;
3312
3313  // Don't try to build an implicit initializer if there were semantic
3314  // errors in any of the initializers (and therefore we might be
3315  // missing some that the user actually wrote).
3316  if (Info.AnyErrorsInInits)
3317    return false;
3318
3319  CXXCtorInitializer *Init = 0;
3320  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3321                                     Indirect, Init))
3322    return true;
3323
3324  if (!Init)
3325    return false;
3326
3327  return Info.addFieldInitializer(Init);
3328}
3329
3330bool
3331Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3332                               CXXCtorInitializer *Initializer) {
3333  assert(Initializer->isDelegatingInitializer());
3334  Constructor->setNumCtorInitializers(1);
3335  CXXCtorInitializer **initializer =
3336    new (Context) CXXCtorInitializer*[1];
3337  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3338  Constructor->setCtorInitializers(initializer);
3339
3340  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3341    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3342    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3343  }
3344
3345  DelegatingCtorDecls.push_back(Constructor);
3346
3347  return false;
3348}
3349
3350bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3351                               ArrayRef<CXXCtorInitializer *> Initializers) {
3352  if (Constructor->isDependentContext()) {
3353    // Just store the initializers as written, they will be checked during
3354    // instantiation.
3355    if (!Initializers.empty()) {
3356      Constructor->setNumCtorInitializers(Initializers.size());
3357      CXXCtorInitializer **baseOrMemberInitializers =
3358        new (Context) CXXCtorInitializer*[Initializers.size()];
3359      memcpy(baseOrMemberInitializers, Initializers.data(),
3360             Initializers.size() * sizeof(CXXCtorInitializer*));
3361      Constructor->setCtorInitializers(baseOrMemberInitializers);
3362    }
3363
3364    // Let template instantiation know whether we had errors.
3365    if (AnyErrors)
3366      Constructor->setInvalidDecl();
3367
3368    return false;
3369  }
3370
3371  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3372
3373  // We need to build the initializer AST according to order of construction
3374  // and not what user specified in the Initializers list.
3375  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3376  if (!ClassDecl)
3377    return true;
3378
3379  bool HadError = false;
3380
3381  for (unsigned i = 0; i < Initializers.size(); i++) {
3382    CXXCtorInitializer *Member = Initializers[i];
3383
3384    if (Member->isBaseInitializer())
3385      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3386    else
3387      Info.AllBaseFields[Member->getAnyMember()] = Member;
3388  }
3389
3390  // Keep track of the direct virtual bases.
3391  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3392  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3393       E = ClassDecl->bases_end(); I != E; ++I) {
3394    if (I->isVirtual())
3395      DirectVBases.insert(I);
3396  }
3397
3398  // Push virtual bases before others.
3399  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3400       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3401
3402    if (CXXCtorInitializer *Value
3403        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3404      // [class.base.init]p7, per DR257:
3405      //   A mem-initializer where the mem-initializer-id names a virtual base
3406      //   class is ignored during execution of a constructor of any class that
3407      //   is not the most derived class.
3408      if (ClassDecl->isAbstract()) {
3409        // FIXME: Provide a fixit to remove the base specifier. This requires
3410        // tracking the location of the associated comma for a base specifier.
3411        Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3412          << VBase->getType() << ClassDecl;
3413        DiagnoseAbstractType(ClassDecl);
3414      }
3415
3416      Info.AllToInit.push_back(Value);
3417    } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3418      // [class.base.init]p8, per DR257:
3419      //   If a given [...] base class is not named by a mem-initializer-id
3420      //   [...] and the entity is not a virtual base class of an abstract
3421      //   class, then [...] the entity is default-initialized.
3422      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3423      CXXCtorInitializer *CXXBaseInit;
3424      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3425                                       VBase, IsInheritedVirtualBase,
3426                                       CXXBaseInit)) {
3427        HadError = true;
3428        continue;
3429      }
3430
3431      Info.AllToInit.push_back(CXXBaseInit);
3432    }
3433  }
3434
3435  // Non-virtual bases.
3436  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3437       E = ClassDecl->bases_end(); Base != E; ++Base) {
3438    // Virtuals are in the virtual base list and already constructed.
3439    if (Base->isVirtual())
3440      continue;
3441
3442    if (CXXCtorInitializer *Value
3443          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3444      Info.AllToInit.push_back(Value);
3445    } else if (!AnyErrors) {
3446      CXXCtorInitializer *CXXBaseInit;
3447      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3448                                       Base, /*IsInheritedVirtualBase=*/false,
3449                                       CXXBaseInit)) {
3450        HadError = true;
3451        continue;
3452      }
3453
3454      Info.AllToInit.push_back(CXXBaseInit);
3455    }
3456  }
3457
3458  // Fields.
3459  for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3460                               MemEnd = ClassDecl->decls_end();
3461       Mem != MemEnd; ++Mem) {
3462    if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3463      // C++ [class.bit]p2:
3464      //   A declaration for a bit-field that omits the identifier declares an
3465      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3466      //   initialized.
3467      if (F->isUnnamedBitfield())
3468        continue;
3469
3470      // If we're not generating the implicit copy/move constructor, then we'll
3471      // handle anonymous struct/union fields based on their individual
3472      // indirect fields.
3473      if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3474        continue;
3475
3476      if (CollectFieldInitializer(*this, Info, F))
3477        HadError = true;
3478      continue;
3479    }
3480
3481    // Beyond this point, we only consider default initialization.
3482    if (Info.isImplicitCopyOrMove())
3483      continue;
3484
3485    if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3486      if (F->getType()->isIncompleteArrayType()) {
3487        assert(ClassDecl->hasFlexibleArrayMember() &&
3488               "Incomplete array type is not valid");
3489        continue;
3490      }
3491
3492      // Initialize each field of an anonymous struct individually.
3493      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3494        HadError = true;
3495
3496      continue;
3497    }
3498  }
3499
3500  unsigned NumInitializers = Info.AllToInit.size();
3501  if (NumInitializers > 0) {
3502    Constructor->setNumCtorInitializers(NumInitializers);
3503    CXXCtorInitializer **baseOrMemberInitializers =
3504      new (Context) CXXCtorInitializer*[NumInitializers];
3505    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3506           NumInitializers * sizeof(CXXCtorInitializer*));
3507    Constructor->setCtorInitializers(baseOrMemberInitializers);
3508
3509    // Constructors implicitly reference the base and member
3510    // destructors.
3511    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3512                                           Constructor->getParent());
3513  }
3514
3515  return HadError;
3516}
3517
3518static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3519  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3520    const RecordDecl *RD = RT->getDecl();
3521    if (RD->isAnonymousStructOrUnion()) {
3522      for (RecordDecl::field_iterator Field = RD->field_begin(),
3523          E = RD->field_end(); Field != E; ++Field)
3524        PopulateKeysForFields(*Field, IdealInits);
3525      return;
3526    }
3527  }
3528  IdealInits.push_back(Field);
3529}
3530
3531static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3532  return Context.getCanonicalType(BaseType).getTypePtr();
3533}
3534
3535static const void *GetKeyForMember(ASTContext &Context,
3536                                   CXXCtorInitializer *Member) {
3537  if (!Member->isAnyMemberInitializer())
3538    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3539
3540  return Member->getAnyMember();
3541}
3542
3543static void DiagnoseBaseOrMemInitializerOrder(
3544    Sema &SemaRef, const CXXConstructorDecl *Constructor,
3545    ArrayRef<CXXCtorInitializer *> Inits) {
3546  if (Constructor->getDeclContext()->isDependentContext())
3547    return;
3548
3549  // Don't check initializers order unless the warning is enabled at the
3550  // location of at least one initializer.
3551  bool ShouldCheckOrder = false;
3552  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3553    CXXCtorInitializer *Init = Inits[InitIndex];
3554    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3555                                         Init->getSourceLocation())
3556          != DiagnosticsEngine::Ignored) {
3557      ShouldCheckOrder = true;
3558      break;
3559    }
3560  }
3561  if (!ShouldCheckOrder)
3562    return;
3563
3564  // Build the list of bases and members in the order that they'll
3565  // actually be initialized.  The explicit initializers should be in
3566  // this same order but may be missing things.
3567  SmallVector<const void*, 32> IdealInitKeys;
3568
3569  const CXXRecordDecl *ClassDecl = Constructor->getParent();
3570
3571  // 1. Virtual bases.
3572  for (CXXRecordDecl::base_class_const_iterator VBase =
3573       ClassDecl->vbases_begin(),
3574       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3575    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3576
3577  // 2. Non-virtual bases.
3578  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3579       E = ClassDecl->bases_end(); Base != E; ++Base) {
3580    if (Base->isVirtual())
3581      continue;
3582    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3583  }
3584
3585  // 3. Direct fields.
3586  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3587       E = ClassDecl->field_end(); Field != E; ++Field) {
3588    if (Field->isUnnamedBitfield())
3589      continue;
3590
3591    PopulateKeysForFields(*Field, IdealInitKeys);
3592  }
3593
3594  unsigned NumIdealInits = IdealInitKeys.size();
3595  unsigned IdealIndex = 0;
3596
3597  CXXCtorInitializer *PrevInit = 0;
3598  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3599    CXXCtorInitializer *Init = Inits[InitIndex];
3600    const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3601
3602    // Scan forward to try to find this initializer in the idealized
3603    // initializers list.
3604    for (; IdealIndex != NumIdealInits; ++IdealIndex)
3605      if (InitKey == IdealInitKeys[IdealIndex])
3606        break;
3607
3608    // If we didn't find this initializer, it must be because we
3609    // scanned past it on a previous iteration.  That can only
3610    // happen if we're out of order;  emit a warning.
3611    if (IdealIndex == NumIdealInits && PrevInit) {
3612      Sema::SemaDiagnosticBuilder D =
3613        SemaRef.Diag(PrevInit->getSourceLocation(),
3614                     diag::warn_initializer_out_of_order);
3615
3616      if (PrevInit->isAnyMemberInitializer())
3617        D << 0 << PrevInit->getAnyMember()->getDeclName();
3618      else
3619        D << 1 << PrevInit->getTypeSourceInfo()->getType();
3620
3621      if (Init->isAnyMemberInitializer())
3622        D << 0 << Init->getAnyMember()->getDeclName();
3623      else
3624        D << 1 << Init->getTypeSourceInfo()->getType();
3625
3626      // Move back to the initializer's location in the ideal list.
3627      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3628        if (InitKey == IdealInitKeys[IdealIndex])
3629          break;
3630
3631      assert(IdealIndex != NumIdealInits &&
3632             "initializer not found in initializer list");
3633    }
3634
3635    PrevInit = Init;
3636  }
3637}
3638
3639namespace {
3640bool CheckRedundantInit(Sema &S,
3641                        CXXCtorInitializer *Init,
3642                        CXXCtorInitializer *&PrevInit) {
3643  if (!PrevInit) {
3644    PrevInit = Init;
3645    return false;
3646  }
3647
3648  if (FieldDecl *Field = Init->getAnyMember())
3649    S.Diag(Init->getSourceLocation(),
3650           diag::err_multiple_mem_initialization)
3651      << Field->getDeclName()
3652      << Init->getSourceRange();
3653  else {
3654    const Type *BaseClass = Init->getBaseClass();
3655    assert(BaseClass && "neither field nor base");
3656    S.Diag(Init->getSourceLocation(),
3657           diag::err_multiple_base_initialization)
3658      << QualType(BaseClass, 0)
3659      << Init->getSourceRange();
3660  }
3661  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3662    << 0 << PrevInit->getSourceRange();
3663
3664  return true;
3665}
3666
3667typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3668typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3669
3670bool CheckRedundantUnionInit(Sema &S,
3671                             CXXCtorInitializer *Init,
3672                             RedundantUnionMap &Unions) {
3673  FieldDecl *Field = Init->getAnyMember();
3674  RecordDecl *Parent = Field->getParent();
3675  NamedDecl *Child = Field;
3676
3677  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3678    if (Parent->isUnion()) {
3679      UnionEntry &En = Unions[Parent];
3680      if (En.first && En.first != Child) {
3681        S.Diag(Init->getSourceLocation(),
3682               diag::err_multiple_mem_union_initialization)
3683          << Field->getDeclName()
3684          << Init->getSourceRange();
3685        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3686          << 0 << En.second->getSourceRange();
3687        return true;
3688      }
3689      if (!En.first) {
3690        En.first = Child;
3691        En.second = Init;
3692      }
3693      if (!Parent->isAnonymousStructOrUnion())
3694        return false;
3695    }
3696
3697    Child = Parent;
3698    Parent = cast<RecordDecl>(Parent->getDeclContext());
3699  }
3700
3701  return false;
3702}
3703}
3704
3705/// ActOnMemInitializers - Handle the member initializers for a constructor.
3706void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3707                                SourceLocation ColonLoc,
3708                                ArrayRef<CXXCtorInitializer*> MemInits,
3709                                bool AnyErrors) {
3710  if (!ConstructorDecl)
3711    return;
3712
3713  AdjustDeclIfTemplate(ConstructorDecl);
3714
3715  CXXConstructorDecl *Constructor
3716    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3717
3718  if (!Constructor) {
3719    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3720    return;
3721  }
3722
3723  // Mapping for the duplicate initializers check.
3724  // For member initializers, this is keyed with a FieldDecl*.
3725  // For base initializers, this is keyed with a Type*.
3726  llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
3727
3728  // Mapping for the inconsistent anonymous-union initializers check.
3729  RedundantUnionMap MemberUnions;
3730
3731  bool HadError = false;
3732  for (unsigned i = 0; i < MemInits.size(); i++) {
3733    CXXCtorInitializer *Init = MemInits[i];
3734
3735    // Set the source order index.
3736    Init->setSourceOrder(i);
3737
3738    if (Init->isAnyMemberInitializer()) {
3739      FieldDecl *Field = Init->getAnyMember();
3740      if (CheckRedundantInit(*this, Init, Members[Field]) ||
3741          CheckRedundantUnionInit(*this, Init, MemberUnions))
3742        HadError = true;
3743    } else if (Init->isBaseInitializer()) {
3744      const void *Key =
3745          GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3746      if (CheckRedundantInit(*this, Init, Members[Key]))
3747        HadError = true;
3748    } else {
3749      assert(Init->isDelegatingInitializer());
3750      // This must be the only initializer
3751      if (MemInits.size() != 1) {
3752        Diag(Init->getSourceLocation(),
3753             diag::err_delegating_initializer_alone)
3754          << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3755        // We will treat this as being the only initializer.
3756      }
3757      SetDelegatingInitializer(Constructor, MemInits[i]);
3758      // Return immediately as the initializer is set.
3759      return;
3760    }
3761  }
3762
3763  if (HadError)
3764    return;
3765
3766  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
3767
3768  SetCtorInitializers(Constructor, AnyErrors, MemInits);
3769}
3770
3771void
3772Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3773                                             CXXRecordDecl *ClassDecl) {
3774  // Ignore dependent contexts. Also ignore unions, since their members never
3775  // have destructors implicitly called.
3776  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3777    return;
3778
3779  // FIXME: all the access-control diagnostics are positioned on the
3780  // field/base declaration.  That's probably good; that said, the
3781  // user might reasonably want to know why the destructor is being
3782  // emitted, and we currently don't say.
3783
3784  // Non-static data members.
3785  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3786       E = ClassDecl->field_end(); I != E; ++I) {
3787    FieldDecl *Field = *I;
3788    if (Field->isInvalidDecl())
3789      continue;
3790
3791    // Don't destroy incomplete or zero-length arrays.
3792    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3793      continue;
3794
3795    QualType FieldType = Context.getBaseElementType(Field->getType());
3796
3797    const RecordType* RT = FieldType->getAs<RecordType>();
3798    if (!RT)
3799      continue;
3800
3801    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3802    if (FieldClassDecl->isInvalidDecl())
3803      continue;
3804    if (FieldClassDecl->hasIrrelevantDestructor())
3805      continue;
3806    // The destructor for an implicit anonymous union member is never invoked.
3807    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3808      continue;
3809
3810    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3811    assert(Dtor && "No dtor found for FieldClassDecl!");
3812    CheckDestructorAccess(Field->getLocation(), Dtor,
3813                          PDiag(diag::err_access_dtor_field)
3814                            << Field->getDeclName()
3815                            << FieldType);
3816
3817    MarkFunctionReferenced(Location, Dtor);
3818    DiagnoseUseOfDecl(Dtor, Location);
3819  }
3820
3821  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3822
3823  // Bases.
3824  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3825       E = ClassDecl->bases_end(); Base != E; ++Base) {
3826    // Bases are always records in a well-formed non-dependent class.
3827    const RecordType *RT = Base->getType()->getAs<RecordType>();
3828
3829    // Remember direct virtual bases.
3830    if (Base->isVirtual())
3831      DirectVirtualBases.insert(RT);
3832
3833    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3834    // If our base class is invalid, we probably can't get its dtor anyway.
3835    if (BaseClassDecl->isInvalidDecl())
3836      continue;
3837    if (BaseClassDecl->hasIrrelevantDestructor())
3838      continue;
3839
3840    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3841    assert(Dtor && "No dtor found for BaseClassDecl!");
3842
3843    // FIXME: caret should be on the start of the class name
3844    CheckDestructorAccess(Base->getLocStart(), Dtor,
3845                          PDiag(diag::err_access_dtor_base)
3846                            << Base->getType()
3847                            << Base->getSourceRange(),
3848                          Context.getTypeDeclType(ClassDecl));
3849
3850    MarkFunctionReferenced(Location, Dtor);
3851    DiagnoseUseOfDecl(Dtor, Location);
3852  }
3853
3854  // Virtual bases.
3855  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3856       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3857
3858    // Bases are always records in a well-formed non-dependent class.
3859    const RecordType *RT = VBase->getType()->castAs<RecordType>();
3860
3861    // Ignore direct virtual bases.
3862    if (DirectVirtualBases.count(RT))
3863      continue;
3864
3865    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3866    // If our base class is invalid, we probably can't get its dtor anyway.
3867    if (BaseClassDecl->isInvalidDecl())
3868      continue;
3869    if (BaseClassDecl->hasIrrelevantDestructor())
3870      continue;
3871
3872    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3873    assert(Dtor && "No dtor found for BaseClassDecl!");
3874    if (CheckDestructorAccess(
3875            ClassDecl->getLocation(), Dtor,
3876            PDiag(diag::err_access_dtor_vbase)
3877                << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3878            Context.getTypeDeclType(ClassDecl)) ==
3879        AR_accessible) {
3880      CheckDerivedToBaseConversion(
3881          Context.getTypeDeclType(ClassDecl), VBase->getType(),
3882          diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3883          SourceRange(), DeclarationName(), 0);
3884    }
3885
3886    MarkFunctionReferenced(Location, Dtor);
3887    DiagnoseUseOfDecl(Dtor, Location);
3888  }
3889}
3890
3891void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3892  if (!CDtorDecl)
3893    return;
3894
3895  if (CXXConstructorDecl *Constructor
3896      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3897    SetCtorInitializers(Constructor, /*AnyErrors=*/false);
3898}
3899
3900bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3901                                  unsigned DiagID, AbstractDiagSelID SelID) {
3902  class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3903    unsigned DiagID;
3904    AbstractDiagSelID SelID;
3905
3906  public:
3907    NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3908      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3909
3910    void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
3911      if (Suppressed) return;
3912      if (SelID == -1)
3913        S.Diag(Loc, DiagID) << T;
3914      else
3915        S.Diag(Loc, DiagID) << SelID << T;
3916    }
3917  } Diagnoser(DiagID, SelID);
3918
3919  return RequireNonAbstractType(Loc, T, Diagnoser);
3920}
3921
3922bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3923                                  TypeDiagnoser &Diagnoser) {
3924  if (!getLangOpts().CPlusPlus)
3925    return false;
3926
3927  if (const ArrayType *AT = Context.getAsArrayType(T))
3928    return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3929
3930  if (const PointerType *PT = T->getAs<PointerType>()) {
3931    // Find the innermost pointer type.
3932    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3933      PT = T;
3934
3935    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3936      return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3937  }
3938
3939  const RecordType *RT = T->getAs<RecordType>();
3940  if (!RT)
3941    return false;
3942
3943  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3944
3945  // We can't answer whether something is abstract until it has a
3946  // definition.  If it's currently being defined, we'll walk back
3947  // over all the declarations when we have a full definition.
3948  const CXXRecordDecl *Def = RD->getDefinition();
3949  if (!Def || Def->isBeingDefined())
3950    return false;
3951
3952  if (!RD->isAbstract())
3953    return false;
3954
3955  Diagnoser.diagnose(*this, Loc, T);
3956  DiagnoseAbstractType(RD);
3957
3958  return true;
3959}
3960
3961void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3962  // Check if we've already emitted the list of pure virtual functions
3963  // for this class.
3964  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3965    return;
3966
3967  // If the diagnostic is suppressed, don't emit the notes. We're only
3968  // going to emit them once, so try to attach them to a diagnostic we're
3969  // actually going to show.
3970  if (Diags.isLastDiagnosticIgnored())
3971    return;
3972
3973  CXXFinalOverriderMap FinalOverriders;
3974  RD->getFinalOverriders(FinalOverriders);
3975
3976  // Keep a set of seen pure methods so we won't diagnose the same method
3977  // more than once.
3978  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3979
3980  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3981                                   MEnd = FinalOverriders.end();
3982       M != MEnd;
3983       ++M) {
3984    for (OverridingMethods::iterator SO = M->second.begin(),
3985                                  SOEnd = M->second.end();
3986         SO != SOEnd; ++SO) {
3987      // C++ [class.abstract]p4:
3988      //   A class is abstract if it contains or inherits at least one
3989      //   pure virtual function for which the final overrider is pure
3990      //   virtual.
3991
3992      //
3993      if (SO->second.size() != 1)
3994        continue;
3995
3996      if (!SO->second.front().Method->isPure())
3997        continue;
3998
3999      if (!SeenPureMethods.insert(SO->second.front().Method))
4000        continue;
4001
4002      Diag(SO->second.front().Method->getLocation(),
4003           diag::note_pure_virtual_function)
4004        << SO->second.front().Method->getDeclName() << RD->getDeclName();
4005    }
4006  }
4007
4008  if (!PureVirtualClassDiagSet)
4009    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4010  PureVirtualClassDiagSet->insert(RD);
4011}
4012
4013namespace {
4014struct AbstractUsageInfo {
4015  Sema &S;
4016  CXXRecordDecl *Record;
4017  CanQualType AbstractType;
4018  bool Invalid;
4019
4020  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4021    : S(S), Record(Record),
4022      AbstractType(S.Context.getCanonicalType(
4023                   S.Context.getTypeDeclType(Record))),
4024      Invalid(false) {}
4025
4026  void DiagnoseAbstractType() {
4027    if (Invalid) return;
4028    S.DiagnoseAbstractType(Record);
4029    Invalid = true;
4030  }
4031
4032  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4033};
4034
4035struct CheckAbstractUsage {
4036  AbstractUsageInfo &Info;
4037  const NamedDecl *Ctx;
4038
4039  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4040    : Info(Info), Ctx(Ctx) {}
4041
4042  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4043    switch (TL.getTypeLocClass()) {
4044#define ABSTRACT_TYPELOC(CLASS, PARENT)
4045#define TYPELOC(CLASS, PARENT) \
4046    case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4047#include "clang/AST/TypeLocNodes.def"
4048    }
4049  }
4050
4051  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4052    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4053    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4054      if (!TL.getArg(I))
4055        continue;
4056
4057      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4058      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4059    }
4060  }
4061
4062  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4063    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4064  }
4065
4066  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4067    // Visit the type parameters from a permissive context.
4068    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4069      TemplateArgumentLoc TAL = TL.getArgLoc(I);
4070      if (TAL.getArgument().getKind() == TemplateArgument::Type)
4071        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4072          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4073      // TODO: other template argument types?
4074    }
4075  }
4076
4077  // Visit pointee types from a permissive context.
4078#define CheckPolymorphic(Type) \
4079  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4080    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4081  }
4082  CheckPolymorphic(PointerTypeLoc)
4083  CheckPolymorphic(ReferenceTypeLoc)
4084  CheckPolymorphic(MemberPointerTypeLoc)
4085  CheckPolymorphic(BlockPointerTypeLoc)
4086  CheckPolymorphic(AtomicTypeLoc)
4087
4088  /// Handle all the types we haven't given a more specific
4089  /// implementation for above.
4090  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4091    // Every other kind of type that we haven't called out already
4092    // that has an inner type is either (1) sugar or (2) contains that
4093    // inner type in some way as a subobject.
4094    if (TypeLoc Next = TL.getNextTypeLoc())
4095      return Visit(Next, Sel);
4096
4097    // If there's no inner type and we're in a permissive context,
4098    // don't diagnose.
4099    if (Sel == Sema::AbstractNone) return;
4100
4101    // Check whether the type matches the abstract type.
4102    QualType T = TL.getType();
4103    if (T->isArrayType()) {
4104      Sel = Sema::AbstractArrayType;
4105      T = Info.S.Context.getBaseElementType(T);
4106    }
4107    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4108    if (CT != Info.AbstractType) return;
4109
4110    // It matched; do some magic.
4111    if (Sel == Sema::AbstractArrayType) {
4112      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4113        << T << TL.getSourceRange();
4114    } else {
4115      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4116        << Sel << T << TL.getSourceRange();
4117    }
4118    Info.DiagnoseAbstractType();
4119  }
4120};
4121
4122void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4123                                  Sema::AbstractDiagSelID Sel) {
4124  CheckAbstractUsage(*this, D).Visit(TL, Sel);
4125}
4126
4127}
4128
4129/// Check for invalid uses of an abstract type in a method declaration.
4130static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4131                                    CXXMethodDecl *MD) {
4132  // No need to do the check on definitions, which require that
4133  // the return/param types be complete.
4134  if (MD->doesThisDeclarationHaveABody())
4135    return;
4136
4137  // For safety's sake, just ignore it if we don't have type source
4138  // information.  This should never happen for non-implicit methods,
4139  // but...
4140  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4141    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4142}
4143
4144/// Check for invalid uses of an abstract type within a class definition.
4145static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4146                                    CXXRecordDecl *RD) {
4147  for (CXXRecordDecl::decl_iterator
4148         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4149    Decl *D = *I;
4150    if (D->isImplicit()) continue;
4151
4152    // Methods and method templates.
4153    if (isa<CXXMethodDecl>(D)) {
4154      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4155    } else if (isa<FunctionTemplateDecl>(D)) {
4156      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4157      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4158
4159    // Fields and static variables.
4160    } else if (isa<FieldDecl>(D)) {
4161      FieldDecl *FD = cast<FieldDecl>(D);
4162      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4163        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4164    } else if (isa<VarDecl>(D)) {
4165      VarDecl *VD = cast<VarDecl>(D);
4166      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4167        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4168
4169    // Nested classes and class templates.
4170    } else if (isa<CXXRecordDecl>(D)) {
4171      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4172    } else if (isa<ClassTemplateDecl>(D)) {
4173      CheckAbstractClassUsage(Info,
4174                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4175    }
4176  }
4177}
4178
4179/// \brief Perform semantic checks on a class definition that has been
4180/// completing, introducing implicitly-declared members, checking for
4181/// abstract types, etc.
4182void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4183  if (!Record)
4184    return;
4185
4186  if (Record->isAbstract() && !Record->isInvalidDecl()) {
4187    AbstractUsageInfo Info(*this, Record);
4188    CheckAbstractClassUsage(Info, Record);
4189  }
4190
4191  // If this is not an aggregate type and has no user-declared constructor,
4192  // complain about any non-static data members of reference or const scalar
4193  // type, since they will never get initializers.
4194  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4195      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4196      !Record->isLambda()) {
4197    bool Complained = false;
4198    for (RecordDecl::field_iterator F = Record->field_begin(),
4199                                 FEnd = Record->field_end();
4200         F != FEnd; ++F) {
4201      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4202        continue;
4203
4204      if (F->getType()->isReferenceType() ||
4205          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4206        if (!Complained) {
4207          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4208            << Record->getTagKind() << Record;
4209          Complained = true;
4210        }
4211
4212        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4213          << F->getType()->isReferenceType()
4214          << F->getDeclName();
4215      }
4216    }
4217  }
4218
4219  if (Record->isDynamicClass() && !Record->isDependentType())
4220    DynamicClasses.push_back(Record);
4221
4222  if (Record->getIdentifier()) {
4223    // C++ [class.mem]p13:
4224    //   If T is the name of a class, then each of the following shall have a
4225    //   name different from T:
4226    //     - every member of every anonymous union that is a member of class T.
4227    //
4228    // C++ [class.mem]p14:
4229    //   In addition, if class T has a user-declared constructor (12.1), every
4230    //   non-static data member of class T shall have a name different from T.
4231    DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4232    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4233         ++I) {
4234      NamedDecl *D = *I;
4235      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4236          isa<IndirectFieldDecl>(D)) {
4237        Diag(D->getLocation(), diag::err_member_name_of_class)
4238          << D->getDeclName();
4239        break;
4240      }
4241    }
4242  }
4243
4244  // Warn if the class has virtual methods but non-virtual public destructor.
4245  if (Record->isPolymorphic() && !Record->isDependentType()) {
4246    CXXDestructorDecl *dtor = Record->getDestructor();
4247    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
4248      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4249           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4250  }
4251
4252  if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4253    Diag(Record->getLocation(), diag::warn_abstract_final_class);
4254    DiagnoseAbstractType(Record);
4255  }
4256
4257  if (!Record->isDependentType()) {
4258    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4259                                     MEnd = Record->method_end();
4260         M != MEnd; ++M) {
4261      // See if a method overloads virtual methods in a base
4262      // class without overriding any.
4263      if (!M->isStatic())
4264        DiagnoseHiddenVirtualMethods(*M);
4265
4266      // Check whether the explicitly-defaulted special members are valid.
4267      if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4268        CheckExplicitlyDefaultedSpecialMember(*M);
4269
4270      // For an explicitly defaulted or deleted special member, we defer
4271      // determining triviality until the class is complete. That time is now!
4272      if (!M->isImplicit() && !M->isUserProvided()) {
4273        CXXSpecialMember CSM = getSpecialMember(*M);
4274        if (CSM != CXXInvalid) {
4275          M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4276
4277          // Inform the class that we've finished declaring this member.
4278          Record->finishedDefaultedOrDeletedMember(*M);
4279        }
4280      }
4281    }
4282  }
4283
4284  // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4285  // function that is not a constructor declares that member function to be
4286  // const. [...] The class of which that function is a member shall be
4287  // a literal type.
4288  //
4289  // If the class has virtual bases, any constexpr members will already have
4290  // been diagnosed by the checks performed on the member declaration, so
4291  // suppress this (less useful) diagnostic.
4292  //
4293  // We delay this until we know whether an explicitly-defaulted (or deleted)
4294  // destructor for the class is trivial.
4295  if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4296      !Record->isLiteral() && !Record->getNumVBases()) {
4297    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4298                                     MEnd = Record->method_end();
4299         M != MEnd; ++M) {
4300      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4301        switch (Record->getTemplateSpecializationKind()) {
4302        case TSK_ImplicitInstantiation:
4303        case TSK_ExplicitInstantiationDeclaration:
4304        case TSK_ExplicitInstantiationDefinition:
4305          // If a template instantiates to a non-literal type, but its members
4306          // instantiate to constexpr functions, the template is technically
4307          // ill-formed, but we allow it for sanity.
4308          continue;
4309
4310        case TSK_Undeclared:
4311        case TSK_ExplicitSpecialization:
4312          RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4313                             diag::err_constexpr_method_non_literal);
4314          break;
4315        }
4316
4317        // Only produce one error per class.
4318        break;
4319      }
4320    }
4321  }
4322
4323  // Declare inheriting constructors. We do this eagerly here because:
4324  // - The standard requires an eager diagnostic for conflicting inheriting
4325  //   constructors from different classes.
4326  // - The lazy declaration of the other implicit constructors is so as to not
4327  //   waste space and performance on classes that are not meant to be
4328  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4329  //   have inheriting constructors.
4330  DeclareInheritingConstructors(Record);
4331}
4332
4333/// Is the special member function which would be selected to perform the
4334/// specified operation on the specified class type a constexpr constructor?
4335static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4336                                     Sema::CXXSpecialMember CSM,
4337                                     bool ConstArg) {
4338  Sema::SpecialMemberOverloadResult *SMOR =
4339      S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4340                            false, false, false, false);
4341  if (!SMOR || !SMOR->getMethod())
4342    // A constructor we wouldn't select can't be "involved in initializing"
4343    // anything.
4344    return true;
4345  return SMOR->getMethod()->isConstexpr();
4346}
4347
4348/// Determine whether the specified special member function would be constexpr
4349/// if it were implicitly defined.
4350static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4351                                              Sema::CXXSpecialMember CSM,
4352                                              bool ConstArg) {
4353  if (!S.getLangOpts().CPlusPlus11)
4354    return false;
4355
4356  // C++11 [dcl.constexpr]p4:
4357  // In the definition of a constexpr constructor [...]
4358  bool Ctor = true;
4359  switch (CSM) {
4360  case Sema::CXXDefaultConstructor:
4361    // Since default constructor lookup is essentially trivial (and cannot
4362    // involve, for instance, template instantiation), we compute whether a
4363    // defaulted default constructor is constexpr directly within CXXRecordDecl.
4364    //
4365    // This is important for performance; we need to know whether the default
4366    // constructor is constexpr to determine whether the type is a literal type.
4367    return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4368
4369  case Sema::CXXCopyConstructor:
4370  case Sema::CXXMoveConstructor:
4371    // For copy or move constructors, we need to perform overload resolution.
4372    break;
4373
4374  case Sema::CXXCopyAssignment:
4375  case Sema::CXXMoveAssignment:
4376    if (!S.getLangOpts().CPlusPlus1y)
4377      return false;
4378    // In C++1y, we need to perform overload resolution.
4379    Ctor = false;
4380    break;
4381
4382  case Sema::CXXDestructor:
4383  case Sema::CXXInvalid:
4384    return false;
4385  }
4386
4387  //   -- if the class is a non-empty union, or for each non-empty anonymous
4388  //      union member of a non-union class, exactly one non-static data member
4389  //      shall be initialized; [DR1359]
4390  //
4391  // If we squint, this is guaranteed, since exactly one non-static data member
4392  // will be initialized (if the constructor isn't deleted), we just don't know
4393  // which one.
4394  if (Ctor && ClassDecl->isUnion())
4395    return true;
4396
4397  //   -- the class shall not have any virtual base classes;
4398  if (Ctor && ClassDecl->getNumVBases())
4399    return false;
4400
4401  // C++1y [class.copy]p26:
4402  //   -- [the class] is a literal type, and
4403  if (!Ctor && !ClassDecl->isLiteral())
4404    return false;
4405
4406  //   -- every constructor involved in initializing [...] base class
4407  //      sub-objects shall be a constexpr constructor;
4408  //   -- the assignment operator selected to copy/move each direct base
4409  //      class is a constexpr function, and
4410  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4411                                       BEnd = ClassDecl->bases_end();
4412       B != BEnd; ++B) {
4413    const RecordType *BaseType = B->getType()->getAs<RecordType>();
4414    if (!BaseType) continue;
4415
4416    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4417    if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4418      return false;
4419  }
4420
4421  //   -- every constructor involved in initializing non-static data members
4422  //      [...] shall be a constexpr constructor;
4423  //   -- every non-static data member and base class sub-object shall be
4424  //      initialized
4425  //   -- for each non-stastic data member of X that is of class type (or array
4426  //      thereof), the assignment operator selected to copy/move that member is
4427  //      a constexpr function
4428  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4429                               FEnd = ClassDecl->field_end();
4430       F != FEnd; ++F) {
4431    if (F->isInvalidDecl())
4432      continue;
4433    if (const RecordType *RecordTy =
4434            S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4435      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4436      if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4437        return false;
4438    }
4439  }
4440
4441  // All OK, it's constexpr!
4442  return true;
4443}
4444
4445static Sema::ImplicitExceptionSpecification
4446computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4447  switch (S.getSpecialMember(MD)) {
4448  case Sema::CXXDefaultConstructor:
4449    return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4450  case Sema::CXXCopyConstructor:
4451    return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4452  case Sema::CXXCopyAssignment:
4453    return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4454  case Sema::CXXMoveConstructor:
4455    return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4456  case Sema::CXXMoveAssignment:
4457    return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4458  case Sema::CXXDestructor:
4459    return S.ComputeDefaultedDtorExceptionSpec(MD);
4460  case Sema::CXXInvalid:
4461    break;
4462  }
4463  assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4464         "only special members have implicit exception specs");
4465  return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4466}
4467
4468static void
4469updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4470                    const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4471  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4472  ExceptSpec.getEPI(EPI);
4473  FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4474                                        FPT->getArgTypes(), EPI));
4475}
4476
4477static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4478                                                            CXXMethodDecl *MD) {
4479  FunctionProtoType::ExtProtoInfo EPI;
4480
4481  // Build an exception specification pointing back at this member.
4482  EPI.ExceptionSpecType = EST_Unevaluated;
4483  EPI.ExceptionSpecDecl = MD;
4484
4485  // Set the calling convention to the default for C++ instance methods.
4486  EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4487      S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4488                                            /*IsCXXMethod=*/true));
4489  return EPI;
4490}
4491
4492void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4493  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4494  if (FPT->getExceptionSpecType() != EST_Unevaluated)
4495    return;
4496
4497  // Evaluate the exception specification.
4498  ImplicitExceptionSpecification ExceptSpec =
4499      computeImplicitExceptionSpec(*this, Loc, MD);
4500
4501  // Update the type of the special member to use it.
4502  updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4503
4504  // A user-provided destructor can be defined outside the class. When that
4505  // happens, be sure to update the exception specification on both
4506  // declarations.
4507  const FunctionProtoType *CanonicalFPT =
4508    MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4509  if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4510    updateExceptionSpec(*this, MD->getCanonicalDecl(),
4511                        CanonicalFPT, ExceptSpec);
4512}
4513
4514void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4515  CXXRecordDecl *RD = MD->getParent();
4516  CXXSpecialMember CSM = getSpecialMember(MD);
4517
4518  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4519         "not an explicitly-defaulted special member");
4520
4521  // Whether this was the first-declared instance of the constructor.
4522  // This affects whether we implicitly add an exception spec and constexpr.
4523  bool First = MD == MD->getCanonicalDecl();
4524
4525  bool HadError = false;
4526
4527  // C++11 [dcl.fct.def.default]p1:
4528  //   A function that is explicitly defaulted shall
4529  //     -- be a special member function (checked elsewhere),
4530  //     -- have the same type (except for ref-qualifiers, and except that a
4531  //        copy operation can take a non-const reference) as an implicit
4532  //        declaration, and
4533  //     -- not have default arguments.
4534  unsigned ExpectedParams = 1;
4535  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4536    ExpectedParams = 0;
4537  if (MD->getNumParams() != ExpectedParams) {
4538    // This also checks for default arguments: a copy or move constructor with a
4539    // default argument is classified as a default constructor, and assignment
4540    // operations and destructors can't have default arguments.
4541    Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4542      << CSM << MD->getSourceRange();
4543    HadError = true;
4544  } else if (MD->isVariadic()) {
4545    Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4546      << CSM << MD->getSourceRange();
4547    HadError = true;
4548  }
4549
4550  const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4551
4552  bool CanHaveConstParam = false;
4553  if (CSM == CXXCopyConstructor)
4554    CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4555  else if (CSM == CXXCopyAssignment)
4556    CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4557
4558  QualType ReturnType = Context.VoidTy;
4559  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4560    // Check for return type matching.
4561    ReturnType = Type->getResultType();
4562    QualType ExpectedReturnType =
4563        Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4564    if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4565      Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4566        << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4567      HadError = true;
4568    }
4569
4570    // A defaulted special member cannot have cv-qualifiers.
4571    if (Type->getTypeQuals()) {
4572      Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4573        << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
4574      HadError = true;
4575    }
4576  }
4577
4578  // Check for parameter type matching.
4579  QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4580  bool HasConstParam = false;
4581  if (ExpectedParams && ArgType->isReferenceType()) {
4582    // Argument must be reference to possibly-const T.
4583    QualType ReferentType = ArgType->getPointeeType();
4584    HasConstParam = ReferentType.isConstQualified();
4585
4586    if (ReferentType.isVolatileQualified()) {
4587      Diag(MD->getLocation(),
4588           diag::err_defaulted_special_member_volatile_param) << CSM;
4589      HadError = true;
4590    }
4591
4592    if (HasConstParam && !CanHaveConstParam) {
4593      if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4594        Diag(MD->getLocation(),
4595             diag::err_defaulted_special_member_copy_const_param)
4596          << (CSM == CXXCopyAssignment);
4597        // FIXME: Explain why this special member can't be const.
4598      } else {
4599        Diag(MD->getLocation(),
4600             diag::err_defaulted_special_member_move_const_param)
4601          << (CSM == CXXMoveAssignment);
4602      }
4603      HadError = true;
4604    }
4605  } else if (ExpectedParams) {
4606    // A copy assignment operator can take its argument by value, but a
4607    // defaulted one cannot.
4608    assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4609    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4610    HadError = true;
4611  }
4612
4613  // C++11 [dcl.fct.def.default]p2:
4614  //   An explicitly-defaulted function may be declared constexpr only if it
4615  //   would have been implicitly declared as constexpr,
4616  // Do not apply this rule to members of class templates, since core issue 1358
4617  // makes such functions always instantiate to constexpr functions. For
4618  // functions which cannot be constexpr (for non-constructors in C++11 and for
4619  // destructors in C++1y), this is checked elsewhere.
4620  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4621                                                     HasConstParam);
4622  if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4623                                 : isa<CXXConstructorDecl>(MD)) &&
4624      MD->isConstexpr() && !Constexpr &&
4625      MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4626    Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4627    // FIXME: Explain why the special member can't be constexpr.
4628    HadError = true;
4629  }
4630
4631  //   and may have an explicit exception-specification only if it is compatible
4632  //   with the exception-specification on the implicit declaration.
4633  if (Type->hasExceptionSpec()) {
4634    // Delay the check if this is the first declaration of the special member,
4635    // since we may not have parsed some necessary in-class initializers yet.
4636    if (First) {
4637      // If the exception specification needs to be instantiated, do so now,
4638      // before we clobber it with an EST_Unevaluated specification below.
4639      if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4640        InstantiateExceptionSpec(MD->getLocStart(), MD);
4641        Type = MD->getType()->getAs<FunctionProtoType>();
4642      }
4643      DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4644    } else
4645      CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4646  }
4647
4648  //   If a function is explicitly defaulted on its first declaration,
4649  if (First) {
4650    //  -- it is implicitly considered to be constexpr if the implicit
4651    //     definition would be,
4652    MD->setConstexpr(Constexpr);
4653
4654    //  -- it is implicitly considered to have the same exception-specification
4655    //     as if it had been implicitly declared,
4656    FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4657    EPI.ExceptionSpecType = EST_Unevaluated;
4658    EPI.ExceptionSpecDecl = MD;
4659    MD->setType(Context.getFunctionType(ReturnType,
4660                                        ArrayRef<QualType>(&ArgType,
4661                                                           ExpectedParams),
4662                                        EPI));
4663  }
4664
4665  if (ShouldDeleteSpecialMember(MD, CSM)) {
4666    if (First) {
4667      SetDeclDeleted(MD, MD->getLocation());
4668    } else {
4669      // C++11 [dcl.fct.def.default]p4:
4670      //   [For a] user-provided explicitly-defaulted function [...] if such a
4671      //   function is implicitly defined as deleted, the program is ill-formed.
4672      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4673      HadError = true;
4674    }
4675  }
4676
4677  if (HadError)
4678    MD->setInvalidDecl();
4679}
4680
4681/// Check whether the exception specification provided for an
4682/// explicitly-defaulted special member matches the exception specification
4683/// that would have been generated for an implicit special member, per
4684/// C++11 [dcl.fct.def.default]p2.
4685void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4686    CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4687  // Compute the implicit exception specification.
4688  CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4689                                                       /*IsCXXMethod=*/true);
4690  FunctionProtoType::ExtProtoInfo EPI(CC);
4691  computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4692  const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4693    Context.getFunctionType(Context.VoidTy, None, EPI));
4694
4695  // Ensure that it matches.
4696  CheckEquivalentExceptionSpec(
4697    PDiag(diag::err_incorrect_defaulted_exception_spec)
4698      << getSpecialMember(MD), PDiag(),
4699    ImplicitType, SourceLocation(),
4700    SpecifiedType, MD->getLocation());
4701}
4702
4703void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4704  for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4705       I != N; ++I)
4706    CheckExplicitlyDefaultedMemberExceptionSpec(
4707      DelayedDefaultedMemberExceptionSpecs[I].first,
4708      DelayedDefaultedMemberExceptionSpecs[I].second);
4709
4710  DelayedDefaultedMemberExceptionSpecs.clear();
4711}
4712
4713namespace {
4714struct SpecialMemberDeletionInfo {
4715  Sema &S;
4716  CXXMethodDecl *MD;
4717  Sema::CXXSpecialMember CSM;
4718  bool Diagnose;
4719
4720  // Properties of the special member, computed for convenience.
4721  bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4722  SourceLocation Loc;
4723
4724  bool AllFieldsAreConst;
4725
4726  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4727                            Sema::CXXSpecialMember CSM, bool Diagnose)
4728    : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4729      IsConstructor(false), IsAssignment(false), IsMove(false),
4730      ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4731      AllFieldsAreConst(true) {
4732    switch (CSM) {
4733      case Sema::CXXDefaultConstructor:
4734      case Sema::CXXCopyConstructor:
4735        IsConstructor = true;
4736        break;
4737      case Sema::CXXMoveConstructor:
4738        IsConstructor = true;
4739        IsMove = true;
4740        break;
4741      case Sema::CXXCopyAssignment:
4742        IsAssignment = true;
4743        break;
4744      case Sema::CXXMoveAssignment:
4745        IsAssignment = true;
4746        IsMove = true;
4747        break;
4748      case Sema::CXXDestructor:
4749        break;
4750      case Sema::CXXInvalid:
4751        llvm_unreachable("invalid special member kind");
4752    }
4753
4754    if (MD->getNumParams()) {
4755      ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4756      VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4757    }
4758  }
4759
4760  bool inUnion() const { return MD->getParent()->isUnion(); }
4761
4762  /// Look up the corresponding special member in the given class.
4763  Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4764                                              unsigned Quals) {
4765    unsigned TQ = MD->getTypeQualifiers();
4766    // cv-qualifiers on class members don't affect default ctor / dtor calls.
4767    if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4768      Quals = 0;
4769    return S.LookupSpecialMember(Class, CSM,
4770                                 ConstArg || (Quals & Qualifiers::Const),
4771                                 VolatileArg || (Quals & Qualifiers::Volatile),
4772                                 MD->getRefQualifier() == RQ_RValue,
4773                                 TQ & Qualifiers::Const,
4774                                 TQ & Qualifiers::Volatile);
4775  }
4776
4777  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4778
4779  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4780  bool shouldDeleteForField(FieldDecl *FD);
4781  bool shouldDeleteForAllConstMembers();
4782
4783  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4784                                     unsigned Quals);
4785  bool shouldDeleteForSubobjectCall(Subobject Subobj,
4786                                    Sema::SpecialMemberOverloadResult *SMOR,
4787                                    bool IsDtorCallInCtor);
4788
4789  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4790};
4791}
4792
4793/// Is the given special member inaccessible when used on the given
4794/// sub-object.
4795bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4796                                             CXXMethodDecl *target) {
4797  /// If we're operating on a base class, the object type is the
4798  /// type of this special member.
4799  QualType objectTy;
4800  AccessSpecifier access = target->getAccess();
4801  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4802    objectTy = S.Context.getTypeDeclType(MD->getParent());
4803    access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4804
4805  // If we're operating on a field, the object type is the type of the field.
4806  } else {
4807    objectTy = S.Context.getTypeDeclType(target->getParent());
4808  }
4809
4810  return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4811}
4812
4813/// Check whether we should delete a special member due to the implicit
4814/// definition containing a call to a special member of a subobject.
4815bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4816    Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4817    bool IsDtorCallInCtor) {
4818  CXXMethodDecl *Decl = SMOR->getMethod();
4819  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4820
4821  int DiagKind = -1;
4822
4823  if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4824    DiagKind = !Decl ? 0 : 1;
4825  else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4826    DiagKind = 2;
4827  else if (!isAccessible(Subobj, Decl))
4828    DiagKind = 3;
4829  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4830           !Decl->isTrivial()) {
4831    // A member of a union must have a trivial corresponding special member.
4832    // As a weird special case, a destructor call from a union's constructor
4833    // must be accessible and non-deleted, but need not be trivial. Such a
4834    // destructor is never actually called, but is semantically checked as
4835    // if it were.
4836    DiagKind = 4;
4837  }
4838
4839  if (DiagKind == -1)
4840    return false;
4841
4842  if (Diagnose) {
4843    if (Field) {
4844      S.Diag(Field->getLocation(),
4845             diag::note_deleted_special_member_class_subobject)
4846        << CSM << MD->getParent() << /*IsField*/true
4847        << Field << DiagKind << IsDtorCallInCtor;
4848    } else {
4849      CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4850      S.Diag(Base->getLocStart(),
4851             diag::note_deleted_special_member_class_subobject)
4852        << CSM << MD->getParent() << /*IsField*/false
4853        << Base->getType() << DiagKind << IsDtorCallInCtor;
4854    }
4855
4856    if (DiagKind == 1)
4857      S.NoteDeletedFunction(Decl);
4858    // FIXME: Explain inaccessibility if DiagKind == 3.
4859  }
4860
4861  return true;
4862}
4863
4864/// Check whether we should delete a special member function due to having a
4865/// direct or virtual base class or non-static data member of class type M.
4866bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4867    CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
4868  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4869
4870  // C++11 [class.ctor]p5:
4871  // -- any direct or virtual base class, or non-static data member with no
4872  //    brace-or-equal-initializer, has class type M (or array thereof) and
4873  //    either M has no default constructor or overload resolution as applied
4874  //    to M's default constructor results in an ambiguity or in a function
4875  //    that is deleted or inaccessible
4876  // C++11 [class.copy]p11, C++11 [class.copy]p23:
4877  // -- a direct or virtual base class B that cannot be copied/moved because
4878  //    overload resolution, as applied to B's corresponding special member,
4879  //    results in an ambiguity or a function that is deleted or inaccessible
4880  //    from the defaulted special member
4881  // C++11 [class.dtor]p5:
4882  // -- any direct or virtual base class [...] has a type with a destructor
4883  //    that is deleted or inaccessible
4884  if (!(CSM == Sema::CXXDefaultConstructor &&
4885        Field && Field->hasInClassInitializer()) &&
4886      shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
4887    return true;
4888
4889  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4890  // -- any direct or virtual base class or non-static data member has a
4891  //    type with a destructor that is deleted or inaccessible
4892  if (IsConstructor) {
4893    Sema::SpecialMemberOverloadResult *SMOR =
4894        S.LookupSpecialMember(Class, Sema::CXXDestructor,
4895                              false, false, false, false, false);
4896    if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4897      return true;
4898  }
4899
4900  return false;
4901}
4902
4903/// Check whether we should delete a special member function due to the class
4904/// having a particular direct or virtual base class.
4905bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4906  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4907  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
4908}
4909
4910/// Check whether we should delete a special member function due to the class
4911/// having a particular non-static data member.
4912bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4913  QualType FieldType = S.Context.getBaseElementType(FD->getType());
4914  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4915
4916  if (CSM == Sema::CXXDefaultConstructor) {
4917    // For a default constructor, all references must be initialized in-class
4918    // and, if a union, it must have a non-const member.
4919    if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4920      if (Diagnose)
4921        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4922          << MD->getParent() << FD << FieldType << /*Reference*/0;
4923      return true;
4924    }
4925    // C++11 [class.ctor]p5: any non-variant non-static data member of
4926    // const-qualified type (or array thereof) with no
4927    // brace-or-equal-initializer does not have a user-provided default
4928    // constructor.
4929    if (!inUnion() && FieldType.isConstQualified() &&
4930        !FD->hasInClassInitializer() &&
4931        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4932      if (Diagnose)
4933        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4934          << MD->getParent() << FD << FD->getType() << /*Const*/1;
4935      return true;
4936    }
4937
4938    if (inUnion() && !FieldType.isConstQualified())
4939      AllFieldsAreConst = false;
4940  } else if (CSM == Sema::CXXCopyConstructor) {
4941    // For a copy constructor, data members must not be of rvalue reference
4942    // type.
4943    if (FieldType->isRValueReferenceType()) {
4944      if (Diagnose)
4945        S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4946          << MD->getParent() << FD << FieldType;
4947      return true;
4948    }
4949  } else if (IsAssignment) {
4950    // For an assignment operator, data members must not be of reference type.
4951    if (FieldType->isReferenceType()) {
4952      if (Diagnose)
4953        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4954          << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4955      return true;
4956    }
4957    if (!FieldRecord && FieldType.isConstQualified()) {
4958      // C++11 [class.copy]p23:
4959      // -- a non-static data member of const non-class type (or array thereof)
4960      if (Diagnose)
4961        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4962          << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
4963      return true;
4964    }
4965  }
4966
4967  if (FieldRecord) {
4968    // Some additional restrictions exist on the variant members.
4969    if (!inUnion() && FieldRecord->isUnion() &&
4970        FieldRecord->isAnonymousStructOrUnion()) {
4971      bool AllVariantFieldsAreConst = true;
4972
4973      // FIXME: Handle anonymous unions declared within anonymous unions.
4974      for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4975                                         UE = FieldRecord->field_end();
4976           UI != UE; ++UI) {
4977        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4978
4979        if (!UnionFieldType.isConstQualified())
4980          AllVariantFieldsAreConst = false;
4981
4982        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4983        if (UnionFieldRecord &&
4984            shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4985                                          UnionFieldType.getCVRQualifiers()))
4986          return true;
4987      }
4988
4989      // At least one member in each anonymous union must be non-const
4990      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4991          FieldRecord->field_begin() != FieldRecord->field_end()) {
4992        if (Diagnose)
4993          S.Diag(FieldRecord->getLocation(),
4994                 diag::note_deleted_default_ctor_all_const)
4995            << MD->getParent() << /*anonymous union*/1;
4996        return true;
4997      }
4998
4999      // Don't check the implicit member of the anonymous union type.
5000      // This is technically non-conformant, but sanity demands it.
5001      return false;
5002    }
5003
5004    if (shouldDeleteForClassSubobject(FieldRecord, FD,
5005                                      FieldType.getCVRQualifiers()))
5006      return true;
5007  }
5008
5009  return false;
5010}
5011
5012/// C++11 [class.ctor] p5:
5013///   A defaulted default constructor for a class X is defined as deleted if
5014/// X is a union and all of its variant members are of const-qualified type.
5015bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5016  // This is a silly definition, because it gives an empty union a deleted
5017  // default constructor. Don't do that.
5018  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5019      (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5020    if (Diagnose)
5021      S.Diag(MD->getParent()->getLocation(),
5022             diag::note_deleted_default_ctor_all_const)
5023        << MD->getParent() << /*not anonymous union*/0;
5024    return true;
5025  }
5026  return false;
5027}
5028
5029/// Determine whether a defaulted special member function should be defined as
5030/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5031/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5032bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5033                                     bool Diagnose) {
5034  if (MD->isInvalidDecl())
5035    return false;
5036  CXXRecordDecl *RD = MD->getParent();
5037  assert(!RD->isDependentType() && "do deletion after instantiation");
5038  if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5039    return false;
5040
5041  // C++11 [expr.lambda.prim]p19:
5042  //   The closure type associated with a lambda-expression has a
5043  //   deleted (8.4.3) default constructor and a deleted copy
5044  //   assignment operator.
5045  if (RD->isLambda() &&
5046      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5047    if (Diagnose)
5048      Diag(RD->getLocation(), diag::note_lambda_decl);
5049    return true;
5050  }
5051
5052  // For an anonymous struct or union, the copy and assignment special members
5053  // will never be used, so skip the check. For an anonymous union declared at
5054  // namespace scope, the constructor and destructor are used.
5055  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5056      RD->isAnonymousStructOrUnion())
5057    return false;
5058
5059  // C++11 [class.copy]p7, p18:
5060  //   If the class definition declares a move constructor or move assignment
5061  //   operator, an implicitly declared copy constructor or copy assignment
5062  //   operator is defined as deleted.
5063  if (MD->isImplicit() &&
5064      (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5065    CXXMethodDecl *UserDeclaredMove = 0;
5066
5067    // In Microsoft mode, a user-declared move only causes the deletion of the
5068    // corresponding copy operation, not both copy operations.
5069    if (RD->hasUserDeclaredMoveConstructor() &&
5070        (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5071      if (!Diagnose) return true;
5072
5073      // Find any user-declared move constructor.
5074      for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5075                                        E = RD->ctor_end(); I != E; ++I) {
5076        if (I->isMoveConstructor()) {
5077          UserDeclaredMove = *I;
5078          break;
5079        }
5080      }
5081      assert(UserDeclaredMove);
5082    } else if (RD->hasUserDeclaredMoveAssignment() &&
5083               (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5084      if (!Diagnose) return true;
5085
5086      // Find any user-declared move assignment operator.
5087      for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5088                                          E = RD->method_end(); I != E; ++I) {
5089        if (I->isMoveAssignmentOperator()) {
5090          UserDeclaredMove = *I;
5091          break;
5092        }
5093      }
5094      assert(UserDeclaredMove);
5095    }
5096
5097    if (UserDeclaredMove) {
5098      Diag(UserDeclaredMove->getLocation(),
5099           diag::note_deleted_copy_user_declared_move)
5100        << (CSM == CXXCopyAssignment) << RD
5101        << UserDeclaredMove->isMoveAssignmentOperator();
5102      return true;
5103    }
5104  }
5105
5106  // Do access control from the special member function
5107  ContextRAII MethodContext(*this, MD);
5108
5109  // C++11 [class.dtor]p5:
5110  // -- for a virtual destructor, lookup of the non-array deallocation function
5111  //    results in an ambiguity or in a function that is deleted or inaccessible
5112  if (CSM == CXXDestructor && MD->isVirtual()) {
5113    FunctionDecl *OperatorDelete = 0;
5114    DeclarationName Name =
5115      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5116    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5117                                 OperatorDelete, false)) {
5118      if (Diagnose)
5119        Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5120      return true;
5121    }
5122  }
5123
5124  SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5125
5126  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5127                                          BE = RD->bases_end(); BI != BE; ++BI)
5128    if (!BI->isVirtual() &&
5129        SMI.shouldDeleteForBase(BI))
5130      return true;
5131
5132  // Per DR1611, do not consider virtual bases of constructors of abstract
5133  // classes, since we are not going to construct them.
5134  if (!RD->isAbstract() || !SMI.IsConstructor) {
5135    for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5136                                            BE = RD->vbases_end();
5137         BI != BE; ++BI)
5138      if (SMI.shouldDeleteForBase(BI))
5139        return true;
5140  }
5141
5142  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5143                                     FE = RD->field_end(); FI != FE; ++FI)
5144    if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5145        SMI.shouldDeleteForField(*FI))
5146      return true;
5147
5148  if (SMI.shouldDeleteForAllConstMembers())
5149    return true;
5150
5151  return false;
5152}
5153
5154/// Perform lookup for a special member of the specified kind, and determine
5155/// whether it is trivial. If the triviality can be determined without the
5156/// lookup, skip it. This is intended for use when determining whether a
5157/// special member of a containing object is trivial, and thus does not ever
5158/// perform overload resolution for default constructors.
5159///
5160/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5161/// member that was most likely to be intended to be trivial, if any.
5162static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5163                                     Sema::CXXSpecialMember CSM, unsigned Quals,
5164                                     CXXMethodDecl **Selected) {
5165  if (Selected)
5166    *Selected = 0;
5167
5168  switch (CSM) {
5169  case Sema::CXXInvalid:
5170    llvm_unreachable("not a special member");
5171
5172  case Sema::CXXDefaultConstructor:
5173    // C++11 [class.ctor]p5:
5174    //   A default constructor is trivial if:
5175    //    - all the [direct subobjects] have trivial default constructors
5176    //
5177    // Note, no overload resolution is performed in this case.
5178    if (RD->hasTrivialDefaultConstructor())
5179      return true;
5180
5181    if (Selected) {
5182      // If there's a default constructor which could have been trivial, dig it
5183      // out. Otherwise, if there's any user-provided default constructor, point
5184      // to that as an example of why there's not a trivial one.
5185      CXXConstructorDecl *DefCtor = 0;
5186      if (RD->needsImplicitDefaultConstructor())
5187        S.DeclareImplicitDefaultConstructor(RD);
5188      for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5189                                        CE = RD->ctor_end(); CI != CE; ++CI) {
5190        if (!CI->isDefaultConstructor())
5191          continue;
5192        DefCtor = *CI;
5193        if (!DefCtor->isUserProvided())
5194          break;
5195      }
5196
5197      *Selected = DefCtor;
5198    }
5199
5200    return false;
5201
5202  case Sema::CXXDestructor:
5203    // C++11 [class.dtor]p5:
5204    //   A destructor is trivial if:
5205    //    - all the direct [subobjects] have trivial destructors
5206    if (RD->hasTrivialDestructor())
5207      return true;
5208
5209    if (Selected) {
5210      if (RD->needsImplicitDestructor())
5211        S.DeclareImplicitDestructor(RD);
5212      *Selected = RD->getDestructor();
5213    }
5214
5215    return false;
5216
5217  case Sema::CXXCopyConstructor:
5218    // C++11 [class.copy]p12:
5219    //   A copy constructor is trivial if:
5220    //    - the constructor selected to copy each direct [subobject] is trivial
5221    if (RD->hasTrivialCopyConstructor()) {
5222      if (Quals == Qualifiers::Const)
5223        // We must either select the trivial copy constructor or reach an
5224        // ambiguity; no need to actually perform overload resolution.
5225        return true;
5226    } else if (!Selected) {
5227      return false;
5228    }
5229    // In C++98, we are not supposed to perform overload resolution here, but we
5230    // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5231    // cases like B as having a non-trivial copy constructor:
5232    //   struct A { template<typename T> A(T&); };
5233    //   struct B { mutable A a; };
5234    goto NeedOverloadResolution;
5235
5236  case Sema::CXXCopyAssignment:
5237    // C++11 [class.copy]p25:
5238    //   A copy assignment operator is trivial if:
5239    //    - the assignment operator selected to copy each direct [subobject] is
5240    //      trivial
5241    if (RD->hasTrivialCopyAssignment()) {
5242      if (Quals == Qualifiers::Const)
5243        return true;
5244    } else if (!Selected) {
5245      return false;
5246    }
5247    // In C++98, we are not supposed to perform overload resolution here, but we
5248    // treat that as a language defect.
5249    goto NeedOverloadResolution;
5250
5251  case Sema::CXXMoveConstructor:
5252  case Sema::CXXMoveAssignment:
5253  NeedOverloadResolution:
5254    Sema::SpecialMemberOverloadResult *SMOR =
5255      S.LookupSpecialMember(RD, CSM,
5256                            Quals & Qualifiers::Const,
5257                            Quals & Qualifiers::Volatile,
5258                            /*RValueThis*/false, /*ConstThis*/false,
5259                            /*VolatileThis*/false);
5260
5261    // The standard doesn't describe how to behave if the lookup is ambiguous.
5262    // We treat it as not making the member non-trivial, just like the standard
5263    // mandates for the default constructor. This should rarely matter, because
5264    // the member will also be deleted.
5265    if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5266      return true;
5267
5268    if (!SMOR->getMethod()) {
5269      assert(SMOR->getKind() ==
5270             Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5271      return false;
5272    }
5273
5274    // We deliberately don't check if we found a deleted special member. We're
5275    // not supposed to!
5276    if (Selected)
5277      *Selected = SMOR->getMethod();
5278    return SMOR->getMethod()->isTrivial();
5279  }
5280
5281  llvm_unreachable("unknown special method kind");
5282}
5283
5284static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5285  for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5286       CI != CE; ++CI)
5287    if (!CI->isImplicit())
5288      return *CI;
5289
5290  // Look for constructor templates.
5291  typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5292  for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5293    if (CXXConstructorDecl *CD =
5294          dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5295      return CD;
5296  }
5297
5298  return 0;
5299}
5300
5301/// The kind of subobject we are checking for triviality. The values of this
5302/// enumeration are used in diagnostics.
5303enum TrivialSubobjectKind {
5304  /// The subobject is a base class.
5305  TSK_BaseClass,
5306  /// The subobject is a non-static data member.
5307  TSK_Field,
5308  /// The object is actually the complete object.
5309  TSK_CompleteObject
5310};
5311
5312/// Check whether the special member selected for a given type would be trivial.
5313static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5314                                      QualType SubType,
5315                                      Sema::CXXSpecialMember CSM,
5316                                      TrivialSubobjectKind Kind,
5317                                      bool Diagnose) {
5318  CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5319  if (!SubRD)
5320    return true;
5321
5322  CXXMethodDecl *Selected;
5323  if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5324                               Diagnose ? &Selected : 0))
5325    return true;
5326
5327  if (Diagnose) {
5328    if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5329      S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5330        << Kind << SubType.getUnqualifiedType();
5331      if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5332        S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5333    } else if (!Selected)
5334      S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5335        << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5336    else if (Selected->isUserProvided()) {
5337      if (Kind == TSK_CompleteObject)
5338        S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5339          << Kind << SubType.getUnqualifiedType() << CSM;
5340      else {
5341        S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5342          << Kind << SubType.getUnqualifiedType() << CSM;
5343        S.Diag(Selected->getLocation(), diag::note_declared_at);
5344      }
5345    } else {
5346      if (Kind != TSK_CompleteObject)
5347        S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5348          << Kind << SubType.getUnqualifiedType() << CSM;
5349
5350      // Explain why the defaulted or deleted special member isn't trivial.
5351      S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5352    }
5353  }
5354
5355  return false;
5356}
5357
5358/// Check whether the members of a class type allow a special member to be
5359/// trivial.
5360static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5361                                     Sema::CXXSpecialMember CSM,
5362                                     bool ConstArg, bool Diagnose) {
5363  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5364                                     FE = RD->field_end(); FI != FE; ++FI) {
5365    if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5366      continue;
5367
5368    QualType FieldType = S.Context.getBaseElementType(FI->getType());
5369
5370    // Pretend anonymous struct or union members are members of this class.
5371    if (FI->isAnonymousStructOrUnion()) {
5372      if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5373                                    CSM, ConstArg, Diagnose))
5374        return false;
5375      continue;
5376    }
5377
5378    // C++11 [class.ctor]p5:
5379    //   A default constructor is trivial if [...]
5380    //    -- no non-static data member of its class has a
5381    //       brace-or-equal-initializer
5382    if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5383      if (Diagnose)
5384        S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5385      return false;
5386    }
5387
5388    // Objective C ARC 4.3.5:
5389    //   [...] nontrivally ownership-qualified types are [...] not trivially
5390    //   default constructible, copy constructible, move constructible, copy
5391    //   assignable, move assignable, or destructible [...]
5392    if (S.getLangOpts().ObjCAutoRefCount &&
5393        FieldType.hasNonTrivialObjCLifetime()) {
5394      if (Diagnose)
5395        S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5396          << RD << FieldType.getObjCLifetime();
5397      return false;
5398    }
5399
5400    if (ConstArg && !FI->isMutable())
5401      FieldType.addConst();
5402    if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5403                                   TSK_Field, Diagnose))
5404      return false;
5405  }
5406
5407  return true;
5408}
5409
5410/// Diagnose why the specified class does not have a trivial special member of
5411/// the given kind.
5412void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5413  QualType Ty = Context.getRecordType(RD);
5414  if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5415    Ty.addConst();
5416
5417  checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5418                            TSK_CompleteObject, /*Diagnose*/true);
5419}
5420
5421/// Determine whether a defaulted or deleted special member function is trivial,
5422/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5423/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5424bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5425                                  bool Diagnose) {
5426  assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5427
5428  CXXRecordDecl *RD = MD->getParent();
5429
5430  bool ConstArg = false;
5431
5432  // C++11 [class.copy]p12, p25:
5433  //   A [special member] is trivial if its declared parameter type is the same
5434  //   as if it had been implicitly declared [...]
5435  switch (CSM) {
5436  case CXXDefaultConstructor:
5437  case CXXDestructor:
5438    // Trivial default constructors and destructors cannot have parameters.
5439    break;
5440
5441  case CXXCopyConstructor:
5442  case CXXCopyAssignment: {
5443    // Trivial copy operations always have const, non-volatile parameter types.
5444    ConstArg = true;
5445    const ParmVarDecl *Param0 = MD->getParamDecl(0);
5446    const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5447    if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5448      if (Diagnose)
5449        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5450          << Param0->getSourceRange() << Param0->getType()
5451          << Context.getLValueReferenceType(
5452               Context.getRecordType(RD).withConst());
5453      return false;
5454    }
5455    break;
5456  }
5457
5458  case CXXMoveConstructor:
5459  case CXXMoveAssignment: {
5460    // Trivial move operations always have non-cv-qualified parameters.
5461    const ParmVarDecl *Param0 = MD->getParamDecl(0);
5462    const RValueReferenceType *RT =
5463      Param0->getType()->getAs<RValueReferenceType>();
5464    if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5465      if (Diagnose)
5466        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5467          << Param0->getSourceRange() << Param0->getType()
5468          << Context.getRValueReferenceType(Context.getRecordType(RD));
5469      return false;
5470    }
5471    break;
5472  }
5473
5474  case CXXInvalid:
5475    llvm_unreachable("not a special member");
5476  }
5477
5478  // FIXME: We require that the parameter-declaration-clause is equivalent to
5479  // that of an implicit declaration, not just that the declared parameter type
5480  // matches, in order to prevent absuridities like a function simultaneously
5481  // being a trivial copy constructor and a non-trivial default constructor.
5482  // This issue has not yet been assigned a core issue number.
5483  if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5484    if (Diagnose)
5485      Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5486           diag::note_nontrivial_default_arg)
5487        << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5488    return false;
5489  }
5490  if (MD->isVariadic()) {
5491    if (Diagnose)
5492      Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5493    return false;
5494  }
5495
5496  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5497  //   A copy/move [constructor or assignment operator] is trivial if
5498  //    -- the [member] selected to copy/move each direct base class subobject
5499  //       is trivial
5500  //
5501  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5502  //   A [default constructor or destructor] is trivial if
5503  //    -- all the direct base classes have trivial [default constructors or
5504  //       destructors]
5505  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5506                                          BE = RD->bases_end(); BI != BE; ++BI)
5507    if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5508                                   ConstArg ? BI->getType().withConst()
5509                                            : BI->getType(),
5510                                   CSM, TSK_BaseClass, Diagnose))
5511      return false;
5512
5513  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5514  //   A copy/move [constructor or assignment operator] for a class X is
5515  //   trivial if
5516  //    -- for each non-static data member of X that is of class type (or array
5517  //       thereof), the constructor selected to copy/move that member is
5518  //       trivial
5519  //
5520  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5521  //   A [default constructor or destructor] is trivial if
5522  //    -- for all of the non-static data members of its class that are of class
5523  //       type (or array thereof), each such class has a trivial [default
5524  //       constructor or destructor]
5525  if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5526    return false;
5527
5528  // C++11 [class.dtor]p5:
5529  //   A destructor is trivial if [...]
5530  //    -- the destructor is not virtual
5531  if (CSM == CXXDestructor && MD->isVirtual()) {
5532    if (Diagnose)
5533      Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5534    return false;
5535  }
5536
5537  // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5538  //   A [special member] for class X is trivial if [...]
5539  //    -- class X has no virtual functions and no virtual base classes
5540  if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5541    if (!Diagnose)
5542      return false;
5543
5544    if (RD->getNumVBases()) {
5545      // Check for virtual bases. We already know that the corresponding
5546      // member in all bases is trivial, so vbases must all be direct.
5547      CXXBaseSpecifier &BS = *RD->vbases_begin();
5548      assert(BS.isVirtual());
5549      Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5550      return false;
5551    }
5552
5553    // Must have a virtual method.
5554    for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5555                                        ME = RD->method_end(); MI != ME; ++MI) {
5556      if (MI->isVirtual()) {
5557        SourceLocation MLoc = MI->getLocStart();
5558        Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5559        return false;
5560      }
5561    }
5562
5563    llvm_unreachable("dynamic class with no vbases and no virtual functions");
5564  }
5565
5566  // Looks like it's trivial!
5567  return true;
5568}
5569
5570/// \brief Data used with FindHiddenVirtualMethod
5571namespace {
5572  struct FindHiddenVirtualMethodData {
5573    Sema *S;
5574    CXXMethodDecl *Method;
5575    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5576    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5577  };
5578}
5579
5580/// \brief Check whether any most overriden method from MD in Methods
5581static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5582                   const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5583  if (MD->size_overridden_methods() == 0)
5584    return Methods.count(MD->getCanonicalDecl());
5585  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5586                                      E = MD->end_overridden_methods();
5587       I != E; ++I)
5588    if (CheckMostOverridenMethods(*I, Methods))
5589      return true;
5590  return false;
5591}
5592
5593/// \brief Member lookup function that determines whether a given C++
5594/// method overloads virtual methods in a base class without overriding any,
5595/// to be used with CXXRecordDecl::lookupInBases().
5596static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5597                                    CXXBasePath &Path,
5598                                    void *UserData) {
5599  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5600
5601  FindHiddenVirtualMethodData &Data
5602    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5603
5604  DeclarationName Name = Data.Method->getDeclName();
5605  assert(Name.getNameKind() == DeclarationName::Identifier);
5606
5607  bool foundSameNameMethod = false;
5608  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5609  for (Path.Decls = BaseRecord->lookup(Name);
5610       !Path.Decls.empty();
5611       Path.Decls = Path.Decls.slice(1)) {
5612    NamedDecl *D = Path.Decls.front();
5613    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5614      MD = MD->getCanonicalDecl();
5615      foundSameNameMethod = true;
5616      // Interested only in hidden virtual methods.
5617      if (!MD->isVirtual())
5618        continue;
5619      // If the method we are checking overrides a method from its base
5620      // don't warn about the other overloaded methods.
5621      if (!Data.S->IsOverload(Data.Method, MD, false))
5622        return true;
5623      // Collect the overload only if its hidden.
5624      if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5625        overloadedMethods.push_back(MD);
5626    }
5627  }
5628
5629  if (foundSameNameMethod)
5630    Data.OverloadedMethods.append(overloadedMethods.begin(),
5631                                   overloadedMethods.end());
5632  return foundSameNameMethod;
5633}
5634
5635/// \brief Add the most overriden methods from MD to Methods
5636static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5637                         llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5638  if (MD->size_overridden_methods() == 0)
5639    Methods.insert(MD->getCanonicalDecl());
5640  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5641                                      E = MD->end_overridden_methods();
5642       I != E; ++I)
5643    AddMostOverridenMethods(*I, Methods);
5644}
5645
5646/// \brief Check if a method overloads virtual methods in a base class without
5647/// overriding any.
5648void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5649                          SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5650  if (!MD->getDeclName().isIdentifier())
5651    return;
5652
5653  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5654                     /*bool RecordPaths=*/false,
5655                     /*bool DetectVirtual=*/false);
5656  FindHiddenVirtualMethodData Data;
5657  Data.Method = MD;
5658  Data.S = this;
5659
5660  // Keep the base methods that were overriden or introduced in the subclass
5661  // by 'using' in a set. A base method not in this set is hidden.
5662  CXXRecordDecl *DC = MD->getParent();
5663  DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5664  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5665    NamedDecl *ND = *I;
5666    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5667      ND = shad->getTargetDecl();
5668    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5669      AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5670  }
5671
5672  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5673    OverloadedMethods = Data.OverloadedMethods;
5674}
5675
5676void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5677                          SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5678  for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5679    CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5680    PartialDiagnostic PD = PDiag(
5681         diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5682    HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5683    Diag(overloadedMD->getLocation(), PD);
5684  }
5685}
5686
5687/// \brief Diagnose methods which overload virtual methods in a base class
5688/// without overriding any.
5689void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5690  if (MD->isInvalidDecl())
5691    return;
5692
5693  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5694                               MD->getLocation()) == DiagnosticsEngine::Ignored)
5695    return;
5696
5697  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5698  FindHiddenVirtualMethods(MD, OverloadedMethods);
5699  if (!OverloadedMethods.empty()) {
5700    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5701      << MD << (OverloadedMethods.size() > 1);
5702
5703    NoteHiddenVirtualMethods(MD, OverloadedMethods);
5704  }
5705}
5706
5707void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5708                                             Decl *TagDecl,
5709                                             SourceLocation LBrac,
5710                                             SourceLocation RBrac,
5711                                             AttributeList *AttrList) {
5712  if (!TagDecl)
5713    return;
5714
5715  AdjustDeclIfTemplate(TagDecl);
5716
5717  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5718    if (l->getKind() != AttributeList::AT_Visibility)
5719      continue;
5720    l->setInvalid();
5721    Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5722      l->getName();
5723  }
5724
5725  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5726              // strict aliasing violation!
5727              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5728              FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5729
5730  CheckCompletedCXXClass(
5731                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5732}
5733
5734/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5735/// special functions, such as the default constructor, copy
5736/// constructor, or destructor, to the given C++ class (C++
5737/// [special]p1).  This routine can only be executed just before the
5738/// definition of the class is complete.
5739void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
5740  if (!ClassDecl->hasUserDeclaredConstructor())
5741    ++ASTContext::NumImplicitDefaultConstructors;
5742
5743  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
5744    ++ASTContext::NumImplicitCopyConstructors;
5745
5746    // If the properties or semantics of the copy constructor couldn't be
5747    // determined while the class was being declared, force a declaration
5748    // of it now.
5749    if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5750      DeclareImplicitCopyConstructor(ClassDecl);
5751  }
5752
5753  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
5754    ++ASTContext::NumImplicitMoveConstructors;
5755
5756    if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5757      DeclareImplicitMoveConstructor(ClassDecl);
5758  }
5759
5760  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5761    ++ASTContext::NumImplicitCopyAssignmentOperators;
5762
5763    // If we have a dynamic class, then the copy assignment operator may be
5764    // virtual, so we have to declare it immediately. This ensures that, e.g.,
5765    // it shows up in the right place in the vtable and that we diagnose
5766    // problems with the implicit exception specification.
5767    if (ClassDecl->isDynamicClass() ||
5768        ClassDecl->needsOverloadResolutionForCopyAssignment())
5769      DeclareImplicitCopyAssignment(ClassDecl);
5770  }
5771
5772  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
5773    ++ASTContext::NumImplicitMoveAssignmentOperators;
5774
5775    // Likewise for the move assignment operator.
5776    if (ClassDecl->isDynamicClass() ||
5777        ClassDecl->needsOverloadResolutionForMoveAssignment())
5778      DeclareImplicitMoveAssignment(ClassDecl);
5779  }
5780
5781  if (!ClassDecl->hasUserDeclaredDestructor()) {
5782    ++ASTContext::NumImplicitDestructors;
5783
5784    // If we have a dynamic class, then the destructor may be virtual, so we
5785    // have to declare the destructor immediately. This ensures that, e.g., it
5786    // shows up in the right place in the vtable and that we diagnose problems
5787    // with the implicit exception specification.
5788    if (ClassDecl->isDynamicClass() ||
5789        ClassDecl->needsOverloadResolutionForDestructor())
5790      DeclareImplicitDestructor(ClassDecl);
5791  }
5792}
5793
5794void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5795  if (!D)
5796    return;
5797
5798  int NumParamList = D->getNumTemplateParameterLists();
5799  for (int i = 0; i < NumParamList; i++) {
5800    TemplateParameterList* Params = D->getTemplateParameterList(i);
5801    for (TemplateParameterList::iterator Param = Params->begin(),
5802                                      ParamEnd = Params->end();
5803          Param != ParamEnd; ++Param) {
5804      NamedDecl *Named = cast<NamedDecl>(*Param);
5805      if (Named->getDeclName()) {
5806        S->AddDecl(Named);
5807        IdResolver.AddDecl(Named);
5808      }
5809    }
5810  }
5811}
5812
5813void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
5814  if (!D)
5815    return;
5816
5817  TemplateParameterList *Params = 0;
5818  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5819    Params = Template->getTemplateParameters();
5820  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5821           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5822    Params = PartialSpec->getTemplateParameters();
5823  else
5824    return;
5825
5826  for (TemplateParameterList::iterator Param = Params->begin(),
5827                                    ParamEnd = Params->end();
5828       Param != ParamEnd; ++Param) {
5829    NamedDecl *Named = cast<NamedDecl>(*Param);
5830    if (Named->getDeclName()) {
5831      S->AddDecl(Named);
5832      IdResolver.AddDecl(Named);
5833    }
5834  }
5835}
5836
5837void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5838  if (!RecordD) return;
5839  AdjustDeclIfTemplate(RecordD);
5840  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
5841  PushDeclContext(S, Record);
5842}
5843
5844void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5845  if (!RecordD) return;
5846  PopDeclContext();
5847}
5848
5849/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5850/// parsing a top-level (non-nested) C++ class, and we are now
5851/// parsing those parts of the given Method declaration that could
5852/// not be parsed earlier (C++ [class.mem]p2), such as default
5853/// arguments. This action should enter the scope of the given
5854/// Method declaration as if we had just parsed the qualified method
5855/// name. However, it should not bring the parameters into scope;
5856/// that will be performed by ActOnDelayedCXXMethodParameter.
5857void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5858}
5859
5860/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5861/// C++ method declaration. We're (re-)introducing the given
5862/// function parameter into scope for use in parsing later parts of
5863/// the method declaration. For example, we could see an
5864/// ActOnParamDefaultArgument event for this parameter.
5865void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
5866  if (!ParamD)
5867    return;
5868
5869  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
5870
5871  // If this parameter has an unparsed default argument, clear it out
5872  // to make way for the parsed default argument.
5873  if (Param->hasUnparsedDefaultArg())
5874    Param->setDefaultArg(0);
5875
5876  S->AddDecl(Param);
5877  if (Param->getDeclName())
5878    IdResolver.AddDecl(Param);
5879}
5880
5881/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5882/// processing the delayed method declaration for Method. The method
5883/// declaration is now considered finished. There may be a separate
5884/// ActOnStartOfFunctionDef action later (not necessarily
5885/// immediately!) for this method, if it was also defined inside the
5886/// class body.
5887void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5888  if (!MethodD)
5889    return;
5890
5891  AdjustDeclIfTemplate(MethodD);
5892
5893  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
5894
5895  // Now that we have our default arguments, check the constructor
5896  // again. It could produce additional diagnostics or affect whether
5897  // the class has implicitly-declared destructors, among other
5898  // things.
5899  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5900    CheckConstructor(Constructor);
5901
5902  // Check the default arguments, which we may have added.
5903  if (!Method->isInvalidDecl())
5904    CheckCXXDefaultArguments(Method);
5905}
5906
5907/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
5908/// the well-formedness of the constructor declarator @p D with type @p
5909/// R. If there are any errors in the declarator, this routine will
5910/// emit diagnostics and set the invalid bit to true.  In any case, the type
5911/// will be updated to reflect a well-formed type for the constructor and
5912/// returned.
5913QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
5914                                          StorageClass &SC) {
5915  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5916
5917  // C++ [class.ctor]p3:
5918  //   A constructor shall not be virtual (10.3) or static (9.4). A
5919  //   constructor can be invoked for a const, volatile or const
5920  //   volatile object. A constructor shall not be declared const,
5921  //   volatile, or const volatile (9.3.2).
5922  if (isVirtual) {
5923    if (!D.isInvalidType())
5924      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5925        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5926        << SourceRange(D.getIdentifierLoc());
5927    D.setInvalidType();
5928  }
5929  if (SC == SC_Static) {
5930    if (!D.isInvalidType())
5931      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5932        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5933        << SourceRange(D.getIdentifierLoc());
5934    D.setInvalidType();
5935    SC = SC_None;
5936  }
5937
5938  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5939  if (FTI.TypeQuals != 0) {
5940    if (FTI.TypeQuals & Qualifiers::Const)
5941      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5942        << "const" << SourceRange(D.getIdentifierLoc());
5943    if (FTI.TypeQuals & Qualifiers::Volatile)
5944      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5945        << "volatile" << SourceRange(D.getIdentifierLoc());
5946    if (FTI.TypeQuals & Qualifiers::Restrict)
5947      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5948        << "restrict" << SourceRange(D.getIdentifierLoc());
5949    D.setInvalidType();
5950  }
5951
5952  // C++0x [class.ctor]p4:
5953  //   A constructor shall not be declared with a ref-qualifier.
5954  if (FTI.hasRefQualifier()) {
5955    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5956      << FTI.RefQualifierIsLValueRef
5957      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5958    D.setInvalidType();
5959  }
5960
5961  // Rebuild the function type "R" without any type qualifiers (in
5962  // case any of the errors above fired) and with "void" as the
5963  // return type, since constructors don't have return types.
5964  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5965  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5966    return R;
5967
5968  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5969  EPI.TypeQuals = 0;
5970  EPI.RefQualifier = RQ_None;
5971
5972  return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
5973}
5974
5975/// CheckConstructor - Checks a fully-formed constructor for
5976/// well-formedness, issuing any diagnostics required. Returns true if
5977/// the constructor declarator is invalid.
5978void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5979  CXXRecordDecl *ClassDecl
5980    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5981  if (!ClassDecl)
5982    return Constructor->setInvalidDecl();
5983
5984  // C++ [class.copy]p3:
5985  //   A declaration of a constructor for a class X is ill-formed if
5986  //   its first parameter is of type (optionally cv-qualified) X and
5987  //   either there are no other parameters or else all other
5988  //   parameters have default arguments.
5989  if (!Constructor->isInvalidDecl() &&
5990      ((Constructor->getNumParams() == 1) ||
5991       (Constructor->getNumParams() > 1 &&
5992        Constructor->getParamDecl(1)->hasDefaultArg())) &&
5993      Constructor->getTemplateSpecializationKind()
5994                                              != TSK_ImplicitInstantiation) {
5995    QualType ParamType = Constructor->getParamDecl(0)->getType();
5996    QualType ClassTy = Context.getTagDeclType(ClassDecl);
5997    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5998      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5999      const char *ConstRef
6000        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6001                                                        : " const &";
6002      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6003        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6004
6005      // FIXME: Rather that making the constructor invalid, we should endeavor
6006      // to fix the type.
6007      Constructor->setInvalidDecl();
6008    }
6009  }
6010}
6011
6012/// CheckDestructor - Checks a fully-formed destructor definition for
6013/// well-formedness, issuing any diagnostics required.  Returns true
6014/// on error.
6015bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6016  CXXRecordDecl *RD = Destructor->getParent();
6017
6018  if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6019    SourceLocation Loc;
6020
6021    if (!Destructor->isImplicit())
6022      Loc = Destructor->getLocation();
6023    else
6024      Loc = RD->getLocation();
6025
6026    // If we have a virtual destructor, look up the deallocation function
6027    FunctionDecl *OperatorDelete = 0;
6028    DeclarationName Name =
6029    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6030    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6031      return true;
6032
6033    MarkFunctionReferenced(Loc, OperatorDelete);
6034
6035    Destructor->setOperatorDelete(OperatorDelete);
6036  }
6037
6038  return false;
6039}
6040
6041static inline bool
6042FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6043  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6044          FTI.ArgInfo[0].Param &&
6045          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
6046}
6047
6048/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6049/// the well-formednes of the destructor declarator @p D with type @p
6050/// R. If there are any errors in the declarator, this routine will
6051/// emit diagnostics and set the declarator to invalid.  Even if this happens,
6052/// will be updated to reflect a well-formed type for the destructor and
6053/// returned.
6054QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6055                                         StorageClass& SC) {
6056  // C++ [class.dtor]p1:
6057  //   [...] A typedef-name that names a class is a class-name
6058  //   (7.1.3); however, a typedef-name that names a class shall not
6059  //   be used as the identifier in the declarator for a destructor
6060  //   declaration.
6061  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6062  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6063    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6064      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6065  else if (const TemplateSpecializationType *TST =
6066             DeclaratorType->getAs<TemplateSpecializationType>())
6067    if (TST->isTypeAlias())
6068      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6069        << DeclaratorType << 1;
6070
6071  // C++ [class.dtor]p2:
6072  //   A destructor is used to destroy objects of its class type. A
6073  //   destructor takes no parameters, and no return type can be
6074  //   specified for it (not even void). The address of a destructor
6075  //   shall not be taken. A destructor shall not be static. A
6076  //   destructor can be invoked for a const, volatile or const
6077  //   volatile object. A destructor shall not be declared const,
6078  //   volatile or const volatile (9.3.2).
6079  if (SC == SC_Static) {
6080    if (!D.isInvalidType())
6081      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6082        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6083        << SourceRange(D.getIdentifierLoc())
6084        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6085
6086    SC = SC_None;
6087  }
6088  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6089    // Destructors don't have return types, but the parser will
6090    // happily parse something like:
6091    //
6092    //   class X {
6093    //     float ~X();
6094    //   };
6095    //
6096    // The return type will be eliminated later.
6097    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6098      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6099      << SourceRange(D.getIdentifierLoc());
6100  }
6101
6102  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6103  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6104    if (FTI.TypeQuals & Qualifiers::Const)
6105      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6106        << "const" << SourceRange(D.getIdentifierLoc());
6107    if (FTI.TypeQuals & Qualifiers::Volatile)
6108      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6109        << "volatile" << SourceRange(D.getIdentifierLoc());
6110    if (FTI.TypeQuals & Qualifiers::Restrict)
6111      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6112        << "restrict" << SourceRange(D.getIdentifierLoc());
6113    D.setInvalidType();
6114  }
6115
6116  // C++0x [class.dtor]p2:
6117  //   A destructor shall not be declared with a ref-qualifier.
6118  if (FTI.hasRefQualifier()) {
6119    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6120      << FTI.RefQualifierIsLValueRef
6121      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6122    D.setInvalidType();
6123  }
6124
6125  // Make sure we don't have any parameters.
6126  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
6127    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6128
6129    // Delete the parameters.
6130    FTI.freeArgs();
6131    D.setInvalidType();
6132  }
6133
6134  // Make sure the destructor isn't variadic.
6135  if (FTI.isVariadic) {
6136    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6137    D.setInvalidType();
6138  }
6139
6140  // Rebuild the function type "R" without any type qualifiers or
6141  // parameters (in case any of the errors above fired) and with
6142  // "void" as the return type, since destructors don't have return
6143  // types.
6144  if (!D.isInvalidType())
6145    return R;
6146
6147  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6148  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6149  EPI.Variadic = false;
6150  EPI.TypeQuals = 0;
6151  EPI.RefQualifier = RQ_None;
6152  return Context.getFunctionType(Context.VoidTy, None, EPI);
6153}
6154
6155/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6156/// well-formednes of the conversion function declarator @p D with
6157/// type @p R. If there are any errors in the declarator, this routine
6158/// will emit diagnostics and return true. Otherwise, it will return
6159/// false. Either way, the type @p R will be updated to reflect a
6160/// well-formed type for the conversion operator.
6161void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6162                                     StorageClass& SC) {
6163  // C++ [class.conv.fct]p1:
6164  //   Neither parameter types nor return type can be specified. The
6165  //   type of a conversion function (8.3.5) is "function taking no
6166  //   parameter returning conversion-type-id."
6167  if (SC == SC_Static) {
6168    if (!D.isInvalidType())
6169      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6170        << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6171        << D.getName().getSourceRange();
6172    D.setInvalidType();
6173    SC = SC_None;
6174  }
6175
6176  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6177
6178  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6179    // Conversion functions don't have return types, but the parser will
6180    // happily parse something like:
6181    //
6182    //   class X {
6183    //     float operator bool();
6184    //   };
6185    //
6186    // The return type will be changed later anyway.
6187    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6188      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6189      << SourceRange(D.getIdentifierLoc());
6190    D.setInvalidType();
6191  }
6192
6193  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6194
6195  // Make sure we don't have any parameters.
6196  if (Proto->getNumArgs() > 0) {
6197    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6198
6199    // Delete the parameters.
6200    D.getFunctionTypeInfo().freeArgs();
6201    D.setInvalidType();
6202  } else if (Proto->isVariadic()) {
6203    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6204    D.setInvalidType();
6205  }
6206
6207  // Diagnose "&operator bool()" and other such nonsense.  This
6208  // is actually a gcc extension which we don't support.
6209  if (Proto->getResultType() != ConvType) {
6210    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6211      << Proto->getResultType();
6212    D.setInvalidType();
6213    ConvType = Proto->getResultType();
6214  }
6215
6216  // C++ [class.conv.fct]p4:
6217  //   The conversion-type-id shall not represent a function type nor
6218  //   an array type.
6219  if (ConvType->isArrayType()) {
6220    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6221    ConvType = Context.getPointerType(ConvType);
6222    D.setInvalidType();
6223  } else if (ConvType->isFunctionType()) {
6224    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6225    ConvType = Context.getPointerType(ConvType);
6226    D.setInvalidType();
6227  }
6228
6229  // Rebuild the function type "R" without any parameters (in case any
6230  // of the errors above fired) and with the conversion type as the
6231  // return type.
6232  if (D.isInvalidType())
6233    R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6234
6235  // C++0x explicit conversion operators.
6236  if (D.getDeclSpec().isExplicitSpecified())
6237    Diag(D.getDeclSpec().getExplicitSpecLoc(),
6238         getLangOpts().CPlusPlus11 ?
6239           diag::warn_cxx98_compat_explicit_conversion_functions :
6240           diag::ext_explicit_conversion_functions)
6241      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6242}
6243
6244/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6245/// the declaration of the given C++ conversion function. This routine
6246/// is responsible for recording the conversion function in the C++
6247/// class, if possible.
6248Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6249  assert(Conversion && "Expected to receive a conversion function declaration");
6250
6251  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6252
6253  // Make sure we aren't redeclaring the conversion function.
6254  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6255
6256  // C++ [class.conv.fct]p1:
6257  //   [...] A conversion function is never used to convert a
6258  //   (possibly cv-qualified) object to the (possibly cv-qualified)
6259  //   same object type (or a reference to it), to a (possibly
6260  //   cv-qualified) base class of that type (or a reference to it),
6261  //   or to (possibly cv-qualified) void.
6262  // FIXME: Suppress this warning if the conversion function ends up being a
6263  // virtual function that overrides a virtual function in a base class.
6264  QualType ClassType
6265    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6266  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6267    ConvType = ConvTypeRef->getPointeeType();
6268  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6269      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6270    /* Suppress diagnostics for instantiations. */;
6271  else if (ConvType->isRecordType()) {
6272    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6273    if (ConvType == ClassType)
6274      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6275        << ClassType;
6276    else if (IsDerivedFrom(ClassType, ConvType))
6277      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6278        <<  ClassType << ConvType;
6279  } else if (ConvType->isVoidType()) {
6280    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6281      << ClassType << ConvType;
6282  }
6283
6284  if (FunctionTemplateDecl *ConversionTemplate
6285                                = Conversion->getDescribedFunctionTemplate())
6286    return ConversionTemplate;
6287
6288  return Conversion;
6289}
6290
6291//===----------------------------------------------------------------------===//
6292// Namespace Handling
6293//===----------------------------------------------------------------------===//
6294
6295/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6296/// reopened.
6297static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6298                                            SourceLocation Loc,
6299                                            IdentifierInfo *II, bool *IsInline,
6300                                            NamespaceDecl *PrevNS) {
6301  assert(*IsInline != PrevNS->isInline());
6302
6303  // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6304  // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6305  // inline namespaces, with the intention of bringing names into namespace std.
6306  //
6307  // We support this just well enough to get that case working; this is not
6308  // sufficient to support reopening namespaces as inline in general.
6309  if (*IsInline && II && II->getName().startswith("__atomic") &&
6310      S.getSourceManager().isInSystemHeader(Loc)) {
6311    // Mark all prior declarations of the namespace as inline.
6312    for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6313         NS = NS->getPreviousDecl())
6314      NS->setInline(*IsInline);
6315    // Patch up the lookup table for the containing namespace. This isn't really
6316    // correct, but it's good enough for this particular case.
6317    for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6318                                    E = PrevNS->decls_end(); I != E; ++I)
6319      if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6320        PrevNS->getParent()->makeDeclVisibleInContext(ND);
6321    return;
6322  }
6323
6324  if (PrevNS->isInline())
6325    // The user probably just forgot the 'inline', so suggest that it
6326    // be added back.
6327    S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6328      << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6329  else
6330    S.Diag(Loc, diag::err_inline_namespace_mismatch)
6331      << IsInline;
6332
6333  S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6334  *IsInline = PrevNS->isInline();
6335}
6336
6337/// ActOnStartNamespaceDef - This is called at the start of a namespace
6338/// definition.
6339Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6340                                   SourceLocation InlineLoc,
6341                                   SourceLocation NamespaceLoc,
6342                                   SourceLocation IdentLoc,
6343                                   IdentifierInfo *II,
6344                                   SourceLocation LBrace,
6345                                   AttributeList *AttrList) {
6346  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6347  // For anonymous namespace, take the location of the left brace.
6348  SourceLocation Loc = II ? IdentLoc : LBrace;
6349  bool IsInline = InlineLoc.isValid();
6350  bool IsInvalid = false;
6351  bool IsStd = false;
6352  bool AddToKnown = false;
6353  Scope *DeclRegionScope = NamespcScope->getParent();
6354
6355  NamespaceDecl *PrevNS = 0;
6356  if (II) {
6357    // C++ [namespace.def]p2:
6358    //   The identifier in an original-namespace-definition shall not
6359    //   have been previously defined in the declarative region in
6360    //   which the original-namespace-definition appears. The
6361    //   identifier in an original-namespace-definition is the name of
6362    //   the namespace. Subsequently in that declarative region, it is
6363    //   treated as an original-namespace-name.
6364    //
6365    // Since namespace names are unique in their scope, and we don't
6366    // look through using directives, just look for any ordinary names.
6367
6368    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6369    Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6370    Decl::IDNS_Namespace;
6371    NamedDecl *PrevDecl = 0;
6372    DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6373    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6374         ++I) {
6375      if ((*I)->getIdentifierNamespace() & IDNS) {
6376        PrevDecl = *I;
6377        break;
6378      }
6379    }
6380
6381    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6382
6383    if (PrevNS) {
6384      // This is an extended namespace definition.
6385      if (IsInline != PrevNS->isInline())
6386        DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6387                                        &IsInline, PrevNS);
6388    } else if (PrevDecl) {
6389      // This is an invalid name redefinition.
6390      Diag(Loc, diag::err_redefinition_different_kind)
6391        << II;
6392      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6393      IsInvalid = true;
6394      // Continue on to push Namespc as current DeclContext and return it.
6395    } else if (II->isStr("std") &&
6396               CurContext->getRedeclContext()->isTranslationUnit()) {
6397      // This is the first "real" definition of the namespace "std", so update
6398      // our cache of the "std" namespace to point at this definition.
6399      PrevNS = getStdNamespace();
6400      IsStd = true;
6401      AddToKnown = !IsInline;
6402    } else {
6403      // We've seen this namespace for the first time.
6404      AddToKnown = !IsInline;
6405    }
6406  } else {
6407    // Anonymous namespaces.
6408
6409    // Determine whether the parent already has an anonymous namespace.
6410    DeclContext *Parent = CurContext->getRedeclContext();
6411    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6412      PrevNS = TU->getAnonymousNamespace();
6413    } else {
6414      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6415      PrevNS = ND->getAnonymousNamespace();
6416    }
6417
6418    if (PrevNS && IsInline != PrevNS->isInline())
6419      DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6420                                      &IsInline, PrevNS);
6421  }
6422
6423  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6424                                                 StartLoc, Loc, II, PrevNS);
6425  if (IsInvalid)
6426    Namespc->setInvalidDecl();
6427
6428  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6429
6430  // FIXME: Should we be merging attributes?
6431  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6432    PushNamespaceVisibilityAttr(Attr, Loc);
6433
6434  if (IsStd)
6435    StdNamespace = Namespc;
6436  if (AddToKnown)
6437    KnownNamespaces[Namespc] = false;
6438
6439  if (II) {
6440    PushOnScopeChains(Namespc, DeclRegionScope);
6441  } else {
6442    // Link the anonymous namespace into its parent.
6443    DeclContext *Parent = CurContext->getRedeclContext();
6444    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6445      TU->setAnonymousNamespace(Namespc);
6446    } else {
6447      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6448    }
6449
6450    CurContext->addDecl(Namespc);
6451
6452    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6453    //   behaves as if it were replaced by
6454    //     namespace unique { /* empty body */ }
6455    //     using namespace unique;
6456    //     namespace unique { namespace-body }
6457    //   where all occurrences of 'unique' in a translation unit are
6458    //   replaced by the same identifier and this identifier differs
6459    //   from all other identifiers in the entire program.
6460
6461    // We just create the namespace with an empty name and then add an
6462    // implicit using declaration, just like the standard suggests.
6463    //
6464    // CodeGen enforces the "universally unique" aspect by giving all
6465    // declarations semantically contained within an anonymous
6466    // namespace internal linkage.
6467
6468    if (!PrevNS) {
6469      UsingDirectiveDecl* UD
6470        = UsingDirectiveDecl::Create(Context, Parent,
6471                                     /* 'using' */ LBrace,
6472                                     /* 'namespace' */ SourceLocation(),
6473                                     /* qualifier */ NestedNameSpecifierLoc(),
6474                                     /* identifier */ SourceLocation(),
6475                                     Namespc,
6476                                     /* Ancestor */ Parent);
6477      UD->setImplicit();
6478      Parent->addDecl(UD);
6479    }
6480  }
6481
6482  ActOnDocumentableDecl(Namespc);
6483
6484  // Although we could have an invalid decl (i.e. the namespace name is a
6485  // redefinition), push it as current DeclContext and try to continue parsing.
6486  // FIXME: We should be able to push Namespc here, so that the each DeclContext
6487  // for the namespace has the declarations that showed up in that particular
6488  // namespace definition.
6489  PushDeclContext(NamespcScope, Namespc);
6490  return Namespc;
6491}
6492
6493/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6494/// is a namespace alias, returns the namespace it points to.
6495static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6496  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6497    return AD->getNamespace();
6498  return dyn_cast_or_null<NamespaceDecl>(D);
6499}
6500
6501/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6502/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6503void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6504  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6505  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6506  Namespc->setRBraceLoc(RBrace);
6507  PopDeclContext();
6508  if (Namespc->hasAttr<VisibilityAttr>())
6509    PopPragmaVisibility(true, RBrace);
6510}
6511
6512CXXRecordDecl *Sema::getStdBadAlloc() const {
6513  return cast_or_null<CXXRecordDecl>(
6514                                  StdBadAlloc.get(Context.getExternalSource()));
6515}
6516
6517NamespaceDecl *Sema::getStdNamespace() const {
6518  return cast_or_null<NamespaceDecl>(
6519                                 StdNamespace.get(Context.getExternalSource()));
6520}
6521
6522/// \brief Retrieve the special "std" namespace, which may require us to
6523/// implicitly define the namespace.
6524NamespaceDecl *Sema::getOrCreateStdNamespace() {
6525  if (!StdNamespace) {
6526    // The "std" namespace has not yet been defined, so build one implicitly.
6527    StdNamespace = NamespaceDecl::Create(Context,
6528                                         Context.getTranslationUnitDecl(),
6529                                         /*Inline=*/false,
6530                                         SourceLocation(), SourceLocation(),
6531                                         &PP.getIdentifierTable().get("std"),
6532                                         /*PrevDecl=*/0);
6533    getStdNamespace()->setImplicit(true);
6534  }
6535
6536  return getStdNamespace();
6537}
6538
6539bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6540  assert(getLangOpts().CPlusPlus &&
6541         "Looking for std::initializer_list outside of C++.");
6542
6543  // We're looking for implicit instantiations of
6544  // template <typename E> class std::initializer_list.
6545
6546  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6547    return false;
6548
6549  ClassTemplateDecl *Template = 0;
6550  const TemplateArgument *Arguments = 0;
6551
6552  if (const RecordType *RT = Ty->getAs<RecordType>()) {
6553
6554    ClassTemplateSpecializationDecl *Specialization =
6555        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6556    if (!Specialization)
6557      return false;
6558
6559    Template = Specialization->getSpecializedTemplate();
6560    Arguments = Specialization->getTemplateArgs().data();
6561  } else if (const TemplateSpecializationType *TST =
6562                 Ty->getAs<TemplateSpecializationType>()) {
6563    Template = dyn_cast_or_null<ClassTemplateDecl>(
6564        TST->getTemplateName().getAsTemplateDecl());
6565    Arguments = TST->getArgs();
6566  }
6567  if (!Template)
6568    return false;
6569
6570  if (!StdInitializerList) {
6571    // Haven't recognized std::initializer_list yet, maybe this is it.
6572    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6573    if (TemplateClass->getIdentifier() !=
6574            &PP.getIdentifierTable().get("initializer_list") ||
6575        !getStdNamespace()->InEnclosingNamespaceSetOf(
6576            TemplateClass->getDeclContext()))
6577      return false;
6578    // This is a template called std::initializer_list, but is it the right
6579    // template?
6580    TemplateParameterList *Params = Template->getTemplateParameters();
6581    if (Params->getMinRequiredArguments() != 1)
6582      return false;
6583    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6584      return false;
6585
6586    // It's the right template.
6587    StdInitializerList = Template;
6588  }
6589
6590  if (Template != StdInitializerList)
6591    return false;
6592
6593  // This is an instance of std::initializer_list. Find the argument type.
6594  if (Element)
6595    *Element = Arguments[0].getAsType();
6596  return true;
6597}
6598
6599static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6600  NamespaceDecl *Std = S.getStdNamespace();
6601  if (!Std) {
6602    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6603    return 0;
6604  }
6605
6606  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6607                      Loc, Sema::LookupOrdinaryName);
6608  if (!S.LookupQualifiedName(Result, Std)) {
6609    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6610    return 0;
6611  }
6612  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6613  if (!Template) {
6614    Result.suppressDiagnostics();
6615    // We found something weird. Complain about the first thing we found.
6616    NamedDecl *Found = *Result.begin();
6617    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6618    return 0;
6619  }
6620
6621  // We found some template called std::initializer_list. Now verify that it's
6622  // correct.
6623  TemplateParameterList *Params = Template->getTemplateParameters();
6624  if (Params->getMinRequiredArguments() != 1 ||
6625      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6626    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6627    return 0;
6628  }
6629
6630  return Template;
6631}
6632
6633QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6634  if (!StdInitializerList) {
6635    StdInitializerList = LookupStdInitializerList(*this, Loc);
6636    if (!StdInitializerList)
6637      return QualType();
6638  }
6639
6640  TemplateArgumentListInfo Args(Loc, Loc);
6641  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6642                                       Context.getTrivialTypeSourceInfo(Element,
6643                                                                        Loc)));
6644  return Context.getCanonicalType(
6645      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6646}
6647
6648bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6649  // C++ [dcl.init.list]p2:
6650  //   A constructor is an initializer-list constructor if its first parameter
6651  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
6652  //   std::initializer_list<E> for some type E, and either there are no other
6653  //   parameters or else all other parameters have default arguments.
6654  if (Ctor->getNumParams() < 1 ||
6655      (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6656    return false;
6657
6658  QualType ArgType = Ctor->getParamDecl(0)->getType();
6659  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6660    ArgType = RT->getPointeeType().getUnqualifiedType();
6661
6662  return isStdInitializerList(ArgType, 0);
6663}
6664
6665/// \brief Determine whether a using statement is in a context where it will be
6666/// apply in all contexts.
6667static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6668  switch (CurContext->getDeclKind()) {
6669    case Decl::TranslationUnit:
6670      return true;
6671    case Decl::LinkageSpec:
6672      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6673    default:
6674      return false;
6675  }
6676}
6677
6678namespace {
6679
6680// Callback to only accept typo corrections that are namespaces.
6681class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6682public:
6683  bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6684    if (NamedDecl *ND = candidate.getCorrectionDecl())
6685      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6686    return false;
6687  }
6688};
6689
6690}
6691
6692static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6693                                       CXXScopeSpec &SS,
6694                                       SourceLocation IdentLoc,
6695                                       IdentifierInfo *Ident) {
6696  NamespaceValidatorCCC Validator;
6697  R.clear();
6698  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6699                                               R.getLookupKind(), Sc, &SS,
6700                                               Validator)) {
6701    if (DeclContext *DC = S.computeDeclContext(SS, false)) {
6702      std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6703      bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
6704                              Ident->getName().equals(CorrectedStr);
6705      S.diagnoseTypo(Corrected,
6706                     S.PDiag(diag::err_using_directive_member_suggest)
6707                       << Ident << DC << DroppedSpecifier << SS.getRange(),
6708                     S.PDiag(diag::note_namespace_defined_here));
6709    } else {
6710      S.diagnoseTypo(Corrected,
6711                     S.PDiag(diag::err_using_directive_suggest) << Ident,
6712                     S.PDiag(diag::note_namespace_defined_here));
6713    }
6714    R.addDecl(Corrected.getCorrectionDecl());
6715    return true;
6716  }
6717  return false;
6718}
6719
6720Decl *Sema::ActOnUsingDirective(Scope *S,
6721                                          SourceLocation UsingLoc,
6722                                          SourceLocation NamespcLoc,
6723                                          CXXScopeSpec &SS,
6724                                          SourceLocation IdentLoc,
6725                                          IdentifierInfo *NamespcName,
6726                                          AttributeList *AttrList) {
6727  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6728  assert(NamespcName && "Invalid NamespcName.");
6729  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
6730
6731  // This can only happen along a recovery path.
6732  while (S->getFlags() & Scope::TemplateParamScope)
6733    S = S->getParent();
6734  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6735
6736  UsingDirectiveDecl *UDir = 0;
6737  NestedNameSpecifier *Qualifier = 0;
6738  if (SS.isSet())
6739    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6740
6741  // Lookup namespace name.
6742  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6743  LookupParsedName(R, S, &SS);
6744  if (R.isAmbiguous())
6745    return 0;
6746
6747  if (R.empty()) {
6748    R.clear();
6749    // Allow "using namespace std;" or "using namespace ::std;" even if
6750    // "std" hasn't been defined yet, for GCC compatibility.
6751    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6752        NamespcName->isStr("std")) {
6753      Diag(IdentLoc, diag::ext_using_undefined_std);
6754      R.addDecl(getOrCreateStdNamespace());
6755      R.resolveKind();
6756    }
6757    // Otherwise, attempt typo correction.
6758    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
6759  }
6760
6761  if (!R.empty()) {
6762    NamedDecl *Named = R.getFoundDecl();
6763    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6764        && "expected namespace decl");
6765    // C++ [namespace.udir]p1:
6766    //   A using-directive specifies that the names in the nominated
6767    //   namespace can be used in the scope in which the
6768    //   using-directive appears after the using-directive. During
6769    //   unqualified name lookup (3.4.1), the names appear as if they
6770    //   were declared in the nearest enclosing namespace which
6771    //   contains both the using-directive and the nominated
6772    //   namespace. [Note: in this context, "contains" means "contains
6773    //   directly or indirectly". ]
6774
6775    // Find enclosing context containing both using-directive and
6776    // nominated namespace.
6777    NamespaceDecl *NS = getNamespaceDecl(Named);
6778    DeclContext *CommonAncestor = cast<DeclContext>(NS);
6779    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6780      CommonAncestor = CommonAncestor->getParent();
6781
6782    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
6783                                      SS.getWithLocInContext(Context),
6784                                      IdentLoc, Named, CommonAncestor);
6785
6786    if (IsUsingDirectiveInToplevelContext(CurContext) &&
6787        !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
6788      Diag(IdentLoc, diag::warn_using_directive_in_header);
6789    }
6790
6791    PushUsingDirective(S, UDir);
6792  } else {
6793    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6794  }
6795
6796  if (UDir)
6797    ProcessDeclAttributeList(S, UDir, AttrList);
6798
6799  return UDir;
6800}
6801
6802void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6803  // If the scope has an associated entity and the using directive is at
6804  // namespace or translation unit scope, add the UsingDirectiveDecl into
6805  // its lookup structure so qualified name lookup can find it.
6806  DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6807  if (Ctx && !Ctx->isFunctionOrMethod())
6808    Ctx->addDecl(UDir);
6809  else
6810    // Otherwise, it is at block sope. The using-directives will affect lookup
6811    // only to the end of the scope.
6812    S->PushUsingDirective(UDir);
6813}
6814
6815
6816Decl *Sema::ActOnUsingDeclaration(Scope *S,
6817                                  AccessSpecifier AS,
6818                                  bool HasUsingKeyword,
6819                                  SourceLocation UsingLoc,
6820                                  CXXScopeSpec &SS,
6821                                  UnqualifiedId &Name,
6822                                  AttributeList *AttrList,
6823                                  bool HasTypenameKeyword,
6824                                  SourceLocation TypenameLoc) {
6825  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6826
6827  switch (Name.getKind()) {
6828  case UnqualifiedId::IK_ImplicitSelfParam:
6829  case UnqualifiedId::IK_Identifier:
6830  case UnqualifiedId::IK_OperatorFunctionId:
6831  case UnqualifiedId::IK_LiteralOperatorId:
6832  case UnqualifiedId::IK_ConversionFunctionId:
6833    break;
6834
6835  case UnqualifiedId::IK_ConstructorName:
6836  case UnqualifiedId::IK_ConstructorTemplateId:
6837    // C++11 inheriting constructors.
6838    Diag(Name.getLocStart(),
6839         getLangOpts().CPlusPlus11 ?
6840           diag::warn_cxx98_compat_using_decl_constructor :
6841           diag::err_using_decl_constructor)
6842      << SS.getRange();
6843
6844    if (getLangOpts().CPlusPlus11) break;
6845
6846    return 0;
6847
6848  case UnqualifiedId::IK_DestructorName:
6849    Diag(Name.getLocStart(), diag::err_using_decl_destructor)
6850      << SS.getRange();
6851    return 0;
6852
6853  case UnqualifiedId::IK_TemplateId:
6854    Diag(Name.getLocStart(), diag::err_using_decl_template_id)
6855      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
6856    return 0;
6857  }
6858
6859  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6860  DeclarationName TargetName = TargetNameInfo.getName();
6861  if (!TargetName)
6862    return 0;
6863
6864  // Warn about access declarations.
6865  if (!HasUsingKeyword) {
6866    Diag(Name.getLocStart(),
6867         getLangOpts().CPlusPlus11 ? diag::err_access_decl
6868                                   : diag::warn_access_decl_deprecated)
6869      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
6870  }
6871
6872  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6873      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6874    return 0;
6875
6876  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
6877                                        TargetNameInfo, AttrList,
6878                                        /* IsInstantiation */ false,
6879                                        HasTypenameKeyword, TypenameLoc);
6880  if (UD)
6881    PushOnScopeChains(UD, S, /*AddToContext*/ false);
6882
6883  return UD;
6884}
6885
6886/// \brief Determine whether a using declaration considers the given
6887/// declarations as "equivalent", e.g., if they are redeclarations of
6888/// the same entity or are both typedefs of the same type.
6889static bool
6890IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6891                         bool &SuppressRedeclaration) {
6892  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6893    SuppressRedeclaration = false;
6894    return true;
6895  }
6896
6897  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6898    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
6899      SuppressRedeclaration = true;
6900      return Context.hasSameType(TD1->getUnderlyingType(),
6901                                 TD2->getUnderlyingType());
6902    }
6903
6904  return false;
6905}
6906
6907
6908/// Determines whether to create a using shadow decl for a particular
6909/// decl, given the set of decls existing prior to this using lookup.
6910bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6911                                const LookupResult &Previous) {
6912  // Diagnose finding a decl which is not from a base class of the
6913  // current class.  We do this now because there are cases where this
6914  // function will silently decide not to build a shadow decl, which
6915  // will pre-empt further diagnostics.
6916  //
6917  // We don't need to do this in C++0x because we do the check once on
6918  // the qualifier.
6919  //
6920  // FIXME: diagnose the following if we care enough:
6921  //   struct A { int foo; };
6922  //   struct B : A { using A::foo; };
6923  //   template <class T> struct C : A {};
6924  //   template <class T> struct D : C<T> { using B::foo; } // <---
6925  // This is invalid (during instantiation) in C++03 because B::foo
6926  // resolves to the using decl in B, which is not a base class of D<T>.
6927  // We can't diagnose it immediately because C<T> is an unknown
6928  // specialization.  The UsingShadowDecl in D<T> then points directly
6929  // to A::foo, which will look well-formed when we instantiate.
6930  // The right solution is to not collapse the shadow-decl chain.
6931  if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
6932    DeclContext *OrigDC = Orig->getDeclContext();
6933
6934    // Handle enums and anonymous structs.
6935    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6936    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6937    while (OrigRec->isAnonymousStructOrUnion())
6938      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6939
6940    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6941      if (OrigDC == CurContext) {
6942        Diag(Using->getLocation(),
6943             diag::err_using_decl_nested_name_specifier_is_current_class)
6944          << Using->getQualifierLoc().getSourceRange();
6945        Diag(Orig->getLocation(), diag::note_using_decl_target);
6946        return true;
6947      }
6948
6949      Diag(Using->getQualifierLoc().getBeginLoc(),
6950           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6951        << Using->getQualifier()
6952        << cast<CXXRecordDecl>(CurContext)
6953        << Using->getQualifierLoc().getSourceRange();
6954      Diag(Orig->getLocation(), diag::note_using_decl_target);
6955      return true;
6956    }
6957  }
6958
6959  if (Previous.empty()) return false;
6960
6961  NamedDecl *Target = Orig;
6962  if (isa<UsingShadowDecl>(Target))
6963    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6964
6965  // If the target happens to be one of the previous declarations, we
6966  // don't have a conflict.
6967  //
6968  // FIXME: but we might be increasing its access, in which case we
6969  // should redeclare it.
6970  NamedDecl *NonTag = 0, *Tag = 0;
6971  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6972         I != E; ++I) {
6973    NamedDecl *D = (*I)->getUnderlyingDecl();
6974    bool Result;
6975    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6976      return Result;
6977
6978    (isa<TagDecl>(D) ? Tag : NonTag) = D;
6979  }
6980
6981  if (Target->isFunctionOrFunctionTemplate()) {
6982    FunctionDecl *FD;
6983    if (isa<FunctionTemplateDecl>(Target))
6984      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6985    else
6986      FD = cast<FunctionDecl>(Target);
6987
6988    NamedDecl *OldDecl = 0;
6989    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6990    case Ovl_Overload:
6991      return false;
6992
6993    case Ovl_NonFunction:
6994      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6995      break;
6996
6997    // We found a decl with the exact signature.
6998    case Ovl_Match:
6999      // If we're in a record, we want to hide the target, so we
7000      // return true (without a diagnostic) to tell the caller not to
7001      // build a shadow decl.
7002      if (CurContext->isRecord())
7003        return true;
7004
7005      // If we're not in a record, this is an error.
7006      Diag(Using->getLocation(), diag::err_using_decl_conflict);
7007      break;
7008    }
7009
7010    Diag(Target->getLocation(), diag::note_using_decl_target);
7011    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7012    return true;
7013  }
7014
7015  // Target is not a function.
7016
7017  if (isa<TagDecl>(Target)) {
7018    // No conflict between a tag and a non-tag.
7019    if (!Tag) return false;
7020
7021    Diag(Using->getLocation(), diag::err_using_decl_conflict);
7022    Diag(Target->getLocation(), diag::note_using_decl_target);
7023    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7024    return true;
7025  }
7026
7027  // No conflict between a tag and a non-tag.
7028  if (!NonTag) return false;
7029
7030  Diag(Using->getLocation(), diag::err_using_decl_conflict);
7031  Diag(Target->getLocation(), diag::note_using_decl_target);
7032  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7033  return true;
7034}
7035
7036/// Builds a shadow declaration corresponding to a 'using' declaration.
7037UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7038                                            UsingDecl *UD,
7039                                            NamedDecl *Orig) {
7040
7041  // If we resolved to another shadow declaration, just coalesce them.
7042  NamedDecl *Target = Orig;
7043  if (isa<UsingShadowDecl>(Target)) {
7044    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7045    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7046  }
7047
7048  UsingShadowDecl *Shadow
7049    = UsingShadowDecl::Create(Context, CurContext,
7050                              UD->getLocation(), UD, Target);
7051  UD->addShadowDecl(Shadow);
7052
7053  Shadow->setAccess(UD->getAccess());
7054  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7055    Shadow->setInvalidDecl();
7056
7057  if (S)
7058    PushOnScopeChains(Shadow, S);
7059  else
7060    CurContext->addDecl(Shadow);
7061
7062
7063  return Shadow;
7064}
7065
7066/// Hides a using shadow declaration.  This is required by the current
7067/// using-decl implementation when a resolvable using declaration in a
7068/// class is followed by a declaration which would hide or override
7069/// one or more of the using decl's targets; for example:
7070///
7071///   struct Base { void foo(int); };
7072///   struct Derived : Base {
7073///     using Base::foo;
7074///     void foo(int);
7075///   };
7076///
7077/// The governing language is C++03 [namespace.udecl]p12:
7078///
7079///   When a using-declaration brings names from a base class into a
7080///   derived class scope, member functions in the derived class
7081///   override and/or hide member functions with the same name and
7082///   parameter types in a base class (rather than conflicting).
7083///
7084/// There are two ways to implement this:
7085///   (1) optimistically create shadow decls when they're not hidden
7086///       by existing declarations, or
7087///   (2) don't create any shadow decls (or at least don't make them
7088///       visible) until we've fully parsed/instantiated the class.
7089/// The problem with (1) is that we might have to retroactively remove
7090/// a shadow decl, which requires several O(n) operations because the
7091/// decl structures are (very reasonably) not designed for removal.
7092/// (2) avoids this but is very fiddly and phase-dependent.
7093void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7094  if (Shadow->getDeclName().getNameKind() ==
7095        DeclarationName::CXXConversionFunctionName)
7096    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7097
7098  // Remove it from the DeclContext...
7099  Shadow->getDeclContext()->removeDecl(Shadow);
7100
7101  // ...and the scope, if applicable...
7102  if (S) {
7103    S->RemoveDecl(Shadow);
7104    IdResolver.RemoveDecl(Shadow);
7105  }
7106
7107  // ...and the using decl.
7108  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7109
7110  // TODO: complain somehow if Shadow was used.  It shouldn't
7111  // be possible for this to happen, because...?
7112}
7113
7114namespace {
7115class UsingValidatorCCC : public CorrectionCandidateCallback {
7116public:
7117  UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation)
7118      : HasTypenameKeyword(HasTypenameKeyword),
7119        IsInstantiation(IsInstantiation) {}
7120
7121  bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7122    NamedDecl *ND = Candidate.getCorrectionDecl();
7123
7124    // Keywords are not valid here.
7125    if (!ND || isa<NamespaceDecl>(ND))
7126      return false;
7127
7128    // Completely unqualified names are invalid for a 'using' declaration.
7129    if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7130      return false;
7131
7132    if (isa<TypeDecl>(ND))
7133      return HasTypenameKeyword || !IsInstantiation;
7134
7135    return !HasTypenameKeyword;
7136  }
7137
7138private:
7139  bool HasTypenameKeyword;
7140  bool IsInstantiation;
7141};
7142} // end anonymous namespace
7143
7144/// Builds a using declaration.
7145///
7146/// \param IsInstantiation - Whether this call arises from an
7147///   instantiation of an unresolved using declaration.  We treat
7148///   the lookup differently for these declarations.
7149NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7150                                       SourceLocation UsingLoc,
7151                                       CXXScopeSpec &SS,
7152                                       const DeclarationNameInfo &NameInfo,
7153                                       AttributeList *AttrList,
7154                                       bool IsInstantiation,
7155                                       bool HasTypenameKeyword,
7156                                       SourceLocation TypenameLoc) {
7157  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7158  SourceLocation IdentLoc = NameInfo.getLoc();
7159  assert(IdentLoc.isValid() && "Invalid TargetName location.");
7160
7161  // FIXME: We ignore attributes for now.
7162
7163  if (SS.isEmpty()) {
7164    Diag(IdentLoc, diag::err_using_requires_qualname);
7165    return 0;
7166  }
7167
7168  // Do the redeclaration lookup in the current scope.
7169  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7170                        ForRedeclaration);
7171  Previous.setHideTags(false);
7172  if (S) {
7173    LookupName(Previous, S);
7174
7175    // It is really dumb that we have to do this.
7176    LookupResult::Filter F = Previous.makeFilter();
7177    while (F.hasNext()) {
7178      NamedDecl *D = F.next();
7179      if (!isDeclInScope(D, CurContext, S))
7180        F.erase();
7181    }
7182    F.done();
7183  } else {
7184    assert(IsInstantiation && "no scope in non-instantiation");
7185    assert(CurContext->isRecord() && "scope not record in instantiation");
7186    LookupQualifiedName(Previous, CurContext);
7187  }
7188
7189  // Check for invalid redeclarations.
7190  if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7191                                  SS, IdentLoc, Previous))
7192    return 0;
7193
7194  // Check for bad qualifiers.
7195  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7196    return 0;
7197
7198  DeclContext *LookupContext = computeDeclContext(SS);
7199  NamedDecl *D;
7200  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7201  if (!LookupContext) {
7202    if (HasTypenameKeyword) {
7203      // FIXME: not all declaration name kinds are legal here
7204      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7205                                              UsingLoc, TypenameLoc,
7206                                              QualifierLoc,
7207                                              IdentLoc, NameInfo.getName());
7208    } else {
7209      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7210                                           QualifierLoc, NameInfo);
7211    }
7212  } else {
7213    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7214                          NameInfo, HasTypenameKeyword);
7215  }
7216  D->setAccess(AS);
7217  CurContext->addDecl(D);
7218
7219  if (!LookupContext) return D;
7220  UsingDecl *UD = cast<UsingDecl>(D);
7221
7222  if (RequireCompleteDeclContext(SS, LookupContext)) {
7223    UD->setInvalidDecl();
7224    return UD;
7225  }
7226
7227  // The normal rules do not apply to inheriting constructor declarations.
7228  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7229    if (CheckInheritingConstructorUsingDecl(UD))
7230      UD->setInvalidDecl();
7231    return UD;
7232  }
7233
7234  // Otherwise, look up the target name.
7235
7236  LookupResult R(*this, NameInfo, LookupOrdinaryName);
7237
7238  // Unlike most lookups, we don't always want to hide tag
7239  // declarations: tag names are visible through the using declaration
7240  // even if hidden by ordinary names, *except* in a dependent context
7241  // where it's important for the sanity of two-phase lookup.
7242  if (!IsInstantiation)
7243    R.setHideTags(false);
7244
7245  // For the purposes of this lookup, we have a base object type
7246  // equal to that of the current context.
7247  if (CurContext->isRecord()) {
7248    R.setBaseObjectType(
7249                   Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7250  }
7251
7252  LookupQualifiedName(R, LookupContext);
7253
7254  // Try to correct typos if possible.
7255  if (R.empty()) {
7256    UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation);
7257    if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7258                                               R.getLookupKind(), S, &SS, CCC)){
7259      // We reject any correction for which ND would be NULL.
7260      NamedDecl *ND = Corrected.getCorrectionDecl();
7261      R.setLookupName(Corrected.getCorrection());
7262      R.addDecl(ND);
7263      // We reject candidates where DroppedSpecifier == true, hence the
7264      // literal '0' below.
7265      diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7266                                << NameInfo.getName() << LookupContext << 0
7267                                << SS.getRange());
7268    } else {
7269      Diag(IdentLoc, diag::err_no_member)
7270        << NameInfo.getName() << LookupContext << SS.getRange();
7271      UD->setInvalidDecl();
7272      return UD;
7273    }
7274  }
7275
7276  if (R.isAmbiguous()) {
7277    UD->setInvalidDecl();
7278    return UD;
7279  }
7280
7281  if (HasTypenameKeyword) {
7282    // If we asked for a typename and got a non-type decl, error out.
7283    if (!R.getAsSingle<TypeDecl>()) {
7284      Diag(IdentLoc, diag::err_using_typename_non_type);
7285      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7286        Diag((*I)->getUnderlyingDecl()->getLocation(),
7287             diag::note_using_decl_target);
7288      UD->setInvalidDecl();
7289      return UD;
7290    }
7291  } else {
7292    // If we asked for a non-typename and we got a type, error out,
7293    // but only if this is an instantiation of an unresolved using
7294    // decl.  Otherwise just silently find the type name.
7295    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7296      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7297      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7298      UD->setInvalidDecl();
7299      return UD;
7300    }
7301  }
7302
7303  // C++0x N2914 [namespace.udecl]p6:
7304  // A using-declaration shall not name a namespace.
7305  if (R.getAsSingle<NamespaceDecl>()) {
7306    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7307      << SS.getRange();
7308    UD->setInvalidDecl();
7309    return UD;
7310  }
7311
7312  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7313    if (!CheckUsingShadowDecl(UD, *I, Previous))
7314      BuildUsingShadowDecl(S, UD, *I);
7315  }
7316
7317  return UD;
7318}
7319
7320/// Additional checks for a using declaration referring to a constructor name.
7321bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7322  assert(!UD->hasTypename() && "expecting a constructor name");
7323
7324  const Type *SourceType = UD->getQualifier()->getAsType();
7325  assert(SourceType &&
7326         "Using decl naming constructor doesn't have type in scope spec.");
7327  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7328
7329  // Check whether the named type is a direct base class.
7330  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7331  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7332  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7333       BaseIt != BaseE; ++BaseIt) {
7334    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7335    if (CanonicalSourceType == BaseType)
7336      break;
7337    if (BaseIt->getType()->isDependentType())
7338      break;
7339  }
7340
7341  if (BaseIt == BaseE) {
7342    // Did not find SourceType in the bases.
7343    Diag(UD->getUsingLoc(),
7344         diag::err_using_decl_constructor_not_in_direct_base)
7345      << UD->getNameInfo().getSourceRange()
7346      << QualType(SourceType, 0) << TargetClass;
7347    return true;
7348  }
7349
7350  if (!CurContext->isDependentContext())
7351    BaseIt->setInheritConstructors();
7352
7353  return false;
7354}
7355
7356/// Checks that the given using declaration is not an invalid
7357/// redeclaration.  Note that this is checking only for the using decl
7358/// itself, not for any ill-formedness among the UsingShadowDecls.
7359bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7360                                       bool HasTypenameKeyword,
7361                                       const CXXScopeSpec &SS,
7362                                       SourceLocation NameLoc,
7363                                       const LookupResult &Prev) {
7364  // C++03 [namespace.udecl]p8:
7365  // C++0x [namespace.udecl]p10:
7366  //   A using-declaration is a declaration and can therefore be used
7367  //   repeatedly where (and only where) multiple declarations are
7368  //   allowed.
7369  //
7370  // That's in non-member contexts.
7371  if (!CurContext->getRedeclContext()->isRecord())
7372    return false;
7373
7374  NestedNameSpecifier *Qual
7375    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7376
7377  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7378    NamedDecl *D = *I;
7379
7380    bool DTypename;
7381    NestedNameSpecifier *DQual;
7382    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7383      DTypename = UD->hasTypename();
7384      DQual = UD->getQualifier();
7385    } else if (UnresolvedUsingValueDecl *UD
7386                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7387      DTypename = false;
7388      DQual = UD->getQualifier();
7389    } else if (UnresolvedUsingTypenameDecl *UD
7390                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7391      DTypename = true;
7392      DQual = UD->getQualifier();
7393    } else continue;
7394
7395    // using decls differ if one says 'typename' and the other doesn't.
7396    // FIXME: non-dependent using decls?
7397    if (HasTypenameKeyword != DTypename) continue;
7398
7399    // using decls differ if they name different scopes (but note that
7400    // template instantiation can cause this check to trigger when it
7401    // didn't before instantiation).
7402    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7403        Context.getCanonicalNestedNameSpecifier(DQual))
7404      continue;
7405
7406    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7407    Diag(D->getLocation(), diag::note_using_decl) << 1;
7408    return true;
7409  }
7410
7411  return false;
7412}
7413
7414
7415/// Checks that the given nested-name qualifier used in a using decl
7416/// in the current context is appropriately related to the current
7417/// scope.  If an error is found, diagnoses it and returns true.
7418bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7419                                   const CXXScopeSpec &SS,
7420                                   SourceLocation NameLoc) {
7421  DeclContext *NamedContext = computeDeclContext(SS);
7422
7423  if (!CurContext->isRecord()) {
7424    // C++03 [namespace.udecl]p3:
7425    // C++0x [namespace.udecl]p8:
7426    //   A using-declaration for a class member shall be a member-declaration.
7427
7428    // If we weren't able to compute a valid scope, it must be a
7429    // dependent class scope.
7430    if (!NamedContext || NamedContext->isRecord()) {
7431      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7432        << SS.getRange();
7433      return true;
7434    }
7435
7436    // Otherwise, everything is known to be fine.
7437    return false;
7438  }
7439
7440  // The current scope is a record.
7441
7442  // If the named context is dependent, we can't decide much.
7443  if (!NamedContext) {
7444    // FIXME: in C++0x, we can diagnose if we can prove that the
7445    // nested-name-specifier does not refer to a base class, which is
7446    // still possible in some cases.
7447
7448    // Otherwise we have to conservatively report that things might be
7449    // okay.
7450    return false;
7451  }
7452
7453  if (!NamedContext->isRecord()) {
7454    // Ideally this would point at the last name in the specifier,
7455    // but we don't have that level of source info.
7456    Diag(SS.getRange().getBegin(),
7457         diag::err_using_decl_nested_name_specifier_is_not_class)
7458      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7459    return true;
7460  }
7461
7462  if (!NamedContext->isDependentContext() &&
7463      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7464    return true;
7465
7466  if (getLangOpts().CPlusPlus11) {
7467    // C++0x [namespace.udecl]p3:
7468    //   In a using-declaration used as a member-declaration, the
7469    //   nested-name-specifier shall name a base class of the class
7470    //   being defined.
7471
7472    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7473                                 cast<CXXRecordDecl>(NamedContext))) {
7474      if (CurContext == NamedContext) {
7475        Diag(NameLoc,
7476             diag::err_using_decl_nested_name_specifier_is_current_class)
7477          << SS.getRange();
7478        return true;
7479      }
7480
7481      Diag(SS.getRange().getBegin(),
7482           diag::err_using_decl_nested_name_specifier_is_not_base_class)
7483        << (NestedNameSpecifier*) SS.getScopeRep()
7484        << cast<CXXRecordDecl>(CurContext)
7485        << SS.getRange();
7486      return true;
7487    }
7488
7489    return false;
7490  }
7491
7492  // C++03 [namespace.udecl]p4:
7493  //   A using-declaration used as a member-declaration shall refer
7494  //   to a member of a base class of the class being defined [etc.].
7495
7496  // Salient point: SS doesn't have to name a base class as long as
7497  // lookup only finds members from base classes.  Therefore we can
7498  // diagnose here only if we can prove that that can't happen,
7499  // i.e. if the class hierarchies provably don't intersect.
7500
7501  // TODO: it would be nice if "definitely valid" results were cached
7502  // in the UsingDecl and UsingShadowDecl so that these checks didn't
7503  // need to be repeated.
7504
7505  struct UserData {
7506    llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7507
7508    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7509      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7510      Data->Bases.insert(Base);
7511      return true;
7512    }
7513
7514    bool hasDependentBases(const CXXRecordDecl *Class) {
7515      return !Class->forallBases(collect, this);
7516    }
7517
7518    /// Returns true if the base is dependent or is one of the
7519    /// accumulated base classes.
7520    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7521      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7522      return !Data->Bases.count(Base);
7523    }
7524
7525    bool mightShareBases(const CXXRecordDecl *Class) {
7526      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7527    }
7528  };
7529
7530  UserData Data;
7531
7532  // Returns false if we find a dependent base.
7533  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7534    return false;
7535
7536  // Returns false if the class has a dependent base or if it or one
7537  // of its bases is present in the base set of the current context.
7538  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7539    return false;
7540
7541  Diag(SS.getRange().getBegin(),
7542       diag::err_using_decl_nested_name_specifier_is_not_base_class)
7543    << (NestedNameSpecifier*) SS.getScopeRep()
7544    << cast<CXXRecordDecl>(CurContext)
7545    << SS.getRange();
7546
7547  return true;
7548}
7549
7550Decl *Sema::ActOnAliasDeclaration(Scope *S,
7551                                  AccessSpecifier AS,
7552                                  MultiTemplateParamsArg TemplateParamLists,
7553                                  SourceLocation UsingLoc,
7554                                  UnqualifiedId &Name,
7555                                  AttributeList *AttrList,
7556                                  TypeResult Type) {
7557  // Skip up to the relevant declaration scope.
7558  while (S->getFlags() & Scope::TemplateParamScope)
7559    S = S->getParent();
7560  assert((S->getFlags() & Scope::DeclScope) &&
7561         "got alias-declaration outside of declaration scope");
7562
7563  if (Type.isInvalid())
7564    return 0;
7565
7566  bool Invalid = false;
7567  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7568  TypeSourceInfo *TInfo = 0;
7569  GetTypeFromParser(Type.get(), &TInfo);
7570
7571  if (DiagnoseClassNameShadow(CurContext, NameInfo))
7572    return 0;
7573
7574  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7575                                      UPPC_DeclarationType)) {
7576    Invalid = true;
7577    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7578                                             TInfo->getTypeLoc().getBeginLoc());
7579  }
7580
7581  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7582  LookupName(Previous, S);
7583
7584  // Warn about shadowing the name of a template parameter.
7585  if (Previous.isSingleResult() &&
7586      Previous.getFoundDecl()->isTemplateParameter()) {
7587    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
7588    Previous.clear();
7589  }
7590
7591  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7592         "name in alias declaration must be an identifier");
7593  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7594                                               Name.StartLocation,
7595                                               Name.Identifier, TInfo);
7596
7597  NewTD->setAccess(AS);
7598
7599  if (Invalid)
7600    NewTD->setInvalidDecl();
7601
7602  ProcessDeclAttributeList(S, NewTD, AttrList);
7603
7604  CheckTypedefForVariablyModifiedType(S, NewTD);
7605  Invalid |= NewTD->isInvalidDecl();
7606
7607  bool Redeclaration = false;
7608
7609  NamedDecl *NewND;
7610  if (TemplateParamLists.size()) {
7611    TypeAliasTemplateDecl *OldDecl = 0;
7612    TemplateParameterList *OldTemplateParams = 0;
7613
7614    if (TemplateParamLists.size() != 1) {
7615      Diag(UsingLoc, diag::err_alias_template_extra_headers)
7616        << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7617         TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
7618    }
7619    TemplateParameterList *TemplateParams = TemplateParamLists[0];
7620
7621    // Only consider previous declarations in the same scope.
7622    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7623                         /*ExplicitInstantiationOrSpecialization*/false);
7624    if (!Previous.empty()) {
7625      Redeclaration = true;
7626
7627      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7628      if (!OldDecl && !Invalid) {
7629        Diag(UsingLoc, diag::err_redefinition_different_kind)
7630          << Name.Identifier;
7631
7632        NamedDecl *OldD = Previous.getRepresentativeDecl();
7633        if (OldD->getLocation().isValid())
7634          Diag(OldD->getLocation(), diag::note_previous_definition);
7635
7636        Invalid = true;
7637      }
7638
7639      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7640        if (TemplateParameterListsAreEqual(TemplateParams,
7641                                           OldDecl->getTemplateParameters(),
7642                                           /*Complain=*/true,
7643                                           TPL_TemplateMatch))
7644          OldTemplateParams = OldDecl->getTemplateParameters();
7645        else
7646          Invalid = true;
7647
7648        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7649        if (!Invalid &&
7650            !Context.hasSameType(OldTD->getUnderlyingType(),
7651                                 NewTD->getUnderlyingType())) {
7652          // FIXME: The C++0x standard does not clearly say this is ill-formed,
7653          // but we can't reasonably accept it.
7654          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7655            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7656          if (OldTD->getLocation().isValid())
7657            Diag(OldTD->getLocation(), diag::note_previous_definition);
7658          Invalid = true;
7659        }
7660      }
7661    }
7662
7663    // Merge any previous default template arguments into our parameters,
7664    // and check the parameter list.
7665    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7666                                   TPC_TypeAliasTemplate))
7667      return 0;
7668
7669    TypeAliasTemplateDecl *NewDecl =
7670      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7671                                    Name.Identifier, TemplateParams,
7672                                    NewTD);
7673
7674    NewDecl->setAccess(AS);
7675
7676    if (Invalid)
7677      NewDecl->setInvalidDecl();
7678    else if (OldDecl)
7679      NewDecl->setPreviousDeclaration(OldDecl);
7680
7681    NewND = NewDecl;
7682  } else {
7683    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7684    NewND = NewTD;
7685  }
7686
7687  if (!Redeclaration)
7688    PushOnScopeChains(NewND, S);
7689
7690  ActOnDocumentableDecl(NewND);
7691  return NewND;
7692}
7693
7694Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
7695                                             SourceLocation NamespaceLoc,
7696                                             SourceLocation AliasLoc,
7697                                             IdentifierInfo *Alias,
7698                                             CXXScopeSpec &SS,
7699                                             SourceLocation IdentLoc,
7700                                             IdentifierInfo *Ident) {
7701
7702  // Lookup the namespace name.
7703  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7704  LookupParsedName(R, S, &SS);
7705
7706  // Check if we have a previous declaration with the same name.
7707  NamedDecl *PrevDecl
7708    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7709                       ForRedeclaration);
7710  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7711    PrevDecl = 0;
7712
7713  if (PrevDecl) {
7714    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
7715      // We already have an alias with the same name that points to the same
7716      // namespace, so don't create a new one.
7717      // FIXME: At some point, we'll want to create the (redundant)
7718      // declaration to maintain better source information.
7719      if (!R.isAmbiguous() && !R.empty() &&
7720          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
7721        return 0;
7722    }
7723
7724    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7725      diag::err_redefinition_different_kind;
7726    Diag(AliasLoc, DiagID) << Alias;
7727    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7728    return 0;
7729  }
7730
7731  if (R.isAmbiguous())
7732    return 0;
7733
7734  if (R.empty()) {
7735    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
7736      Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7737      return 0;
7738    }
7739  }
7740
7741  NamespaceAliasDecl *AliasDecl =
7742    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
7743                               Alias, SS.getWithLocInContext(Context),
7744                               IdentLoc, R.getFoundDecl());
7745
7746  PushOnScopeChains(AliasDecl, S);
7747  return AliasDecl;
7748}
7749
7750Sema::ImplicitExceptionSpecification
7751Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7752                                               CXXMethodDecl *MD) {
7753  CXXRecordDecl *ClassDecl = MD->getParent();
7754
7755  // C++ [except.spec]p14:
7756  //   An implicitly declared special member function (Clause 12) shall have an
7757  //   exception-specification. [...]
7758  ImplicitExceptionSpecification ExceptSpec(*this);
7759  if (ClassDecl->isInvalidDecl())
7760    return ExceptSpec;
7761
7762  // Direct base-class constructors.
7763  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7764                                       BEnd = ClassDecl->bases_end();
7765       B != BEnd; ++B) {
7766    if (B->isVirtual()) // Handled below.
7767      continue;
7768
7769    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7770      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7771      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7772      // If this is a deleted function, add it anyway. This might be conformant
7773      // with the standard. This might not. I'm not sure. It might not matter.
7774      if (Constructor)
7775        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7776    }
7777  }
7778
7779  // Virtual base-class constructors.
7780  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7781                                       BEnd = ClassDecl->vbases_end();
7782       B != BEnd; ++B) {
7783    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7784      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7785      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7786      // If this is a deleted function, add it anyway. This might be conformant
7787      // with the standard. This might not. I'm not sure. It might not matter.
7788      if (Constructor)
7789        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7790    }
7791  }
7792
7793  // Field constructors.
7794  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7795                               FEnd = ClassDecl->field_end();
7796       F != FEnd; ++F) {
7797    if (F->hasInClassInitializer()) {
7798      if (Expr *E = F->getInClassInitializer())
7799        ExceptSpec.CalledExpr(E);
7800      else if (!F->isInvalidDecl())
7801        // DR1351:
7802        //   If the brace-or-equal-initializer of a non-static data member
7803        //   invokes a defaulted default constructor of its class or of an
7804        //   enclosing class in a potentially evaluated subexpression, the
7805        //   program is ill-formed.
7806        //
7807        // This resolution is unworkable: the exception specification of the
7808        // default constructor can be needed in an unevaluated context, in
7809        // particular, in the operand of a noexcept-expression, and we can be
7810        // unable to compute an exception specification for an enclosed class.
7811        //
7812        // We do not allow an in-class initializer to require the evaluation
7813        // of the exception specification for any in-class initializer whose
7814        // definition is not lexically complete.
7815        Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
7816    } else if (const RecordType *RecordTy
7817              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7818      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7819      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7820      // If this is a deleted function, add it anyway. This might be conformant
7821      // with the standard. This might not. I'm not sure. It might not matter.
7822      // In particular, the problem is that this function never gets called. It
7823      // might just be ill-formed because this function attempts to refer to
7824      // a deleted function here.
7825      if (Constructor)
7826        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7827    }
7828  }
7829
7830  return ExceptSpec;
7831}
7832
7833Sema::ImplicitExceptionSpecification
7834Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7835  CXXRecordDecl *ClassDecl = CD->getParent();
7836
7837  // C++ [except.spec]p14:
7838  //   An inheriting constructor [...] shall have an exception-specification. [...]
7839  ImplicitExceptionSpecification ExceptSpec(*this);
7840  if (ClassDecl->isInvalidDecl())
7841    return ExceptSpec;
7842
7843  // Inherited constructor.
7844  const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7845  const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7846  // FIXME: Copying or moving the parameters could add extra exceptions to the
7847  // set, as could the default arguments for the inherited constructor. This
7848  // will be addressed when we implement the resolution of core issue 1351.
7849  ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7850
7851  // Direct base-class constructors.
7852  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7853                                       BEnd = ClassDecl->bases_end();
7854       B != BEnd; ++B) {
7855    if (B->isVirtual()) // Handled below.
7856      continue;
7857
7858    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7859      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7860      if (BaseClassDecl == InheritedDecl)
7861        continue;
7862      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7863      if (Constructor)
7864        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7865    }
7866  }
7867
7868  // Virtual base-class constructors.
7869  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7870                                       BEnd = ClassDecl->vbases_end();
7871       B != BEnd; ++B) {
7872    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7873      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7874      if (BaseClassDecl == InheritedDecl)
7875        continue;
7876      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7877      if (Constructor)
7878        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7879    }
7880  }
7881
7882  // Field constructors.
7883  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7884                               FEnd = ClassDecl->field_end();
7885       F != FEnd; ++F) {
7886    if (F->hasInClassInitializer()) {
7887      if (Expr *E = F->getInClassInitializer())
7888        ExceptSpec.CalledExpr(E);
7889      else if (!F->isInvalidDecl())
7890        Diag(CD->getLocation(),
7891             diag::err_in_class_initializer_references_def_ctor) << CD;
7892    } else if (const RecordType *RecordTy
7893              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7894      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7895      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7896      if (Constructor)
7897        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7898    }
7899  }
7900
7901  return ExceptSpec;
7902}
7903
7904namespace {
7905/// RAII object to register a special member as being currently declared.
7906struct DeclaringSpecialMember {
7907  Sema &S;
7908  Sema::SpecialMemberDecl D;
7909  bool WasAlreadyBeingDeclared;
7910
7911  DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7912    : S(S), D(RD, CSM) {
7913    WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7914    if (WasAlreadyBeingDeclared)
7915      // This almost never happens, but if it does, ensure that our cache
7916      // doesn't contain a stale result.
7917      S.SpecialMemberCache.clear();
7918
7919    // FIXME: Register a note to be produced if we encounter an error while
7920    // declaring the special member.
7921  }
7922  ~DeclaringSpecialMember() {
7923    if (!WasAlreadyBeingDeclared)
7924      S.SpecialMembersBeingDeclared.erase(D);
7925  }
7926
7927  /// \brief Are we already trying to declare this special member?
7928  bool isAlreadyBeingDeclared() const {
7929    return WasAlreadyBeingDeclared;
7930  }
7931};
7932}
7933
7934CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7935                                                     CXXRecordDecl *ClassDecl) {
7936  // C++ [class.ctor]p5:
7937  //   A default constructor for a class X is a constructor of class X
7938  //   that can be called without an argument. If there is no
7939  //   user-declared constructor for class X, a default constructor is
7940  //   implicitly declared. An implicitly-declared default constructor
7941  //   is an inline public member of its class.
7942  assert(ClassDecl->needsImplicitDefaultConstructor() &&
7943         "Should not build implicit default constructor!");
7944
7945  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7946  if (DSM.isAlreadyBeingDeclared())
7947    return 0;
7948
7949  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7950                                                     CXXDefaultConstructor,
7951                                                     false);
7952
7953  // Create the actual constructor declaration.
7954  CanQualType ClassType
7955    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7956  SourceLocation ClassLoc = ClassDecl->getLocation();
7957  DeclarationName Name
7958    = Context.DeclarationNames.getCXXConstructorName(ClassType);
7959  DeclarationNameInfo NameInfo(Name, ClassLoc);
7960  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7961      Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
7962      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7963      Constexpr);
7964  DefaultCon->setAccess(AS_public);
7965  DefaultCon->setDefaulted();
7966  DefaultCon->setImplicit();
7967
7968  // Build an exception specification pointing back at this constructor.
7969  FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
7970  DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
7971
7972  // We don't need to use SpecialMemberIsTrivial here; triviality for default
7973  // constructors is easy to compute.
7974  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7975
7976  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7977    SetDeclDeleted(DefaultCon, ClassLoc);
7978
7979  // Note that we have declared this constructor.
7980  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7981
7982  if (Scope *S = getScopeForContext(ClassDecl))
7983    PushOnScopeChains(DefaultCon, S, false);
7984  ClassDecl->addDecl(DefaultCon);
7985
7986  return DefaultCon;
7987}
7988
7989void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7990                                            CXXConstructorDecl *Constructor) {
7991  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7992          !Constructor->doesThisDeclarationHaveABody() &&
7993          !Constructor->isDeleted()) &&
7994    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
7995
7996  CXXRecordDecl *ClassDecl = Constructor->getParent();
7997  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
7998
7999  SynthesizedFunctionScope Scope(*this, Constructor);
8000  DiagnosticErrorTrap Trap(Diags);
8001  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8002      Trap.hasErrorOccurred()) {
8003    Diag(CurrentLocation, diag::note_member_synthesized_at)
8004      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8005    Constructor->setInvalidDecl();
8006    return;
8007  }
8008
8009  SourceLocation Loc = Constructor->getLocation();
8010  Constructor->setBody(new (Context) CompoundStmt(Loc));
8011
8012  Constructor->markUsed(Context);
8013  MarkVTableUsed(CurrentLocation, ClassDecl);
8014
8015  if (ASTMutationListener *L = getASTMutationListener()) {
8016    L->CompletedImplicitDefinition(Constructor);
8017  }
8018}
8019
8020void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8021  // Check that any explicitly-defaulted methods have exception specifications
8022  // compatible with their implicit exception specifications.
8023  CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
8024}
8025
8026namespace {
8027/// Information on inheriting constructors to declare.
8028class InheritingConstructorInfo {
8029public:
8030  InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8031      : SemaRef(SemaRef), Derived(Derived) {
8032    // Mark the constructors that we already have in the derived class.
8033    //
8034    // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8035    //   unless there is a user-declared constructor with the same signature in
8036    //   the class where the using-declaration appears.
8037    visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8038  }
8039
8040  void inheritAll(CXXRecordDecl *RD) {
8041    visitAll(RD, &InheritingConstructorInfo::inherit);
8042  }
8043
8044private:
8045  /// Information about an inheriting constructor.
8046  struct InheritingConstructor {
8047    InheritingConstructor()
8048      : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8049
8050    /// If \c true, a constructor with this signature is already declared
8051    /// in the derived class.
8052    bool DeclaredInDerived;
8053
8054    /// The constructor which is inherited.
8055    const CXXConstructorDecl *BaseCtor;
8056
8057    /// The derived constructor we declared.
8058    CXXConstructorDecl *DerivedCtor;
8059  };
8060
8061  /// Inheriting constructors with a given canonical type. There can be at
8062  /// most one such non-template constructor, and any number of templated
8063  /// constructors.
8064  struct InheritingConstructorsForType {
8065    InheritingConstructor NonTemplate;
8066    SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8067        Templates;
8068
8069    InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8070      if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8071        TemplateParameterList *ParamList = FTD->getTemplateParameters();
8072        for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8073          if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8074                                               false, S.TPL_TemplateMatch))
8075            return Templates[I].second;
8076        Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8077        return Templates.back().second;
8078      }
8079
8080      return NonTemplate;
8081    }
8082  };
8083
8084  /// Get or create the inheriting constructor record for a constructor.
8085  InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8086                                  QualType CtorType) {
8087    return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8088        .getEntry(SemaRef, Ctor);
8089  }
8090
8091  typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8092
8093  /// Process all constructors for a class.
8094  void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8095    for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8096                                      CtorE = RD->ctor_end();
8097         CtorIt != CtorE; ++CtorIt)
8098      (this->*Callback)(*CtorIt);
8099    for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8100             I(RD->decls_begin()), E(RD->decls_end());
8101         I != E; ++I) {
8102      const FunctionDecl *FD = (*I)->getTemplatedDecl();
8103      if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8104        (this->*Callback)(CD);
8105    }
8106  }
8107
8108  /// Note that a constructor (or constructor template) was declared in Derived.
8109  void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8110    getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8111  }
8112
8113  /// Inherit a single constructor.
8114  void inherit(const CXXConstructorDecl *Ctor) {
8115    const FunctionProtoType *CtorType =
8116        Ctor->getType()->castAs<FunctionProtoType>();
8117    ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8118    FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8119
8120    SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8121
8122    // Core issue (no number yet): the ellipsis is always discarded.
8123    if (EPI.Variadic) {
8124      SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8125      SemaRef.Diag(Ctor->getLocation(),
8126                   diag::note_using_decl_constructor_ellipsis);
8127      EPI.Variadic = false;
8128    }
8129
8130    // Declare a constructor for each number of parameters.
8131    //
8132    // C++11 [class.inhctor]p1:
8133    //   The candidate set of inherited constructors from the class X named in
8134    //   the using-declaration consists of [... modulo defects ...] for each
8135    //   constructor or constructor template of X, the set of constructors or
8136    //   constructor templates that results from omitting any ellipsis parameter
8137    //   specification and successively omitting parameters with a default
8138    //   argument from the end of the parameter-type-list
8139    unsigned MinParams = minParamsToInherit(Ctor);
8140    unsigned Params = Ctor->getNumParams();
8141    if (Params >= MinParams) {
8142      do
8143        declareCtor(UsingLoc, Ctor,
8144                    SemaRef.Context.getFunctionType(
8145                        Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8146      while (Params > MinParams &&
8147             Ctor->getParamDecl(--Params)->hasDefaultArg());
8148    }
8149  }
8150
8151  /// Find the using-declaration which specified that we should inherit the
8152  /// constructors of \p Base.
8153  SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8154    // No fancy lookup required; just look for the base constructor name
8155    // directly within the derived class.
8156    ASTContext &Context = SemaRef.Context;
8157    DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8158        Context.getCanonicalType(Context.getRecordType(Base)));
8159    DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8160    return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8161  }
8162
8163  unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8164    // C++11 [class.inhctor]p3:
8165    //   [F]or each constructor template in the candidate set of inherited
8166    //   constructors, a constructor template is implicitly declared
8167    if (Ctor->getDescribedFunctionTemplate())
8168      return 0;
8169
8170    //   For each non-template constructor in the candidate set of inherited
8171    //   constructors other than a constructor having no parameters or a
8172    //   copy/move constructor having a single parameter, a constructor is
8173    //   implicitly declared [...]
8174    if (Ctor->getNumParams() == 0)
8175      return 1;
8176    if (Ctor->isCopyOrMoveConstructor())
8177      return 2;
8178
8179    // Per discussion on core reflector, never inherit a constructor which
8180    // would become a default, copy, or move constructor of Derived either.
8181    const ParmVarDecl *PD = Ctor->getParamDecl(0);
8182    const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8183    return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8184  }
8185
8186  /// Declare a single inheriting constructor, inheriting the specified
8187  /// constructor, with the given type.
8188  void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8189                   QualType DerivedType) {
8190    InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8191
8192    // C++11 [class.inhctor]p3:
8193    //   ... a constructor is implicitly declared with the same constructor
8194    //   characteristics unless there is a user-declared constructor with
8195    //   the same signature in the class where the using-declaration appears
8196    if (Entry.DeclaredInDerived)
8197      return;
8198
8199    // C++11 [class.inhctor]p7:
8200    //   If two using-declarations declare inheriting constructors with the
8201    //   same signature, the program is ill-formed
8202    if (Entry.DerivedCtor) {
8203      if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8204        // Only diagnose this once per constructor.
8205        if (Entry.DerivedCtor->isInvalidDecl())
8206          return;
8207        Entry.DerivedCtor->setInvalidDecl();
8208
8209        SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8210        SemaRef.Diag(BaseCtor->getLocation(),
8211                     diag::note_using_decl_constructor_conflict_current_ctor);
8212        SemaRef.Diag(Entry.BaseCtor->getLocation(),
8213                     diag::note_using_decl_constructor_conflict_previous_ctor);
8214        SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8215                     diag::note_using_decl_constructor_conflict_previous_using);
8216      } else {
8217        // Core issue (no number): if the same inheriting constructor is
8218        // produced by multiple base class constructors from the same base
8219        // class, the inheriting constructor is defined as deleted.
8220        SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8221      }
8222
8223      return;
8224    }
8225
8226    ASTContext &Context = SemaRef.Context;
8227    DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8228        Context.getCanonicalType(Context.getRecordType(Derived)));
8229    DeclarationNameInfo NameInfo(Name, UsingLoc);
8230
8231    TemplateParameterList *TemplateParams = 0;
8232    if (const FunctionTemplateDecl *FTD =
8233            BaseCtor->getDescribedFunctionTemplate()) {
8234      TemplateParams = FTD->getTemplateParameters();
8235      // We're reusing template parameters from a different DeclContext. This
8236      // is questionable at best, but works out because the template depth in
8237      // both places is guaranteed to be 0.
8238      // FIXME: Rebuild the template parameters in the new context, and
8239      // transform the function type to refer to them.
8240    }
8241
8242    // Build type source info pointing at the using-declaration. This is
8243    // required by template instantiation.
8244    TypeSourceInfo *TInfo =
8245        Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8246    FunctionProtoTypeLoc ProtoLoc =
8247        TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8248
8249    CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8250        Context, Derived, UsingLoc, NameInfo, DerivedType,
8251        TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8252        /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8253
8254    // Build an unevaluated exception specification for this constructor.
8255    const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8256    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8257    EPI.ExceptionSpecType = EST_Unevaluated;
8258    EPI.ExceptionSpecDecl = DerivedCtor;
8259    DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8260                                                 FPT->getArgTypes(), EPI));
8261
8262    // Build the parameter declarations.
8263    SmallVector<ParmVarDecl *, 16> ParamDecls;
8264    for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8265      TypeSourceInfo *TInfo =
8266          Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8267      ParmVarDecl *PD = ParmVarDecl::Create(
8268          Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8269          FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8270      PD->setScopeInfo(0, I);
8271      PD->setImplicit();
8272      ParamDecls.push_back(PD);
8273      ProtoLoc.setArg(I, PD);
8274    }
8275
8276    // Set up the new constructor.
8277    DerivedCtor->setAccess(BaseCtor->getAccess());
8278    DerivedCtor->setParams(ParamDecls);
8279    DerivedCtor->setInheritedConstructor(BaseCtor);
8280    if (BaseCtor->isDeleted())
8281      SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8282
8283    // If this is a constructor template, build the template declaration.
8284    if (TemplateParams) {
8285      FunctionTemplateDecl *DerivedTemplate =
8286          FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8287                                       TemplateParams, DerivedCtor);
8288      DerivedTemplate->setAccess(BaseCtor->getAccess());
8289      DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8290      Derived->addDecl(DerivedTemplate);
8291    } else {
8292      Derived->addDecl(DerivedCtor);
8293    }
8294
8295    Entry.BaseCtor = BaseCtor;
8296    Entry.DerivedCtor = DerivedCtor;
8297  }
8298
8299  Sema &SemaRef;
8300  CXXRecordDecl *Derived;
8301  typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8302  MapType Map;
8303};
8304}
8305
8306void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8307  // Defer declaring the inheriting constructors until the class is
8308  // instantiated.
8309  if (ClassDecl->isDependentContext())
8310    return;
8311
8312  // Find base classes from which we might inherit constructors.
8313  SmallVector<CXXRecordDecl*, 4> InheritedBases;
8314  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8315                                          BaseE = ClassDecl->bases_end();
8316       BaseIt != BaseE; ++BaseIt)
8317    if (BaseIt->getInheritConstructors())
8318      InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
8319
8320  // Go no further if we're not inheriting any constructors.
8321  if (InheritedBases.empty())
8322    return;
8323
8324  // Declare the inherited constructors.
8325  InheritingConstructorInfo ICI(*this, ClassDecl);
8326  for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8327    ICI.inheritAll(InheritedBases[I]);
8328}
8329
8330void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8331                                       CXXConstructorDecl *Constructor) {
8332  CXXRecordDecl *ClassDecl = Constructor->getParent();
8333  assert(Constructor->getInheritedConstructor() &&
8334         !Constructor->doesThisDeclarationHaveABody() &&
8335         !Constructor->isDeleted());
8336
8337  SynthesizedFunctionScope Scope(*this, Constructor);
8338  DiagnosticErrorTrap Trap(Diags);
8339  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8340      Trap.hasErrorOccurred()) {
8341    Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8342      << Context.getTagDeclType(ClassDecl);
8343    Constructor->setInvalidDecl();
8344    return;
8345  }
8346
8347  SourceLocation Loc = Constructor->getLocation();
8348  Constructor->setBody(new (Context) CompoundStmt(Loc));
8349
8350  Constructor->markUsed(Context);
8351  MarkVTableUsed(CurrentLocation, ClassDecl);
8352
8353  if (ASTMutationListener *L = getASTMutationListener()) {
8354    L->CompletedImplicitDefinition(Constructor);
8355  }
8356}
8357
8358
8359Sema::ImplicitExceptionSpecification
8360Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8361  CXXRecordDecl *ClassDecl = MD->getParent();
8362
8363  // C++ [except.spec]p14:
8364  //   An implicitly declared special member function (Clause 12) shall have
8365  //   an exception-specification.
8366  ImplicitExceptionSpecification ExceptSpec(*this);
8367  if (ClassDecl->isInvalidDecl())
8368    return ExceptSpec;
8369
8370  // Direct base-class destructors.
8371  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8372                                       BEnd = ClassDecl->bases_end();
8373       B != BEnd; ++B) {
8374    if (B->isVirtual()) // Handled below.
8375      continue;
8376
8377    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8378      ExceptSpec.CalledDecl(B->getLocStart(),
8379                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8380  }
8381
8382  // Virtual base-class destructors.
8383  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8384                                       BEnd = ClassDecl->vbases_end();
8385       B != BEnd; ++B) {
8386    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8387      ExceptSpec.CalledDecl(B->getLocStart(),
8388                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8389  }
8390
8391  // Field destructors.
8392  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8393                               FEnd = ClassDecl->field_end();
8394       F != FEnd; ++F) {
8395    if (const RecordType *RecordTy
8396        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8397      ExceptSpec.CalledDecl(F->getLocation(),
8398                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8399  }
8400
8401  return ExceptSpec;
8402}
8403
8404CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8405  // C++ [class.dtor]p2:
8406  //   If a class has no user-declared destructor, a destructor is
8407  //   declared implicitly. An implicitly-declared destructor is an
8408  //   inline public member of its class.
8409  assert(ClassDecl->needsImplicitDestructor());
8410
8411  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8412  if (DSM.isAlreadyBeingDeclared())
8413    return 0;
8414
8415  // Create the actual destructor declaration.
8416  CanQualType ClassType
8417    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8418  SourceLocation ClassLoc = ClassDecl->getLocation();
8419  DeclarationName Name
8420    = Context.DeclarationNames.getCXXDestructorName(ClassType);
8421  DeclarationNameInfo NameInfo(Name, ClassLoc);
8422  CXXDestructorDecl *Destructor
8423      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8424                                  QualType(), 0, /*isInline=*/true,
8425                                  /*isImplicitlyDeclared=*/true);
8426  Destructor->setAccess(AS_public);
8427  Destructor->setDefaulted();
8428  Destructor->setImplicit();
8429
8430  // Build an exception specification pointing back at this destructor.
8431  FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
8432  Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8433
8434  AddOverriddenMethods(ClassDecl, Destructor);
8435
8436  // We don't need to use SpecialMemberIsTrivial here; triviality for
8437  // destructors is easy to compute.
8438  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8439
8440  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8441    SetDeclDeleted(Destructor, ClassLoc);
8442
8443  // Note that we have declared this destructor.
8444  ++ASTContext::NumImplicitDestructorsDeclared;
8445
8446  // Introduce this destructor into its scope.
8447  if (Scope *S = getScopeForContext(ClassDecl))
8448    PushOnScopeChains(Destructor, S, false);
8449  ClassDecl->addDecl(Destructor);
8450
8451  return Destructor;
8452}
8453
8454void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
8455                                    CXXDestructorDecl *Destructor) {
8456  assert((Destructor->isDefaulted() &&
8457          !Destructor->doesThisDeclarationHaveABody() &&
8458          !Destructor->isDeleted()) &&
8459         "DefineImplicitDestructor - call it for implicit default dtor");
8460  CXXRecordDecl *ClassDecl = Destructor->getParent();
8461  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
8462
8463  if (Destructor->isInvalidDecl())
8464    return;
8465
8466  SynthesizedFunctionScope Scope(*this, Destructor);
8467
8468  DiagnosticErrorTrap Trap(Diags);
8469  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8470                                         Destructor->getParent());
8471
8472  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
8473    Diag(CurrentLocation, diag::note_member_synthesized_at)
8474      << CXXDestructor << Context.getTagDeclType(ClassDecl);
8475
8476    Destructor->setInvalidDecl();
8477    return;
8478  }
8479
8480  SourceLocation Loc = Destructor->getLocation();
8481  Destructor->setBody(new (Context) CompoundStmt(Loc));
8482  Destructor->markUsed(Context);
8483  MarkVTableUsed(CurrentLocation, ClassDecl);
8484
8485  if (ASTMutationListener *L = getASTMutationListener()) {
8486    L->CompletedImplicitDefinition(Destructor);
8487  }
8488}
8489
8490/// \brief Perform any semantic analysis which needs to be delayed until all
8491/// pending class member declarations have been parsed.
8492void Sema::ActOnFinishCXXMemberDecls() {
8493  // If the context is an invalid C++ class, just suppress these checks.
8494  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8495    if (Record->isInvalidDecl()) {
8496      DelayedDestructorExceptionSpecChecks.clear();
8497      return;
8498    }
8499  }
8500
8501  // Perform any deferred checking of exception specifications for virtual
8502  // destructors.
8503  for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8504       i != e; ++i) {
8505    const CXXDestructorDecl *Dtor =
8506        DelayedDestructorExceptionSpecChecks[i].first;
8507    assert(!Dtor->getParent()->isDependentType() &&
8508           "Should not ever add destructors of templates into the list.");
8509    CheckOverridingFunctionExceptionSpec(Dtor,
8510        DelayedDestructorExceptionSpecChecks[i].second);
8511  }
8512  DelayedDestructorExceptionSpecChecks.clear();
8513}
8514
8515void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8516                                         CXXDestructorDecl *Destructor) {
8517  assert(getLangOpts().CPlusPlus11 &&
8518         "adjusting dtor exception specs was introduced in c++11");
8519
8520  // C++11 [class.dtor]p3:
8521  //   A declaration of a destructor that does not have an exception-
8522  //   specification is implicitly considered to have the same exception-
8523  //   specification as an implicit declaration.
8524  const FunctionProtoType *DtorType = Destructor->getType()->
8525                                        getAs<FunctionProtoType>();
8526  if (DtorType->hasExceptionSpec())
8527    return;
8528
8529  // Replace the destructor's type, building off the existing one. Fortunately,
8530  // the only thing of interest in the destructor type is its extended info.
8531  // The return and arguments are fixed.
8532  FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8533  EPI.ExceptionSpecType = EST_Unevaluated;
8534  EPI.ExceptionSpecDecl = Destructor;
8535  Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8536
8537  // FIXME: If the destructor has a body that could throw, and the newly created
8538  // spec doesn't allow exceptions, we should emit a warning, because this
8539  // change in behavior can break conforming C++03 programs at runtime.
8540  // However, we don't have a body or an exception specification yet, so it
8541  // needs to be done somewhere else.
8542}
8543
8544namespace {
8545/// \brief An abstract base class for all helper classes used in building the
8546//  copy/move operators. These classes serve as factory functions and help us
8547//  avoid using the same Expr* in the AST twice.
8548class ExprBuilder {
8549  ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8550  ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8551
8552protected:
8553  static Expr *assertNotNull(Expr *E) {
8554    assert(E && "Expression construction must not fail.");
8555    return E;
8556  }
8557
8558public:
8559  ExprBuilder() {}
8560  virtual ~ExprBuilder() {}
8561
8562  virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8563};
8564
8565class RefBuilder: public ExprBuilder {
8566  VarDecl *Var;
8567  QualType VarType;
8568
8569public:
8570  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8571    return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8572  }
8573
8574  RefBuilder(VarDecl *Var, QualType VarType)
8575      : Var(Var), VarType(VarType) {}
8576};
8577
8578class ThisBuilder: public ExprBuilder {
8579public:
8580  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8581    return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8582  }
8583};
8584
8585class CastBuilder: public ExprBuilder {
8586  const ExprBuilder &Builder;
8587  QualType Type;
8588  ExprValueKind Kind;
8589  const CXXCastPath &Path;
8590
8591public:
8592  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8593    return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8594                                             CK_UncheckedDerivedToBase, Kind,
8595                                             &Path).take());
8596  }
8597
8598  CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8599              const CXXCastPath &Path)
8600      : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8601};
8602
8603class DerefBuilder: public ExprBuilder {
8604  const ExprBuilder &Builder;
8605
8606public:
8607  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8608    return assertNotNull(
8609        S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8610  }
8611
8612  DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8613};
8614
8615class MemberBuilder: public ExprBuilder {
8616  const ExprBuilder &Builder;
8617  QualType Type;
8618  CXXScopeSpec SS;
8619  bool IsArrow;
8620  LookupResult &MemberLookup;
8621
8622public:
8623  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8624    return assertNotNull(S.BuildMemberReferenceExpr(
8625        Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8626        MemberLookup, 0).take());
8627  }
8628
8629  MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8630                LookupResult &MemberLookup)
8631      : Builder(Builder), Type(Type), IsArrow(IsArrow),
8632        MemberLookup(MemberLookup) {}
8633};
8634
8635class MoveCastBuilder: public ExprBuilder {
8636  const ExprBuilder &Builder;
8637
8638public:
8639  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8640    return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8641  }
8642
8643  MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8644};
8645
8646class LvalueConvBuilder: public ExprBuilder {
8647  const ExprBuilder &Builder;
8648
8649public:
8650  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8651    return assertNotNull(
8652        S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8653  }
8654
8655  LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8656};
8657
8658class SubscriptBuilder: public ExprBuilder {
8659  const ExprBuilder &Base;
8660  const ExprBuilder &Index;
8661
8662public:
8663  virtual Expr *build(Sema &S, SourceLocation Loc) const
8664      LLVM_OVERRIDE {
8665    return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8666        Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8667  }
8668
8669  SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8670      : Base(Base), Index(Index) {}
8671};
8672
8673} // end anonymous namespace
8674
8675/// When generating a defaulted copy or move assignment operator, if a field
8676/// should be copied with __builtin_memcpy rather than via explicit assignments,
8677/// do so. This optimization only applies for arrays of scalars, and for arrays
8678/// of class type where the selected copy/move-assignment operator is trivial.
8679static StmtResult
8680buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8681                           const ExprBuilder &ToB, const ExprBuilder &FromB) {
8682  // Compute the size of the memory buffer to be copied.
8683  QualType SizeType = S.Context.getSizeType();
8684  llvm::APInt Size(S.Context.getTypeSize(SizeType),
8685                   S.Context.getTypeSizeInChars(T).getQuantity());
8686
8687  // Take the address of the field references for "from" and "to". We
8688  // directly construct UnaryOperators here because semantic analysis
8689  // does not permit us to take the address of an xvalue.
8690  Expr *From = FromB.build(S, Loc);
8691  From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8692                         S.Context.getPointerType(From->getType()),
8693                         VK_RValue, OK_Ordinary, Loc);
8694  Expr *To = ToB.build(S, Loc);
8695  To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8696                       S.Context.getPointerType(To->getType()),
8697                       VK_RValue, OK_Ordinary, Loc);
8698
8699  const Type *E = T->getBaseElementTypeUnsafe();
8700  bool NeedsCollectableMemCpy =
8701    E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8702
8703  // Create a reference to the __builtin_objc_memmove_collectable function
8704  StringRef MemCpyName = NeedsCollectableMemCpy ?
8705    "__builtin_objc_memmove_collectable" :
8706    "__builtin_memcpy";
8707  LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8708                 Sema::LookupOrdinaryName);
8709  S.LookupName(R, S.TUScope, true);
8710
8711  FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8712  if (!MemCpy)
8713    // Something went horribly wrong earlier, and we will have complained
8714    // about it.
8715    return StmtError();
8716
8717  ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8718                                            VK_RValue, Loc, 0);
8719  assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8720
8721  Expr *CallArgs[] = {
8722    To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8723  };
8724  ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8725                                    Loc, CallArgs, Loc);
8726
8727  assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8728  return S.Owned(Call.takeAs<Stmt>());
8729}
8730
8731/// \brief Builds a statement that copies/moves the given entity from \p From to
8732/// \c To.
8733///
8734/// This routine is used to copy/move the members of a class with an
8735/// implicitly-declared copy/move assignment operator. When the entities being
8736/// copied are arrays, this routine builds for loops to copy them.
8737///
8738/// \param S The Sema object used for type-checking.
8739///
8740/// \param Loc The location where the implicit copy/move is being generated.
8741///
8742/// \param T The type of the expressions being copied/moved. Both expressions
8743/// must have this type.
8744///
8745/// \param To The expression we are copying/moving to.
8746///
8747/// \param From The expression we are copying/moving from.
8748///
8749/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
8750/// Otherwise, it's a non-static member subobject.
8751///
8752/// \param Copying Whether we're copying or moving.
8753///
8754/// \param Depth Internal parameter recording the depth of the recursion.
8755///
8756/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8757/// if a memcpy should be used instead.
8758static StmtResult
8759buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8760                                 const ExprBuilder &To, const ExprBuilder &From,
8761                                 bool CopyingBaseSubobject, bool Copying,
8762                                 unsigned Depth = 0) {
8763  // C++11 [class.copy]p28:
8764  //   Each subobject is assigned in the manner appropriate to its type:
8765  //
8766  //     - if the subobject is of class type, as if by a call to operator= with
8767  //       the subobject as the object expression and the corresponding
8768  //       subobject of x as a single function argument (as if by explicit
8769  //       qualification; that is, ignoring any possible virtual overriding
8770  //       functions in more derived classes);
8771  //
8772  // C++03 [class.copy]p13:
8773  //     - if the subobject is of class type, the copy assignment operator for
8774  //       the class is used (as if by explicit qualification; that is,
8775  //       ignoring any possible virtual overriding functions in more derived
8776  //       classes);
8777  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8778    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8779
8780    // Look for operator=.
8781    DeclarationName Name
8782      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8783    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8784    S.LookupQualifiedName(OpLookup, ClassDecl, false);
8785
8786    // Prior to C++11, filter out any result that isn't a copy/move-assignment
8787    // operator.
8788    if (!S.getLangOpts().CPlusPlus11) {
8789      LookupResult::Filter F = OpLookup.makeFilter();
8790      while (F.hasNext()) {
8791        NamedDecl *D = F.next();
8792        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8793          if (Method->isCopyAssignmentOperator() ||
8794              (!Copying && Method->isMoveAssignmentOperator()))
8795            continue;
8796
8797        F.erase();
8798      }
8799      F.done();
8800    }
8801
8802    // Suppress the protected check (C++ [class.protected]) for each of the
8803    // assignment operators we found. This strange dance is required when
8804    // we're assigning via a base classes's copy-assignment operator. To
8805    // ensure that we're getting the right base class subobject (without
8806    // ambiguities), we need to cast "this" to that subobject type; to
8807    // ensure that we don't go through the virtual call mechanism, we need
8808    // to qualify the operator= name with the base class (see below). However,
8809    // this means that if the base class has a protected copy assignment
8810    // operator, the protected member access check will fail. So, we
8811    // rewrite "protected" access to "public" access in this case, since we
8812    // know by construction that we're calling from a derived class.
8813    if (CopyingBaseSubobject) {
8814      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8815           L != LEnd; ++L) {
8816        if (L.getAccess() == AS_protected)
8817          L.setAccess(AS_public);
8818      }
8819    }
8820
8821    // Create the nested-name-specifier that will be used to qualify the
8822    // reference to operator=; this is required to suppress the virtual
8823    // call mechanism.
8824    CXXScopeSpec SS;
8825    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
8826    SS.MakeTrivial(S.Context,
8827                   NestedNameSpecifier::Create(S.Context, 0, false,
8828                                               CanonicalT),
8829                   Loc);
8830
8831    // Create the reference to operator=.
8832    ExprResult OpEqualRef
8833      = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
8834                                   SS, /*TemplateKWLoc=*/SourceLocation(),
8835                                   /*FirstQualifierInScope=*/0,
8836                                   OpLookup,
8837                                   /*TemplateArgs=*/0,
8838                                   /*SuppressQualifierCheck=*/true);
8839    if (OpEqualRef.isInvalid())
8840      return StmtError();
8841
8842    // Build the call to the assignment operator.
8843
8844    Expr *FromInst = From.build(S, Loc);
8845    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
8846                                                  OpEqualRef.takeAs<Expr>(),
8847                                                  Loc, FromInst, Loc);
8848    if (Call.isInvalid())
8849      return StmtError();
8850
8851    // If we built a call to a trivial 'operator=' while copying an array,
8852    // bail out. We'll replace the whole shebang with a memcpy.
8853    CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8854    if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8855      return StmtResult((Stmt*)0);
8856
8857    // Convert to an expression-statement, and clean up any produced
8858    // temporaries.
8859    return S.ActOnExprStmt(Call);
8860  }
8861
8862  //     - if the subobject is of scalar type, the built-in assignment
8863  //       operator is used.
8864  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
8865  if (!ArrayTy) {
8866    ExprResult Assignment = S.CreateBuiltinBinOp(
8867        Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
8868    if (Assignment.isInvalid())
8869      return StmtError();
8870    return S.ActOnExprStmt(Assignment);
8871  }
8872
8873  //     - if the subobject is an array, each element is assigned, in the
8874  //       manner appropriate to the element type;
8875
8876  // Construct a loop over the array bounds, e.g.,
8877  //
8878  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8879  //
8880  // that will copy each of the array elements.
8881  QualType SizeType = S.Context.getSizeType();
8882
8883  // Create the iteration variable.
8884  IdentifierInfo *IterationVarName = 0;
8885  {
8886    SmallString<8> Str;
8887    llvm::raw_svector_ostream OS(Str);
8888    OS << "__i" << Depth;
8889    IterationVarName = &S.Context.Idents.get(OS.str());
8890  }
8891  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
8892                                          IterationVarName, SizeType,
8893                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
8894                                          SC_None);
8895
8896  // Initialize the iteration variable to zero.
8897  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8898  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8899
8900  // Creates a reference to the iteration variable.
8901  RefBuilder IterationVarRef(IterationVar, SizeType);
8902  LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
8903
8904  // Create the DeclStmt that holds the iteration variable.
8905  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
8906
8907  // Subscript the "from" and "to" expressions with the iteration variable.
8908  SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
8909  MoveCastBuilder FromIndexMove(FromIndexCopy);
8910  const ExprBuilder *FromIndex;
8911  if (Copying)
8912    FromIndex = &FromIndexCopy;
8913  else
8914    FromIndex = &FromIndexMove;
8915
8916  SubscriptBuilder ToIndex(To, IterationVarRefRVal);
8917
8918  // Build the copy/move for an individual element of the array.
8919  StmtResult Copy =
8920    buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8921                                     ToIndex, *FromIndex, CopyingBaseSubobject,
8922                                     Copying, Depth + 1);
8923  // Bail out if copying fails or if we determined that we should use memcpy.
8924  if (Copy.isInvalid() || !Copy.get())
8925    return Copy;
8926
8927  // Create the comparison against the array bound.
8928  llvm::APInt Upper
8929    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8930  Expr *Comparison
8931    = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
8932                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8933                                     BO_NE, S.Context.BoolTy,
8934                                     VK_RValue, OK_Ordinary, Loc, false);
8935
8936  // Create the pre-increment of the iteration variable.
8937  Expr *Increment
8938    = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
8939                                    SizeType, VK_LValue, OK_Ordinary, Loc);
8940
8941  // Construct the loop that copies all elements of this array.
8942  return S.ActOnForStmt(Loc, Loc, InitStmt,
8943                        S.MakeFullExpr(Comparison),
8944                        0, S.MakeFullDiscardedValueExpr(Increment),
8945                        Loc, Copy.take());
8946}
8947
8948static StmtResult
8949buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8950                      const ExprBuilder &To, const ExprBuilder &From,
8951                      bool CopyingBaseSubobject, bool Copying) {
8952  // Maybe we should use a memcpy?
8953  if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8954      T.isTriviallyCopyableType(S.Context))
8955    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8956
8957  StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8958                                                     CopyingBaseSubobject,
8959                                                     Copying, 0));
8960
8961  // If we ended up picking a trivial assignment operator for an array of a
8962  // non-trivially-copyable class type, just emit a memcpy.
8963  if (!Result.isInvalid() && !Result.get())
8964    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8965
8966  return Result;
8967}
8968
8969Sema::ImplicitExceptionSpecification
8970Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8971  CXXRecordDecl *ClassDecl = MD->getParent();
8972
8973  ImplicitExceptionSpecification ExceptSpec(*this);
8974  if (ClassDecl->isInvalidDecl())
8975    return ExceptSpec;
8976
8977  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8978  assert(T->getNumArgs() == 1 && "not a copy assignment op");
8979  unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8980
8981  // C++ [except.spec]p14:
8982  //   An implicitly declared special member function (Clause 12) shall have an
8983  //   exception-specification. [...]
8984
8985  // It is unspecified whether or not an implicit copy assignment operator
8986  // attempts to deduplicate calls to assignment operators of virtual bases are
8987  // made. As such, this exception specification is effectively unspecified.
8988  // Based on a similar decision made for constness in C++0x, we're erring on
8989  // the side of assuming such calls to be made regardless of whether they
8990  // actually happen.
8991  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8992                                       BaseEnd = ClassDecl->bases_end();
8993       Base != BaseEnd; ++Base) {
8994    if (Base->isVirtual())
8995      continue;
8996
8997    CXXRecordDecl *BaseClassDecl
8998      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8999    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9000                                                            ArgQuals, false, 0))
9001      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
9002  }
9003
9004  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9005                                       BaseEnd = ClassDecl->vbases_end();
9006       Base != BaseEnd; ++Base) {
9007    CXXRecordDecl *BaseClassDecl
9008      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9009    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9010                                                            ArgQuals, false, 0))
9011      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
9012  }
9013
9014  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9015                                  FieldEnd = ClassDecl->field_end();
9016       Field != FieldEnd;
9017       ++Field) {
9018    QualType FieldType = Context.getBaseElementType(Field->getType());
9019    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9020      if (CXXMethodDecl *CopyAssign =
9021          LookupCopyingAssignment(FieldClassDecl,
9022                                  ArgQuals | FieldType.getCVRQualifiers(),
9023                                  false, 0))
9024        ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
9025    }
9026  }
9027
9028  return ExceptSpec;
9029}
9030
9031CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9032  // Note: The following rules are largely analoguous to the copy
9033  // constructor rules. Note that virtual bases are not taken into account
9034  // for determining the argument type of the operator. Note also that
9035  // operators taking an object instead of a reference are allowed.
9036  assert(ClassDecl->needsImplicitCopyAssignment());
9037
9038  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9039  if (DSM.isAlreadyBeingDeclared())
9040    return 0;
9041
9042  QualType ArgType = Context.getTypeDeclType(ClassDecl);
9043  QualType RetType = Context.getLValueReferenceType(ArgType);
9044  bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9045  if (Const)
9046    ArgType = ArgType.withConst();
9047  ArgType = Context.getLValueReferenceType(ArgType);
9048
9049  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9050                                                     CXXCopyAssignment,
9051                                                     Const);
9052
9053  //   An implicitly-declared copy assignment operator is an inline public
9054  //   member of its class.
9055  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9056  SourceLocation ClassLoc = ClassDecl->getLocation();
9057  DeclarationNameInfo NameInfo(Name, ClassLoc);
9058  CXXMethodDecl *CopyAssignment =
9059      CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9060                            /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9061                            /*isInline=*/ true, Constexpr, SourceLocation());
9062  CopyAssignment->setAccess(AS_public);
9063  CopyAssignment->setDefaulted();
9064  CopyAssignment->setImplicit();
9065
9066  // Build an exception specification pointing back at this member.
9067  FunctionProtoType::ExtProtoInfo EPI =
9068      getImplicitMethodEPI(*this, CopyAssignment);
9069  CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9070
9071  // Add the parameter to the operator.
9072  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
9073                                               ClassLoc, ClassLoc, /*Id=*/0,
9074                                               ArgType, /*TInfo=*/0,
9075                                               SC_None, 0);
9076  CopyAssignment->setParams(FromParam);
9077
9078  AddOverriddenMethods(ClassDecl, CopyAssignment);
9079
9080  CopyAssignment->setTrivial(
9081    ClassDecl->needsOverloadResolutionForCopyAssignment()
9082      ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9083      : ClassDecl->hasTrivialCopyAssignment());
9084
9085  // C++11 [class.copy]p19:
9086  //   ....  If the class definition does not explicitly declare a copy
9087  //   assignment operator, there is no user-declared move constructor, and
9088  //   there is no user-declared move assignment operator, a copy assignment
9089  //   operator is implicitly declared as defaulted.
9090  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
9091    SetDeclDeleted(CopyAssignment, ClassLoc);
9092
9093  // Note that we have added this copy-assignment operator.
9094  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9095
9096  if (Scope *S = getScopeForContext(ClassDecl))
9097    PushOnScopeChains(CopyAssignment, S, false);
9098  ClassDecl->addDecl(CopyAssignment);
9099
9100  return CopyAssignment;
9101}
9102
9103/// Diagnose an implicit copy operation for a class which is odr-used, but
9104/// which is deprecated because the class has a user-declared copy constructor,
9105/// copy assignment operator, or destructor.
9106static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9107                                            SourceLocation UseLoc) {
9108  assert(CopyOp->isImplicit());
9109
9110  CXXRecordDecl *RD = CopyOp->getParent();
9111  CXXMethodDecl *UserDeclaredOperation = 0;
9112
9113  // In Microsoft mode, assignment operations don't affect constructors and
9114  // vice versa.
9115  if (RD->hasUserDeclaredDestructor()) {
9116    UserDeclaredOperation = RD->getDestructor();
9117  } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9118             RD->hasUserDeclaredCopyConstructor() &&
9119             !S.getLangOpts().MicrosoftMode) {
9120    // Find any user-declared copy constructor.
9121    for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9122                                      E = RD->ctor_end(); I != E; ++I) {
9123      if (I->isCopyConstructor()) {
9124        UserDeclaredOperation = *I;
9125        break;
9126      }
9127    }
9128    assert(UserDeclaredOperation);
9129  } else if (isa<CXXConstructorDecl>(CopyOp) &&
9130             RD->hasUserDeclaredCopyAssignment() &&
9131             !S.getLangOpts().MicrosoftMode) {
9132    // Find any user-declared move assignment operator.
9133    for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9134                                        E = RD->method_end(); I != E; ++I) {
9135      if (I->isCopyAssignmentOperator()) {
9136        UserDeclaredOperation = *I;
9137        break;
9138      }
9139    }
9140    assert(UserDeclaredOperation);
9141  }
9142
9143  if (UserDeclaredOperation) {
9144    S.Diag(UserDeclaredOperation->getLocation(),
9145         diag::warn_deprecated_copy_operation)
9146      << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9147      << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9148    S.Diag(UseLoc, diag::note_member_synthesized_at)
9149      << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9150                                          : Sema::CXXCopyAssignment)
9151      << RD;
9152  }
9153}
9154
9155void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9156                                        CXXMethodDecl *CopyAssignOperator) {
9157  assert((CopyAssignOperator->isDefaulted() &&
9158          CopyAssignOperator->isOverloadedOperator() &&
9159          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
9160          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9161          !CopyAssignOperator->isDeleted()) &&
9162         "DefineImplicitCopyAssignment called for wrong function");
9163
9164  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9165
9166  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9167    CopyAssignOperator->setInvalidDecl();
9168    return;
9169  }
9170
9171  // C++11 [class.copy]p18:
9172  //   The [definition of an implicitly declared copy assignment operator] is
9173  //   deprecated if the class has a user-declared copy constructor or a
9174  //   user-declared destructor.
9175  if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9176    diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9177
9178  CopyAssignOperator->markUsed(Context);
9179
9180  SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
9181  DiagnosticErrorTrap Trap(Diags);
9182
9183  // C++0x [class.copy]p30:
9184  //   The implicitly-defined or explicitly-defaulted copy assignment operator
9185  //   for a non-union class X performs memberwise copy assignment of its
9186  //   subobjects. The direct base classes of X are assigned first, in the
9187  //   order of their declaration in the base-specifier-list, and then the
9188  //   immediate non-static data members of X are assigned, in the order in
9189  //   which they were declared in the class definition.
9190
9191  // The statements that form the synthesized function body.
9192  SmallVector<Stmt*, 8> Statements;
9193
9194  // The parameter for the "other" object, which we are copying from.
9195  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9196  Qualifiers OtherQuals = Other->getType().getQualifiers();
9197  QualType OtherRefType = Other->getType();
9198  if (const LValueReferenceType *OtherRef
9199                                = OtherRefType->getAs<LValueReferenceType>()) {
9200    OtherRefType = OtherRef->getPointeeType();
9201    OtherQuals = OtherRefType.getQualifiers();
9202  }
9203
9204  // Our location for everything implicitly-generated.
9205  SourceLocation Loc = CopyAssignOperator->getLocation();
9206
9207  // Builds a DeclRefExpr for the "other" object.
9208  RefBuilder OtherRef(Other, OtherRefType);
9209
9210  // Builds the "this" pointer.
9211  ThisBuilder This;
9212
9213  // Assign base classes.
9214  bool Invalid = false;
9215  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9216       E = ClassDecl->bases_end(); Base != E; ++Base) {
9217    // Form the assignment:
9218    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9219    QualType BaseType = Base->getType().getUnqualifiedType();
9220    if (!BaseType->isRecordType()) {
9221      Invalid = true;
9222      continue;
9223    }
9224
9225    CXXCastPath BasePath;
9226    BasePath.push_back(Base);
9227
9228    // Construct the "from" expression, which is an implicit cast to the
9229    // appropriately-qualified base type.
9230    CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9231                     VK_LValue, BasePath);
9232
9233    // Dereference "this".
9234    DerefBuilder DerefThis(This);
9235    CastBuilder To(DerefThis,
9236                   Context.getCVRQualifiedType(
9237                       BaseType, CopyAssignOperator->getTypeQualifiers()),
9238                   VK_LValue, BasePath);
9239
9240    // Build the copy.
9241    StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
9242                                            To, From,
9243                                            /*CopyingBaseSubobject=*/true,
9244                                            /*Copying=*/true);
9245    if (Copy.isInvalid()) {
9246      Diag(CurrentLocation, diag::note_member_synthesized_at)
9247        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9248      CopyAssignOperator->setInvalidDecl();
9249      return;
9250    }
9251
9252    // Success! Record the copy.
9253    Statements.push_back(Copy.takeAs<Expr>());
9254  }
9255
9256  // Assign non-static members.
9257  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9258                                  FieldEnd = ClassDecl->field_end();
9259       Field != FieldEnd; ++Field) {
9260    if (Field->isUnnamedBitfield())
9261      continue;
9262
9263    if (Field->isInvalidDecl()) {
9264      Invalid = true;
9265      continue;
9266    }
9267
9268    // Check for members of reference type; we can't copy those.
9269    if (Field->getType()->isReferenceType()) {
9270      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9271        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9272      Diag(Field->getLocation(), diag::note_declared_at);
9273      Diag(CurrentLocation, diag::note_member_synthesized_at)
9274        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9275      Invalid = true;
9276      continue;
9277    }
9278
9279    // Check for members of const-qualified, non-class type.
9280    QualType BaseType = Context.getBaseElementType(Field->getType());
9281    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9282      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9283        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9284      Diag(Field->getLocation(), diag::note_declared_at);
9285      Diag(CurrentLocation, diag::note_member_synthesized_at)
9286        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9287      Invalid = true;
9288      continue;
9289    }
9290
9291    // Suppress assigning zero-width bitfields.
9292    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9293      continue;
9294
9295    QualType FieldType = Field->getType().getNonReferenceType();
9296    if (FieldType->isIncompleteArrayType()) {
9297      assert(ClassDecl->hasFlexibleArrayMember() &&
9298             "Incomplete array type is not valid");
9299      continue;
9300    }
9301
9302    // Build references to the field in the object we're copying from and to.
9303    CXXScopeSpec SS; // Intentionally empty
9304    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9305                              LookupMemberName);
9306    MemberLookup.addDecl(*Field);
9307    MemberLookup.resolveKind();
9308
9309    MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9310
9311    MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
9312
9313    // Build the copy of this field.
9314    StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
9315                                            To, From,
9316                                            /*CopyingBaseSubobject=*/false,
9317                                            /*Copying=*/true);
9318    if (Copy.isInvalid()) {
9319      Diag(CurrentLocation, diag::note_member_synthesized_at)
9320        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9321      CopyAssignOperator->setInvalidDecl();
9322      return;
9323    }
9324
9325    // Success! Record the copy.
9326    Statements.push_back(Copy.takeAs<Stmt>());
9327  }
9328
9329  if (!Invalid) {
9330    // Add a "return *this;"
9331    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9332
9333    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9334    if (Return.isInvalid())
9335      Invalid = true;
9336    else {
9337      Statements.push_back(Return.takeAs<Stmt>());
9338
9339      if (Trap.hasErrorOccurred()) {
9340        Diag(CurrentLocation, diag::note_member_synthesized_at)
9341          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9342        Invalid = true;
9343      }
9344    }
9345  }
9346
9347  if (Invalid) {
9348    CopyAssignOperator->setInvalidDecl();
9349    return;
9350  }
9351
9352  StmtResult Body;
9353  {
9354    CompoundScopeRAII CompoundScope(*this);
9355    Body = ActOnCompoundStmt(Loc, Loc, Statements,
9356                             /*isStmtExpr=*/false);
9357    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9358  }
9359  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
9360
9361  if (ASTMutationListener *L = getASTMutationListener()) {
9362    L->CompletedImplicitDefinition(CopyAssignOperator);
9363  }
9364}
9365
9366Sema::ImplicitExceptionSpecification
9367Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9368  CXXRecordDecl *ClassDecl = MD->getParent();
9369
9370  ImplicitExceptionSpecification ExceptSpec(*this);
9371  if (ClassDecl->isInvalidDecl())
9372    return ExceptSpec;
9373
9374  // C++0x [except.spec]p14:
9375  //   An implicitly declared special member function (Clause 12) shall have an
9376  //   exception-specification. [...]
9377
9378  // It is unspecified whether or not an implicit move assignment operator
9379  // attempts to deduplicate calls to assignment operators of virtual bases are
9380  // made. As such, this exception specification is effectively unspecified.
9381  // Based on a similar decision made for constness in C++0x, we're erring on
9382  // the side of assuming such calls to be made regardless of whether they
9383  // actually happen.
9384  // Note that a move constructor is not implicitly declared when there are
9385  // virtual bases, but it can still be user-declared and explicitly defaulted.
9386  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9387                                       BaseEnd = ClassDecl->bases_end();
9388       Base != BaseEnd; ++Base) {
9389    if (Base->isVirtual())
9390      continue;
9391
9392    CXXRecordDecl *BaseClassDecl
9393      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9394    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9395                                                           0, false, 0))
9396      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9397  }
9398
9399  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9400                                       BaseEnd = ClassDecl->vbases_end();
9401       Base != BaseEnd; ++Base) {
9402    CXXRecordDecl *BaseClassDecl
9403      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9404    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9405                                                           0, false, 0))
9406      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9407  }
9408
9409  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9410                                  FieldEnd = ClassDecl->field_end();
9411       Field != FieldEnd;
9412       ++Field) {
9413    QualType FieldType = Context.getBaseElementType(Field->getType());
9414    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9415      if (CXXMethodDecl *MoveAssign =
9416              LookupMovingAssignment(FieldClassDecl,
9417                                     FieldType.getCVRQualifiers(),
9418                                     false, 0))
9419        ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
9420    }
9421  }
9422
9423  return ExceptSpec;
9424}
9425
9426/// Determine whether the class type has any direct or indirect virtual base
9427/// classes which have a non-trivial move assignment operator.
9428static bool
9429hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9430  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9431                                          BaseEnd = ClassDecl->vbases_end();
9432       Base != BaseEnd; ++Base) {
9433    CXXRecordDecl *BaseClass =
9434        cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9435
9436    // Try to declare the move assignment. If it would be deleted, then the
9437    // class does not have a non-trivial move assignment.
9438    if (BaseClass->needsImplicitMoveAssignment())
9439      S.DeclareImplicitMoveAssignment(BaseClass);
9440
9441    if (BaseClass->hasNonTrivialMoveAssignment())
9442      return true;
9443  }
9444
9445  return false;
9446}
9447
9448/// Determine whether the given type either has a move constructor or is
9449/// trivially copyable.
9450static bool
9451hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9452  Type = S.Context.getBaseElementType(Type);
9453
9454  // FIXME: Technically, non-trivially-copyable non-class types, such as
9455  // reference types, are supposed to return false here, but that appears
9456  // to be a standard defect.
9457  CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
9458  if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
9459    return true;
9460
9461  if (Type.isTriviallyCopyableType(S.Context))
9462    return true;
9463
9464  if (IsConstructor) {
9465    // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9466    // give the right answer.
9467    if (ClassDecl->needsImplicitMoveConstructor())
9468      S.DeclareImplicitMoveConstructor(ClassDecl);
9469    return ClassDecl->hasMoveConstructor();
9470  }
9471
9472  // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9473  // give the right answer.
9474  if (ClassDecl->needsImplicitMoveAssignment())
9475    S.DeclareImplicitMoveAssignment(ClassDecl);
9476  return ClassDecl->hasMoveAssignment();
9477}
9478
9479/// Determine whether all non-static data members and direct or virtual bases
9480/// of class \p ClassDecl have either a move operation, or are trivially
9481/// copyable.
9482static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9483                                            bool IsConstructor) {
9484  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9485                                          BaseEnd = ClassDecl->bases_end();
9486       Base != BaseEnd; ++Base) {
9487    if (Base->isVirtual())
9488      continue;
9489
9490    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9491      return false;
9492  }
9493
9494  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9495                                          BaseEnd = ClassDecl->vbases_end();
9496       Base != BaseEnd; ++Base) {
9497    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9498      return false;
9499  }
9500
9501  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9502                                     FieldEnd = ClassDecl->field_end();
9503       Field != FieldEnd; ++Field) {
9504    if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
9505      return false;
9506  }
9507
9508  return true;
9509}
9510
9511CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9512  // C++11 [class.copy]p20:
9513  //   If the definition of a class X does not explicitly declare a move
9514  //   assignment operator, one will be implicitly declared as defaulted
9515  //   if and only if:
9516  //
9517  //   - [first 4 bullets]
9518  assert(ClassDecl->needsImplicitMoveAssignment());
9519
9520  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9521  if (DSM.isAlreadyBeingDeclared())
9522    return 0;
9523
9524  // [Checked after we build the declaration]
9525  //   - the move assignment operator would not be implicitly defined as
9526  //     deleted,
9527
9528  // [DR1402]:
9529  //   - X has no direct or indirect virtual base class with a non-trivial
9530  //     move assignment operator, and
9531  //   - each of X's non-static data members and direct or virtual base classes
9532  //     has a type that either has a move assignment operator or is trivially
9533  //     copyable.
9534  if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9535      !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9536    ClassDecl->setFailedImplicitMoveAssignment();
9537    return 0;
9538  }
9539
9540  // Note: The following rules are largely analoguous to the move
9541  // constructor rules.
9542
9543  QualType ArgType = Context.getTypeDeclType(ClassDecl);
9544  QualType RetType = Context.getLValueReferenceType(ArgType);
9545  ArgType = Context.getRValueReferenceType(ArgType);
9546
9547  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9548                                                     CXXMoveAssignment,
9549                                                     false);
9550
9551  //   An implicitly-declared move assignment operator is an inline public
9552  //   member of its class.
9553  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9554  SourceLocation ClassLoc = ClassDecl->getLocation();
9555  DeclarationNameInfo NameInfo(Name, ClassLoc);
9556  CXXMethodDecl *MoveAssignment =
9557      CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9558                            /*TInfo=*/0, /*StorageClass=*/SC_None,
9559                            /*isInline=*/true, Constexpr, SourceLocation());
9560  MoveAssignment->setAccess(AS_public);
9561  MoveAssignment->setDefaulted();
9562  MoveAssignment->setImplicit();
9563
9564  // Build an exception specification pointing back at this member.
9565  FunctionProtoType::ExtProtoInfo EPI =
9566      getImplicitMethodEPI(*this, MoveAssignment);
9567  MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9568
9569  // Add the parameter to the operator.
9570  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9571                                               ClassLoc, ClassLoc, /*Id=*/0,
9572                                               ArgType, /*TInfo=*/0,
9573                                               SC_None, 0);
9574  MoveAssignment->setParams(FromParam);
9575
9576  AddOverriddenMethods(ClassDecl, MoveAssignment);
9577
9578  MoveAssignment->setTrivial(
9579    ClassDecl->needsOverloadResolutionForMoveAssignment()
9580      ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9581      : ClassDecl->hasTrivialMoveAssignment());
9582
9583  // C++0x [class.copy]p9:
9584  //   If the definition of a class X does not explicitly declare a move
9585  //   assignment operator, one will be implicitly declared as defaulted if and
9586  //   only if:
9587  //   [...]
9588  //   - the move assignment operator would not be implicitly defined as
9589  //     deleted.
9590  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
9591    // Cache this result so that we don't try to generate this over and over
9592    // on every lookup, leaking memory and wasting time.
9593    ClassDecl->setFailedImplicitMoveAssignment();
9594    return 0;
9595  }
9596
9597  // Note that we have added this copy-assignment operator.
9598  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9599
9600  if (Scope *S = getScopeForContext(ClassDecl))
9601    PushOnScopeChains(MoveAssignment, S, false);
9602  ClassDecl->addDecl(MoveAssignment);
9603
9604  return MoveAssignment;
9605}
9606
9607void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9608                                        CXXMethodDecl *MoveAssignOperator) {
9609  assert((MoveAssignOperator->isDefaulted() &&
9610          MoveAssignOperator->isOverloadedOperator() &&
9611          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
9612          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9613          !MoveAssignOperator->isDeleted()) &&
9614         "DefineImplicitMoveAssignment called for wrong function");
9615
9616  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9617
9618  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9619    MoveAssignOperator->setInvalidDecl();
9620    return;
9621  }
9622
9623  MoveAssignOperator->markUsed(Context);
9624
9625  SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
9626  DiagnosticErrorTrap Trap(Diags);
9627
9628  // C++0x [class.copy]p28:
9629  //   The implicitly-defined or move assignment operator for a non-union class
9630  //   X performs memberwise move assignment of its subobjects. The direct base
9631  //   classes of X are assigned first, in the order of their declaration in the
9632  //   base-specifier-list, and then the immediate non-static data members of X
9633  //   are assigned, in the order in which they were declared in the class
9634  //   definition.
9635
9636  // The statements that form the synthesized function body.
9637  SmallVector<Stmt*, 8> Statements;
9638
9639  // The parameter for the "other" object, which we are move from.
9640  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9641  QualType OtherRefType = Other->getType()->
9642      getAs<RValueReferenceType>()->getPointeeType();
9643  assert(!OtherRefType.getQualifiers() &&
9644         "Bad argument type of defaulted move assignment");
9645
9646  // Our location for everything implicitly-generated.
9647  SourceLocation Loc = MoveAssignOperator->getLocation();
9648
9649  // Builds a reference to the "other" object.
9650  RefBuilder OtherRef(Other, OtherRefType);
9651  // Cast to rvalue.
9652  MoveCastBuilder MoveOther(OtherRef);
9653
9654  // Builds the "this" pointer.
9655  ThisBuilder This;
9656
9657  // Assign base classes.
9658  bool Invalid = false;
9659  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9660       E = ClassDecl->bases_end(); Base != E; ++Base) {
9661    // Form the assignment:
9662    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9663    QualType BaseType = Base->getType().getUnqualifiedType();
9664    if (!BaseType->isRecordType()) {
9665      Invalid = true;
9666      continue;
9667    }
9668
9669    CXXCastPath BasePath;
9670    BasePath.push_back(Base);
9671
9672    // Construct the "from" expression, which is an implicit cast to the
9673    // appropriately-qualified base type.
9674    CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
9675
9676    // Dereference "this".
9677    DerefBuilder DerefThis(This);
9678
9679    // Implicitly cast "this" to the appropriately-qualified base type.
9680    CastBuilder To(DerefThis,
9681                   Context.getCVRQualifiedType(
9682                       BaseType, MoveAssignOperator->getTypeQualifiers()),
9683                   VK_LValue, BasePath);
9684
9685    // Build the move.
9686    StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
9687                                            To, From,
9688                                            /*CopyingBaseSubobject=*/true,
9689                                            /*Copying=*/false);
9690    if (Move.isInvalid()) {
9691      Diag(CurrentLocation, diag::note_member_synthesized_at)
9692        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9693      MoveAssignOperator->setInvalidDecl();
9694      return;
9695    }
9696
9697    // Success! Record the move.
9698    Statements.push_back(Move.takeAs<Expr>());
9699  }
9700
9701  // Assign non-static members.
9702  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9703                                  FieldEnd = ClassDecl->field_end();
9704       Field != FieldEnd; ++Field) {
9705    if (Field->isUnnamedBitfield())
9706      continue;
9707
9708    if (Field->isInvalidDecl()) {
9709      Invalid = true;
9710      continue;
9711    }
9712
9713    // Check for members of reference type; we can't move those.
9714    if (Field->getType()->isReferenceType()) {
9715      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9716        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9717      Diag(Field->getLocation(), diag::note_declared_at);
9718      Diag(CurrentLocation, diag::note_member_synthesized_at)
9719        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9720      Invalid = true;
9721      continue;
9722    }
9723
9724    // Check for members of const-qualified, non-class type.
9725    QualType BaseType = Context.getBaseElementType(Field->getType());
9726    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9727      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9728        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9729      Diag(Field->getLocation(), diag::note_declared_at);
9730      Diag(CurrentLocation, diag::note_member_synthesized_at)
9731        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9732      Invalid = true;
9733      continue;
9734    }
9735
9736    // Suppress assigning zero-width bitfields.
9737    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9738      continue;
9739
9740    QualType FieldType = Field->getType().getNonReferenceType();
9741    if (FieldType->isIncompleteArrayType()) {
9742      assert(ClassDecl->hasFlexibleArrayMember() &&
9743             "Incomplete array type is not valid");
9744      continue;
9745    }
9746
9747    // Build references to the field in the object we're copying from and to.
9748    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9749                              LookupMemberName);
9750    MemberLookup.addDecl(*Field);
9751    MemberLookup.resolveKind();
9752    MemberBuilder From(MoveOther, OtherRefType,
9753                       /*IsArrow=*/false, MemberLookup);
9754    MemberBuilder To(This, getCurrentThisType(),
9755                     /*IsArrow=*/true, MemberLookup);
9756
9757    assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
9758        "Member reference with rvalue base must be rvalue except for reference "
9759        "members, which aren't allowed for move assignment.");
9760
9761    // Build the move of this field.
9762    StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
9763                                            To, From,
9764                                            /*CopyingBaseSubobject=*/false,
9765                                            /*Copying=*/false);
9766    if (Move.isInvalid()) {
9767      Diag(CurrentLocation, diag::note_member_synthesized_at)
9768        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9769      MoveAssignOperator->setInvalidDecl();
9770      return;
9771    }
9772
9773    // Success! Record the copy.
9774    Statements.push_back(Move.takeAs<Stmt>());
9775  }
9776
9777  if (!Invalid) {
9778    // Add a "return *this;"
9779    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9780
9781    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9782    if (Return.isInvalid())
9783      Invalid = true;
9784    else {
9785      Statements.push_back(Return.takeAs<Stmt>());
9786
9787      if (Trap.hasErrorOccurred()) {
9788        Diag(CurrentLocation, diag::note_member_synthesized_at)
9789          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9790        Invalid = true;
9791      }
9792    }
9793  }
9794
9795  if (Invalid) {
9796    MoveAssignOperator->setInvalidDecl();
9797    return;
9798  }
9799
9800  StmtResult Body;
9801  {
9802    CompoundScopeRAII CompoundScope(*this);
9803    Body = ActOnCompoundStmt(Loc, Loc, Statements,
9804                             /*isStmtExpr=*/false);
9805    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9806  }
9807  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9808
9809  if (ASTMutationListener *L = getASTMutationListener()) {
9810    L->CompletedImplicitDefinition(MoveAssignOperator);
9811  }
9812}
9813
9814Sema::ImplicitExceptionSpecification
9815Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9816  CXXRecordDecl *ClassDecl = MD->getParent();
9817
9818  ImplicitExceptionSpecification ExceptSpec(*this);
9819  if (ClassDecl->isInvalidDecl())
9820    return ExceptSpec;
9821
9822  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9823  assert(T->getNumArgs() >= 1 && "not a copy ctor");
9824  unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9825
9826  // C++ [except.spec]p14:
9827  //   An implicitly declared special member function (Clause 12) shall have an
9828  //   exception-specification. [...]
9829  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9830                                       BaseEnd = ClassDecl->bases_end();
9831       Base != BaseEnd;
9832       ++Base) {
9833    // Virtual bases are handled below.
9834    if (Base->isVirtual())
9835      continue;
9836
9837    CXXRecordDecl *BaseClassDecl
9838      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9839    if (CXXConstructorDecl *CopyConstructor =
9840          LookupCopyingConstructor(BaseClassDecl, Quals))
9841      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9842  }
9843  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9844                                       BaseEnd = ClassDecl->vbases_end();
9845       Base != BaseEnd;
9846       ++Base) {
9847    CXXRecordDecl *BaseClassDecl
9848      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9849    if (CXXConstructorDecl *CopyConstructor =
9850          LookupCopyingConstructor(BaseClassDecl, Quals))
9851      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9852  }
9853  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9854                                  FieldEnd = ClassDecl->field_end();
9855       Field != FieldEnd;
9856       ++Field) {
9857    QualType FieldType = Context.getBaseElementType(Field->getType());
9858    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9859      if (CXXConstructorDecl *CopyConstructor =
9860              LookupCopyingConstructor(FieldClassDecl,
9861                                       Quals | FieldType.getCVRQualifiers()))
9862      ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
9863    }
9864  }
9865
9866  return ExceptSpec;
9867}
9868
9869CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9870                                                    CXXRecordDecl *ClassDecl) {
9871  // C++ [class.copy]p4:
9872  //   If the class definition does not explicitly declare a copy
9873  //   constructor, one is declared implicitly.
9874  assert(ClassDecl->needsImplicitCopyConstructor());
9875
9876  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9877  if (DSM.isAlreadyBeingDeclared())
9878    return 0;
9879
9880  QualType ClassType = Context.getTypeDeclType(ClassDecl);
9881  QualType ArgType = ClassType;
9882  bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
9883  if (Const)
9884    ArgType = ArgType.withConst();
9885  ArgType = Context.getLValueReferenceType(ArgType);
9886
9887  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9888                                                     CXXCopyConstructor,
9889                                                     Const);
9890
9891  DeclarationName Name
9892    = Context.DeclarationNames.getCXXConstructorName(
9893                                           Context.getCanonicalType(ClassType));
9894  SourceLocation ClassLoc = ClassDecl->getLocation();
9895  DeclarationNameInfo NameInfo(Name, ClassLoc);
9896
9897  //   An implicitly-declared copy constructor is an inline public
9898  //   member of its class.
9899  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
9900      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9901      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9902      Constexpr);
9903  CopyConstructor->setAccess(AS_public);
9904  CopyConstructor->setDefaulted();
9905
9906  // Build an exception specification pointing back at this member.
9907  FunctionProtoType::ExtProtoInfo EPI =
9908      getImplicitMethodEPI(*this, CopyConstructor);
9909  CopyConstructor->setType(
9910      Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9911
9912  // Add the parameter to the constructor.
9913  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
9914                                               ClassLoc, ClassLoc,
9915                                               /*IdentifierInfo=*/0,
9916                                               ArgType, /*TInfo=*/0,
9917                                               SC_None, 0);
9918  CopyConstructor->setParams(FromParam);
9919
9920  CopyConstructor->setTrivial(
9921    ClassDecl->needsOverloadResolutionForCopyConstructor()
9922      ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9923      : ClassDecl->hasTrivialCopyConstructor());
9924
9925  // C++11 [class.copy]p8:
9926  //   ... If the class definition does not explicitly declare a copy
9927  //   constructor, there is no user-declared move constructor, and there is no
9928  //   user-declared move assignment operator, a copy constructor is implicitly
9929  //   declared as defaulted.
9930  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
9931    SetDeclDeleted(CopyConstructor, ClassLoc);
9932
9933  // Note that we have declared this constructor.
9934  ++ASTContext::NumImplicitCopyConstructorsDeclared;
9935
9936  if (Scope *S = getScopeForContext(ClassDecl))
9937    PushOnScopeChains(CopyConstructor, S, false);
9938  ClassDecl->addDecl(CopyConstructor);
9939
9940  return CopyConstructor;
9941}
9942
9943void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
9944                                   CXXConstructorDecl *CopyConstructor) {
9945  assert((CopyConstructor->isDefaulted() &&
9946          CopyConstructor->isCopyConstructor() &&
9947          !CopyConstructor->doesThisDeclarationHaveABody() &&
9948          !CopyConstructor->isDeleted()) &&
9949         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
9950
9951  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
9952  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
9953
9954  // C++11 [class.copy]p7:
9955  //   The [definition of an implicitly declared copy constructor] is
9956  //   deprecated if the class has a user-declared copy assignment operator
9957  //   or a user-declared destructor.
9958  if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
9959    diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
9960
9961  SynthesizedFunctionScope Scope(*this, CopyConstructor);
9962  DiagnosticErrorTrap Trap(Diags);
9963
9964  if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
9965      Trap.hasErrorOccurred()) {
9966    Diag(CurrentLocation, diag::note_member_synthesized_at)
9967      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
9968    CopyConstructor->setInvalidDecl();
9969  }  else {
9970    Sema::CompoundScopeRAII CompoundScope(*this);
9971    CopyConstructor->setBody(ActOnCompoundStmt(
9972        CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
9973        /*isStmtExpr=*/ false).takeAs<Stmt>());
9974  }
9975
9976  CopyConstructor->markUsed(Context);
9977  if (ASTMutationListener *L = getASTMutationListener()) {
9978    L->CompletedImplicitDefinition(CopyConstructor);
9979  }
9980}
9981
9982Sema::ImplicitExceptionSpecification
9983Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9984  CXXRecordDecl *ClassDecl = MD->getParent();
9985
9986  // C++ [except.spec]p14:
9987  //   An implicitly declared special member function (Clause 12) shall have an
9988  //   exception-specification. [...]
9989  ImplicitExceptionSpecification ExceptSpec(*this);
9990  if (ClassDecl->isInvalidDecl())
9991    return ExceptSpec;
9992
9993  // Direct base-class constructors.
9994  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9995                                       BEnd = ClassDecl->bases_end();
9996       B != BEnd; ++B) {
9997    if (B->isVirtual()) // Handled below.
9998      continue;
9999
10000    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10001      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10002      CXXConstructorDecl *Constructor =
10003          LookupMovingConstructor(BaseClassDecl, 0);
10004      // If this is a deleted function, add it anyway. This might be conformant
10005      // with the standard. This might not. I'm not sure. It might not matter.
10006      if (Constructor)
10007        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
10008    }
10009  }
10010
10011  // Virtual base-class constructors.
10012  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
10013                                       BEnd = ClassDecl->vbases_end();
10014       B != BEnd; ++B) {
10015    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10016      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10017      CXXConstructorDecl *Constructor =
10018          LookupMovingConstructor(BaseClassDecl, 0);
10019      // If this is a deleted function, add it anyway. This might be conformant
10020      // with the standard. This might not. I'm not sure. It might not matter.
10021      if (Constructor)
10022        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
10023    }
10024  }
10025
10026  // Field constructors.
10027  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10028                               FEnd = ClassDecl->field_end();
10029       F != FEnd; ++F) {
10030    QualType FieldType = Context.getBaseElementType(F->getType());
10031    if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10032      CXXConstructorDecl *Constructor =
10033          LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10034      // If this is a deleted function, add it anyway. This might be conformant
10035      // with the standard. This might not. I'm not sure. It might not matter.
10036      // In particular, the problem is that this function never gets called. It
10037      // might just be ill-formed because this function attempts to refer to
10038      // a deleted function here.
10039      if (Constructor)
10040        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10041    }
10042  }
10043
10044  return ExceptSpec;
10045}
10046
10047CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10048                                                    CXXRecordDecl *ClassDecl) {
10049  // C++11 [class.copy]p9:
10050  //   If the definition of a class X does not explicitly declare a move
10051  //   constructor, one will be implicitly declared as defaulted if and only if:
10052  //
10053  //   - [first 4 bullets]
10054  assert(ClassDecl->needsImplicitMoveConstructor());
10055
10056  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10057  if (DSM.isAlreadyBeingDeclared())
10058    return 0;
10059
10060  // [Checked after we build the declaration]
10061  //   - the move assignment operator would not be implicitly defined as
10062  //     deleted,
10063
10064  // [DR1402]:
10065  //   - each of X's non-static data members and direct or virtual base classes
10066  //     has a type that either has a move constructor or is trivially copyable.
10067  if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
10068    ClassDecl->setFailedImplicitMoveConstructor();
10069    return 0;
10070  }
10071
10072  QualType ClassType = Context.getTypeDeclType(ClassDecl);
10073  QualType ArgType = Context.getRValueReferenceType(ClassType);
10074
10075  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10076                                                     CXXMoveConstructor,
10077                                                     false);
10078
10079  DeclarationName Name
10080    = Context.DeclarationNames.getCXXConstructorName(
10081                                           Context.getCanonicalType(ClassType));
10082  SourceLocation ClassLoc = ClassDecl->getLocation();
10083  DeclarationNameInfo NameInfo(Name, ClassLoc);
10084
10085  // C++11 [class.copy]p11:
10086  //   An implicitly-declared copy/move constructor is an inline public
10087  //   member of its class.
10088  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10089      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
10090      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10091      Constexpr);
10092  MoveConstructor->setAccess(AS_public);
10093  MoveConstructor->setDefaulted();
10094
10095  // Build an exception specification pointing back at this member.
10096  FunctionProtoType::ExtProtoInfo EPI =
10097      getImplicitMethodEPI(*this, MoveConstructor);
10098  MoveConstructor->setType(
10099      Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10100
10101  // Add the parameter to the constructor.
10102  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10103                                               ClassLoc, ClassLoc,
10104                                               /*IdentifierInfo=*/0,
10105                                               ArgType, /*TInfo=*/0,
10106                                               SC_None, 0);
10107  MoveConstructor->setParams(FromParam);
10108
10109  MoveConstructor->setTrivial(
10110    ClassDecl->needsOverloadResolutionForMoveConstructor()
10111      ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10112      : ClassDecl->hasTrivialMoveConstructor());
10113
10114  // C++0x [class.copy]p9:
10115  //   If the definition of a class X does not explicitly declare a move
10116  //   constructor, one will be implicitly declared as defaulted if and only if:
10117  //   [...]
10118  //   - the move constructor would not be implicitly defined as deleted.
10119  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10120    // Cache this result so that we don't try to generate this over and over
10121    // on every lookup, leaking memory and wasting time.
10122    ClassDecl->setFailedImplicitMoveConstructor();
10123    return 0;
10124  }
10125
10126  // Note that we have declared this constructor.
10127  ++ASTContext::NumImplicitMoveConstructorsDeclared;
10128
10129  if (Scope *S = getScopeForContext(ClassDecl))
10130    PushOnScopeChains(MoveConstructor, S, false);
10131  ClassDecl->addDecl(MoveConstructor);
10132
10133  return MoveConstructor;
10134}
10135
10136void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10137                                   CXXConstructorDecl *MoveConstructor) {
10138  assert((MoveConstructor->isDefaulted() &&
10139          MoveConstructor->isMoveConstructor() &&
10140          !MoveConstructor->doesThisDeclarationHaveABody() &&
10141          !MoveConstructor->isDeleted()) &&
10142         "DefineImplicitMoveConstructor - call it for implicit move ctor");
10143
10144  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10145  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10146
10147  SynthesizedFunctionScope Scope(*this, MoveConstructor);
10148  DiagnosticErrorTrap Trap(Diags);
10149
10150  if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
10151      Trap.hasErrorOccurred()) {
10152    Diag(CurrentLocation, diag::note_member_synthesized_at)
10153      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10154    MoveConstructor->setInvalidDecl();
10155  }  else {
10156    Sema::CompoundScopeRAII CompoundScope(*this);
10157    MoveConstructor->setBody(ActOnCompoundStmt(
10158        MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10159        /*isStmtExpr=*/ false).takeAs<Stmt>());
10160  }
10161
10162  MoveConstructor->markUsed(Context);
10163
10164  if (ASTMutationListener *L = getASTMutationListener()) {
10165    L->CompletedImplicitDefinition(MoveConstructor);
10166  }
10167}
10168
10169bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
10170  return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
10171}
10172
10173/// \brief Mark the call operator of the given lambda closure type as "used".
10174static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
10175  CXXMethodDecl *CallOperator
10176    = cast<CXXMethodDecl>(
10177        Lambda->lookup(
10178          S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
10179  CallOperator->setReferenced();
10180  CallOperator->markUsed(S.Context);
10181}
10182
10183void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10184       SourceLocation CurrentLocation,
10185       CXXConversionDecl *Conv)
10186{
10187  CXXRecordDecl *Lambda = Conv->getParent();
10188
10189  // Make sure that the lambda call operator is marked used.
10190  markLambdaCallOperatorUsed(*this, Lambda);
10191
10192  Conv->markUsed(Context);
10193
10194  SynthesizedFunctionScope Scope(*this, Conv);
10195  DiagnosticErrorTrap Trap(Diags);
10196
10197  // Return the address of the __invoke function.
10198  DeclarationName InvokeName = &Context.Idents.get("__invoke");
10199  CXXMethodDecl *Invoke
10200    = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
10201  Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
10202                                       VK_LValue, Conv->getLocation()).take();
10203  assert(FunctionRef && "Can't refer to __invoke function?");
10204  Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10205  Conv->setBody(new (Context) CompoundStmt(Context, Return,
10206                                           Conv->getLocation(),
10207                                           Conv->getLocation()));
10208
10209  // Fill in the __invoke function with a dummy implementation. IR generation
10210  // will fill in the actual details.
10211  Invoke->markUsed(Context);
10212  Invoke->setReferenced();
10213  Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10214
10215  if (ASTMutationListener *L = getASTMutationListener()) {
10216    L->CompletedImplicitDefinition(Conv);
10217    L->CompletedImplicitDefinition(Invoke);
10218  }
10219}
10220
10221void Sema::DefineImplicitLambdaToBlockPointerConversion(
10222       SourceLocation CurrentLocation,
10223       CXXConversionDecl *Conv)
10224{
10225  Conv->markUsed(Context);
10226
10227  SynthesizedFunctionScope Scope(*this, Conv);
10228  DiagnosticErrorTrap Trap(Diags);
10229
10230  // Copy-initialize the lambda object as needed to capture it.
10231  Expr *This = ActOnCXXThis(CurrentLocation).take();
10232  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
10233
10234  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10235                                                        Conv->getLocation(),
10236                                                        Conv, DerefThis);
10237
10238  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10239  // behavior.  Note that only the general conversion function does this
10240  // (since it's unusable otherwise); in the case where we inline the
10241  // block literal, it has block literal lifetime semantics.
10242  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
10243    BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10244                                          CK_CopyAndAutoreleaseBlockObject,
10245                                          BuildBlock.get(), 0, VK_RValue);
10246
10247  if (BuildBlock.isInvalid()) {
10248    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10249    Conv->setInvalidDecl();
10250    return;
10251  }
10252
10253  // Create the return statement that returns the block from the conversion
10254  // function.
10255  StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
10256  if (Return.isInvalid()) {
10257    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10258    Conv->setInvalidDecl();
10259    return;
10260  }
10261
10262  // Set the body of the conversion function.
10263  Stmt *ReturnS = Return.take();
10264  Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
10265                                           Conv->getLocation(),
10266                                           Conv->getLocation()));
10267
10268  // We're done; notify the mutation listener, if any.
10269  if (ASTMutationListener *L = getASTMutationListener()) {
10270    L->CompletedImplicitDefinition(Conv);
10271  }
10272}
10273
10274/// \brief Determine whether the given list arguments contains exactly one
10275/// "real" (non-default) argument.
10276static bool hasOneRealArgument(MultiExprArg Args) {
10277  switch (Args.size()) {
10278  case 0:
10279    return false;
10280
10281  default:
10282    if (!Args[1]->isDefaultArgument())
10283      return false;
10284
10285    // fall through
10286  case 1:
10287    return !Args[0]->isDefaultArgument();
10288  }
10289
10290  return false;
10291}
10292
10293ExprResult
10294Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10295                            CXXConstructorDecl *Constructor,
10296                            MultiExprArg ExprArgs,
10297                            bool HadMultipleCandidates,
10298                            bool IsListInitialization,
10299                            bool RequiresZeroInit,
10300                            unsigned ConstructKind,
10301                            SourceRange ParenRange) {
10302  bool Elidable = false;
10303
10304  // C++0x [class.copy]p34:
10305  //   When certain criteria are met, an implementation is allowed to
10306  //   omit the copy/move construction of a class object, even if the
10307  //   copy/move constructor and/or destructor for the object have
10308  //   side effects. [...]
10309  //     - when a temporary class object that has not been bound to a
10310  //       reference (12.2) would be copied/moved to a class object
10311  //       with the same cv-unqualified type, the copy/move operation
10312  //       can be omitted by constructing the temporary object
10313  //       directly into the target of the omitted copy/move
10314  if (ConstructKind == CXXConstructExpr::CK_Complete &&
10315      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
10316    Expr *SubExpr = ExprArgs[0];
10317    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
10318  }
10319
10320  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
10321                               Elidable, ExprArgs, HadMultipleCandidates,
10322                               IsListInitialization, RequiresZeroInit,
10323                               ConstructKind, ParenRange);
10324}
10325
10326/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10327/// including handling of its default argument expressions.
10328ExprResult
10329Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10330                            CXXConstructorDecl *Constructor, bool Elidable,
10331                            MultiExprArg ExprArgs,
10332                            bool HadMultipleCandidates,
10333                            bool IsListInitialization,
10334                            bool RequiresZeroInit,
10335                            unsigned ConstructKind,
10336                            SourceRange ParenRange) {
10337  MarkFunctionReferenced(ConstructLoc, Constructor);
10338  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
10339                                        Constructor, Elidable, ExprArgs,
10340                                        HadMultipleCandidates,
10341                                        IsListInitialization, RequiresZeroInit,
10342              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10343                                        ParenRange));
10344}
10345
10346void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
10347  if (VD->isInvalidDecl()) return;
10348
10349  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
10350  if (ClassDecl->isInvalidDecl()) return;
10351  if (ClassDecl->hasIrrelevantDestructor()) return;
10352  if (ClassDecl->isDependentContext()) return;
10353
10354  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10355  MarkFunctionReferenced(VD->getLocation(), Destructor);
10356  CheckDestructorAccess(VD->getLocation(), Destructor,
10357                        PDiag(diag::err_access_dtor_var)
10358                        << VD->getDeclName()
10359                        << VD->getType());
10360  DiagnoseUseOfDecl(Destructor, VD->getLocation());
10361
10362  if (!VD->hasGlobalStorage()) return;
10363
10364  // Emit warning for non-trivial dtor in global scope (a real global,
10365  // class-static, function-static).
10366  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10367
10368  // TODO: this should be re-enabled for static locals by !CXAAtExit
10369  if (!VD->isStaticLocal())
10370    Diag(VD->getLocation(), diag::warn_global_destructor);
10371}
10372
10373/// \brief Given a constructor and the set of arguments provided for the
10374/// constructor, convert the arguments and add any required default arguments
10375/// to form a proper call to this constructor.
10376///
10377/// \returns true if an error occurred, false otherwise.
10378bool
10379Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10380                              MultiExprArg ArgsPtr,
10381                              SourceLocation Loc,
10382                              SmallVectorImpl<Expr*> &ConvertedArgs,
10383                              bool AllowExplicit,
10384                              bool IsListInitialization) {
10385  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10386  unsigned NumArgs = ArgsPtr.size();
10387  Expr **Args = ArgsPtr.data();
10388
10389  const FunctionProtoType *Proto
10390    = Constructor->getType()->getAs<FunctionProtoType>();
10391  assert(Proto && "Constructor without a prototype?");
10392  unsigned NumArgsInProto = Proto->getNumArgs();
10393
10394  // If too few arguments are available, we'll fill in the rest with defaults.
10395  if (NumArgs < NumArgsInProto)
10396    ConvertedArgs.reserve(NumArgsInProto);
10397  else
10398    ConvertedArgs.reserve(NumArgs);
10399
10400  VariadicCallType CallType =
10401    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
10402  SmallVector<Expr *, 8> AllArgs;
10403  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10404                                        Proto, 0,
10405                                        llvm::makeArrayRef(Args, NumArgs),
10406                                        AllArgs,
10407                                        CallType, AllowExplicit,
10408                                        IsListInitialization);
10409  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
10410
10411  DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
10412
10413  CheckConstructorCall(Constructor,
10414                       llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10415                                                        AllArgs.size()),
10416                       Proto, Loc);
10417
10418  return Invalid;
10419}
10420
10421static inline bool
10422CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10423                                       const FunctionDecl *FnDecl) {
10424  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
10425  if (isa<NamespaceDecl>(DC)) {
10426    return SemaRef.Diag(FnDecl->getLocation(),
10427                        diag::err_operator_new_delete_declared_in_namespace)
10428      << FnDecl->getDeclName();
10429  }
10430
10431  if (isa<TranslationUnitDecl>(DC) &&
10432      FnDecl->getStorageClass() == SC_Static) {
10433    return SemaRef.Diag(FnDecl->getLocation(),
10434                        diag::err_operator_new_delete_declared_static)
10435      << FnDecl->getDeclName();
10436  }
10437
10438  return false;
10439}
10440
10441static inline bool
10442CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10443                            CanQualType ExpectedResultType,
10444                            CanQualType ExpectedFirstParamType,
10445                            unsigned DependentParamTypeDiag,
10446                            unsigned InvalidParamTypeDiag) {
10447  QualType ResultType =
10448    FnDecl->getType()->getAs<FunctionType>()->getResultType();
10449
10450  // Check that the result type is not dependent.
10451  if (ResultType->isDependentType())
10452    return SemaRef.Diag(FnDecl->getLocation(),
10453                        diag::err_operator_new_delete_dependent_result_type)
10454    << FnDecl->getDeclName() << ExpectedResultType;
10455
10456  // Check that the result type is what we expect.
10457  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10458    return SemaRef.Diag(FnDecl->getLocation(),
10459                        diag::err_operator_new_delete_invalid_result_type)
10460    << FnDecl->getDeclName() << ExpectedResultType;
10461
10462  // A function template must have at least 2 parameters.
10463  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10464    return SemaRef.Diag(FnDecl->getLocation(),
10465                      diag::err_operator_new_delete_template_too_few_parameters)
10466        << FnDecl->getDeclName();
10467
10468  // The function decl must have at least 1 parameter.
10469  if (FnDecl->getNumParams() == 0)
10470    return SemaRef.Diag(FnDecl->getLocation(),
10471                        diag::err_operator_new_delete_too_few_parameters)
10472      << FnDecl->getDeclName();
10473
10474  // Check the first parameter type is not dependent.
10475  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10476  if (FirstParamType->isDependentType())
10477    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10478      << FnDecl->getDeclName() << ExpectedFirstParamType;
10479
10480  // Check that the first parameter type is what we expect.
10481  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10482      ExpectedFirstParamType)
10483    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10484    << FnDecl->getDeclName() << ExpectedFirstParamType;
10485
10486  return false;
10487}
10488
10489static bool
10490CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10491  // C++ [basic.stc.dynamic.allocation]p1:
10492  //   A program is ill-formed if an allocation function is declared in a
10493  //   namespace scope other than global scope or declared static in global
10494  //   scope.
10495  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10496    return true;
10497
10498  CanQualType SizeTy =
10499    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10500
10501  // C++ [basic.stc.dynamic.allocation]p1:
10502  //  The return type shall be void*. The first parameter shall have type
10503  //  std::size_t.
10504  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10505                                  SizeTy,
10506                                  diag::err_operator_new_dependent_param_type,
10507                                  diag::err_operator_new_param_type))
10508    return true;
10509
10510  // C++ [basic.stc.dynamic.allocation]p1:
10511  //  The first parameter shall not have an associated default argument.
10512  if (FnDecl->getParamDecl(0)->hasDefaultArg())
10513    return SemaRef.Diag(FnDecl->getLocation(),
10514                        diag::err_operator_new_default_arg)
10515      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10516
10517  return false;
10518}
10519
10520static bool
10521CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
10522  // C++ [basic.stc.dynamic.deallocation]p1:
10523  //   A program is ill-formed if deallocation functions are declared in a
10524  //   namespace scope other than global scope or declared static in global
10525  //   scope.
10526  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10527    return true;
10528
10529  // C++ [basic.stc.dynamic.deallocation]p2:
10530  //   Each deallocation function shall return void and its first parameter
10531  //   shall be void*.
10532  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10533                                  SemaRef.Context.VoidPtrTy,
10534                                 diag::err_operator_delete_dependent_param_type,
10535                                 diag::err_operator_delete_param_type))
10536    return true;
10537
10538  return false;
10539}
10540
10541/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10542/// of this overloaded operator is well-formed. If so, returns false;
10543/// otherwise, emits appropriate diagnostics and returns true.
10544bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
10545  assert(FnDecl && FnDecl->isOverloadedOperator() &&
10546         "Expected an overloaded operator declaration");
10547
10548  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10549
10550  // C++ [over.oper]p5:
10551  //   The allocation and deallocation functions, operator new,
10552  //   operator new[], operator delete and operator delete[], are
10553  //   described completely in 3.7.3. The attributes and restrictions
10554  //   found in the rest of this subclause do not apply to them unless
10555  //   explicitly stated in 3.7.3.
10556  if (Op == OO_Delete || Op == OO_Array_Delete)
10557    return CheckOperatorDeleteDeclaration(*this, FnDecl);
10558
10559  if (Op == OO_New || Op == OO_Array_New)
10560    return CheckOperatorNewDeclaration(*this, FnDecl);
10561
10562  // C++ [over.oper]p6:
10563  //   An operator function shall either be a non-static member
10564  //   function or be a non-member function and have at least one
10565  //   parameter whose type is a class, a reference to a class, an
10566  //   enumeration, or a reference to an enumeration.
10567  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10568    if (MethodDecl->isStatic())
10569      return Diag(FnDecl->getLocation(),
10570                  diag::err_operator_overload_static) << FnDecl->getDeclName();
10571  } else {
10572    bool ClassOrEnumParam = false;
10573    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10574                                   ParamEnd = FnDecl->param_end();
10575         Param != ParamEnd; ++Param) {
10576      QualType ParamType = (*Param)->getType().getNonReferenceType();
10577      if (ParamType->isDependentType() || ParamType->isRecordType() ||
10578          ParamType->isEnumeralType()) {
10579        ClassOrEnumParam = true;
10580        break;
10581      }
10582    }
10583
10584    if (!ClassOrEnumParam)
10585      return Diag(FnDecl->getLocation(),
10586                  diag::err_operator_overload_needs_class_or_enum)
10587        << FnDecl->getDeclName();
10588  }
10589
10590  // C++ [over.oper]p8:
10591  //   An operator function cannot have default arguments (8.3.6),
10592  //   except where explicitly stated below.
10593  //
10594  // Only the function-call operator allows default arguments
10595  // (C++ [over.call]p1).
10596  if (Op != OO_Call) {
10597    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10598         Param != FnDecl->param_end(); ++Param) {
10599      if ((*Param)->hasDefaultArg())
10600        return Diag((*Param)->getLocation(),
10601                    diag::err_operator_overload_default_arg)
10602          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
10603    }
10604  }
10605
10606  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10607    { false, false, false }
10608#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10609    , { Unary, Binary, MemberOnly }
10610#include "clang/Basic/OperatorKinds.def"
10611  };
10612
10613  bool CanBeUnaryOperator = OperatorUses[Op][0];
10614  bool CanBeBinaryOperator = OperatorUses[Op][1];
10615  bool MustBeMemberOperator = OperatorUses[Op][2];
10616
10617  // C++ [over.oper]p8:
10618  //   [...] Operator functions cannot have more or fewer parameters
10619  //   than the number required for the corresponding operator, as
10620  //   described in the rest of this subclause.
10621  unsigned NumParams = FnDecl->getNumParams()
10622                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
10623  if (Op != OO_Call &&
10624      ((NumParams == 1 && !CanBeUnaryOperator) ||
10625       (NumParams == 2 && !CanBeBinaryOperator) ||
10626       (NumParams < 1) || (NumParams > 2))) {
10627    // We have the wrong number of parameters.
10628    unsigned ErrorKind;
10629    if (CanBeUnaryOperator && CanBeBinaryOperator) {
10630      ErrorKind = 2;  // 2 -> unary or binary.
10631    } else if (CanBeUnaryOperator) {
10632      ErrorKind = 0;  // 0 -> unary
10633    } else {
10634      assert(CanBeBinaryOperator &&
10635             "All non-call overloaded operators are unary or binary!");
10636      ErrorKind = 1;  // 1 -> binary
10637    }
10638
10639    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
10640      << FnDecl->getDeclName() << NumParams << ErrorKind;
10641  }
10642
10643  // Overloaded operators other than operator() cannot be variadic.
10644  if (Op != OO_Call &&
10645      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
10646    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
10647      << FnDecl->getDeclName();
10648  }
10649
10650  // Some operators must be non-static member functions.
10651  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10652    return Diag(FnDecl->getLocation(),
10653                diag::err_operator_overload_must_be_member)
10654      << FnDecl->getDeclName();
10655  }
10656
10657  // C++ [over.inc]p1:
10658  //   The user-defined function called operator++ implements the
10659  //   prefix and postfix ++ operator. If this function is a member
10660  //   function with no parameters, or a non-member function with one
10661  //   parameter of class or enumeration type, it defines the prefix
10662  //   increment operator ++ for objects of that type. If the function
10663  //   is a member function with one parameter (which shall be of type
10664  //   int) or a non-member function with two parameters (the second
10665  //   of which shall be of type int), it defines the postfix
10666  //   increment operator ++ for objects of that type.
10667  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10668    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10669    bool ParamIsInt = false;
10670    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
10671      ParamIsInt = BT->getKind() == BuiltinType::Int;
10672
10673    if (!ParamIsInt)
10674      return Diag(LastParam->getLocation(),
10675                  diag::err_operator_overload_post_incdec_must_be_int)
10676        << LastParam->getType() << (Op == OO_MinusMinus);
10677  }
10678
10679  return false;
10680}
10681
10682/// CheckLiteralOperatorDeclaration - Check whether the declaration
10683/// of this literal operator function is well-formed. If so, returns
10684/// false; otherwise, emits appropriate diagnostics and returns true.
10685bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
10686  if (isa<CXXMethodDecl>(FnDecl)) {
10687    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10688      << FnDecl->getDeclName();
10689    return true;
10690  }
10691
10692  if (FnDecl->isExternC()) {
10693    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10694    return true;
10695  }
10696
10697  bool Valid = false;
10698
10699  // This might be the definition of a literal operator template.
10700  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10701  // This might be a specialization of a literal operator template.
10702  if (!TpDecl)
10703    TpDecl = FnDecl->getPrimaryTemplate();
10704
10705  // template <char...> type operator "" name() is the only valid template
10706  // signature, and the only valid signature with no parameters.
10707  if (TpDecl) {
10708    if (FnDecl->param_size() == 0) {
10709      // Must have only one template parameter
10710      TemplateParameterList *Params = TpDecl->getTemplateParameters();
10711      if (Params->size() == 1) {
10712        NonTypeTemplateParmDecl *PmDecl =
10713          dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
10714
10715        // The template parameter must be a char parameter pack.
10716        if (PmDecl && PmDecl->isTemplateParameterPack() &&
10717            Context.hasSameType(PmDecl->getType(), Context.CharTy))
10718          Valid = true;
10719      }
10720    }
10721  } else if (FnDecl->param_size()) {
10722    // Check the first parameter
10723    FunctionDecl::param_iterator Param = FnDecl->param_begin();
10724
10725    QualType T = (*Param)->getType().getUnqualifiedType();
10726
10727    // unsigned long long int, long double, and any character type are allowed
10728    // as the only parameters.
10729    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10730        Context.hasSameType(T, Context.LongDoubleTy) ||
10731        Context.hasSameType(T, Context.CharTy) ||
10732        Context.hasSameType(T, Context.WideCharTy) ||
10733        Context.hasSameType(T, Context.Char16Ty) ||
10734        Context.hasSameType(T, Context.Char32Ty)) {
10735      if (++Param == FnDecl->param_end())
10736        Valid = true;
10737      goto FinishedParams;
10738    }
10739
10740    // Otherwise it must be a pointer to const; let's strip those qualifiers.
10741    const PointerType *PT = T->getAs<PointerType>();
10742    if (!PT)
10743      goto FinishedParams;
10744    T = PT->getPointeeType();
10745    if (!T.isConstQualified() || T.isVolatileQualified())
10746      goto FinishedParams;
10747    T = T.getUnqualifiedType();
10748
10749    // Move on to the second parameter;
10750    ++Param;
10751
10752    // If there is no second parameter, the first must be a const char *
10753    if (Param == FnDecl->param_end()) {
10754      if (Context.hasSameType(T, Context.CharTy))
10755        Valid = true;
10756      goto FinishedParams;
10757    }
10758
10759    // const char *, const wchar_t*, const char16_t*, and const char32_t*
10760    // are allowed as the first parameter to a two-parameter function
10761    if (!(Context.hasSameType(T, Context.CharTy) ||
10762          Context.hasSameType(T, Context.WideCharTy) ||
10763          Context.hasSameType(T, Context.Char16Ty) ||
10764          Context.hasSameType(T, Context.Char32Ty)))
10765      goto FinishedParams;
10766
10767    // The second and final parameter must be an std::size_t
10768    T = (*Param)->getType().getUnqualifiedType();
10769    if (Context.hasSameType(T, Context.getSizeType()) &&
10770        ++Param == FnDecl->param_end())
10771      Valid = true;
10772  }
10773
10774  // FIXME: This diagnostic is absolutely terrible.
10775FinishedParams:
10776  if (!Valid) {
10777    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10778      << FnDecl->getDeclName();
10779    return true;
10780  }
10781
10782  // A parameter-declaration-clause containing a default argument is not
10783  // equivalent to any of the permitted forms.
10784  for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10785                                    ParamEnd = FnDecl->param_end();
10786       Param != ParamEnd; ++Param) {
10787    if ((*Param)->hasDefaultArg()) {
10788      Diag((*Param)->getDefaultArgRange().getBegin(),
10789           diag::err_literal_operator_default_argument)
10790        << (*Param)->getDefaultArgRange();
10791      break;
10792    }
10793  }
10794
10795  StringRef LiteralName
10796    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10797  if (LiteralName[0] != '_') {
10798    // C++11 [usrlit.suffix]p1:
10799    //   Literal suffix identifiers that do not start with an underscore
10800    //   are reserved for future standardization.
10801    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10802      << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
10803  }
10804
10805  return false;
10806}
10807
10808/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10809/// linkage specification, including the language and (if present)
10810/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10811/// the location of the language string literal, which is provided
10812/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10813/// the '{' brace. Otherwise, this linkage specification does not
10814/// have any braces.
10815Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10816                                           SourceLocation LangLoc,
10817                                           StringRef Lang,
10818                                           SourceLocation LBraceLoc) {
10819  LinkageSpecDecl::LanguageIDs Language;
10820  if (Lang == "\"C\"")
10821    Language = LinkageSpecDecl::lang_c;
10822  else if (Lang == "\"C++\"")
10823    Language = LinkageSpecDecl::lang_cxx;
10824  else {
10825    Diag(LangLoc, diag::err_bad_language);
10826    return 0;
10827  }
10828
10829  // FIXME: Add all the various semantics of linkage specifications
10830
10831  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
10832                                               ExternLoc, LangLoc, Language,
10833                                               LBraceLoc.isValid());
10834  CurContext->addDecl(D);
10835  PushDeclContext(S, D);
10836  return D;
10837}
10838
10839/// ActOnFinishLinkageSpecification - Complete the definition of
10840/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10841/// valid, it's the position of the closing '}' brace in a linkage
10842/// specification that uses braces.
10843Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
10844                                            Decl *LinkageSpec,
10845                                            SourceLocation RBraceLoc) {
10846  if (LinkageSpec) {
10847    if (RBraceLoc.isValid()) {
10848      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10849      LSDecl->setRBraceLoc(RBraceLoc);
10850    }
10851    PopDeclContext();
10852  }
10853  return LinkageSpec;
10854}
10855
10856Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10857                                  AttributeList *AttrList,
10858                                  SourceLocation SemiLoc) {
10859  Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10860  // Attribute declarations appertain to empty declaration so we handle
10861  // them here.
10862  if (AttrList)
10863    ProcessDeclAttributeList(S, ED, AttrList);
10864
10865  CurContext->addDecl(ED);
10866  return ED;
10867}
10868
10869/// \brief Perform semantic analysis for the variable declaration that
10870/// occurs within a C++ catch clause, returning the newly-created
10871/// variable.
10872VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
10873                                         TypeSourceInfo *TInfo,
10874                                         SourceLocation StartLoc,
10875                                         SourceLocation Loc,
10876                                         IdentifierInfo *Name) {
10877  bool Invalid = false;
10878  QualType ExDeclType = TInfo->getType();
10879
10880  // Arrays and functions decay.
10881  if (ExDeclType->isArrayType())
10882    ExDeclType = Context.getArrayDecayedType(ExDeclType);
10883  else if (ExDeclType->isFunctionType())
10884    ExDeclType = Context.getPointerType(ExDeclType);
10885
10886  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10887  // The exception-declaration shall not denote a pointer or reference to an
10888  // incomplete type, other than [cv] void*.
10889  // N2844 forbids rvalue references.
10890  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
10891    Diag(Loc, diag::err_catch_rvalue_ref);
10892    Invalid = true;
10893  }
10894
10895  QualType BaseType = ExDeclType;
10896  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
10897  unsigned DK = diag::err_catch_incomplete;
10898  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
10899    BaseType = Ptr->getPointeeType();
10900    Mode = 1;
10901    DK = diag::err_catch_incomplete_ptr;
10902  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
10903    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
10904    BaseType = Ref->getPointeeType();
10905    Mode = 2;
10906    DK = diag::err_catch_incomplete_ref;
10907  }
10908  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
10909      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
10910    Invalid = true;
10911
10912  if (!Invalid && !ExDeclType->isDependentType() &&
10913      RequireNonAbstractType(Loc, ExDeclType,
10914                             diag::err_abstract_type_in_decl,
10915                             AbstractVariableType))
10916    Invalid = true;
10917
10918  // Only the non-fragile NeXT runtime currently supports C++ catches
10919  // of ObjC types, and no runtime supports catching ObjC types by value.
10920  if (!Invalid && getLangOpts().ObjC1) {
10921    QualType T = ExDeclType;
10922    if (const ReferenceType *RT = T->getAs<ReferenceType>())
10923      T = RT->getPointeeType();
10924
10925    if (T->isObjCObjectType()) {
10926      Diag(Loc, diag::err_objc_object_catch);
10927      Invalid = true;
10928    } else if (T->isObjCObjectPointerType()) {
10929      // FIXME: should this be a test for macosx-fragile specifically?
10930      if (getLangOpts().ObjCRuntime.isFragile())
10931        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
10932    }
10933  }
10934
10935  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10936                                    ExDeclType, TInfo, SC_None);
10937  ExDecl->setExceptionVariable(true);
10938
10939  // In ARC, infer 'retaining' for variables of retainable type.
10940  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
10941    Invalid = true;
10942
10943  if (!Invalid && !ExDeclType->isDependentType()) {
10944    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
10945      // Insulate this from anything else we might currently be parsing.
10946      EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10947
10948      // C++ [except.handle]p16:
10949      //   The object declared in an exception-declaration or, if the
10950      //   exception-declaration does not specify a name, a temporary (12.2) is
10951      //   copy-initialized (8.5) from the exception object. [...]
10952      //   The object is destroyed when the handler exits, after the destruction
10953      //   of any automatic objects initialized within the handler.
10954      //
10955      // We just pretend to initialize the object with itself, then make sure
10956      // it can be destroyed later.
10957      QualType initType = ExDeclType;
10958
10959      InitializedEntity entity =
10960        InitializedEntity::InitializeVariable(ExDecl);
10961      InitializationKind initKind =
10962        InitializationKind::CreateCopy(Loc, SourceLocation());
10963
10964      Expr *opaqueValue =
10965        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10966      InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10967      ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
10968      if (result.isInvalid())
10969        Invalid = true;
10970      else {
10971        // If the constructor used was non-trivial, set this as the
10972        // "initializer".
10973        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10974        if (!construct->getConstructor()->isTrivial()) {
10975          Expr *init = MaybeCreateExprWithCleanups(construct);
10976          ExDecl->setInit(init);
10977        }
10978
10979        // And make sure it's destructable.
10980        FinalizeVarWithDestructor(ExDecl, recordType);
10981      }
10982    }
10983  }
10984
10985  if (Invalid)
10986    ExDecl->setInvalidDecl();
10987
10988  return ExDecl;
10989}
10990
10991/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10992/// handler.
10993Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
10994  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10995  bool Invalid = D.isInvalidType();
10996
10997  // Check for unexpanded parameter packs.
10998  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10999                                      UPPC_ExceptionType)) {
11000    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11001                                             D.getIdentifierLoc());
11002    Invalid = true;
11003  }
11004
11005  IdentifierInfo *II = D.getIdentifier();
11006  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11007                                             LookupOrdinaryName,
11008                                             ForRedeclaration)) {
11009    // The scope should be freshly made just for us. There is just no way
11010    // it contains any previous declaration.
11011    assert(!S->isDeclScope(PrevDecl));
11012    if (PrevDecl->isTemplateParameter()) {
11013      // Maybe we will complain about the shadowed template parameter.
11014      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11015      PrevDecl = 0;
11016    }
11017  }
11018
11019  if (D.getCXXScopeSpec().isSet() && !Invalid) {
11020    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11021      << D.getCXXScopeSpec().getRange();
11022    Invalid = true;
11023  }
11024
11025  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
11026                                              D.getLocStart(),
11027                                              D.getIdentifierLoc(),
11028                                              D.getIdentifier());
11029  if (Invalid)
11030    ExDecl->setInvalidDecl();
11031
11032  // Add the exception declaration into this scope.
11033  if (II)
11034    PushOnScopeChains(ExDecl, S);
11035  else
11036    CurContext->addDecl(ExDecl);
11037
11038  ProcessDeclAttributes(S, ExDecl, D);
11039  return ExDecl;
11040}
11041
11042Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11043                                         Expr *AssertExpr,
11044                                         Expr *AssertMessageExpr,
11045                                         SourceLocation RParenLoc) {
11046  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
11047
11048  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11049    return 0;
11050
11051  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11052                                      AssertMessage, RParenLoc, false);
11053}
11054
11055Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11056                                         Expr *AssertExpr,
11057                                         StringLiteral *AssertMessage,
11058                                         SourceLocation RParenLoc,
11059                                         bool Failed) {
11060  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11061      !Failed) {
11062    // In a static_assert-declaration, the constant-expression shall be a
11063    // constant expression that can be contextually converted to bool.
11064    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11065    if (Converted.isInvalid())
11066      Failed = true;
11067
11068    llvm::APSInt Cond;
11069    if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
11070          diag::err_static_assert_expression_is_not_constant,
11071          /*AllowFold=*/false).isInvalid())
11072      Failed = true;
11073
11074    if (!Failed && !Cond) {
11075      SmallString<256> MsgBuffer;
11076      llvm::raw_svector_ostream Msg(MsgBuffer);
11077      AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
11078      Diag(StaticAssertLoc, diag::err_static_assert_failed)
11079        << Msg.str() << AssertExpr->getSourceRange();
11080      Failed = true;
11081    }
11082  }
11083
11084  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
11085                                        AssertExpr, AssertMessage, RParenLoc,
11086                                        Failed);
11087
11088  CurContext->addDecl(Decl);
11089  return Decl;
11090}
11091
11092/// \brief Perform semantic analysis of the given friend type declaration.
11093///
11094/// \returns A friend declaration that.
11095FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
11096                                      SourceLocation FriendLoc,
11097                                      TypeSourceInfo *TSInfo) {
11098  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11099
11100  QualType T = TSInfo->getType();
11101  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
11102
11103  // C++03 [class.friend]p2:
11104  //   An elaborated-type-specifier shall be used in a friend declaration
11105  //   for a class.*
11106  //
11107  //   * The class-key of the elaborated-type-specifier is required.
11108  if (!ActiveTemplateInstantiations.empty()) {
11109    // Do not complain about the form of friend template types during
11110    // template instantiation; we will already have complained when the
11111    // template was declared.
11112  } else {
11113    if (!T->isElaboratedTypeSpecifier()) {
11114      // If we evaluated the type to a record type, suggest putting
11115      // a tag in front.
11116      if (const RecordType *RT = T->getAs<RecordType>()) {
11117        RecordDecl *RD = RT->getDecl();
11118
11119        std::string InsertionText = std::string(" ") + RD->getKindName();
11120
11121        Diag(TypeRange.getBegin(),
11122             getLangOpts().CPlusPlus11 ?
11123               diag::warn_cxx98_compat_unelaborated_friend_type :
11124               diag::ext_unelaborated_friend_type)
11125          << (unsigned) RD->getTagKind()
11126          << T
11127          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11128                                        InsertionText);
11129      } else {
11130        Diag(FriendLoc,
11131             getLangOpts().CPlusPlus11 ?
11132               diag::warn_cxx98_compat_nonclass_type_friend :
11133               diag::ext_nonclass_type_friend)
11134          << T
11135          << TypeRange;
11136      }
11137    } else if (T->getAs<EnumType>()) {
11138      Diag(FriendLoc,
11139           getLangOpts().CPlusPlus11 ?
11140             diag::warn_cxx98_compat_enum_friend :
11141             diag::ext_enum_friend)
11142        << T
11143        << TypeRange;
11144    }
11145
11146    // C++11 [class.friend]p3:
11147    //   A friend declaration that does not declare a function shall have one
11148    //   of the following forms:
11149    //     friend elaborated-type-specifier ;
11150    //     friend simple-type-specifier ;
11151    //     friend typename-specifier ;
11152    if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11153      Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11154  }
11155
11156  //   If the type specifier in a friend declaration designates a (possibly
11157  //   cv-qualified) class type, that class is declared as a friend; otherwise,
11158  //   the friend declaration is ignored.
11159  return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
11160}
11161
11162/// Handle a friend tag declaration where the scope specifier was
11163/// templated.
11164Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11165                                    unsigned TagSpec, SourceLocation TagLoc,
11166                                    CXXScopeSpec &SS,
11167                                    IdentifierInfo *Name,
11168                                    SourceLocation NameLoc,
11169                                    AttributeList *Attr,
11170                                    MultiTemplateParamsArg TempParamLists) {
11171  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11172
11173  bool isExplicitSpecialization = false;
11174  bool Invalid = false;
11175
11176  if (TemplateParameterList *TemplateParams =
11177          MatchTemplateParametersToScopeSpecifier(
11178              TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11179              isExplicitSpecialization, Invalid)) {
11180    if (TemplateParams->size() > 0) {
11181      // This is a declaration of a class template.
11182      if (Invalid)
11183        return 0;
11184
11185      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11186                                SS, Name, NameLoc, Attr,
11187                                TemplateParams, AS_public,
11188                                /*ModulePrivateLoc=*/SourceLocation(),
11189                                TempParamLists.size() - 1,
11190                                TempParamLists.data()).take();
11191    } else {
11192      // The "template<>" header is extraneous.
11193      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11194        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11195      isExplicitSpecialization = true;
11196    }
11197  }
11198
11199  if (Invalid) return 0;
11200
11201  bool isAllExplicitSpecializations = true;
11202  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
11203    if (TempParamLists[I]->size()) {
11204      isAllExplicitSpecializations = false;
11205      break;
11206    }
11207  }
11208
11209  // FIXME: don't ignore attributes.
11210
11211  // If it's explicit specializations all the way down, just forget
11212  // about the template header and build an appropriate non-templated
11213  // friend.  TODO: for source fidelity, remember the headers.
11214  if (isAllExplicitSpecializations) {
11215    if (SS.isEmpty()) {
11216      bool Owned = false;
11217      bool IsDependent = false;
11218      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11219                      Attr, AS_public,
11220                      /*ModulePrivateLoc=*/SourceLocation(),
11221                      MultiTemplateParamsArg(), Owned, IsDependent,
11222                      /*ScopedEnumKWLoc=*/SourceLocation(),
11223                      /*ScopedEnumUsesClassTag=*/false,
11224                      /*UnderlyingType=*/TypeResult());
11225    }
11226
11227    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11228    ElaboratedTypeKeyword Keyword
11229      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11230    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
11231                                   *Name, NameLoc);
11232    if (T.isNull())
11233      return 0;
11234
11235    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11236    if (isa<DependentNameType>(T)) {
11237      DependentNameTypeLoc TL =
11238          TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11239      TL.setElaboratedKeywordLoc(TagLoc);
11240      TL.setQualifierLoc(QualifierLoc);
11241      TL.setNameLoc(NameLoc);
11242    } else {
11243      ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
11244      TL.setElaboratedKeywordLoc(TagLoc);
11245      TL.setQualifierLoc(QualifierLoc);
11246      TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
11247    }
11248
11249    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11250                                            TSI, FriendLoc, TempParamLists);
11251    Friend->setAccess(AS_public);
11252    CurContext->addDecl(Friend);
11253    return Friend;
11254  }
11255
11256  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11257
11258
11259
11260  // Handle the case of a templated-scope friend class.  e.g.
11261  //   template <class T> class A<T>::B;
11262  // FIXME: we don't support these right now.
11263  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11264  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11265  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11266  DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11267  TL.setElaboratedKeywordLoc(TagLoc);
11268  TL.setQualifierLoc(SS.getWithLocInContext(Context));
11269  TL.setNameLoc(NameLoc);
11270
11271  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11272                                          TSI, FriendLoc, TempParamLists);
11273  Friend->setAccess(AS_public);
11274  Friend->setUnsupportedFriend(true);
11275  CurContext->addDecl(Friend);
11276  return Friend;
11277}
11278
11279
11280/// Handle a friend type declaration.  This works in tandem with
11281/// ActOnTag.
11282///
11283/// Notes on friend class templates:
11284///
11285/// We generally treat friend class declarations as if they were
11286/// declaring a class.  So, for example, the elaborated type specifier
11287/// in a friend declaration is required to obey the restrictions of a
11288/// class-head (i.e. no typedefs in the scope chain), template
11289/// parameters are required to match up with simple template-ids, &c.
11290/// However, unlike when declaring a template specialization, it's
11291/// okay to refer to a template specialization without an empty
11292/// template parameter declaration, e.g.
11293///   friend class A<T>::B<unsigned>;
11294/// We permit this as a special case; if there are any template
11295/// parameters present at all, require proper matching, i.e.
11296///   template <> template \<class T> friend class A<int>::B;
11297Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
11298                                MultiTemplateParamsArg TempParams) {
11299  SourceLocation Loc = DS.getLocStart();
11300
11301  assert(DS.isFriendSpecified());
11302  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11303
11304  // Try to convert the decl specifier to a type.  This works for
11305  // friend templates because ActOnTag never produces a ClassTemplateDecl
11306  // for a TUK_Friend.
11307  Declarator TheDeclarator(DS, Declarator::MemberContext);
11308  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11309  QualType T = TSI->getType();
11310  if (TheDeclarator.isInvalidType())
11311    return 0;
11312
11313  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11314    return 0;
11315
11316  // This is definitely an error in C++98.  It's probably meant to
11317  // be forbidden in C++0x, too, but the specification is just
11318  // poorly written.
11319  //
11320  // The problem is with declarations like the following:
11321  //   template <T> friend A<T>::foo;
11322  // where deciding whether a class C is a friend or not now hinges
11323  // on whether there exists an instantiation of A that causes
11324  // 'foo' to equal C.  There are restrictions on class-heads
11325  // (which we declare (by fiat) elaborated friend declarations to
11326  // be) that makes this tractable.
11327  //
11328  // FIXME: handle "template <> friend class A<T>;", which
11329  // is possibly well-formed?  Who even knows?
11330  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
11331    Diag(Loc, diag::err_tagless_friend_type_template)
11332      << DS.getSourceRange();
11333    return 0;
11334  }
11335
11336  // C++98 [class.friend]p1: A friend of a class is a function
11337  //   or class that is not a member of the class . . .
11338  // This is fixed in DR77, which just barely didn't make the C++03
11339  // deadline.  It's also a very silly restriction that seriously
11340  // affects inner classes and which nobody else seems to implement;
11341  // thus we never diagnose it, not even in -pedantic.
11342  //
11343  // But note that we could warn about it: it's always useless to
11344  // friend one of your own members (it's not, however, worthless to
11345  // friend a member of an arbitrary specialization of your template).
11346
11347  Decl *D;
11348  if (unsigned NumTempParamLists = TempParams.size())
11349    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
11350                                   NumTempParamLists,
11351                                   TempParams.data(),
11352                                   TSI,
11353                                   DS.getFriendSpecLoc());
11354  else
11355    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
11356
11357  if (!D)
11358    return 0;
11359
11360  D->setAccess(AS_public);
11361  CurContext->addDecl(D);
11362
11363  return D;
11364}
11365
11366NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11367                                        MultiTemplateParamsArg TemplateParams) {
11368  const DeclSpec &DS = D.getDeclSpec();
11369
11370  assert(DS.isFriendSpecified());
11371  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11372
11373  SourceLocation Loc = D.getIdentifierLoc();
11374  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11375
11376  // C++ [class.friend]p1
11377  //   A friend of a class is a function or class....
11378  // Note that this sees through typedefs, which is intended.
11379  // It *doesn't* see through dependent types, which is correct
11380  // according to [temp.arg.type]p3:
11381  //   If a declaration acquires a function type through a
11382  //   type dependent on a template-parameter and this causes
11383  //   a declaration that does not use the syntactic form of a
11384  //   function declarator to have a function type, the program
11385  //   is ill-formed.
11386  if (!TInfo->getType()->isFunctionType()) {
11387    Diag(Loc, diag::err_unexpected_friend);
11388
11389    // It might be worthwhile to try to recover by creating an
11390    // appropriate declaration.
11391    return 0;
11392  }
11393
11394  // C++ [namespace.memdef]p3
11395  //  - If a friend declaration in a non-local class first declares a
11396  //    class or function, the friend class or function is a member
11397  //    of the innermost enclosing namespace.
11398  //  - The name of the friend is not found by simple name lookup
11399  //    until a matching declaration is provided in that namespace
11400  //    scope (either before or after the class declaration granting
11401  //    friendship).
11402  //  - If a friend function is called, its name may be found by the
11403  //    name lookup that considers functions from namespaces and
11404  //    classes associated with the types of the function arguments.
11405  //  - When looking for a prior declaration of a class or a function
11406  //    declared as a friend, scopes outside the innermost enclosing
11407  //    namespace scope are not considered.
11408
11409  CXXScopeSpec &SS = D.getCXXScopeSpec();
11410  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11411  DeclarationName Name = NameInfo.getName();
11412  assert(Name);
11413
11414  // Check for unexpanded parameter packs.
11415  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11416      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11417      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11418    return 0;
11419
11420  // The context we found the declaration in, or in which we should
11421  // create the declaration.
11422  DeclContext *DC;
11423  Scope *DCScope = S;
11424  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
11425                        ForRedeclaration);
11426
11427  // There are five cases here.
11428  //   - There's no scope specifier and we're in a local class. Only look
11429  //     for functions declared in the immediately-enclosing block scope.
11430  // We recover from invalid scope qualifiers as if they just weren't there.
11431  FunctionDecl *FunctionContainingLocalClass = 0;
11432  if ((SS.isInvalid() || !SS.isSet()) &&
11433      (FunctionContainingLocalClass =
11434           cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11435    // C++11 [class.friend]p11:
11436    //   If a friend declaration appears in a local class and the name
11437    //   specified is an unqualified name, a prior declaration is
11438    //   looked up without considering scopes that are outside the
11439    //   innermost enclosing non-class scope. For a friend function
11440    //   declaration, if there is no prior declaration, the program is
11441    //   ill-formed.
11442
11443    // Find the innermost enclosing non-class scope. This is the block
11444    // scope containing the local class definition (or for a nested class,
11445    // the outer local class).
11446    DCScope = S->getFnParent();
11447
11448    // Look up the function name in the scope.
11449    Previous.clear(LookupLocalFriendName);
11450    LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11451
11452    if (!Previous.empty()) {
11453      // All possible previous declarations must have the same context:
11454      // either they were declared at block scope or they are members of
11455      // one of the enclosing local classes.
11456      DC = Previous.getRepresentativeDecl()->getDeclContext();
11457    } else {
11458      // This is ill-formed, but provide the context that we would have
11459      // declared the function in, if we were permitted to, for error recovery.
11460      DC = FunctionContainingLocalClass;
11461    }
11462
11463    // C++ [class.friend]p6:
11464    //   A function can be defined in a friend declaration of a class if and
11465    //   only if the class is a non-local class (9.8), the function name is
11466    //   unqualified, and the function has namespace scope.
11467    if (D.isFunctionDefinition()) {
11468      Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11469    }
11470
11471  //   - There's no scope specifier, in which case we just go to the
11472  //     appropriate scope and look for a function or function template
11473  //     there as appropriate.
11474  } else if (SS.isInvalid() || !SS.isSet()) {
11475    // C++11 [namespace.memdef]p3:
11476    //   If the name in a friend declaration is neither qualified nor
11477    //   a template-id and the declaration is a function or an
11478    //   elaborated-type-specifier, the lookup to determine whether
11479    //   the entity has been previously declared shall not consider
11480    //   any scopes outside the innermost enclosing namespace.
11481    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
11482
11483    // Find the appropriate context according to the above.
11484    DC = CurContext;
11485
11486    // Skip class contexts.  If someone can cite chapter and verse
11487    // for this behavior, that would be nice --- it's what GCC and
11488    // EDG do, and it seems like a reasonable intent, but the spec
11489    // really only says that checks for unqualified existing
11490    // declarations should stop at the nearest enclosing namespace,
11491    // not that they should only consider the nearest enclosing
11492    // namespace.
11493    while (DC->isRecord())
11494      DC = DC->getParent();
11495
11496    DeclContext *LookupDC = DC;
11497    while (LookupDC->isTransparentContext())
11498      LookupDC = LookupDC->getParent();
11499
11500    while (true) {
11501      LookupQualifiedName(Previous, LookupDC);
11502
11503      if (!Previous.empty()) {
11504        DC = LookupDC;
11505        break;
11506      }
11507
11508      if (isTemplateId) {
11509        if (isa<TranslationUnitDecl>(LookupDC)) break;
11510      } else {
11511        if (LookupDC->isFileContext()) break;
11512      }
11513      LookupDC = LookupDC->getParent();
11514    }
11515
11516    DCScope = getScopeForDeclContext(S, DC);
11517
11518  //   - There's a non-dependent scope specifier, in which case we
11519  //     compute it and do a previous lookup there for a function
11520  //     or function template.
11521  } else if (!SS.getScopeRep()->isDependent()) {
11522    DC = computeDeclContext(SS);
11523    if (!DC) return 0;
11524
11525    if (RequireCompleteDeclContext(SS, DC)) return 0;
11526
11527    LookupQualifiedName(Previous, DC);
11528
11529    // Ignore things found implicitly in the wrong scope.
11530    // TODO: better diagnostics for this case.  Suggesting the right
11531    // qualified scope would be nice...
11532    LookupResult::Filter F = Previous.makeFilter();
11533    while (F.hasNext()) {
11534      NamedDecl *D = F.next();
11535      if (!DC->InEnclosingNamespaceSetOf(
11536              D->getDeclContext()->getRedeclContext()))
11537        F.erase();
11538    }
11539    F.done();
11540
11541    if (Previous.empty()) {
11542      D.setInvalidType();
11543      Diag(Loc, diag::err_qualified_friend_not_found)
11544          << Name << TInfo->getType();
11545      return 0;
11546    }
11547
11548    // C++ [class.friend]p1: A friend of a class is a function or
11549    //   class that is not a member of the class . . .
11550    if (DC->Equals(CurContext))
11551      Diag(DS.getFriendSpecLoc(),
11552           getLangOpts().CPlusPlus11 ?
11553             diag::warn_cxx98_compat_friend_is_member :
11554             diag::err_friend_is_member);
11555
11556    if (D.isFunctionDefinition()) {
11557      // C++ [class.friend]p6:
11558      //   A function can be defined in a friend declaration of a class if and
11559      //   only if the class is a non-local class (9.8), the function name is
11560      //   unqualified, and the function has namespace scope.
11561      SemaDiagnosticBuilder DB
11562        = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11563
11564      DB << SS.getScopeRep();
11565      if (DC->isFileContext())
11566        DB << FixItHint::CreateRemoval(SS.getRange());
11567      SS.clear();
11568    }
11569
11570  //   - There's a scope specifier that does not match any template
11571  //     parameter lists, in which case we use some arbitrary context,
11572  //     create a method or method template, and wait for instantiation.
11573  //   - There's a scope specifier that does match some template
11574  //     parameter lists, which we don't handle right now.
11575  } else {
11576    if (D.isFunctionDefinition()) {
11577      // C++ [class.friend]p6:
11578      //   A function can be defined in a friend declaration of a class if and
11579      //   only if the class is a non-local class (9.8), the function name is
11580      //   unqualified, and the function has namespace scope.
11581      Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11582        << SS.getScopeRep();
11583    }
11584
11585    DC = CurContext;
11586    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
11587  }
11588
11589  if (!DC->isRecord()) {
11590    // This implies that it has to be an operator or function.
11591    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11592        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11593        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
11594      Diag(Loc, diag::err_introducing_special_friend) <<
11595        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11596         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
11597      return 0;
11598    }
11599  }
11600
11601  // FIXME: This is an egregious hack to cope with cases where the scope stack
11602  // does not contain the declaration context, i.e., in an out-of-line
11603  // definition of a class.
11604  Scope FakeDCScope(S, Scope::DeclScope, Diags);
11605  if (!DCScope) {
11606    FakeDCScope.setEntity(DC);
11607    DCScope = &FakeDCScope;
11608  }
11609
11610  bool AddToScope = true;
11611  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
11612                                          TemplateParams, AddToScope);
11613  if (!ND) return 0;
11614
11615  assert(ND->getLexicalDeclContext() == CurContext);
11616
11617  // If we performed typo correction, we might have added a scope specifier
11618  // and changed the decl context.
11619  DC = ND->getDeclContext();
11620
11621  // Add the function declaration to the appropriate lookup tables,
11622  // adjusting the redeclarations list as necessary.  We don't
11623  // want to do this yet if the friending class is dependent.
11624  //
11625  // Also update the scope-based lookup if the target context's
11626  // lookup context is in lexical scope.
11627  if (!CurContext->isDependentContext()) {
11628    DC = DC->getRedeclContext();
11629    DC->makeDeclVisibleInContext(ND);
11630    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11631      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
11632  }
11633
11634  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
11635                                       D.getIdentifierLoc(), ND,
11636                                       DS.getFriendSpecLoc());
11637  FrD->setAccess(AS_public);
11638  CurContext->addDecl(FrD);
11639
11640  if (ND->isInvalidDecl()) {
11641    FrD->setInvalidDecl();
11642  } else {
11643    if (DC->isRecord()) CheckFriendAccess(ND);
11644
11645    FunctionDecl *FD;
11646    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11647      FD = FTD->getTemplatedDecl();
11648    else
11649      FD = cast<FunctionDecl>(ND);
11650
11651    // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11652    // default argument expression, that declaration shall be a definition
11653    // and shall be the only declaration of the function or function
11654    // template in the translation unit.
11655    if (functionDeclHasDefaultArgument(FD)) {
11656      if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11657        Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11658        Diag(OldFD->getLocation(), diag::note_previous_declaration);
11659      } else if (!D.isFunctionDefinition())
11660        Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11661    }
11662
11663    // Mark templated-scope function declarations as unsupported.
11664    if (FD->getNumTemplateParameterLists())
11665      FrD->setUnsupportedFriend(true);
11666  }
11667
11668  return ND;
11669}
11670
11671void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11672  AdjustDeclIfTemplate(Dcl);
11673
11674  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
11675  if (!Fn) {
11676    Diag(DelLoc, diag::err_deleted_non_function);
11677    return;
11678  }
11679
11680  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
11681    // Don't consider the implicit declaration we generate for explicit
11682    // specializations. FIXME: Do not generate these implicit declarations.
11683    if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11684        || Prev->getPreviousDecl()) && !Prev->isDefined()) {
11685      Diag(DelLoc, diag::err_deleted_decl_not_first);
11686      Diag(Prev->getLocation(), diag::note_previous_declaration);
11687    }
11688    // If the declaration wasn't the first, we delete the function anyway for
11689    // recovery.
11690    Fn = Fn->getCanonicalDecl();
11691  }
11692
11693  if (Fn->isDeleted())
11694    return;
11695
11696  // See if we're deleting a function which is already known to override a
11697  // non-deleted virtual function.
11698  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11699    bool IssuedDiagnostic = false;
11700    for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11701                                        E = MD->end_overridden_methods();
11702         I != E; ++I) {
11703      if (!(*MD->begin_overridden_methods())->isDeleted()) {
11704        if (!IssuedDiagnostic) {
11705          Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11706          IssuedDiagnostic = true;
11707        }
11708        Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11709      }
11710    }
11711  }
11712
11713  Fn->setDeletedAsWritten();
11714}
11715
11716void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
11717  CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
11718
11719  if (MD) {
11720    if (MD->getParent()->isDependentType()) {
11721      MD->setDefaulted();
11722      MD->setExplicitlyDefaulted();
11723      return;
11724    }
11725
11726    CXXSpecialMember Member = getSpecialMember(MD);
11727    if (Member == CXXInvalid) {
11728      if (!MD->isInvalidDecl())
11729        Diag(DefaultLoc, diag::err_default_special_members);
11730      return;
11731    }
11732
11733    MD->setDefaulted();
11734    MD->setExplicitlyDefaulted();
11735
11736    // If this definition appears within the record, do the checking when
11737    // the record is complete.
11738    const FunctionDecl *Primary = MD;
11739    if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
11740      // Find the uninstantiated declaration that actually had the '= default'
11741      // on it.
11742      Pattern->isDefined(Primary);
11743
11744    // If the method was defaulted on its first declaration, we will have
11745    // already performed the checking in CheckCompletedCXXClass. Such a
11746    // declaration doesn't trigger an implicit definition.
11747    if (Primary == Primary->getCanonicalDecl())
11748      return;
11749
11750    CheckExplicitlyDefaultedSpecialMember(MD);
11751
11752    // The exception specification is needed because we are defining the
11753    // function.
11754    ResolveExceptionSpec(DefaultLoc,
11755                         MD->getType()->castAs<FunctionProtoType>());
11756
11757    if (MD->isInvalidDecl())
11758      return;
11759
11760    switch (Member) {
11761    case CXXDefaultConstructor:
11762      DefineImplicitDefaultConstructor(DefaultLoc,
11763                                       cast<CXXConstructorDecl>(MD));
11764      break;
11765    case CXXCopyConstructor:
11766      DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
11767      break;
11768    case CXXCopyAssignment:
11769      DefineImplicitCopyAssignment(DefaultLoc, MD);
11770      break;
11771    case CXXDestructor:
11772      DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
11773      break;
11774    case CXXMoveConstructor:
11775      DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
11776      break;
11777    case CXXMoveAssignment:
11778      DefineImplicitMoveAssignment(DefaultLoc, MD);
11779      break;
11780    case CXXInvalid:
11781      llvm_unreachable("Invalid special member.");
11782    }
11783  } else {
11784    Diag(DefaultLoc, diag::err_default_special_members);
11785  }
11786}
11787
11788static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
11789  for (Stmt::child_range CI = S->children(); CI; ++CI) {
11790    Stmt *SubStmt = *CI;
11791    if (!SubStmt)
11792      continue;
11793    if (isa<ReturnStmt>(SubStmt))
11794      Self.Diag(SubStmt->getLocStart(),
11795           diag::err_return_in_constructor_handler);
11796    if (!isa<Expr>(SubStmt))
11797      SearchForReturnInStmt(Self, SubStmt);
11798  }
11799}
11800
11801void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11802  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11803    CXXCatchStmt *Handler = TryBlock->getHandler(I);
11804    SearchForReturnInStmt(*this, Handler);
11805  }
11806}
11807
11808bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
11809                                             const CXXMethodDecl *Old) {
11810  const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11811  const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11812
11813  CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11814
11815  // If the calling conventions match, everything is fine
11816  if (NewCC == OldCC)
11817    return false;
11818
11819  Diag(New->getLocation(),
11820       diag::err_conflicting_overriding_cc_attributes)
11821    << New->getDeclName() << New->getType() << Old->getType();
11822  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11823  return true;
11824}
11825
11826bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
11827                                             const CXXMethodDecl *Old) {
11828  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11829  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
11830
11831  if (Context.hasSameType(NewTy, OldTy) ||
11832      NewTy->isDependentType() || OldTy->isDependentType())
11833    return false;
11834
11835  // Check if the return types are covariant
11836  QualType NewClassTy, OldClassTy;
11837
11838  /// Both types must be pointers or references to classes.
11839  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11840    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
11841      NewClassTy = NewPT->getPointeeType();
11842      OldClassTy = OldPT->getPointeeType();
11843    }
11844  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11845    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11846      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11847        NewClassTy = NewRT->getPointeeType();
11848        OldClassTy = OldRT->getPointeeType();
11849      }
11850    }
11851  }
11852
11853  // The return types aren't either both pointers or references to a class type.
11854  if (NewClassTy.isNull()) {
11855    Diag(New->getLocation(),
11856         diag::err_different_return_type_for_overriding_virtual_function)
11857      << New->getDeclName() << NewTy << OldTy;
11858    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11859
11860    return true;
11861  }
11862
11863  // C++ [class.virtual]p6:
11864  //   If the return type of D::f differs from the return type of B::f, the
11865  //   class type in the return type of D::f shall be complete at the point of
11866  //   declaration of D::f or shall be the class type D.
11867  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11868    if (!RT->isBeingDefined() &&
11869        RequireCompleteType(New->getLocation(), NewClassTy,
11870                            diag::err_covariant_return_incomplete,
11871                            New->getDeclName()))
11872    return true;
11873  }
11874
11875  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
11876    // Check if the new class derives from the old class.
11877    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11878      Diag(New->getLocation(),
11879           diag::err_covariant_return_not_derived)
11880      << New->getDeclName() << NewTy << OldTy;
11881      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11882      return true;
11883    }
11884
11885    // Check if we the conversion from derived to base is valid.
11886    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
11887                    diag::err_covariant_return_inaccessible_base,
11888                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
11889                    // FIXME: Should this point to the return type?
11890                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
11891      // FIXME: this note won't trigger for delayed access control
11892      // diagnostics, and it's impossible to get an undelayed error
11893      // here from access control during the original parse because
11894      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
11895      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11896      return true;
11897    }
11898  }
11899
11900  // The qualifiers of the return types must be the same.
11901  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
11902    Diag(New->getLocation(),
11903         diag::err_covariant_return_type_different_qualifications)
11904    << New->getDeclName() << NewTy << OldTy;
11905    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11906    return true;
11907  };
11908
11909
11910  // The new class type must have the same or less qualifiers as the old type.
11911  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11912    Diag(New->getLocation(),
11913         diag::err_covariant_return_type_class_type_more_qualified)
11914    << New->getDeclName() << NewTy << OldTy;
11915    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11916    return true;
11917  };
11918
11919  return false;
11920}
11921
11922/// \brief Mark the given method pure.
11923///
11924/// \param Method the method to be marked pure.
11925///
11926/// \param InitRange the source range that covers the "0" initializer.
11927bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
11928  SourceLocation EndLoc = InitRange.getEnd();
11929  if (EndLoc.isValid())
11930    Method->setRangeEnd(EndLoc);
11931
11932  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11933    Method->setPure();
11934    return false;
11935  }
11936
11937  if (!Method->isInvalidDecl())
11938    Diag(Method->getLocation(), diag::err_non_virtual_pure)
11939      << Method->getDeclName() << InitRange;
11940  return true;
11941}
11942
11943/// \brief Determine whether the given declaration is a static data member.
11944static bool isStaticDataMember(const Decl *D) {
11945  if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
11946    return Var->isStaticDataMember();
11947
11948  return false;
11949}
11950
11951/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11952/// an initializer for the out-of-line declaration 'Dcl'.  The scope
11953/// is a fresh scope pushed for just this purpose.
11954///
11955/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11956/// static data member of class X, names should be looked up in the scope of
11957/// class X.
11958void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
11959  // If there is no declaration, there was an error parsing it.
11960  if (D == 0 || D->isInvalidDecl()) return;
11961
11962  // We should only get called for declarations with scope specifiers, like:
11963  //   int foo::bar;
11964  assert(D->isOutOfLine());
11965  EnterDeclaratorContext(S, D->getDeclContext());
11966
11967  // If we are parsing the initializer for a static data member, push a
11968  // new expression evaluation context that is associated with this static
11969  // data member.
11970  if (isStaticDataMember(D))
11971    PushExpressionEvaluationContext(PotentiallyEvaluated, D);
11972}
11973
11974/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
11975/// initializer for the out-of-line declaration 'D'.
11976void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
11977  // If there is no declaration, there was an error parsing it.
11978  if (D == 0 || D->isInvalidDecl()) return;
11979
11980  if (isStaticDataMember(D))
11981    PopExpressionEvaluationContext();
11982
11983  assert(D->isOutOfLine());
11984  ExitDeclaratorContext(S);
11985}
11986
11987/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11988/// C++ if/switch/while/for statement.
11989/// e.g: "if (int x = f()) {...}"
11990DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
11991  // C++ 6.4p2:
11992  // The declarator shall not specify a function or an array.
11993  // The type-specifier-seq shall not contain typedef and shall not declare a
11994  // new class or enumeration.
11995  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11996         "Parser allowed 'typedef' as storage class of condition decl.");
11997
11998  Decl *Dcl = ActOnDeclarator(S, D);
11999  if (!Dcl)
12000    return true;
12001
12002  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12003    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
12004      << D.getSourceRange();
12005    return true;
12006  }
12007
12008  return Dcl;
12009}
12010
12011void Sema::LoadExternalVTableUses() {
12012  if (!ExternalSource)
12013    return;
12014
12015  SmallVector<ExternalVTableUse, 4> VTables;
12016  ExternalSource->ReadUsedVTables(VTables);
12017  SmallVector<VTableUse, 4> NewUses;
12018  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12019    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12020      = VTablesUsed.find(VTables[I].Record);
12021    // Even if a definition wasn't required before, it may be required now.
12022    if (Pos != VTablesUsed.end()) {
12023      if (!Pos->second && VTables[I].DefinitionRequired)
12024        Pos->second = true;
12025      continue;
12026    }
12027
12028    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12029    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12030  }
12031
12032  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12033}
12034
12035void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12036                          bool DefinitionRequired) {
12037  // Ignore any vtable uses in unevaluated operands or for classes that do
12038  // not have a vtable.
12039  if (!Class->isDynamicClass() || Class->isDependentContext() ||
12040      CurContext->isDependentContext() || isUnevaluatedContext())
12041    return;
12042
12043  // Try to insert this class into the map.
12044  LoadExternalVTableUses();
12045  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12046  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12047    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12048  if (!Pos.second) {
12049    // If we already had an entry, check to see if we are promoting this vtable
12050    // to required a definition. If so, we need to reappend to the VTableUses
12051    // list, since we may have already processed the first entry.
12052    if (DefinitionRequired && !Pos.first->second) {
12053      Pos.first->second = true;
12054    } else {
12055      // Otherwise, we can early exit.
12056      return;
12057    }
12058  }
12059
12060  // Local classes need to have their virtual members marked
12061  // immediately. For all other classes, we mark their virtual members
12062  // at the end of the translation unit.
12063  if (Class->isLocalClass())
12064    MarkVirtualMembersReferenced(Loc, Class);
12065  else
12066    VTableUses.push_back(std::make_pair(Class, Loc));
12067}
12068
12069bool Sema::DefineUsedVTables() {
12070  LoadExternalVTableUses();
12071  if (VTableUses.empty())
12072    return false;
12073
12074  // Note: The VTableUses vector could grow as a result of marking
12075  // the members of a class as "used", so we check the size each
12076  // time through the loop and prefer indices (which are stable) to
12077  // iterators (which are not).
12078  bool DefinedAnything = false;
12079  for (unsigned I = 0; I != VTableUses.size(); ++I) {
12080    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
12081    if (!Class)
12082      continue;
12083
12084    SourceLocation Loc = VTableUses[I].second;
12085
12086    bool DefineVTable = true;
12087
12088    // If this class has a key function, but that key function is
12089    // defined in another translation unit, we don't need to emit the
12090    // vtable even though we're using it.
12091    const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
12092    if (KeyFunction && !KeyFunction->hasBody()) {
12093      // The key function is in another translation unit.
12094      DefineVTable = false;
12095      TemplateSpecializationKind TSK =
12096          KeyFunction->getTemplateSpecializationKind();
12097      assert(TSK != TSK_ExplicitInstantiationDefinition &&
12098             TSK != TSK_ImplicitInstantiation &&
12099             "Instantiations don't have key functions");
12100      (void)TSK;
12101    } else if (!KeyFunction) {
12102      // If we have a class with no key function that is the subject
12103      // of an explicit instantiation declaration, suppress the
12104      // vtable; it will live with the explicit instantiation
12105      // definition.
12106      bool IsExplicitInstantiationDeclaration
12107        = Class->getTemplateSpecializationKind()
12108                                      == TSK_ExplicitInstantiationDeclaration;
12109      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12110                                 REnd = Class->redecls_end();
12111           R != REnd; ++R) {
12112        TemplateSpecializationKind TSK
12113          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12114        if (TSK == TSK_ExplicitInstantiationDeclaration)
12115          IsExplicitInstantiationDeclaration = true;
12116        else if (TSK == TSK_ExplicitInstantiationDefinition) {
12117          IsExplicitInstantiationDeclaration = false;
12118          break;
12119        }
12120      }
12121
12122      if (IsExplicitInstantiationDeclaration)
12123        DefineVTable = false;
12124    }
12125
12126    // The exception specifications for all virtual members may be needed even
12127    // if we are not providing an authoritative form of the vtable in this TU.
12128    // We may choose to emit it available_externally anyway.
12129    if (!DefineVTable) {
12130      MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12131      continue;
12132    }
12133
12134    // Mark all of the virtual members of this class as referenced, so
12135    // that we can build a vtable. Then, tell the AST consumer that a
12136    // vtable for this class is required.
12137    DefinedAnything = true;
12138    MarkVirtualMembersReferenced(Loc, Class);
12139    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12140    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12141
12142    // Optionally warn if we're emitting a weak vtable.
12143    if (Class->isExternallyVisible() &&
12144        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
12145      const FunctionDecl *KeyFunctionDef = 0;
12146      if (!KeyFunction ||
12147          (KeyFunction->hasBody(KeyFunctionDef) &&
12148           KeyFunctionDef->isInlined()))
12149        Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12150             TSK_ExplicitInstantiationDefinition
12151             ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12152          << Class;
12153    }
12154  }
12155  VTableUses.clear();
12156
12157  return DefinedAnything;
12158}
12159
12160void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12161                                                 const CXXRecordDecl *RD) {
12162  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12163                                      E = RD->method_end(); I != E; ++I)
12164    if ((*I)->isVirtual() && !(*I)->isPure())
12165      ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12166}
12167
12168void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12169                                        const CXXRecordDecl *RD) {
12170  // Mark all functions which will appear in RD's vtable as used.
12171  CXXFinalOverriderMap FinalOverriders;
12172  RD->getFinalOverriders(FinalOverriders);
12173  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12174                                            E = FinalOverriders.end();
12175       I != E; ++I) {
12176    for (OverridingMethods::const_iterator OI = I->second.begin(),
12177                                           OE = I->second.end();
12178         OI != OE; ++OI) {
12179      assert(OI->second.size() > 0 && "no final overrider");
12180      CXXMethodDecl *Overrider = OI->second.front().Method;
12181
12182      // C++ [basic.def.odr]p2:
12183      //   [...] A virtual member function is used if it is not pure. [...]
12184      if (!Overrider->isPure())
12185        MarkFunctionReferenced(Loc, Overrider);
12186    }
12187  }
12188
12189  // Only classes that have virtual bases need a VTT.
12190  if (RD->getNumVBases() == 0)
12191    return;
12192
12193  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12194           e = RD->bases_end(); i != e; ++i) {
12195    const CXXRecordDecl *Base =
12196        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
12197    if (Base->getNumVBases() == 0)
12198      continue;
12199    MarkVirtualMembersReferenced(Loc, Base);
12200  }
12201}
12202
12203/// SetIvarInitializers - This routine builds initialization ASTs for the
12204/// Objective-C implementation whose ivars need be initialized.
12205void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
12206  if (!getLangOpts().CPlusPlus)
12207    return;
12208  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
12209    SmallVector<ObjCIvarDecl*, 8> ivars;
12210    CollectIvarsToConstructOrDestruct(OID, ivars);
12211    if (ivars.empty())
12212      return;
12213    SmallVector<CXXCtorInitializer*, 32> AllToInit;
12214    for (unsigned i = 0; i < ivars.size(); i++) {
12215      FieldDecl *Field = ivars[i];
12216      if (Field->isInvalidDecl())
12217        continue;
12218
12219      CXXCtorInitializer *Member;
12220      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12221      InitializationKind InitKind =
12222        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
12223
12224      InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12225      ExprResult MemberInit =
12226        InitSeq.Perform(*this, InitEntity, InitKind, None);
12227      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
12228      // Note, MemberInit could actually come back empty if no initialization
12229      // is required (e.g., because it would call a trivial default constructor)
12230      if (!MemberInit.get() || MemberInit.isInvalid())
12231        continue;
12232
12233      Member =
12234        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12235                                         SourceLocation(),
12236                                         MemberInit.takeAs<Expr>(),
12237                                         SourceLocation());
12238      AllToInit.push_back(Member);
12239
12240      // Be sure that the destructor is accessible and is marked as referenced.
12241      if (const RecordType *RecordTy
12242                  = Context.getBaseElementType(Field->getType())
12243                                                        ->getAs<RecordType>()) {
12244                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
12245        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
12246          MarkFunctionReferenced(Field->getLocation(), Destructor);
12247          CheckDestructorAccess(Field->getLocation(), Destructor,
12248                            PDiag(diag::err_access_dtor_ivar)
12249                              << Context.getBaseElementType(Field->getType()));
12250        }
12251      }
12252    }
12253    ObjCImplementation->setIvarInitializers(Context,
12254                                            AllToInit.data(), AllToInit.size());
12255  }
12256}
12257
12258static
12259void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12260                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12261                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12262                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12263                           Sema &S) {
12264  if (Ctor->isInvalidDecl())
12265    return;
12266
12267  CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12268
12269  // Target may not be determinable yet, for instance if this is a dependent
12270  // call in an uninstantiated template.
12271  if (Target) {
12272    const FunctionDecl *FNTarget = 0;
12273    (void)Target->hasBody(FNTarget);
12274    Target = const_cast<CXXConstructorDecl*>(
12275      cast_or_null<CXXConstructorDecl>(FNTarget));
12276  }
12277
12278  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12279                     // Avoid dereferencing a null pointer here.
12280                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12281
12282  if (!Current.insert(Canonical))
12283    return;
12284
12285  // We know that beyond here, we aren't chaining into a cycle.
12286  if (!Target || !Target->isDelegatingConstructor() ||
12287      Target->isInvalidDecl() || Valid.count(TCanonical)) {
12288    Valid.insert(Current.begin(), Current.end());
12289    Current.clear();
12290  // We've hit a cycle.
12291  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12292             Current.count(TCanonical)) {
12293    // If we haven't diagnosed this cycle yet, do so now.
12294    if (!Invalid.count(TCanonical)) {
12295      S.Diag((*Ctor->init_begin())->getSourceLocation(),
12296             diag::warn_delegating_ctor_cycle)
12297        << Ctor;
12298
12299      // Don't add a note for a function delegating directly to itself.
12300      if (TCanonical != Canonical)
12301        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12302
12303      CXXConstructorDecl *C = Target;
12304      while (C->getCanonicalDecl() != Canonical) {
12305        const FunctionDecl *FNTarget = 0;
12306        (void)C->getTargetConstructor()->hasBody(FNTarget);
12307        assert(FNTarget && "Ctor cycle through bodiless function");
12308
12309        C = const_cast<CXXConstructorDecl*>(
12310          cast<CXXConstructorDecl>(FNTarget));
12311        S.Diag(C->getLocation(), diag::note_which_delegates_to);
12312      }
12313    }
12314
12315    Invalid.insert(Current.begin(), Current.end());
12316    Current.clear();
12317  } else {
12318    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12319  }
12320}
12321
12322
12323void Sema::CheckDelegatingCtorCycles() {
12324  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12325
12326  for (DelegatingCtorDeclsType::iterator
12327         I = DelegatingCtorDecls.begin(ExternalSource),
12328         E = DelegatingCtorDecls.end();
12329       I != E; ++I)
12330    DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
12331
12332  for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12333                                                         CE = Invalid.end();
12334       CI != CE; ++CI)
12335    (*CI)->setInvalidDecl();
12336}
12337
12338namespace {
12339  /// \brief AST visitor that finds references to the 'this' expression.
12340  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12341    Sema &S;
12342
12343  public:
12344    explicit FindCXXThisExpr(Sema &S) : S(S) { }
12345
12346    bool VisitCXXThisExpr(CXXThisExpr *E) {
12347      S.Diag(E->getLocation(), diag::err_this_static_member_func)
12348        << E->isImplicit();
12349      return false;
12350    }
12351  };
12352}
12353
12354bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12355  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12356  if (!TSInfo)
12357    return false;
12358
12359  TypeLoc TL = TSInfo->getTypeLoc();
12360  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12361  if (!ProtoTL)
12362    return false;
12363
12364  // C++11 [expr.prim.general]p3:
12365  //   [The expression this] shall not appear before the optional
12366  //   cv-qualifier-seq and it shall not appear within the declaration of a
12367  //   static member function (although its type and value category are defined
12368  //   within a static member function as they are within a non-static member
12369  //   function). [ Note: this is because declaration matching does not occur
12370  //  until the complete declarator is known. - end note ]
12371  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12372  FindCXXThisExpr Finder(*this);
12373
12374  // If the return type came after the cv-qualifier-seq, check it now.
12375  if (Proto->hasTrailingReturn() &&
12376      !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
12377    return true;
12378
12379  // Check the exception specification.
12380  if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12381    return true;
12382
12383  return checkThisInStaticMemberFunctionAttributes(Method);
12384}
12385
12386bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12387  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12388  if (!TSInfo)
12389    return false;
12390
12391  TypeLoc TL = TSInfo->getTypeLoc();
12392  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12393  if (!ProtoTL)
12394    return false;
12395
12396  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12397  FindCXXThisExpr Finder(*this);
12398
12399  switch (Proto->getExceptionSpecType()) {
12400  case EST_Uninstantiated:
12401  case EST_Unevaluated:
12402  case EST_BasicNoexcept:
12403  case EST_DynamicNone:
12404  case EST_MSAny:
12405  case EST_None:
12406    break;
12407
12408  case EST_ComputedNoexcept:
12409    if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12410      return true;
12411
12412  case EST_Dynamic:
12413    for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
12414         EEnd = Proto->exception_end();
12415         E != EEnd; ++E) {
12416      if (!Finder.TraverseType(*E))
12417        return true;
12418    }
12419    break;
12420  }
12421
12422  return false;
12423}
12424
12425bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12426  FindCXXThisExpr Finder(*this);
12427
12428  // Check attributes.
12429  for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12430       A != AEnd; ++A) {
12431    // FIXME: This should be emitted by tblgen.
12432    Expr *Arg = 0;
12433    ArrayRef<Expr *> Args;
12434    if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12435      Arg = G->getArg();
12436    else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12437      Arg = G->getArg();
12438    else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12439      Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12440    else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12441      Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12442    else if (ExclusiveLockFunctionAttr *ELF
12443               = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12444      Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12445    else if (SharedLockFunctionAttr *SLF
12446               = dyn_cast<SharedLockFunctionAttr>(*A))
12447      Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12448    else if (ExclusiveTrylockFunctionAttr *ETLF
12449               = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12450      Arg = ETLF->getSuccessValue();
12451      Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12452    } else if (SharedTrylockFunctionAttr *STLF
12453                 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12454      Arg = STLF->getSuccessValue();
12455      Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12456    } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12457      Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12458    else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12459      Arg = LR->getArg();
12460    else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12461      Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12462    else if (ExclusiveLocksRequiredAttr *ELR
12463               = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12464      Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12465    else if (SharedLocksRequiredAttr *SLR
12466               = dyn_cast<SharedLocksRequiredAttr>(*A))
12467      Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12468
12469    if (Arg && !Finder.TraverseStmt(Arg))
12470      return true;
12471
12472    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12473      if (!Finder.TraverseStmt(Args[I]))
12474        return true;
12475    }
12476  }
12477
12478  return false;
12479}
12480
12481void
12482Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12483                                  ArrayRef<ParsedType> DynamicExceptions,
12484                                  ArrayRef<SourceRange> DynamicExceptionRanges,
12485                                  Expr *NoexceptExpr,
12486                                  SmallVectorImpl<QualType> &Exceptions,
12487                                  FunctionProtoType::ExtProtoInfo &EPI) {
12488  Exceptions.clear();
12489  EPI.ExceptionSpecType = EST;
12490  if (EST == EST_Dynamic) {
12491    Exceptions.reserve(DynamicExceptions.size());
12492    for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12493      // FIXME: Preserve type source info.
12494      QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12495
12496      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12497      collectUnexpandedParameterPacks(ET, Unexpanded);
12498      if (!Unexpanded.empty()) {
12499        DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12500                                         UPPC_ExceptionType,
12501                                         Unexpanded);
12502        continue;
12503      }
12504
12505      // Check that the type is valid for an exception spec, and
12506      // drop it if not.
12507      if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12508        Exceptions.push_back(ET);
12509    }
12510    EPI.NumExceptions = Exceptions.size();
12511    EPI.Exceptions = Exceptions.data();
12512    return;
12513  }
12514
12515  if (EST == EST_ComputedNoexcept) {
12516    // If an error occurred, there's no expression here.
12517    if (NoexceptExpr) {
12518      assert((NoexceptExpr->isTypeDependent() ||
12519              NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12520              Context.BoolTy) &&
12521             "Parser should have made sure that the expression is boolean");
12522      if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12523        EPI.ExceptionSpecType = EST_BasicNoexcept;
12524        return;
12525      }
12526
12527      if (!NoexceptExpr->isValueDependent())
12528        NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
12529                         diag::err_noexcept_needs_constant_expression,
12530                         /*AllowFold*/ false).take();
12531      EPI.NoexceptExpr = NoexceptExpr;
12532    }
12533    return;
12534  }
12535}
12536
12537/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12538Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12539  // Implicitly declared functions (e.g. copy constructors) are
12540  // __host__ __device__
12541  if (D->isImplicit())
12542    return CFT_HostDevice;
12543
12544  if (D->hasAttr<CUDAGlobalAttr>())
12545    return CFT_Global;
12546
12547  if (D->hasAttr<CUDADeviceAttr>()) {
12548    if (D->hasAttr<CUDAHostAttr>())
12549      return CFT_HostDevice;
12550    return CFT_Device;
12551  }
12552
12553  return CFT_Host;
12554}
12555
12556bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12557                           CUDAFunctionTarget CalleeTarget) {
12558  // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12559  // Callable from the device only."
12560  if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12561    return true;
12562
12563  // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12564  // Callable from the host only."
12565  // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12566  // Callable from the host only."
12567  if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12568      (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12569    return true;
12570
12571  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12572    return true;
12573
12574  return false;
12575}
12576
12577/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12578///
12579MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12580                                       SourceLocation DeclStart,
12581                                       Declarator &D, Expr *BitWidth,
12582                                       InClassInitStyle InitStyle,
12583                                       AccessSpecifier AS,
12584                                       AttributeList *MSPropertyAttr) {
12585  IdentifierInfo *II = D.getIdentifier();
12586  if (!II) {
12587    Diag(DeclStart, diag::err_anonymous_property);
12588    return NULL;
12589  }
12590  SourceLocation Loc = D.getIdentifierLoc();
12591
12592  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12593  QualType T = TInfo->getType();
12594  if (getLangOpts().CPlusPlus) {
12595    CheckExtraCXXDefaultArguments(D);
12596
12597    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12598                                        UPPC_DataMemberType)) {
12599      D.setInvalidType();
12600      T = Context.IntTy;
12601      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12602    }
12603  }
12604
12605  DiagnoseFunctionSpecifiers(D.getDeclSpec());
12606
12607  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12608    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12609         diag::err_invalid_thread)
12610      << DeclSpec::getSpecifierName(TSCS);
12611
12612  // Check to see if this name was declared as a member previously
12613  NamedDecl *PrevDecl = 0;
12614  LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12615  LookupName(Previous, S);
12616  switch (Previous.getResultKind()) {
12617  case LookupResult::Found:
12618  case LookupResult::FoundUnresolvedValue:
12619    PrevDecl = Previous.getAsSingle<NamedDecl>();
12620    break;
12621
12622  case LookupResult::FoundOverloaded:
12623    PrevDecl = Previous.getRepresentativeDecl();
12624    break;
12625
12626  case LookupResult::NotFound:
12627  case LookupResult::NotFoundInCurrentInstantiation:
12628  case LookupResult::Ambiguous:
12629    break;
12630  }
12631
12632  if (PrevDecl && PrevDecl->isTemplateParameter()) {
12633    // Maybe we will complain about the shadowed template parameter.
12634    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12635    // Just pretend that we didn't see the previous declaration.
12636    PrevDecl = 0;
12637  }
12638
12639  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12640    PrevDecl = 0;
12641
12642  SourceLocation TSSL = D.getLocStart();
12643  MSPropertyDecl *NewPD;
12644  const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12645  NewPD = new (Context) MSPropertyDecl(Record, Loc,
12646                                       II, T, TInfo, TSSL,
12647                                       Data.GetterId, Data.SetterId);
12648  ProcessDeclAttributes(TUScope, NewPD, D);
12649  NewPD->setAccess(AS);
12650
12651  if (NewPD->isInvalidDecl())
12652    Record->setInvalidDecl();
12653
12654  if (D.getDeclSpec().isModulePrivateSpecified())
12655    NewPD->setModulePrivate();
12656
12657  if (NewPD->isInvalidDecl() && PrevDecl) {
12658    // Don't introduce NewFD into scope; there's already something
12659    // with the same name in the same scope.
12660  } else if (II) {
12661    PushOnScopeChains(NewPD, S);
12662  } else
12663    Record->addDecl(NewPD);
12664
12665  return NewPD;
12666}
12667