SemaDeclCXX.cpp revision 0162c1ce296fc48fbe03a31a2ae00b939eef86a8
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclVisitor.h"
21#include "clang/AST/EvaluatedExprVisitor.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/RecordLayout.h"
24#include "clang/AST/RecursiveASTVisitor.h"
25#include "clang/AST/StmtVisitor.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/AST/TypeOrdering.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/SmallString.h"
40#include <map>
41#include <set>
42
43using namespace clang;
44
45//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
49namespace {
50  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51  /// the default argument of a parameter to determine whether it
52  /// contains any ill-formed subexpressions. For example, this will
53  /// diagnose the use of local variables or parameters within the
54  /// default argument expression.
55  class CheckDefaultArgumentVisitor
56    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
57    Expr *DefaultArg;
58    Sema *S;
59
60  public:
61    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
62      : DefaultArg(defarg), S(s) {}
63
64    bool VisitExpr(Expr *Node);
65    bool VisitDeclRefExpr(DeclRefExpr *DRE);
66    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
67    bool VisitLambdaExpr(LambdaExpr *Lambda);
68  };
69
70  /// VisitExpr - Visit all of the children of this expression.
71  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
72    bool IsInvalid = false;
73    for (Stmt::child_range I = Node->children(); I; ++I)
74      IsInvalid |= Visit(*I);
75    return IsInvalid;
76  }
77
78  /// VisitDeclRefExpr - Visit a reference to a declaration, to
79  /// determine whether this declaration can be used in the default
80  /// argument expression.
81  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
82    NamedDecl *Decl = DRE->getDecl();
83    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
84      // C++ [dcl.fct.default]p9
85      //   Default arguments are evaluated each time the function is
86      //   called. The order of evaluation of function arguments is
87      //   unspecified. Consequently, parameters of a function shall not
88      //   be used in default argument expressions, even if they are not
89      //   evaluated. Parameters of a function declared before a default
90      //   argument expression are in scope and can hide namespace and
91      //   class member names.
92      return S->Diag(DRE->getLocStart(),
93                     diag::err_param_default_argument_references_param)
94         << Param->getDeclName() << DefaultArg->getSourceRange();
95    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
96      // C++ [dcl.fct.default]p7
97      //   Local variables shall not be used in default argument
98      //   expressions.
99      if (VDecl->isLocalVarDecl())
100        return S->Diag(DRE->getLocStart(),
101                       diag::err_param_default_argument_references_local)
102          << VDecl->getDeclName() << DefaultArg->getSourceRange();
103    }
104
105    return false;
106  }
107
108  /// VisitCXXThisExpr - Visit a C++ "this" expression.
109  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
110    // C++ [dcl.fct.default]p8:
111    //   The keyword this shall not be used in a default argument of a
112    //   member function.
113    return S->Diag(ThisE->getLocStart(),
114                   diag::err_param_default_argument_references_this)
115               << ThisE->getSourceRange();
116  }
117
118  bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
119    // C++11 [expr.lambda.prim]p13:
120    //   A lambda-expression appearing in a default argument shall not
121    //   implicitly or explicitly capture any entity.
122    if (Lambda->capture_begin() == Lambda->capture_end())
123      return false;
124
125    return S->Diag(Lambda->getLocStart(),
126                   diag::err_lambda_capture_default_arg);
127  }
128}
129
130void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
131                                                      CXXMethodDecl *Method) {
132  // If we have an MSAny spec already, don't bother.
133  if (!Method || ComputedEST == EST_MSAny)
134    return;
135
136  const FunctionProtoType *Proto
137    = Method->getType()->getAs<FunctionProtoType>();
138  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
139  if (!Proto)
140    return;
141
142  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
143
144  // If this function can throw any exceptions, make a note of that.
145  if (EST == EST_MSAny || EST == EST_None) {
146    ClearExceptions();
147    ComputedEST = EST;
148    return;
149  }
150
151  // FIXME: If the call to this decl is using any of its default arguments, we
152  // need to search them for potentially-throwing calls.
153
154  // If this function has a basic noexcept, it doesn't affect the outcome.
155  if (EST == EST_BasicNoexcept)
156    return;
157
158  // If we have a throw-all spec at this point, ignore the function.
159  if (ComputedEST == EST_None)
160    return;
161
162  // If we're still at noexcept(true) and there's a nothrow() callee,
163  // change to that specification.
164  if (EST == EST_DynamicNone) {
165    if (ComputedEST == EST_BasicNoexcept)
166      ComputedEST = EST_DynamicNone;
167    return;
168  }
169
170  // Check out noexcept specs.
171  if (EST == EST_ComputedNoexcept) {
172    FunctionProtoType::NoexceptResult NR =
173        Proto->getNoexceptSpec(Self->Context);
174    assert(NR != FunctionProtoType::NR_NoNoexcept &&
175           "Must have noexcept result for EST_ComputedNoexcept.");
176    assert(NR != FunctionProtoType::NR_Dependent &&
177           "Should not generate implicit declarations for dependent cases, "
178           "and don't know how to handle them anyway.");
179
180    // noexcept(false) -> no spec on the new function
181    if (NR == FunctionProtoType::NR_Throw) {
182      ClearExceptions();
183      ComputedEST = EST_None;
184    }
185    // noexcept(true) won't change anything either.
186    return;
187  }
188
189  assert(EST == EST_Dynamic && "EST case not considered earlier.");
190  assert(ComputedEST != EST_None &&
191         "Shouldn't collect exceptions when throw-all is guaranteed.");
192  ComputedEST = EST_Dynamic;
193  // Record the exceptions in this function's exception specification.
194  for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
195                                          EEnd = Proto->exception_end();
196       E != EEnd; ++E)
197    if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
198      Exceptions.push_back(*E);
199}
200
201void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
202  if (!E || ComputedEST == EST_MSAny)
203    return;
204
205  // FIXME:
206  //
207  // C++0x [except.spec]p14:
208  //   [An] implicit exception-specification specifies the type-id T if and
209  // only if T is allowed by the exception-specification of a function directly
210  // invoked by f's implicit definition; f shall allow all exceptions if any
211  // function it directly invokes allows all exceptions, and f shall allow no
212  // exceptions if every function it directly invokes allows no exceptions.
213  //
214  // Note in particular that if an implicit exception-specification is generated
215  // for a function containing a throw-expression, that specification can still
216  // be noexcept(true).
217  //
218  // Note also that 'directly invoked' is not defined in the standard, and there
219  // is no indication that we should only consider potentially-evaluated calls.
220  //
221  // Ultimately we should implement the intent of the standard: the exception
222  // specification should be the set of exceptions which can be thrown by the
223  // implicit definition. For now, we assume that any non-nothrow expression can
224  // throw any exception.
225
226  if (Self->canThrow(E))
227    ComputedEST = EST_None;
228}
229
230bool
231Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
232                              SourceLocation EqualLoc) {
233  if (RequireCompleteType(Param->getLocation(), Param->getType(),
234                          diag::err_typecheck_decl_incomplete_type)) {
235    Param->setInvalidDecl();
236    return true;
237  }
238
239  // C++ [dcl.fct.default]p5
240  //   A default argument expression is implicitly converted (clause
241  //   4) to the parameter type. The default argument expression has
242  //   the same semantic constraints as the initializer expression in
243  //   a declaration of a variable of the parameter type, using the
244  //   copy-initialization semantics (8.5).
245  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
246                                                                    Param);
247  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
248                                                           EqualLoc);
249  InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
250  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
251  if (Result.isInvalid())
252    return true;
253  Arg = Result.takeAs<Expr>();
254
255  CheckCompletedExpr(Arg, EqualLoc);
256  Arg = MaybeCreateExprWithCleanups(Arg);
257
258  // Okay: add the default argument to the parameter
259  Param->setDefaultArg(Arg);
260
261  // We have already instantiated this parameter; provide each of the
262  // instantiations with the uninstantiated default argument.
263  UnparsedDefaultArgInstantiationsMap::iterator InstPos
264    = UnparsedDefaultArgInstantiations.find(Param);
265  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
266    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
267      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
268
269    // We're done tracking this parameter's instantiations.
270    UnparsedDefaultArgInstantiations.erase(InstPos);
271  }
272
273  return false;
274}
275
276/// ActOnParamDefaultArgument - Check whether the default argument
277/// provided for a function parameter is well-formed. If so, attach it
278/// to the parameter declaration.
279void
280Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
281                                Expr *DefaultArg) {
282  if (!param || !DefaultArg)
283    return;
284
285  ParmVarDecl *Param = cast<ParmVarDecl>(param);
286  UnparsedDefaultArgLocs.erase(Param);
287
288  // Default arguments are only permitted in C++
289  if (!getLangOpts().CPlusPlus) {
290    Diag(EqualLoc, diag::err_param_default_argument)
291      << DefaultArg->getSourceRange();
292    Param->setInvalidDecl();
293    return;
294  }
295
296  // Check for unexpanded parameter packs.
297  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
298    Param->setInvalidDecl();
299    return;
300  }
301
302  // Check that the default argument is well-formed
303  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
304  if (DefaultArgChecker.Visit(DefaultArg)) {
305    Param->setInvalidDecl();
306    return;
307  }
308
309  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
310}
311
312/// ActOnParamUnparsedDefaultArgument - We've seen a default
313/// argument for a function parameter, but we can't parse it yet
314/// because we're inside a class definition. Note that this default
315/// argument will be parsed later.
316void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
317                                             SourceLocation EqualLoc,
318                                             SourceLocation ArgLoc) {
319  if (!param)
320    return;
321
322  ParmVarDecl *Param = cast<ParmVarDecl>(param);
323  if (Param)
324    Param->setUnparsedDefaultArg();
325
326  UnparsedDefaultArgLocs[Param] = ArgLoc;
327}
328
329/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
330/// the default argument for the parameter param failed.
331void Sema::ActOnParamDefaultArgumentError(Decl *param) {
332  if (!param)
333    return;
334
335  ParmVarDecl *Param = cast<ParmVarDecl>(param);
336
337  Param->setInvalidDecl();
338
339  UnparsedDefaultArgLocs.erase(Param);
340}
341
342/// CheckExtraCXXDefaultArguments - Check for any extra default
343/// arguments in the declarator, which is not a function declaration
344/// or definition and therefore is not permitted to have default
345/// arguments. This routine should be invoked for every declarator
346/// that is not a function declaration or definition.
347void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
348  // C++ [dcl.fct.default]p3
349  //   A default argument expression shall be specified only in the
350  //   parameter-declaration-clause of a function declaration or in a
351  //   template-parameter (14.1). It shall not be specified for a
352  //   parameter pack. If it is specified in a
353  //   parameter-declaration-clause, it shall not occur within a
354  //   declarator or abstract-declarator of a parameter-declaration.
355  bool MightBeFunction = D.isFunctionDeclarationContext();
356  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
357    DeclaratorChunk &chunk = D.getTypeObject(i);
358    if (chunk.Kind == DeclaratorChunk::Function) {
359      if (MightBeFunction) {
360        // This is a function declaration. It can have default arguments, but
361        // keep looking in case its return type is a function type with default
362        // arguments.
363        MightBeFunction = false;
364        continue;
365      }
366      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
367        ParmVarDecl *Param =
368          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
369        if (Param->hasUnparsedDefaultArg()) {
370          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
371          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
372            << SourceRange((*Toks)[1].getLocation(),
373                           Toks->back().getLocation());
374          delete Toks;
375          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
376        } else if (Param->getDefaultArg()) {
377          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
378            << Param->getDefaultArg()->getSourceRange();
379          Param->setDefaultArg(0);
380        }
381      }
382    } else if (chunk.Kind != DeclaratorChunk::Paren) {
383      MightBeFunction = false;
384    }
385  }
386}
387
388/// MergeCXXFunctionDecl - Merge two declarations of the same C++
389/// function, once we already know that they have the same
390/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
391/// error, false otherwise.
392bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
393                                Scope *S) {
394  bool Invalid = false;
395
396  // C++ [dcl.fct.default]p4:
397  //   For non-template functions, default arguments can be added in
398  //   later declarations of a function in the same
399  //   scope. Declarations in different scopes have completely
400  //   distinct sets of default arguments. That is, declarations in
401  //   inner scopes do not acquire default arguments from
402  //   declarations in outer scopes, and vice versa. In a given
403  //   function declaration, all parameters subsequent to a
404  //   parameter with a default argument shall have default
405  //   arguments supplied in this or previous declarations. A
406  //   default argument shall not be redefined by a later
407  //   declaration (not even to the same value).
408  //
409  // C++ [dcl.fct.default]p6:
410  //   Except for member functions of class templates, the default arguments
411  //   in a member function definition that appears outside of the class
412  //   definition are added to the set of default arguments provided by the
413  //   member function declaration in the class definition.
414  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
415    ParmVarDecl *OldParam = Old->getParamDecl(p);
416    ParmVarDecl *NewParam = New->getParamDecl(p);
417
418    bool OldParamHasDfl = OldParam->hasDefaultArg();
419    bool NewParamHasDfl = NewParam->hasDefaultArg();
420
421    NamedDecl *ND = Old;
422    if (S && !isDeclInScope(ND, New->getDeclContext(), S))
423      // Ignore default parameters of old decl if they are not in
424      // the same scope.
425      OldParamHasDfl = false;
426
427    if (OldParamHasDfl && NewParamHasDfl) {
428
429      unsigned DiagDefaultParamID =
430        diag::err_param_default_argument_redefinition;
431
432      // MSVC accepts that default parameters be redefined for member functions
433      // of template class. The new default parameter's value is ignored.
434      Invalid = true;
435      if (getLangOpts().MicrosoftExt) {
436        CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
437        if (MD && MD->getParent()->getDescribedClassTemplate()) {
438          // Merge the old default argument into the new parameter.
439          NewParam->setHasInheritedDefaultArg();
440          if (OldParam->hasUninstantiatedDefaultArg())
441            NewParam->setUninstantiatedDefaultArg(
442                                      OldParam->getUninstantiatedDefaultArg());
443          else
444            NewParam->setDefaultArg(OldParam->getInit());
445          DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
446          Invalid = false;
447        }
448      }
449
450      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
451      // hint here. Alternatively, we could walk the type-source information
452      // for NewParam to find the last source location in the type... but it
453      // isn't worth the effort right now. This is the kind of test case that
454      // is hard to get right:
455      //   int f(int);
456      //   void g(int (*fp)(int) = f);
457      //   void g(int (*fp)(int) = &f);
458      Diag(NewParam->getLocation(), DiagDefaultParamID)
459        << NewParam->getDefaultArgRange();
460
461      // Look for the function declaration where the default argument was
462      // actually written, which may be a declaration prior to Old.
463      for (FunctionDecl *Older = Old->getPreviousDecl();
464           Older; Older = Older->getPreviousDecl()) {
465        if (!Older->getParamDecl(p)->hasDefaultArg())
466          break;
467
468        OldParam = Older->getParamDecl(p);
469      }
470
471      Diag(OldParam->getLocation(), diag::note_previous_definition)
472        << OldParam->getDefaultArgRange();
473    } else if (OldParamHasDfl) {
474      // Merge the old default argument into the new parameter.
475      // It's important to use getInit() here;  getDefaultArg()
476      // strips off any top-level ExprWithCleanups.
477      NewParam->setHasInheritedDefaultArg();
478      if (OldParam->hasUninstantiatedDefaultArg())
479        NewParam->setUninstantiatedDefaultArg(
480                                      OldParam->getUninstantiatedDefaultArg());
481      else
482        NewParam->setDefaultArg(OldParam->getInit());
483    } else if (NewParamHasDfl) {
484      if (New->getDescribedFunctionTemplate()) {
485        // Paragraph 4, quoted above, only applies to non-template functions.
486        Diag(NewParam->getLocation(),
487             diag::err_param_default_argument_template_redecl)
488          << NewParam->getDefaultArgRange();
489        Diag(Old->getLocation(), diag::note_template_prev_declaration)
490          << false;
491      } else if (New->getTemplateSpecializationKind()
492                   != TSK_ImplicitInstantiation &&
493                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
494        // C++ [temp.expr.spec]p21:
495        //   Default function arguments shall not be specified in a declaration
496        //   or a definition for one of the following explicit specializations:
497        //     - the explicit specialization of a function template;
498        //     - the explicit specialization of a member function template;
499        //     - the explicit specialization of a member function of a class
500        //       template where the class template specialization to which the
501        //       member function specialization belongs is implicitly
502        //       instantiated.
503        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
504          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
505          << New->getDeclName()
506          << NewParam->getDefaultArgRange();
507      } else if (New->getDeclContext()->isDependentContext()) {
508        // C++ [dcl.fct.default]p6 (DR217):
509        //   Default arguments for a member function of a class template shall
510        //   be specified on the initial declaration of the member function
511        //   within the class template.
512        //
513        // Reading the tea leaves a bit in DR217 and its reference to DR205
514        // leads me to the conclusion that one cannot add default function
515        // arguments for an out-of-line definition of a member function of a
516        // dependent type.
517        int WhichKind = 2;
518        if (CXXRecordDecl *Record
519              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
520          if (Record->getDescribedClassTemplate())
521            WhichKind = 0;
522          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
523            WhichKind = 1;
524          else
525            WhichKind = 2;
526        }
527
528        Diag(NewParam->getLocation(),
529             diag::err_param_default_argument_member_template_redecl)
530          << WhichKind
531          << NewParam->getDefaultArgRange();
532      }
533    }
534  }
535
536  // DR1344: If a default argument is added outside a class definition and that
537  // default argument makes the function a special member function, the program
538  // is ill-formed. This can only happen for constructors.
539  if (isa<CXXConstructorDecl>(New) &&
540      New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
541    CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
542                     OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
543    if (NewSM != OldSM) {
544      ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
545      assert(NewParam->hasDefaultArg());
546      Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
547        << NewParam->getDefaultArgRange() << NewSM;
548      Diag(Old->getLocation(), diag::note_previous_declaration);
549    }
550  }
551
552  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
553  // template has a constexpr specifier then all its declarations shall
554  // contain the constexpr specifier.
555  if (New->isConstexpr() != Old->isConstexpr()) {
556    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
557      << New << New->isConstexpr();
558    Diag(Old->getLocation(), diag::note_previous_declaration);
559    Invalid = true;
560  }
561
562  if (CheckEquivalentExceptionSpec(Old, New))
563    Invalid = true;
564
565  return Invalid;
566}
567
568/// \brief Merge the exception specifications of two variable declarations.
569///
570/// This is called when there's a redeclaration of a VarDecl. The function
571/// checks if the redeclaration might have an exception specification and
572/// validates compatibility and merges the specs if necessary.
573void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
574  // Shortcut if exceptions are disabled.
575  if (!getLangOpts().CXXExceptions)
576    return;
577
578  assert(Context.hasSameType(New->getType(), Old->getType()) &&
579         "Should only be called if types are otherwise the same.");
580
581  QualType NewType = New->getType();
582  QualType OldType = Old->getType();
583
584  // We're only interested in pointers and references to functions, as well
585  // as pointers to member functions.
586  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
587    NewType = R->getPointeeType();
588    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
589  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
590    NewType = P->getPointeeType();
591    OldType = OldType->getAs<PointerType>()->getPointeeType();
592  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
593    NewType = M->getPointeeType();
594    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
595  }
596
597  if (!NewType->isFunctionProtoType())
598    return;
599
600  // There's lots of special cases for functions. For function pointers, system
601  // libraries are hopefully not as broken so that we don't need these
602  // workarounds.
603  if (CheckEquivalentExceptionSpec(
604        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
605        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
606    New->setInvalidDecl();
607  }
608}
609
610/// CheckCXXDefaultArguments - Verify that the default arguments for a
611/// function declaration are well-formed according to C++
612/// [dcl.fct.default].
613void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
614  unsigned NumParams = FD->getNumParams();
615  unsigned p;
616
617  bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
618                  isa<CXXMethodDecl>(FD) &&
619                  cast<CXXMethodDecl>(FD)->getParent()->isLambda();
620
621  // Find first parameter with a default argument
622  for (p = 0; p < NumParams; ++p) {
623    ParmVarDecl *Param = FD->getParamDecl(p);
624    if (Param->hasDefaultArg()) {
625      // C++11 [expr.prim.lambda]p5:
626      //   [...] Default arguments (8.3.6) shall not be specified in the
627      //   parameter-declaration-clause of a lambda-declarator.
628      //
629      // FIXME: Core issue 974 strikes this sentence, we only provide an
630      // extension warning.
631      if (IsLambda)
632        Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
633          << Param->getDefaultArgRange();
634      break;
635    }
636  }
637
638  // C++ [dcl.fct.default]p4:
639  //   In a given function declaration, all parameters
640  //   subsequent to a parameter with a default argument shall
641  //   have default arguments supplied in this or previous
642  //   declarations. A default argument shall not be redefined
643  //   by a later declaration (not even to the same value).
644  unsigned LastMissingDefaultArg = 0;
645  for (; p < NumParams; ++p) {
646    ParmVarDecl *Param = FD->getParamDecl(p);
647    if (!Param->hasDefaultArg()) {
648      if (Param->isInvalidDecl())
649        /* We already complained about this parameter. */;
650      else if (Param->getIdentifier())
651        Diag(Param->getLocation(),
652             diag::err_param_default_argument_missing_name)
653          << Param->getIdentifier();
654      else
655        Diag(Param->getLocation(),
656             diag::err_param_default_argument_missing);
657
658      LastMissingDefaultArg = p;
659    }
660  }
661
662  if (LastMissingDefaultArg > 0) {
663    // Some default arguments were missing. Clear out all of the
664    // default arguments up to (and including) the last missing
665    // default argument, so that we leave the function parameters
666    // in a semantically valid state.
667    for (p = 0; p <= LastMissingDefaultArg; ++p) {
668      ParmVarDecl *Param = FD->getParamDecl(p);
669      if (Param->hasDefaultArg()) {
670        Param->setDefaultArg(0);
671      }
672    }
673  }
674}
675
676// CheckConstexprParameterTypes - Check whether a function's parameter types
677// are all literal types. If so, return true. If not, produce a suitable
678// diagnostic and return false.
679static bool CheckConstexprParameterTypes(Sema &SemaRef,
680                                         const FunctionDecl *FD) {
681  unsigned ArgIndex = 0;
682  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
683  for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
684       e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
685    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
686    SourceLocation ParamLoc = PD->getLocation();
687    if (!(*i)->isDependentType() &&
688        SemaRef.RequireLiteralType(ParamLoc, *i,
689                                   diag::err_constexpr_non_literal_param,
690                                   ArgIndex+1, PD->getSourceRange(),
691                                   isa<CXXConstructorDecl>(FD)))
692      return false;
693  }
694  return true;
695}
696
697/// \brief Get diagnostic %select index for tag kind for
698/// record diagnostic message.
699/// WARNING: Indexes apply to particular diagnostics only!
700///
701/// \returns diagnostic %select index.
702static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
703  switch (Tag) {
704  case TTK_Struct: return 0;
705  case TTK_Interface: return 1;
706  case TTK_Class:  return 2;
707  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
708  }
709}
710
711// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
712// the requirements of a constexpr function definition or a constexpr
713// constructor definition. If so, return true. If not, produce appropriate
714// diagnostics and return false.
715//
716// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
717bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
718  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
719  if (MD && MD->isInstance()) {
720    // C++11 [dcl.constexpr]p4:
721    //  The definition of a constexpr constructor shall satisfy the following
722    //  constraints:
723    //  - the class shall not have any virtual base classes;
724    const CXXRecordDecl *RD = MD->getParent();
725    if (RD->getNumVBases()) {
726      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
727        << isa<CXXConstructorDecl>(NewFD)
728        << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
729      for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
730             E = RD->vbases_end(); I != E; ++I)
731        Diag(I->getLocStart(),
732             diag::note_constexpr_virtual_base_here) << I->getSourceRange();
733      return false;
734    }
735  }
736
737  if (!isa<CXXConstructorDecl>(NewFD)) {
738    // C++11 [dcl.constexpr]p3:
739    //  The definition of a constexpr function shall satisfy the following
740    //  constraints:
741    // - it shall not be virtual;
742    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
743    if (Method && Method->isVirtual()) {
744      Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
745
746      // If it's not obvious why this function is virtual, find an overridden
747      // function which uses the 'virtual' keyword.
748      const CXXMethodDecl *WrittenVirtual = Method;
749      while (!WrittenVirtual->isVirtualAsWritten())
750        WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
751      if (WrittenVirtual != Method)
752        Diag(WrittenVirtual->getLocation(),
753             diag::note_overridden_virtual_function);
754      return false;
755    }
756
757    // - its return type shall be a literal type;
758    QualType RT = NewFD->getResultType();
759    if (!RT->isDependentType() &&
760        RequireLiteralType(NewFD->getLocation(), RT,
761                           diag::err_constexpr_non_literal_return))
762      return false;
763  }
764
765  // - each of its parameter types shall be a literal type;
766  if (!CheckConstexprParameterTypes(*this, NewFD))
767    return false;
768
769  return true;
770}
771
772/// Check the given declaration statement is legal within a constexpr function
773/// body. C++0x [dcl.constexpr]p3,p4.
774///
775/// \return true if the body is OK, false if we have diagnosed a problem.
776static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
777                                   DeclStmt *DS) {
778  // C++0x [dcl.constexpr]p3 and p4:
779  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
780  //  contain only
781  for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
782         DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
783    switch ((*DclIt)->getKind()) {
784    case Decl::StaticAssert:
785    case Decl::Using:
786    case Decl::UsingShadow:
787    case Decl::UsingDirective:
788    case Decl::UnresolvedUsingTypename:
789      //   - static_assert-declarations
790      //   - using-declarations,
791      //   - using-directives,
792      continue;
793
794    case Decl::Typedef:
795    case Decl::TypeAlias: {
796      //   - typedef declarations and alias-declarations that do not define
797      //     classes or enumerations,
798      TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
799      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
800        // Don't allow variably-modified types in constexpr functions.
801        TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
802        SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
803          << TL.getSourceRange() << TL.getType()
804          << isa<CXXConstructorDecl>(Dcl);
805        return false;
806      }
807      continue;
808    }
809
810    case Decl::Enum:
811    case Decl::CXXRecord:
812      // As an extension, we allow the declaration (but not the definition) of
813      // classes and enumerations in all declarations, not just in typedef and
814      // alias declarations.
815      if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
816        SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
817          << isa<CXXConstructorDecl>(Dcl);
818        return false;
819      }
820      continue;
821
822    case Decl::Var:
823      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
824        << isa<CXXConstructorDecl>(Dcl);
825      return false;
826
827    default:
828      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
829        << isa<CXXConstructorDecl>(Dcl);
830      return false;
831    }
832  }
833
834  return true;
835}
836
837/// Check that the given field is initialized within a constexpr constructor.
838///
839/// \param Dcl The constexpr constructor being checked.
840/// \param Field The field being checked. This may be a member of an anonymous
841///        struct or union nested within the class being checked.
842/// \param Inits All declarations, including anonymous struct/union members and
843///        indirect members, for which any initialization was provided.
844/// \param Diagnosed Set to true if an error is produced.
845static void CheckConstexprCtorInitializer(Sema &SemaRef,
846                                          const FunctionDecl *Dcl,
847                                          FieldDecl *Field,
848                                          llvm::SmallSet<Decl*, 16> &Inits,
849                                          bool &Diagnosed) {
850  if (Field->isUnnamedBitfield())
851    return;
852
853  if (Field->isAnonymousStructOrUnion() &&
854      Field->getType()->getAsCXXRecordDecl()->isEmpty())
855    return;
856
857  if (!Inits.count(Field)) {
858    if (!Diagnosed) {
859      SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
860      Diagnosed = true;
861    }
862    SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
863  } else if (Field->isAnonymousStructOrUnion()) {
864    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
865    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
866         I != E; ++I)
867      // If an anonymous union contains an anonymous struct of which any member
868      // is initialized, all members must be initialized.
869      if (!RD->isUnion() || Inits.count(*I))
870        CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
871  }
872}
873
874/// Check the body for the given constexpr function declaration only contains
875/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
876///
877/// \return true if the body is OK, false if we have diagnosed a problem.
878bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
879  if (isa<CXXTryStmt>(Body)) {
880    // C++11 [dcl.constexpr]p3:
881    //  The definition of a constexpr function shall satisfy the following
882    //  constraints: [...]
883    // - its function-body shall be = delete, = default, or a
884    //   compound-statement
885    //
886    // C++11 [dcl.constexpr]p4:
887    //  In the definition of a constexpr constructor, [...]
888    // - its function-body shall not be a function-try-block;
889    Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
890      << isa<CXXConstructorDecl>(Dcl);
891    return false;
892  }
893
894  // - its function-body shall be [...] a compound-statement that contains only
895  CompoundStmt *CompBody = cast<CompoundStmt>(Body);
896
897  SmallVector<SourceLocation, 4> ReturnStmts;
898  for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
899         BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
900    switch ((*BodyIt)->getStmtClass()) {
901    case Stmt::NullStmtClass:
902      //   - null statements,
903      continue;
904
905    case Stmt::DeclStmtClass:
906      //   - static_assert-declarations
907      //   - using-declarations,
908      //   - using-directives,
909      //   - typedef declarations and alias-declarations that do not define
910      //     classes or enumerations,
911      if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
912        return false;
913      continue;
914
915    case Stmt::ReturnStmtClass:
916      //   - and exactly one return statement;
917      if (isa<CXXConstructorDecl>(Dcl))
918        break;
919
920      ReturnStmts.push_back((*BodyIt)->getLocStart());
921      continue;
922
923    default:
924      break;
925    }
926
927    Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
928      << isa<CXXConstructorDecl>(Dcl);
929    return false;
930  }
931
932  if (const CXXConstructorDecl *Constructor
933        = dyn_cast<CXXConstructorDecl>(Dcl)) {
934    const CXXRecordDecl *RD = Constructor->getParent();
935    // DR1359:
936    // - every non-variant non-static data member and base class sub-object
937    //   shall be initialized;
938    // - if the class is a non-empty union, or for each non-empty anonymous
939    //   union member of a non-union class, exactly one non-static data member
940    //   shall be initialized;
941    if (RD->isUnion()) {
942      if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
943        Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
944        return false;
945      }
946    } else if (!Constructor->isDependentContext() &&
947               !Constructor->isDelegatingConstructor()) {
948      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
949
950      // Skip detailed checking if we have enough initializers, and we would
951      // allow at most one initializer per member.
952      bool AnyAnonStructUnionMembers = false;
953      unsigned Fields = 0;
954      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
955           E = RD->field_end(); I != E; ++I, ++Fields) {
956        if (I->isAnonymousStructOrUnion()) {
957          AnyAnonStructUnionMembers = true;
958          break;
959        }
960      }
961      if (AnyAnonStructUnionMembers ||
962          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
963        // Check initialization of non-static data members. Base classes are
964        // always initialized so do not need to be checked. Dependent bases
965        // might not have initializers in the member initializer list.
966        llvm::SmallSet<Decl*, 16> Inits;
967        for (CXXConstructorDecl::init_const_iterator
968               I = Constructor->init_begin(), E = Constructor->init_end();
969             I != E; ++I) {
970          if (FieldDecl *FD = (*I)->getMember())
971            Inits.insert(FD);
972          else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
973            Inits.insert(ID->chain_begin(), ID->chain_end());
974        }
975
976        bool Diagnosed = false;
977        for (CXXRecordDecl::field_iterator I = RD->field_begin(),
978             E = RD->field_end(); I != E; ++I)
979          CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
980        if (Diagnosed)
981          return false;
982      }
983    }
984  } else {
985    if (ReturnStmts.empty()) {
986      Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
987      return false;
988    }
989    if (ReturnStmts.size() > 1) {
990      Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
991      for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
992        Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
993      return false;
994    }
995  }
996
997  // C++11 [dcl.constexpr]p5:
998  //   if no function argument values exist such that the function invocation
999  //   substitution would produce a constant expression, the program is
1000  //   ill-formed; no diagnostic required.
1001  // C++11 [dcl.constexpr]p3:
1002  //   - every constructor call and implicit conversion used in initializing the
1003  //     return value shall be one of those allowed in a constant expression.
1004  // C++11 [dcl.constexpr]p4:
1005  //   - every constructor involved in initializing non-static data members and
1006  //     base class sub-objects shall be a constexpr constructor.
1007  SmallVector<PartialDiagnosticAt, 8> Diags;
1008  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1009    Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1010      << isa<CXXConstructorDecl>(Dcl);
1011    for (size_t I = 0, N = Diags.size(); I != N; ++I)
1012      Diag(Diags[I].first, Diags[I].second);
1013    // Don't return false here: we allow this for compatibility in
1014    // system headers.
1015  }
1016
1017  return true;
1018}
1019
1020/// isCurrentClassName - Determine whether the identifier II is the
1021/// name of the class type currently being defined. In the case of
1022/// nested classes, this will only return true if II is the name of
1023/// the innermost class.
1024bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1025                              const CXXScopeSpec *SS) {
1026  assert(getLangOpts().CPlusPlus && "No class names in C!");
1027
1028  CXXRecordDecl *CurDecl;
1029  if (SS && SS->isSet() && !SS->isInvalid()) {
1030    DeclContext *DC = computeDeclContext(*SS, true);
1031    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1032  } else
1033    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1034
1035  if (CurDecl && CurDecl->getIdentifier())
1036    return &II == CurDecl->getIdentifier();
1037  else
1038    return false;
1039}
1040
1041/// \brief Determine whether the given class is a base class of the given
1042/// class, including looking at dependent bases.
1043static bool findCircularInheritance(const CXXRecordDecl *Class,
1044                                    const CXXRecordDecl *Current) {
1045  SmallVector<const CXXRecordDecl*, 8> Queue;
1046
1047  Class = Class->getCanonicalDecl();
1048  while (true) {
1049    for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1050                                                  E = Current->bases_end();
1051         I != E; ++I) {
1052      CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1053      if (!Base)
1054        continue;
1055
1056      Base = Base->getDefinition();
1057      if (!Base)
1058        continue;
1059
1060      if (Base->getCanonicalDecl() == Class)
1061        return true;
1062
1063      Queue.push_back(Base);
1064    }
1065
1066    if (Queue.empty())
1067      return false;
1068
1069    Current = Queue.back();
1070    Queue.pop_back();
1071  }
1072
1073  return false;
1074}
1075
1076/// \brief Check the validity of a C++ base class specifier.
1077///
1078/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1079/// and returns NULL otherwise.
1080CXXBaseSpecifier *
1081Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1082                         SourceRange SpecifierRange,
1083                         bool Virtual, AccessSpecifier Access,
1084                         TypeSourceInfo *TInfo,
1085                         SourceLocation EllipsisLoc) {
1086  QualType BaseType = TInfo->getType();
1087
1088  // C++ [class.union]p1:
1089  //   A union shall not have base classes.
1090  if (Class->isUnion()) {
1091    Diag(Class->getLocation(), diag::err_base_clause_on_union)
1092      << SpecifierRange;
1093    return 0;
1094  }
1095
1096  if (EllipsisLoc.isValid() &&
1097      !TInfo->getType()->containsUnexpandedParameterPack()) {
1098    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1099      << TInfo->getTypeLoc().getSourceRange();
1100    EllipsisLoc = SourceLocation();
1101  }
1102
1103  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1104
1105  if (BaseType->isDependentType()) {
1106    // Make sure that we don't have circular inheritance among our dependent
1107    // bases. For non-dependent bases, the check for completeness below handles
1108    // this.
1109    if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1110      if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1111          ((BaseDecl = BaseDecl->getDefinition()) &&
1112           findCircularInheritance(Class, BaseDecl))) {
1113        Diag(BaseLoc, diag::err_circular_inheritance)
1114          << BaseType << Context.getTypeDeclType(Class);
1115
1116        if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1117          Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1118            << BaseType;
1119
1120        return 0;
1121      }
1122    }
1123
1124    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1125                                          Class->getTagKind() == TTK_Class,
1126                                          Access, TInfo, EllipsisLoc);
1127  }
1128
1129  // Base specifiers must be record types.
1130  if (!BaseType->isRecordType()) {
1131    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1132    return 0;
1133  }
1134
1135  // C++ [class.union]p1:
1136  //   A union shall not be used as a base class.
1137  if (BaseType->isUnionType()) {
1138    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1139    return 0;
1140  }
1141
1142  // C++ [class.derived]p2:
1143  //   The class-name in a base-specifier shall not be an incompletely
1144  //   defined class.
1145  if (RequireCompleteType(BaseLoc, BaseType,
1146                          diag::err_incomplete_base_class, SpecifierRange)) {
1147    Class->setInvalidDecl();
1148    return 0;
1149  }
1150
1151  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1152  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1153  assert(BaseDecl && "Record type has no declaration");
1154  BaseDecl = BaseDecl->getDefinition();
1155  assert(BaseDecl && "Base type is not incomplete, but has no definition");
1156  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1157  assert(CXXBaseDecl && "Base type is not a C++ type");
1158
1159  // C++ [class]p3:
1160  //   If a class is marked final and it appears as a base-type-specifier in
1161  //   base-clause, the program is ill-formed.
1162  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1163    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1164      << CXXBaseDecl->getDeclName();
1165    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1166      << CXXBaseDecl->getDeclName();
1167    return 0;
1168  }
1169
1170  if (BaseDecl->isInvalidDecl())
1171    Class->setInvalidDecl();
1172
1173  // Create the base specifier.
1174  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1175                                        Class->getTagKind() == TTK_Class,
1176                                        Access, TInfo, EllipsisLoc);
1177}
1178
1179/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1180/// one entry in the base class list of a class specifier, for
1181/// example:
1182///    class foo : public bar, virtual private baz {
1183/// 'public bar' and 'virtual private baz' are each base-specifiers.
1184BaseResult
1185Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1186                         ParsedAttributes &Attributes,
1187                         bool Virtual, AccessSpecifier Access,
1188                         ParsedType basetype, SourceLocation BaseLoc,
1189                         SourceLocation EllipsisLoc) {
1190  if (!classdecl)
1191    return true;
1192
1193  AdjustDeclIfTemplate(classdecl);
1194  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1195  if (!Class)
1196    return true;
1197
1198  // We do not support any C++11 attributes on base-specifiers yet.
1199  // Diagnose any attributes we see.
1200  if (!Attributes.empty()) {
1201    for (AttributeList *Attr = Attributes.getList(); Attr;
1202         Attr = Attr->getNext()) {
1203      if (Attr->isInvalid() ||
1204          Attr->getKind() == AttributeList::IgnoredAttribute)
1205        continue;
1206      Diag(Attr->getLoc(),
1207           Attr->getKind() == AttributeList::UnknownAttribute
1208             ? diag::warn_unknown_attribute_ignored
1209             : diag::err_base_specifier_attribute)
1210        << Attr->getName();
1211    }
1212  }
1213
1214  TypeSourceInfo *TInfo = 0;
1215  GetTypeFromParser(basetype, &TInfo);
1216
1217  if (EllipsisLoc.isInvalid() &&
1218      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1219                                      UPPC_BaseType))
1220    return true;
1221
1222  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1223                                                      Virtual, Access, TInfo,
1224                                                      EllipsisLoc))
1225    return BaseSpec;
1226  else
1227    Class->setInvalidDecl();
1228
1229  return true;
1230}
1231
1232/// \brief Performs the actual work of attaching the given base class
1233/// specifiers to a C++ class.
1234bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1235                                unsigned NumBases) {
1236 if (NumBases == 0)
1237    return false;
1238
1239  // Used to keep track of which base types we have already seen, so
1240  // that we can properly diagnose redundant direct base types. Note
1241  // that the key is always the unqualified canonical type of the base
1242  // class.
1243  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1244
1245  // Copy non-redundant base specifiers into permanent storage.
1246  unsigned NumGoodBases = 0;
1247  bool Invalid = false;
1248  for (unsigned idx = 0; idx < NumBases; ++idx) {
1249    QualType NewBaseType
1250      = Context.getCanonicalType(Bases[idx]->getType());
1251    NewBaseType = NewBaseType.getLocalUnqualifiedType();
1252
1253    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1254    if (KnownBase) {
1255      // C++ [class.mi]p3:
1256      //   A class shall not be specified as a direct base class of a
1257      //   derived class more than once.
1258      Diag(Bases[idx]->getLocStart(),
1259           diag::err_duplicate_base_class)
1260        << KnownBase->getType()
1261        << Bases[idx]->getSourceRange();
1262
1263      // Delete the duplicate base class specifier; we're going to
1264      // overwrite its pointer later.
1265      Context.Deallocate(Bases[idx]);
1266
1267      Invalid = true;
1268    } else {
1269      // Okay, add this new base class.
1270      KnownBase = Bases[idx];
1271      Bases[NumGoodBases++] = Bases[idx];
1272      if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1273        const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1274        if (Class->isInterface() &&
1275              (!RD->isInterface() ||
1276               KnownBase->getAccessSpecifier() != AS_public)) {
1277          // The Microsoft extension __interface does not permit bases that
1278          // are not themselves public interfaces.
1279          Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1280            << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1281            << RD->getSourceRange();
1282          Invalid = true;
1283        }
1284        if (RD->hasAttr<WeakAttr>())
1285          Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1286      }
1287    }
1288  }
1289
1290  // Attach the remaining base class specifiers to the derived class.
1291  Class->setBases(Bases, NumGoodBases);
1292
1293  // Delete the remaining (good) base class specifiers, since their
1294  // data has been copied into the CXXRecordDecl.
1295  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1296    Context.Deallocate(Bases[idx]);
1297
1298  return Invalid;
1299}
1300
1301/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1302/// class, after checking whether there are any duplicate base
1303/// classes.
1304void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1305                               unsigned NumBases) {
1306  if (!ClassDecl || !Bases || !NumBases)
1307    return;
1308
1309  AdjustDeclIfTemplate(ClassDecl);
1310  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1311                       (CXXBaseSpecifier**)(Bases), NumBases);
1312}
1313
1314/// \brief Determine whether the type \p Derived is a C++ class that is
1315/// derived from the type \p Base.
1316bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1317  if (!getLangOpts().CPlusPlus)
1318    return false;
1319
1320  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1321  if (!DerivedRD)
1322    return false;
1323
1324  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1325  if (!BaseRD)
1326    return false;
1327
1328  // If either the base or the derived type is invalid, don't try to
1329  // check whether one is derived from the other.
1330  if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1331    return false;
1332
1333  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1334  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1335}
1336
1337/// \brief Determine whether the type \p Derived is a C++ class that is
1338/// derived from the type \p Base.
1339bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1340  if (!getLangOpts().CPlusPlus)
1341    return false;
1342
1343  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1344  if (!DerivedRD)
1345    return false;
1346
1347  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1348  if (!BaseRD)
1349    return false;
1350
1351  return DerivedRD->isDerivedFrom(BaseRD, Paths);
1352}
1353
1354void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1355                              CXXCastPath &BasePathArray) {
1356  assert(BasePathArray.empty() && "Base path array must be empty!");
1357  assert(Paths.isRecordingPaths() && "Must record paths!");
1358
1359  const CXXBasePath &Path = Paths.front();
1360
1361  // We first go backward and check if we have a virtual base.
1362  // FIXME: It would be better if CXXBasePath had the base specifier for
1363  // the nearest virtual base.
1364  unsigned Start = 0;
1365  for (unsigned I = Path.size(); I != 0; --I) {
1366    if (Path[I - 1].Base->isVirtual()) {
1367      Start = I - 1;
1368      break;
1369    }
1370  }
1371
1372  // Now add all bases.
1373  for (unsigned I = Start, E = Path.size(); I != E; ++I)
1374    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1375}
1376
1377/// \brief Determine whether the given base path includes a virtual
1378/// base class.
1379bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1380  for (CXXCastPath::const_iterator B = BasePath.begin(),
1381                                BEnd = BasePath.end();
1382       B != BEnd; ++B)
1383    if ((*B)->isVirtual())
1384      return true;
1385
1386  return false;
1387}
1388
1389/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1390/// conversion (where Derived and Base are class types) is
1391/// well-formed, meaning that the conversion is unambiguous (and
1392/// that all of the base classes are accessible). Returns true
1393/// and emits a diagnostic if the code is ill-formed, returns false
1394/// otherwise. Loc is the location where this routine should point to
1395/// if there is an error, and Range is the source range to highlight
1396/// if there is an error.
1397bool
1398Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1399                                   unsigned InaccessibleBaseID,
1400                                   unsigned AmbigiousBaseConvID,
1401                                   SourceLocation Loc, SourceRange Range,
1402                                   DeclarationName Name,
1403                                   CXXCastPath *BasePath) {
1404  // First, determine whether the path from Derived to Base is
1405  // ambiguous. This is slightly more expensive than checking whether
1406  // the Derived to Base conversion exists, because here we need to
1407  // explore multiple paths to determine if there is an ambiguity.
1408  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1409                     /*DetectVirtual=*/false);
1410  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1411  assert(DerivationOkay &&
1412         "Can only be used with a derived-to-base conversion");
1413  (void)DerivationOkay;
1414
1415  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1416    if (InaccessibleBaseID) {
1417      // Check that the base class can be accessed.
1418      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1419                                   InaccessibleBaseID)) {
1420        case AR_inaccessible:
1421          return true;
1422        case AR_accessible:
1423        case AR_dependent:
1424        case AR_delayed:
1425          break;
1426      }
1427    }
1428
1429    // Build a base path if necessary.
1430    if (BasePath)
1431      BuildBasePathArray(Paths, *BasePath);
1432    return false;
1433  }
1434
1435  // We know that the derived-to-base conversion is ambiguous, and
1436  // we're going to produce a diagnostic. Perform the derived-to-base
1437  // search just one more time to compute all of the possible paths so
1438  // that we can print them out. This is more expensive than any of
1439  // the previous derived-to-base checks we've done, but at this point
1440  // performance isn't as much of an issue.
1441  Paths.clear();
1442  Paths.setRecordingPaths(true);
1443  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1444  assert(StillOkay && "Can only be used with a derived-to-base conversion");
1445  (void)StillOkay;
1446
1447  // Build up a textual representation of the ambiguous paths, e.g.,
1448  // D -> B -> A, that will be used to illustrate the ambiguous
1449  // conversions in the diagnostic. We only print one of the paths
1450  // to each base class subobject.
1451  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1452
1453  Diag(Loc, AmbigiousBaseConvID)
1454  << Derived << Base << PathDisplayStr << Range << Name;
1455  return true;
1456}
1457
1458bool
1459Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1460                                   SourceLocation Loc, SourceRange Range,
1461                                   CXXCastPath *BasePath,
1462                                   bool IgnoreAccess) {
1463  return CheckDerivedToBaseConversion(Derived, Base,
1464                                      IgnoreAccess ? 0
1465                                       : diag::err_upcast_to_inaccessible_base,
1466                                      diag::err_ambiguous_derived_to_base_conv,
1467                                      Loc, Range, DeclarationName(),
1468                                      BasePath);
1469}
1470
1471
1472/// @brief Builds a string representing ambiguous paths from a
1473/// specific derived class to different subobjects of the same base
1474/// class.
1475///
1476/// This function builds a string that can be used in error messages
1477/// to show the different paths that one can take through the
1478/// inheritance hierarchy to go from the derived class to different
1479/// subobjects of a base class. The result looks something like this:
1480/// @code
1481/// struct D -> struct B -> struct A
1482/// struct D -> struct C -> struct A
1483/// @endcode
1484std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1485  std::string PathDisplayStr;
1486  std::set<unsigned> DisplayedPaths;
1487  for (CXXBasePaths::paths_iterator Path = Paths.begin();
1488       Path != Paths.end(); ++Path) {
1489    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1490      // We haven't displayed a path to this particular base
1491      // class subobject yet.
1492      PathDisplayStr += "\n    ";
1493      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1494      for (CXXBasePath::const_iterator Element = Path->begin();
1495           Element != Path->end(); ++Element)
1496        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1497    }
1498  }
1499
1500  return PathDisplayStr;
1501}
1502
1503//===----------------------------------------------------------------------===//
1504// C++ class member Handling
1505//===----------------------------------------------------------------------===//
1506
1507/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1508bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1509                                SourceLocation ASLoc,
1510                                SourceLocation ColonLoc,
1511                                AttributeList *Attrs) {
1512  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1513  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1514                                                  ASLoc, ColonLoc);
1515  CurContext->addHiddenDecl(ASDecl);
1516  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1517}
1518
1519/// CheckOverrideControl - Check C++11 override control semantics.
1520void Sema::CheckOverrideControl(Decl *D) {
1521  if (D->isInvalidDecl())
1522    return;
1523
1524  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1525
1526  // Do we know which functions this declaration might be overriding?
1527  bool OverridesAreKnown = !MD ||
1528      (!MD->getParent()->hasAnyDependentBases() &&
1529       !MD->getType()->isDependentType());
1530
1531  if (!MD || !MD->isVirtual()) {
1532    if (OverridesAreKnown) {
1533      if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1534        Diag(OA->getLocation(),
1535             diag::override_keyword_only_allowed_on_virtual_member_functions)
1536          << "override" << FixItHint::CreateRemoval(OA->getLocation());
1537        D->dropAttr<OverrideAttr>();
1538      }
1539      if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1540        Diag(FA->getLocation(),
1541             diag::override_keyword_only_allowed_on_virtual_member_functions)
1542          << "final" << FixItHint::CreateRemoval(FA->getLocation());
1543        D->dropAttr<FinalAttr>();
1544      }
1545    }
1546    return;
1547  }
1548
1549  if (!OverridesAreKnown)
1550    return;
1551
1552  // C++11 [class.virtual]p5:
1553  //   If a virtual function is marked with the virt-specifier override and
1554  //   does not override a member function of a base class, the program is
1555  //   ill-formed.
1556  bool HasOverriddenMethods =
1557    MD->begin_overridden_methods() != MD->end_overridden_methods();
1558  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1559    Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1560      << MD->getDeclName();
1561}
1562
1563/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1564/// function overrides a virtual member function marked 'final', according to
1565/// C++11 [class.virtual]p4.
1566bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1567                                                  const CXXMethodDecl *Old) {
1568  if (!Old->hasAttr<FinalAttr>())
1569    return false;
1570
1571  Diag(New->getLocation(), diag::err_final_function_overridden)
1572    << New->getDeclName();
1573  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1574  return true;
1575}
1576
1577static bool InitializationHasSideEffects(const FieldDecl &FD) {
1578  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1579  // FIXME: Destruction of ObjC lifetime types has side-effects.
1580  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1581    return !RD->isCompleteDefinition() ||
1582           !RD->hasTrivialDefaultConstructor() ||
1583           !RD->hasTrivialDestructor();
1584  return false;
1585}
1586
1587/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1588/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1589/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1590/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1591/// present (but parsing it has been deferred).
1592NamedDecl *
1593Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1594                               MultiTemplateParamsArg TemplateParameterLists,
1595                               Expr *BW, const VirtSpecifiers &VS,
1596                               InClassInitStyle InitStyle) {
1597  const DeclSpec &DS = D.getDeclSpec();
1598  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1599  DeclarationName Name = NameInfo.getName();
1600  SourceLocation Loc = NameInfo.getLoc();
1601
1602  // For anonymous bitfields, the location should point to the type.
1603  if (Loc.isInvalid())
1604    Loc = D.getLocStart();
1605
1606  Expr *BitWidth = static_cast<Expr*>(BW);
1607
1608  assert(isa<CXXRecordDecl>(CurContext));
1609  assert(!DS.isFriendSpecified());
1610
1611  bool isFunc = D.isDeclarationOfFunction();
1612
1613  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1614    // The Microsoft extension __interface only permits public member functions
1615    // and prohibits constructors, destructors, operators, non-public member
1616    // functions, static methods and data members.
1617    unsigned InvalidDecl;
1618    bool ShowDeclName = true;
1619    if (!isFunc)
1620      InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1621    else if (AS != AS_public)
1622      InvalidDecl = 2;
1623    else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1624      InvalidDecl = 3;
1625    else switch (Name.getNameKind()) {
1626      case DeclarationName::CXXConstructorName:
1627        InvalidDecl = 4;
1628        ShowDeclName = false;
1629        break;
1630
1631      case DeclarationName::CXXDestructorName:
1632        InvalidDecl = 5;
1633        ShowDeclName = false;
1634        break;
1635
1636      case DeclarationName::CXXOperatorName:
1637      case DeclarationName::CXXConversionFunctionName:
1638        InvalidDecl = 6;
1639        break;
1640
1641      default:
1642        InvalidDecl = 0;
1643        break;
1644    }
1645
1646    if (InvalidDecl) {
1647      if (ShowDeclName)
1648        Diag(Loc, diag::err_invalid_member_in_interface)
1649          << (InvalidDecl-1) << Name;
1650      else
1651        Diag(Loc, diag::err_invalid_member_in_interface)
1652          << (InvalidDecl-1) << "";
1653      return 0;
1654    }
1655  }
1656
1657  // C++ 9.2p6: A member shall not be declared to have automatic storage
1658  // duration (auto, register) or with the extern storage-class-specifier.
1659  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1660  // data members and cannot be applied to names declared const or static,
1661  // and cannot be applied to reference members.
1662  switch (DS.getStorageClassSpec()) {
1663    case DeclSpec::SCS_unspecified:
1664    case DeclSpec::SCS_typedef:
1665    case DeclSpec::SCS_static:
1666      // FALL THROUGH.
1667      break;
1668    case DeclSpec::SCS_mutable:
1669      if (isFunc) {
1670        if (DS.getStorageClassSpecLoc().isValid())
1671          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1672        else
1673          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1674
1675        // FIXME: It would be nicer if the keyword was ignored only for this
1676        // declarator. Otherwise we could get follow-up errors.
1677        D.getMutableDeclSpec().ClearStorageClassSpecs();
1678      }
1679      break;
1680    default:
1681      if (DS.getStorageClassSpecLoc().isValid())
1682        Diag(DS.getStorageClassSpecLoc(),
1683             diag::err_storageclass_invalid_for_member);
1684      else
1685        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1686      D.getMutableDeclSpec().ClearStorageClassSpecs();
1687  }
1688
1689  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1690                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1691                      !isFunc);
1692
1693  if (DS.isConstexprSpecified() && isInstField) {
1694    SemaDiagnosticBuilder B =
1695        Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1696    SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1697    if (InitStyle == ICIS_NoInit) {
1698      B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1699      D.getMutableDeclSpec().ClearConstexprSpec();
1700      const char *PrevSpec;
1701      unsigned DiagID;
1702      bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1703                                         PrevSpec, DiagID, getLangOpts());
1704      (void)Failed;
1705      assert(!Failed && "Making a constexpr member const shouldn't fail");
1706    } else {
1707      B << 1;
1708      const char *PrevSpec;
1709      unsigned DiagID;
1710      if (D.getMutableDeclSpec().SetStorageClassSpec(
1711          *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
1712        assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
1713               "This is the only DeclSpec that should fail to be applied");
1714        B << 1;
1715      } else {
1716        B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1717        isInstField = false;
1718      }
1719    }
1720  }
1721
1722  NamedDecl *Member;
1723  if (isInstField) {
1724    CXXScopeSpec &SS = D.getCXXScopeSpec();
1725
1726    // Data members must have identifiers for names.
1727    if (!Name.isIdentifier()) {
1728      Diag(Loc, diag::err_bad_variable_name)
1729        << Name;
1730      return 0;
1731    }
1732
1733    IdentifierInfo *II = Name.getAsIdentifierInfo();
1734
1735    // Member field could not be with "template" keyword.
1736    // So TemplateParameterLists should be empty in this case.
1737    if (TemplateParameterLists.size()) {
1738      TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1739      if (TemplateParams->size()) {
1740        // There is no such thing as a member field template.
1741        Diag(D.getIdentifierLoc(), diag::err_template_member)
1742            << II
1743            << SourceRange(TemplateParams->getTemplateLoc(),
1744                TemplateParams->getRAngleLoc());
1745      } else {
1746        // There is an extraneous 'template<>' for this member.
1747        Diag(TemplateParams->getTemplateLoc(),
1748            diag::err_template_member_noparams)
1749            << II
1750            << SourceRange(TemplateParams->getTemplateLoc(),
1751                TemplateParams->getRAngleLoc());
1752      }
1753      return 0;
1754    }
1755
1756    if (SS.isSet() && !SS.isInvalid()) {
1757      // The user provided a superfluous scope specifier inside a class
1758      // definition:
1759      //
1760      // class X {
1761      //   int X::member;
1762      // };
1763      if (DeclContext *DC = computeDeclContext(SS, false))
1764        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1765      else
1766        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1767          << Name << SS.getRange();
1768
1769      SS.clear();
1770    }
1771
1772    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1773                         InitStyle, AS);
1774    assert(Member && "HandleField never returns null");
1775  } else {
1776    assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1777
1778    Member = HandleDeclarator(S, D, TemplateParameterLists);
1779    if (!Member) {
1780      return 0;
1781    }
1782
1783    // Non-instance-fields can't have a bitfield.
1784    if (BitWidth) {
1785      if (Member->isInvalidDecl()) {
1786        // don't emit another diagnostic.
1787      } else if (isa<VarDecl>(Member)) {
1788        // C++ 9.6p3: A bit-field shall not be a static member.
1789        // "static member 'A' cannot be a bit-field"
1790        Diag(Loc, diag::err_static_not_bitfield)
1791          << Name << BitWidth->getSourceRange();
1792      } else if (isa<TypedefDecl>(Member)) {
1793        // "typedef member 'x' cannot be a bit-field"
1794        Diag(Loc, diag::err_typedef_not_bitfield)
1795          << Name << BitWidth->getSourceRange();
1796      } else {
1797        // A function typedef ("typedef int f(); f a;").
1798        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1799        Diag(Loc, diag::err_not_integral_type_bitfield)
1800          << Name << cast<ValueDecl>(Member)->getType()
1801          << BitWidth->getSourceRange();
1802      }
1803
1804      BitWidth = 0;
1805      Member->setInvalidDecl();
1806    }
1807
1808    Member->setAccess(AS);
1809
1810    // If we have declared a member function template, set the access of the
1811    // templated declaration as well.
1812    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1813      FunTmpl->getTemplatedDecl()->setAccess(AS);
1814  }
1815
1816  if (VS.isOverrideSpecified())
1817    Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1818  if (VS.isFinalSpecified())
1819    Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1820
1821  if (VS.getLastLocation().isValid()) {
1822    // Update the end location of a method that has a virt-specifiers.
1823    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1824      MD->setRangeEnd(VS.getLastLocation());
1825  }
1826
1827  CheckOverrideControl(Member);
1828
1829  assert((Name || isInstField) && "No identifier for non-field ?");
1830
1831  if (isInstField) {
1832    FieldDecl *FD = cast<FieldDecl>(Member);
1833    FieldCollector->Add(FD);
1834
1835    if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1836                                 FD->getLocation())
1837          != DiagnosticsEngine::Ignored) {
1838      // Remember all explicit private FieldDecls that have a name, no side
1839      // effects and are not part of a dependent type declaration.
1840      if (!FD->isImplicit() && FD->getDeclName() &&
1841          FD->getAccess() == AS_private &&
1842          !FD->hasAttr<UnusedAttr>() &&
1843          !FD->getParent()->isDependentContext() &&
1844          !InitializationHasSideEffects(*FD))
1845        UnusedPrivateFields.insert(FD);
1846    }
1847  }
1848
1849  return Member;
1850}
1851
1852namespace {
1853  class UninitializedFieldVisitor
1854      : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1855    Sema &S;
1856    ValueDecl *VD;
1857  public:
1858    typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1859    UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
1860                                                        S(S) {
1861      if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1862        this->VD = IFD->getAnonField();
1863      else
1864        this->VD = VD;
1865    }
1866
1867    void HandleExpr(Expr *E) {
1868      if (!E) return;
1869
1870      // Expressions like x(x) sometimes lack the surrounding expressions
1871      // but need to be checked anyways.
1872      HandleValue(E);
1873      Visit(E);
1874    }
1875
1876    void HandleValue(Expr *E) {
1877      E = E->IgnoreParens();
1878
1879      if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1880        if (isa<EnumConstantDecl>(ME->getMemberDecl()))
1881          return;
1882
1883        // FieldME is the inner-most MemberExpr that is not an anonymous struct
1884        // or union.
1885        MemberExpr *FieldME = ME;
1886
1887        Expr *Base = E;
1888        while (isa<MemberExpr>(Base)) {
1889          ME = cast<MemberExpr>(Base);
1890
1891          if (isa<VarDecl>(ME->getMemberDecl()))
1892            return;
1893
1894          if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1895            if (!FD->isAnonymousStructOrUnion())
1896              FieldME = ME;
1897
1898          Base = ME->getBase();
1899        }
1900
1901        if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
1902          unsigned diag = VD->getType()->isReferenceType()
1903              ? diag::warn_reference_field_is_uninit
1904              : diag::warn_field_is_uninit;
1905          S.Diag(FieldME->getExprLoc(), diag) << VD;
1906        }
1907        return;
1908      }
1909
1910      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1911        HandleValue(CO->getTrueExpr());
1912        HandleValue(CO->getFalseExpr());
1913        return;
1914      }
1915
1916      if (BinaryConditionalOperator *BCO =
1917              dyn_cast<BinaryConditionalOperator>(E)) {
1918        HandleValue(BCO->getCommon());
1919        HandleValue(BCO->getFalseExpr());
1920        return;
1921      }
1922
1923      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1924        switch (BO->getOpcode()) {
1925        default:
1926          return;
1927        case(BO_PtrMemD):
1928        case(BO_PtrMemI):
1929          HandleValue(BO->getLHS());
1930          return;
1931        case(BO_Comma):
1932          HandleValue(BO->getRHS());
1933          return;
1934        }
1935      }
1936    }
1937
1938    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1939      if (E->getCastKind() == CK_LValueToRValue)
1940        HandleValue(E->getSubExpr());
1941
1942      Inherited::VisitImplicitCastExpr(E);
1943    }
1944
1945    void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1946      Expr *Callee = E->getCallee();
1947      if (isa<MemberExpr>(Callee))
1948        HandleValue(Callee);
1949
1950      Inherited::VisitCXXMemberCallExpr(E);
1951    }
1952  };
1953  static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1954                                                       ValueDecl *VD) {
1955    UninitializedFieldVisitor(S, VD).HandleExpr(E);
1956  }
1957} // namespace
1958
1959/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1960/// in-class initializer for a non-static C++ class member, and after
1961/// instantiating an in-class initializer in a class template. Such actions
1962/// are deferred until the class is complete.
1963void
1964Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
1965                                       Expr *InitExpr) {
1966  FieldDecl *FD = cast<FieldDecl>(D);
1967  assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1968         "must set init style when field is created");
1969
1970  if (!InitExpr) {
1971    FD->setInvalidDecl();
1972    FD->removeInClassInitializer();
1973    return;
1974  }
1975
1976  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1977    FD->setInvalidDecl();
1978    FD->removeInClassInitializer();
1979    return;
1980  }
1981
1982  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1983      != DiagnosticsEngine::Ignored) {
1984    CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1985  }
1986
1987  ExprResult Init = InitExpr;
1988  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1989    if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
1990      Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
1991        << /*at end of ctor*/1 << InitExpr->getSourceRange();
1992    }
1993    Expr **Inits = &InitExpr;
1994    unsigned NumInits = 1;
1995    InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1996    InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
1997        ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1998        : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
1999    InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
2000    Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
2001    if (Init.isInvalid()) {
2002      FD->setInvalidDecl();
2003      return;
2004    }
2005  }
2006
2007  // C++11 [class.base.init]p7:
2008  //   The initialization of each base and member constitutes a
2009  //   full-expression.
2010  Init = ActOnFinishFullExpr(Init.take(), InitLoc);
2011  if (Init.isInvalid()) {
2012    FD->setInvalidDecl();
2013    return;
2014  }
2015
2016  InitExpr = Init.release();
2017
2018  FD->setInClassInitializer(InitExpr);
2019}
2020
2021/// \brief Find the direct and/or virtual base specifiers that
2022/// correspond to the given base type, for use in base initialization
2023/// within a constructor.
2024static bool FindBaseInitializer(Sema &SemaRef,
2025                                CXXRecordDecl *ClassDecl,
2026                                QualType BaseType,
2027                                const CXXBaseSpecifier *&DirectBaseSpec,
2028                                const CXXBaseSpecifier *&VirtualBaseSpec) {
2029  // First, check for a direct base class.
2030  DirectBaseSpec = 0;
2031  for (CXXRecordDecl::base_class_const_iterator Base
2032         = ClassDecl->bases_begin();
2033       Base != ClassDecl->bases_end(); ++Base) {
2034    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2035      // We found a direct base of this type. That's what we're
2036      // initializing.
2037      DirectBaseSpec = &*Base;
2038      break;
2039    }
2040  }
2041
2042  // Check for a virtual base class.
2043  // FIXME: We might be able to short-circuit this if we know in advance that
2044  // there are no virtual bases.
2045  VirtualBaseSpec = 0;
2046  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2047    // We haven't found a base yet; search the class hierarchy for a
2048    // virtual base class.
2049    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2050                       /*DetectVirtual=*/false);
2051    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2052                              BaseType, Paths)) {
2053      for (CXXBasePaths::paths_iterator Path = Paths.begin();
2054           Path != Paths.end(); ++Path) {
2055        if (Path->back().Base->isVirtual()) {
2056          VirtualBaseSpec = Path->back().Base;
2057          break;
2058        }
2059      }
2060    }
2061  }
2062
2063  return DirectBaseSpec || VirtualBaseSpec;
2064}
2065
2066/// \brief Handle a C++ member initializer using braced-init-list syntax.
2067MemInitResult
2068Sema::ActOnMemInitializer(Decl *ConstructorD,
2069                          Scope *S,
2070                          CXXScopeSpec &SS,
2071                          IdentifierInfo *MemberOrBase,
2072                          ParsedType TemplateTypeTy,
2073                          const DeclSpec &DS,
2074                          SourceLocation IdLoc,
2075                          Expr *InitList,
2076                          SourceLocation EllipsisLoc) {
2077  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2078                             DS, IdLoc, InitList,
2079                             EllipsisLoc);
2080}
2081
2082/// \brief Handle a C++ member initializer using parentheses syntax.
2083MemInitResult
2084Sema::ActOnMemInitializer(Decl *ConstructorD,
2085                          Scope *S,
2086                          CXXScopeSpec &SS,
2087                          IdentifierInfo *MemberOrBase,
2088                          ParsedType TemplateTypeTy,
2089                          const DeclSpec &DS,
2090                          SourceLocation IdLoc,
2091                          SourceLocation LParenLoc,
2092                          Expr **Args, unsigned NumArgs,
2093                          SourceLocation RParenLoc,
2094                          SourceLocation EllipsisLoc) {
2095  Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2096                                           llvm::makeArrayRef(Args, NumArgs),
2097                                           RParenLoc);
2098  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2099                             DS, IdLoc, List, EllipsisLoc);
2100}
2101
2102namespace {
2103
2104// Callback to only accept typo corrections that can be a valid C++ member
2105// intializer: either a non-static field member or a base class.
2106class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2107 public:
2108  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2109      : ClassDecl(ClassDecl) {}
2110
2111  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2112    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2113      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2114        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2115      else
2116        return isa<TypeDecl>(ND);
2117    }
2118    return false;
2119  }
2120
2121 private:
2122  CXXRecordDecl *ClassDecl;
2123};
2124
2125}
2126
2127/// \brief Handle a C++ member initializer.
2128MemInitResult
2129Sema::BuildMemInitializer(Decl *ConstructorD,
2130                          Scope *S,
2131                          CXXScopeSpec &SS,
2132                          IdentifierInfo *MemberOrBase,
2133                          ParsedType TemplateTypeTy,
2134                          const DeclSpec &DS,
2135                          SourceLocation IdLoc,
2136                          Expr *Init,
2137                          SourceLocation EllipsisLoc) {
2138  if (!ConstructorD)
2139    return true;
2140
2141  AdjustDeclIfTemplate(ConstructorD);
2142
2143  CXXConstructorDecl *Constructor
2144    = dyn_cast<CXXConstructorDecl>(ConstructorD);
2145  if (!Constructor) {
2146    // The user wrote a constructor initializer on a function that is
2147    // not a C++ constructor. Ignore the error for now, because we may
2148    // have more member initializers coming; we'll diagnose it just
2149    // once in ActOnMemInitializers.
2150    return true;
2151  }
2152
2153  CXXRecordDecl *ClassDecl = Constructor->getParent();
2154
2155  // C++ [class.base.init]p2:
2156  //   Names in a mem-initializer-id are looked up in the scope of the
2157  //   constructor's class and, if not found in that scope, are looked
2158  //   up in the scope containing the constructor's definition.
2159  //   [Note: if the constructor's class contains a member with the
2160  //   same name as a direct or virtual base class of the class, a
2161  //   mem-initializer-id naming the member or base class and composed
2162  //   of a single identifier refers to the class member. A
2163  //   mem-initializer-id for the hidden base class may be specified
2164  //   using a qualified name. ]
2165  if (!SS.getScopeRep() && !TemplateTypeTy) {
2166    // Look for a member, first.
2167    DeclContext::lookup_result Result
2168      = ClassDecl->lookup(MemberOrBase);
2169    if (!Result.empty()) {
2170      ValueDecl *Member;
2171      if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2172          (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2173        if (EllipsisLoc.isValid())
2174          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2175            << MemberOrBase
2176            << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2177
2178        return BuildMemberInitializer(Member, Init, IdLoc);
2179      }
2180    }
2181  }
2182  // It didn't name a member, so see if it names a class.
2183  QualType BaseType;
2184  TypeSourceInfo *TInfo = 0;
2185
2186  if (TemplateTypeTy) {
2187    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2188  } else if (DS.getTypeSpecType() == TST_decltype) {
2189    BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2190  } else {
2191    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2192    LookupParsedName(R, S, &SS);
2193
2194    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2195    if (!TyD) {
2196      if (R.isAmbiguous()) return true;
2197
2198      // We don't want access-control diagnostics here.
2199      R.suppressDiagnostics();
2200
2201      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2202        bool NotUnknownSpecialization = false;
2203        DeclContext *DC = computeDeclContext(SS, false);
2204        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2205          NotUnknownSpecialization = !Record->hasAnyDependentBases();
2206
2207        if (!NotUnknownSpecialization) {
2208          // When the scope specifier can refer to a member of an unknown
2209          // specialization, we take it as a type name.
2210          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2211                                       SS.getWithLocInContext(Context),
2212                                       *MemberOrBase, IdLoc);
2213          if (BaseType.isNull())
2214            return true;
2215
2216          R.clear();
2217          R.setLookupName(MemberOrBase);
2218        }
2219      }
2220
2221      // If no results were found, try to correct typos.
2222      TypoCorrection Corr;
2223      MemInitializerValidatorCCC Validator(ClassDecl);
2224      if (R.empty() && BaseType.isNull() &&
2225          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2226                              Validator, ClassDecl))) {
2227        std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2228        std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
2229        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2230          // We have found a non-static data member with a similar
2231          // name to what was typed; complain and initialize that
2232          // member.
2233          Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2234            << MemberOrBase << true << CorrectedQuotedStr
2235            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2236          Diag(Member->getLocation(), diag::note_previous_decl)
2237            << CorrectedQuotedStr;
2238
2239          return BuildMemberInitializer(Member, Init, IdLoc);
2240        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2241          const CXXBaseSpecifier *DirectBaseSpec;
2242          const CXXBaseSpecifier *VirtualBaseSpec;
2243          if (FindBaseInitializer(*this, ClassDecl,
2244                                  Context.getTypeDeclType(Type),
2245                                  DirectBaseSpec, VirtualBaseSpec)) {
2246            // We have found a direct or virtual base class with a
2247            // similar name to what was typed; complain and initialize
2248            // that base class.
2249            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2250              << MemberOrBase << false << CorrectedQuotedStr
2251              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2252
2253            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2254                                                             : VirtualBaseSpec;
2255            Diag(BaseSpec->getLocStart(),
2256                 diag::note_base_class_specified_here)
2257              << BaseSpec->getType()
2258              << BaseSpec->getSourceRange();
2259
2260            TyD = Type;
2261          }
2262        }
2263      }
2264
2265      if (!TyD && BaseType.isNull()) {
2266        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2267          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2268        return true;
2269      }
2270    }
2271
2272    if (BaseType.isNull()) {
2273      BaseType = Context.getTypeDeclType(TyD);
2274      if (SS.isSet()) {
2275        NestedNameSpecifier *Qualifier =
2276          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2277
2278        // FIXME: preserve source range information
2279        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
2280      }
2281    }
2282  }
2283
2284  if (!TInfo)
2285    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2286
2287  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2288}
2289
2290/// Checks a member initializer expression for cases where reference (or
2291/// pointer) members are bound to by-value parameters (or their addresses).
2292static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2293                                               Expr *Init,
2294                                               SourceLocation IdLoc) {
2295  QualType MemberTy = Member->getType();
2296
2297  // We only handle pointers and references currently.
2298  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2299  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2300    return;
2301
2302  const bool IsPointer = MemberTy->isPointerType();
2303  if (IsPointer) {
2304    if (const UnaryOperator *Op
2305          = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2306      // The only case we're worried about with pointers requires taking the
2307      // address.
2308      if (Op->getOpcode() != UO_AddrOf)
2309        return;
2310
2311      Init = Op->getSubExpr();
2312    } else {
2313      // We only handle address-of expression initializers for pointers.
2314      return;
2315    }
2316  }
2317
2318  if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2319    // Taking the address of a temporary will be diagnosed as a hard error.
2320    if (IsPointer)
2321      return;
2322
2323    S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2324      << Member << Init->getSourceRange();
2325  } else if (const DeclRefExpr *DRE
2326               = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2327    // We only warn when referring to a non-reference parameter declaration.
2328    const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2329    if (!Parameter || Parameter->getType()->isReferenceType())
2330      return;
2331
2332    S.Diag(Init->getExprLoc(),
2333           IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2334                     : diag::warn_bind_ref_member_to_parameter)
2335      << Member << Parameter << Init->getSourceRange();
2336  } else {
2337    // Other initializers are fine.
2338    return;
2339  }
2340
2341  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2342    << (unsigned)IsPointer;
2343}
2344
2345MemInitResult
2346Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2347                             SourceLocation IdLoc) {
2348  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2349  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2350  assert((DirectMember || IndirectMember) &&
2351         "Member must be a FieldDecl or IndirectFieldDecl");
2352
2353  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2354    return true;
2355
2356  if (Member->isInvalidDecl())
2357    return true;
2358
2359  // Diagnose value-uses of fields to initialize themselves, e.g.
2360  //   foo(foo)
2361  // where foo is not also a parameter to the constructor.
2362  // TODO: implement -Wuninitialized and fold this into that framework.
2363  Expr **Args;
2364  unsigned NumArgs;
2365  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2366    Args = ParenList->getExprs();
2367    NumArgs = ParenList->getNumExprs();
2368  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2369    Args = InitList->getInits();
2370    NumArgs = InitList->getNumInits();
2371  } else {
2372    // Template instantiation doesn't reconstruct ParenListExprs for us.
2373    Args = &Init;
2374    NumArgs = 1;
2375  }
2376
2377  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2378        != DiagnosticsEngine::Ignored)
2379    for (unsigned i = 0; i < NumArgs; ++i)
2380      // FIXME: Warn about the case when other fields are used before being
2381      // initialized. For example, let this field be the i'th field. When
2382      // initializing the i'th field, throw a warning if any of the >= i'th
2383      // fields are used, as they are not yet initialized.
2384      // Right now we are only handling the case where the i'th field uses
2385      // itself in its initializer.
2386      // Also need to take into account that some fields may be initialized by
2387      // in-class initializers, see C++11 [class.base.init]p9.
2388      CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
2389
2390  SourceRange InitRange = Init->getSourceRange();
2391
2392  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2393    // Can't check initialization for a member of dependent type or when
2394    // any of the arguments are type-dependent expressions.
2395    DiscardCleanupsInEvaluationContext();
2396  } else {
2397    bool InitList = false;
2398    if (isa<InitListExpr>(Init)) {
2399      InitList = true;
2400      Args = &Init;
2401      NumArgs = 1;
2402
2403      if (isStdInitializerList(Member->getType(), 0)) {
2404        Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2405            << /*at end of ctor*/1 << InitRange;
2406      }
2407    }
2408
2409    // Initialize the member.
2410    InitializedEntity MemberEntity =
2411      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2412                   : InitializedEntity::InitializeMember(IndirectMember, 0);
2413    InitializationKind Kind =
2414      InitList ? InitializationKind::CreateDirectList(IdLoc)
2415               : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2416                                                  InitRange.getEnd());
2417
2418    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2419    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2420                                            MultiExprArg(Args, NumArgs),
2421                                            0);
2422    if (MemberInit.isInvalid())
2423      return true;
2424
2425    // C++11 [class.base.init]p7:
2426    //   The initialization of each base and member constitutes a
2427    //   full-expression.
2428    MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2429    if (MemberInit.isInvalid())
2430      return true;
2431
2432    Init = MemberInit.get();
2433    CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2434  }
2435
2436  if (DirectMember) {
2437    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2438                                            InitRange.getBegin(), Init,
2439                                            InitRange.getEnd());
2440  } else {
2441    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2442                                            InitRange.getBegin(), Init,
2443                                            InitRange.getEnd());
2444  }
2445}
2446
2447MemInitResult
2448Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2449                                 CXXRecordDecl *ClassDecl) {
2450  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2451  if (!LangOpts.CPlusPlus11)
2452    return Diag(NameLoc, diag::err_delegating_ctor)
2453      << TInfo->getTypeLoc().getLocalSourceRange();
2454  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2455
2456  bool InitList = true;
2457  Expr **Args = &Init;
2458  unsigned NumArgs = 1;
2459  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2460    InitList = false;
2461    Args = ParenList->getExprs();
2462    NumArgs = ParenList->getNumExprs();
2463  }
2464
2465  SourceRange InitRange = Init->getSourceRange();
2466  // Initialize the object.
2467  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2468                                     QualType(ClassDecl->getTypeForDecl(), 0));
2469  InitializationKind Kind =
2470    InitList ? InitializationKind::CreateDirectList(NameLoc)
2471             : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2472                                                InitRange.getEnd());
2473  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2474  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2475                                              MultiExprArg(Args, NumArgs),
2476                                              0);
2477  if (DelegationInit.isInvalid())
2478    return true;
2479
2480  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2481         "Delegating constructor with no target?");
2482
2483  // C++11 [class.base.init]p7:
2484  //   The initialization of each base and member constitutes a
2485  //   full-expression.
2486  DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2487                                       InitRange.getBegin());
2488  if (DelegationInit.isInvalid())
2489    return true;
2490
2491  // If we are in a dependent context, template instantiation will
2492  // perform this type-checking again. Just save the arguments that we
2493  // received in a ParenListExpr.
2494  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2495  // of the information that we have about the base
2496  // initializer. However, deconstructing the ASTs is a dicey process,
2497  // and this approach is far more likely to get the corner cases right.
2498  if (CurContext->isDependentContext())
2499    DelegationInit = Owned(Init);
2500
2501  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2502                                          DelegationInit.takeAs<Expr>(),
2503                                          InitRange.getEnd());
2504}
2505
2506MemInitResult
2507Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2508                           Expr *Init, CXXRecordDecl *ClassDecl,
2509                           SourceLocation EllipsisLoc) {
2510  SourceLocation BaseLoc
2511    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2512
2513  if (!BaseType->isDependentType() && !BaseType->isRecordType())
2514    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2515             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2516
2517  // C++ [class.base.init]p2:
2518  //   [...] Unless the mem-initializer-id names a nonstatic data
2519  //   member of the constructor's class or a direct or virtual base
2520  //   of that class, the mem-initializer is ill-formed. A
2521  //   mem-initializer-list can initialize a base class using any
2522  //   name that denotes that base class type.
2523  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2524
2525  SourceRange InitRange = Init->getSourceRange();
2526  if (EllipsisLoc.isValid()) {
2527    // This is a pack expansion.
2528    if (!BaseType->containsUnexpandedParameterPack())  {
2529      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2530        << SourceRange(BaseLoc, InitRange.getEnd());
2531
2532      EllipsisLoc = SourceLocation();
2533    }
2534  } else {
2535    // Check for any unexpanded parameter packs.
2536    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2537      return true;
2538
2539    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2540      return true;
2541  }
2542
2543  // Check for direct and virtual base classes.
2544  const CXXBaseSpecifier *DirectBaseSpec = 0;
2545  const CXXBaseSpecifier *VirtualBaseSpec = 0;
2546  if (!Dependent) {
2547    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2548                                       BaseType))
2549      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2550
2551    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2552                        VirtualBaseSpec);
2553
2554    // C++ [base.class.init]p2:
2555    // Unless the mem-initializer-id names a nonstatic data member of the
2556    // constructor's class or a direct or virtual base of that class, the
2557    // mem-initializer is ill-formed.
2558    if (!DirectBaseSpec && !VirtualBaseSpec) {
2559      // If the class has any dependent bases, then it's possible that
2560      // one of those types will resolve to the same type as
2561      // BaseType. Therefore, just treat this as a dependent base
2562      // class initialization.  FIXME: Should we try to check the
2563      // initialization anyway? It seems odd.
2564      if (ClassDecl->hasAnyDependentBases())
2565        Dependent = true;
2566      else
2567        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2568          << BaseType << Context.getTypeDeclType(ClassDecl)
2569          << BaseTInfo->getTypeLoc().getLocalSourceRange();
2570    }
2571  }
2572
2573  if (Dependent) {
2574    DiscardCleanupsInEvaluationContext();
2575
2576    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2577                                            /*IsVirtual=*/false,
2578                                            InitRange.getBegin(), Init,
2579                                            InitRange.getEnd(), EllipsisLoc);
2580  }
2581
2582  // C++ [base.class.init]p2:
2583  //   If a mem-initializer-id is ambiguous because it designates both
2584  //   a direct non-virtual base class and an inherited virtual base
2585  //   class, the mem-initializer is ill-formed.
2586  if (DirectBaseSpec && VirtualBaseSpec)
2587    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2588      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2589
2590  CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2591  if (!BaseSpec)
2592    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2593
2594  // Initialize the base.
2595  bool InitList = true;
2596  Expr **Args = &Init;
2597  unsigned NumArgs = 1;
2598  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2599    InitList = false;
2600    Args = ParenList->getExprs();
2601    NumArgs = ParenList->getNumExprs();
2602  }
2603
2604  InitializedEntity BaseEntity =
2605    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2606  InitializationKind Kind =
2607    InitList ? InitializationKind::CreateDirectList(BaseLoc)
2608             : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2609                                                InitRange.getEnd());
2610  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2611  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2612                                        MultiExprArg(Args, NumArgs), 0);
2613  if (BaseInit.isInvalid())
2614    return true;
2615
2616  // C++11 [class.base.init]p7:
2617  //   The initialization of each base and member constitutes a
2618  //   full-expression.
2619  BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
2620  if (BaseInit.isInvalid())
2621    return true;
2622
2623  // If we are in a dependent context, template instantiation will
2624  // perform this type-checking again. Just save the arguments that we
2625  // received in a ParenListExpr.
2626  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2627  // of the information that we have about the base
2628  // initializer. However, deconstructing the ASTs is a dicey process,
2629  // and this approach is far more likely to get the corner cases right.
2630  if (CurContext->isDependentContext())
2631    BaseInit = Owned(Init);
2632
2633  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2634                                          BaseSpec->isVirtual(),
2635                                          InitRange.getBegin(),
2636                                          BaseInit.takeAs<Expr>(),
2637                                          InitRange.getEnd(), EllipsisLoc);
2638}
2639
2640// Create a static_cast\<T&&>(expr).
2641static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2642  if (T.isNull()) T = E->getType();
2643  QualType TargetType = SemaRef.BuildReferenceType(
2644      T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
2645  SourceLocation ExprLoc = E->getLocStart();
2646  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2647      TargetType, ExprLoc);
2648
2649  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2650                                   SourceRange(ExprLoc, ExprLoc),
2651                                   E->getSourceRange()).take();
2652}
2653
2654/// ImplicitInitializerKind - How an implicit base or member initializer should
2655/// initialize its base or member.
2656enum ImplicitInitializerKind {
2657  IIK_Default,
2658  IIK_Copy,
2659  IIK_Move,
2660  IIK_Inherit
2661};
2662
2663static bool
2664BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2665                             ImplicitInitializerKind ImplicitInitKind,
2666                             CXXBaseSpecifier *BaseSpec,
2667                             bool IsInheritedVirtualBase,
2668                             CXXCtorInitializer *&CXXBaseInit) {
2669  InitializedEntity InitEntity
2670    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2671                                        IsInheritedVirtualBase);
2672
2673  ExprResult BaseInit;
2674
2675  switch (ImplicitInitKind) {
2676  case IIK_Inherit: {
2677    const CXXRecordDecl *Inherited =
2678        Constructor->getInheritedConstructor()->getParent();
2679    const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2680    if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2681      // C++11 [class.inhctor]p8:
2682      //   Each expression in the expression-list is of the form
2683      //   static_cast<T&&>(p), where p is the name of the corresponding
2684      //   constructor parameter and T is the declared type of p.
2685      SmallVector<Expr*, 16> Args;
2686      for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2687        ParmVarDecl *PD = Constructor->getParamDecl(I);
2688        ExprResult ArgExpr =
2689            SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2690                                     VK_LValue, SourceLocation());
2691        if (ArgExpr.isInvalid())
2692          return true;
2693        Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2694      }
2695
2696      InitializationKind InitKind = InitializationKind::CreateDirect(
2697          Constructor->getLocation(), SourceLocation(), SourceLocation());
2698      InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2699                                     Args.data(), Args.size());
2700      BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2701      break;
2702    }
2703  }
2704  // Fall through.
2705  case IIK_Default: {
2706    InitializationKind InitKind
2707      = InitializationKind::CreateDefault(Constructor->getLocation());
2708    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2709    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2710    break;
2711  }
2712
2713  case IIK_Move:
2714  case IIK_Copy: {
2715    bool Moving = ImplicitInitKind == IIK_Move;
2716    ParmVarDecl *Param = Constructor->getParamDecl(0);
2717    QualType ParamType = Param->getType().getNonReferenceType();
2718
2719    Expr *CopyCtorArg =
2720      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2721                          SourceLocation(), Param, false,
2722                          Constructor->getLocation(), ParamType,
2723                          VK_LValue, 0);
2724
2725    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2726
2727    // Cast to the base class to avoid ambiguities.
2728    QualType ArgTy =
2729      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2730                                       ParamType.getQualifiers());
2731
2732    if (Moving) {
2733      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2734    }
2735
2736    CXXCastPath BasePath;
2737    BasePath.push_back(BaseSpec);
2738    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2739                                            CK_UncheckedDerivedToBase,
2740                                            Moving ? VK_XValue : VK_LValue,
2741                                            &BasePath).take();
2742
2743    InitializationKind InitKind
2744      = InitializationKind::CreateDirect(Constructor->getLocation(),
2745                                         SourceLocation(), SourceLocation());
2746    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2747                                   &CopyCtorArg, 1);
2748    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2749                               MultiExprArg(&CopyCtorArg, 1));
2750    break;
2751  }
2752  }
2753
2754  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2755  if (BaseInit.isInvalid())
2756    return true;
2757
2758  CXXBaseInit =
2759    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2760               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2761                                                        SourceLocation()),
2762                                             BaseSpec->isVirtual(),
2763                                             SourceLocation(),
2764                                             BaseInit.takeAs<Expr>(),
2765                                             SourceLocation(),
2766                                             SourceLocation());
2767
2768  return false;
2769}
2770
2771static bool RefersToRValueRef(Expr *MemRef) {
2772  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2773  return Referenced->getType()->isRValueReferenceType();
2774}
2775
2776static bool
2777BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2778                               ImplicitInitializerKind ImplicitInitKind,
2779                               FieldDecl *Field, IndirectFieldDecl *Indirect,
2780                               CXXCtorInitializer *&CXXMemberInit) {
2781  if (Field->isInvalidDecl())
2782    return true;
2783
2784  SourceLocation Loc = Constructor->getLocation();
2785
2786  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2787    bool Moving = ImplicitInitKind == IIK_Move;
2788    ParmVarDecl *Param = Constructor->getParamDecl(0);
2789    QualType ParamType = Param->getType().getNonReferenceType();
2790
2791    // Suppress copying zero-width bitfields.
2792    if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2793      return false;
2794
2795    Expr *MemberExprBase =
2796      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2797                          SourceLocation(), Param, false,
2798                          Loc, ParamType, VK_LValue, 0);
2799
2800    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2801
2802    if (Moving) {
2803      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2804    }
2805
2806    // Build a reference to this field within the parameter.
2807    CXXScopeSpec SS;
2808    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2809                              Sema::LookupMemberName);
2810    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2811                                  : cast<ValueDecl>(Field), AS_public);
2812    MemberLookup.resolveKind();
2813    ExprResult CtorArg
2814      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2815                                         ParamType, Loc,
2816                                         /*IsArrow=*/false,
2817                                         SS,
2818                                         /*TemplateKWLoc=*/SourceLocation(),
2819                                         /*FirstQualifierInScope=*/0,
2820                                         MemberLookup,
2821                                         /*TemplateArgs=*/0);
2822    if (CtorArg.isInvalid())
2823      return true;
2824
2825    // C++11 [class.copy]p15:
2826    //   - if a member m has rvalue reference type T&&, it is direct-initialized
2827    //     with static_cast<T&&>(x.m);
2828    if (RefersToRValueRef(CtorArg.get())) {
2829      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2830    }
2831
2832    // When the field we are copying is an array, create index variables for
2833    // each dimension of the array. We use these index variables to subscript
2834    // the source array, and other clients (e.g., CodeGen) will perform the
2835    // necessary iteration with these index variables.
2836    SmallVector<VarDecl *, 4> IndexVariables;
2837    QualType BaseType = Field->getType();
2838    QualType SizeType = SemaRef.Context.getSizeType();
2839    bool InitializingArray = false;
2840    while (const ConstantArrayType *Array
2841                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2842      InitializingArray = true;
2843      // Create the iteration variable for this array index.
2844      IdentifierInfo *IterationVarName = 0;
2845      {
2846        SmallString<8> Str;
2847        llvm::raw_svector_ostream OS(Str);
2848        OS << "__i" << IndexVariables.size();
2849        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2850      }
2851      VarDecl *IterationVar
2852        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2853                          IterationVarName, SizeType,
2854                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2855                          SC_None, SC_None);
2856      IndexVariables.push_back(IterationVar);
2857
2858      // Create a reference to the iteration variable.
2859      ExprResult IterationVarRef
2860        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
2861      assert(!IterationVarRef.isInvalid() &&
2862             "Reference to invented variable cannot fail!");
2863      IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2864      assert(!IterationVarRef.isInvalid() &&
2865             "Conversion of invented variable cannot fail!");
2866
2867      // Subscript the array with this iteration variable.
2868      CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
2869                                                        IterationVarRef.take(),
2870                                                        Loc);
2871      if (CtorArg.isInvalid())
2872        return true;
2873
2874      BaseType = Array->getElementType();
2875    }
2876
2877    // The array subscript expression is an lvalue, which is wrong for moving.
2878    if (Moving && InitializingArray)
2879      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2880
2881    // Construct the entity that we will be initializing. For an array, this
2882    // will be first element in the array, which may require several levels
2883    // of array-subscript entities.
2884    SmallVector<InitializedEntity, 4> Entities;
2885    Entities.reserve(1 + IndexVariables.size());
2886    if (Indirect)
2887      Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2888    else
2889      Entities.push_back(InitializedEntity::InitializeMember(Field));
2890    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2891      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2892                                                              0,
2893                                                              Entities.back()));
2894
2895    // Direct-initialize to use the copy constructor.
2896    InitializationKind InitKind =
2897      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2898
2899    Expr *CtorArgE = CtorArg.takeAs<Expr>();
2900    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2901                                   &CtorArgE, 1);
2902
2903    ExprResult MemberInit
2904      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2905                        MultiExprArg(&CtorArgE, 1));
2906    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2907    if (MemberInit.isInvalid())
2908      return true;
2909
2910    if (Indirect) {
2911      assert(IndexVariables.size() == 0 &&
2912             "Indirect field improperly initialized");
2913      CXXMemberInit
2914        = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2915                                                   Loc, Loc,
2916                                                   MemberInit.takeAs<Expr>(),
2917                                                   Loc);
2918    } else
2919      CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2920                                                 Loc, MemberInit.takeAs<Expr>(),
2921                                                 Loc,
2922                                                 IndexVariables.data(),
2923                                                 IndexVariables.size());
2924    return false;
2925  }
2926
2927  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
2928         "Unhandled implicit init kind!");
2929
2930  QualType FieldBaseElementType =
2931    SemaRef.Context.getBaseElementType(Field->getType());
2932
2933  if (FieldBaseElementType->isRecordType()) {
2934    InitializedEntity InitEntity
2935      = Indirect? InitializedEntity::InitializeMember(Indirect)
2936                : InitializedEntity::InitializeMember(Field);
2937    InitializationKind InitKind =
2938      InitializationKind::CreateDefault(Loc);
2939
2940    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2941    ExprResult MemberInit =
2942      InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2943
2944    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2945    if (MemberInit.isInvalid())
2946      return true;
2947
2948    if (Indirect)
2949      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2950                                                               Indirect, Loc,
2951                                                               Loc,
2952                                                               MemberInit.get(),
2953                                                               Loc);
2954    else
2955      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2956                                                               Field, Loc, Loc,
2957                                                               MemberInit.get(),
2958                                                               Loc);
2959    return false;
2960  }
2961
2962  if (!Field->getParent()->isUnion()) {
2963    if (FieldBaseElementType->isReferenceType()) {
2964      SemaRef.Diag(Constructor->getLocation(),
2965                   diag::err_uninitialized_member_in_ctor)
2966      << (int)Constructor->isImplicit()
2967      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2968      << 0 << Field->getDeclName();
2969      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2970      return true;
2971    }
2972
2973    if (FieldBaseElementType.isConstQualified()) {
2974      SemaRef.Diag(Constructor->getLocation(),
2975                   diag::err_uninitialized_member_in_ctor)
2976      << (int)Constructor->isImplicit()
2977      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2978      << 1 << Field->getDeclName();
2979      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2980      return true;
2981    }
2982  }
2983
2984  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2985      FieldBaseElementType->isObjCRetainableType() &&
2986      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2987      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2988    // ARC:
2989    //   Default-initialize Objective-C pointers to NULL.
2990    CXXMemberInit
2991      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2992                                                 Loc, Loc,
2993                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2994                                                 Loc);
2995    return false;
2996  }
2997
2998  // Nothing to initialize.
2999  CXXMemberInit = 0;
3000  return false;
3001}
3002
3003namespace {
3004struct BaseAndFieldInfo {
3005  Sema &S;
3006  CXXConstructorDecl *Ctor;
3007  bool AnyErrorsInInits;
3008  ImplicitInitializerKind IIK;
3009  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3010  SmallVector<CXXCtorInitializer*, 8> AllToInit;
3011
3012  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3013    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3014    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3015    if (Generated && Ctor->isCopyConstructor())
3016      IIK = IIK_Copy;
3017    else if (Generated && Ctor->isMoveConstructor())
3018      IIK = IIK_Move;
3019    else if (Ctor->getInheritedConstructor())
3020      IIK = IIK_Inherit;
3021    else
3022      IIK = IIK_Default;
3023  }
3024
3025  bool isImplicitCopyOrMove() const {
3026    switch (IIK) {
3027    case IIK_Copy:
3028    case IIK_Move:
3029      return true;
3030
3031    case IIK_Default:
3032    case IIK_Inherit:
3033      return false;
3034    }
3035
3036    llvm_unreachable("Invalid ImplicitInitializerKind!");
3037  }
3038
3039  bool addFieldInitializer(CXXCtorInitializer *Init) {
3040    AllToInit.push_back(Init);
3041
3042    // Check whether this initializer makes the field "used".
3043    if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
3044      S.UnusedPrivateFields.remove(Init->getAnyMember());
3045
3046    return false;
3047  }
3048};
3049}
3050
3051/// \brief Determine whether the given indirect field declaration is somewhere
3052/// within an anonymous union.
3053static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3054  for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3055                                      CEnd = F->chain_end();
3056       C != CEnd; ++C)
3057    if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3058      if (Record->isUnion())
3059        return true;
3060
3061  return false;
3062}
3063
3064/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3065/// array type.
3066static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3067  if (T->isIncompleteArrayType())
3068    return true;
3069
3070  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3071    if (!ArrayT->getSize())
3072      return true;
3073
3074    T = ArrayT->getElementType();
3075  }
3076
3077  return false;
3078}
3079
3080static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3081                                    FieldDecl *Field,
3082                                    IndirectFieldDecl *Indirect = 0) {
3083
3084  // Overwhelmingly common case: we have a direct initializer for this field.
3085  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3086    return Info.addFieldInitializer(Init);
3087
3088  // C++11 [class.base.init]p8: if the entity is a non-static data member that
3089  // has a brace-or-equal-initializer, the entity is initialized as specified
3090  // in [dcl.init].
3091  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3092    CXXCtorInitializer *Init;
3093    if (Indirect)
3094      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3095                                                      SourceLocation(),
3096                                                      SourceLocation(), 0,
3097                                                      SourceLocation());
3098    else
3099      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3100                                                      SourceLocation(),
3101                                                      SourceLocation(), 0,
3102                                                      SourceLocation());
3103    return Info.addFieldInitializer(Init);
3104  }
3105
3106  // Don't build an implicit initializer for union members if none was
3107  // explicitly specified.
3108  if (Field->getParent()->isUnion() ||
3109      (Indirect && isWithinAnonymousUnion(Indirect)))
3110    return false;
3111
3112  // Don't initialize incomplete or zero-length arrays.
3113  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3114    return false;
3115
3116  // Don't try to build an implicit initializer if there were semantic
3117  // errors in any of the initializers (and therefore we might be
3118  // missing some that the user actually wrote).
3119  if (Info.AnyErrorsInInits || Field->isInvalidDecl())
3120    return false;
3121
3122  CXXCtorInitializer *Init = 0;
3123  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3124                                     Indirect, Init))
3125    return true;
3126
3127  if (!Init)
3128    return false;
3129
3130  return Info.addFieldInitializer(Init);
3131}
3132
3133bool
3134Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3135                               CXXCtorInitializer *Initializer) {
3136  assert(Initializer->isDelegatingInitializer());
3137  Constructor->setNumCtorInitializers(1);
3138  CXXCtorInitializer **initializer =
3139    new (Context) CXXCtorInitializer*[1];
3140  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3141  Constructor->setCtorInitializers(initializer);
3142
3143  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3144    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3145    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3146  }
3147
3148  DelegatingCtorDecls.push_back(Constructor);
3149
3150  return false;
3151}
3152
3153bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3154                               ArrayRef<CXXCtorInitializer *> Initializers) {
3155  if (Constructor->isDependentContext()) {
3156    // Just store the initializers as written, they will be checked during
3157    // instantiation.
3158    if (!Initializers.empty()) {
3159      Constructor->setNumCtorInitializers(Initializers.size());
3160      CXXCtorInitializer **baseOrMemberInitializers =
3161        new (Context) CXXCtorInitializer*[Initializers.size()];
3162      memcpy(baseOrMemberInitializers, Initializers.data(),
3163             Initializers.size() * sizeof(CXXCtorInitializer*));
3164      Constructor->setCtorInitializers(baseOrMemberInitializers);
3165    }
3166
3167    // Let template instantiation know whether we had errors.
3168    if (AnyErrors)
3169      Constructor->setInvalidDecl();
3170
3171    return false;
3172  }
3173
3174  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3175
3176  // We need to build the initializer AST according to order of construction
3177  // and not what user specified in the Initializers list.
3178  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3179  if (!ClassDecl)
3180    return true;
3181
3182  bool HadError = false;
3183
3184  for (unsigned i = 0; i < Initializers.size(); i++) {
3185    CXXCtorInitializer *Member = Initializers[i];
3186
3187    if (Member->isBaseInitializer())
3188      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3189    else
3190      Info.AllBaseFields[Member->getAnyMember()] = Member;
3191  }
3192
3193  // Keep track of the direct virtual bases.
3194  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3195  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3196       E = ClassDecl->bases_end(); I != E; ++I) {
3197    if (I->isVirtual())
3198      DirectVBases.insert(I);
3199  }
3200
3201  // Push virtual bases before others.
3202  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3203       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3204
3205    if (CXXCtorInitializer *Value
3206        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3207      Info.AllToInit.push_back(Value);
3208    } else if (!AnyErrors) {
3209      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3210      CXXCtorInitializer *CXXBaseInit;
3211      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3212                                       VBase, IsInheritedVirtualBase,
3213                                       CXXBaseInit)) {
3214        HadError = true;
3215        continue;
3216      }
3217
3218      Info.AllToInit.push_back(CXXBaseInit);
3219    }
3220  }
3221
3222  // Non-virtual bases.
3223  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3224       E = ClassDecl->bases_end(); Base != E; ++Base) {
3225    // Virtuals are in the virtual base list and already constructed.
3226    if (Base->isVirtual())
3227      continue;
3228
3229    if (CXXCtorInitializer *Value
3230          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3231      Info.AllToInit.push_back(Value);
3232    } else if (!AnyErrors) {
3233      CXXCtorInitializer *CXXBaseInit;
3234      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3235                                       Base, /*IsInheritedVirtualBase=*/false,
3236                                       CXXBaseInit)) {
3237        HadError = true;
3238        continue;
3239      }
3240
3241      Info.AllToInit.push_back(CXXBaseInit);
3242    }
3243  }
3244
3245  // Fields.
3246  for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3247                               MemEnd = ClassDecl->decls_end();
3248       Mem != MemEnd; ++Mem) {
3249    if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3250      // C++ [class.bit]p2:
3251      //   A declaration for a bit-field that omits the identifier declares an
3252      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3253      //   initialized.
3254      if (F->isUnnamedBitfield())
3255        continue;
3256
3257      // If we're not generating the implicit copy/move constructor, then we'll
3258      // handle anonymous struct/union fields based on their individual
3259      // indirect fields.
3260      if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3261        continue;
3262
3263      if (CollectFieldInitializer(*this, Info, F))
3264        HadError = true;
3265      continue;
3266    }
3267
3268    // Beyond this point, we only consider default initialization.
3269    if (Info.isImplicitCopyOrMove())
3270      continue;
3271
3272    if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3273      if (F->getType()->isIncompleteArrayType()) {
3274        assert(ClassDecl->hasFlexibleArrayMember() &&
3275               "Incomplete array type is not valid");
3276        continue;
3277      }
3278
3279      // Initialize each field of an anonymous struct individually.
3280      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3281        HadError = true;
3282
3283      continue;
3284    }
3285  }
3286
3287  unsigned NumInitializers = Info.AllToInit.size();
3288  if (NumInitializers > 0) {
3289    Constructor->setNumCtorInitializers(NumInitializers);
3290    CXXCtorInitializer **baseOrMemberInitializers =
3291      new (Context) CXXCtorInitializer*[NumInitializers];
3292    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3293           NumInitializers * sizeof(CXXCtorInitializer*));
3294    Constructor->setCtorInitializers(baseOrMemberInitializers);
3295
3296    // Constructors implicitly reference the base and member
3297    // destructors.
3298    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3299                                           Constructor->getParent());
3300  }
3301
3302  return HadError;
3303}
3304
3305static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3306  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3307    const RecordDecl *RD = RT->getDecl();
3308    if (RD->isAnonymousStructOrUnion()) {
3309      for (RecordDecl::field_iterator Field = RD->field_begin(),
3310          E = RD->field_end(); Field != E; ++Field)
3311        PopulateKeysForFields(*Field, IdealInits);
3312      return;
3313    }
3314  }
3315  IdealInits.push_back(Field);
3316}
3317
3318static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3319  return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3320}
3321
3322static void *GetKeyForMember(ASTContext &Context,
3323                             CXXCtorInitializer *Member) {
3324  if (!Member->isAnyMemberInitializer())
3325    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3326
3327  return Member->getAnyMember();
3328}
3329
3330static void DiagnoseBaseOrMemInitializerOrder(
3331    Sema &SemaRef, const CXXConstructorDecl *Constructor,
3332    ArrayRef<CXXCtorInitializer *> Inits) {
3333  if (Constructor->getDeclContext()->isDependentContext())
3334    return;
3335
3336  // Don't check initializers order unless the warning is enabled at the
3337  // location of at least one initializer.
3338  bool ShouldCheckOrder = false;
3339  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3340    CXXCtorInitializer *Init = Inits[InitIndex];
3341    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3342                                         Init->getSourceLocation())
3343          != DiagnosticsEngine::Ignored) {
3344      ShouldCheckOrder = true;
3345      break;
3346    }
3347  }
3348  if (!ShouldCheckOrder)
3349    return;
3350
3351  // Build the list of bases and members in the order that they'll
3352  // actually be initialized.  The explicit initializers should be in
3353  // this same order but may be missing things.
3354  SmallVector<const void*, 32> IdealInitKeys;
3355
3356  const CXXRecordDecl *ClassDecl = Constructor->getParent();
3357
3358  // 1. Virtual bases.
3359  for (CXXRecordDecl::base_class_const_iterator VBase =
3360       ClassDecl->vbases_begin(),
3361       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3362    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3363
3364  // 2. Non-virtual bases.
3365  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3366       E = ClassDecl->bases_end(); Base != E; ++Base) {
3367    if (Base->isVirtual())
3368      continue;
3369    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3370  }
3371
3372  // 3. Direct fields.
3373  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3374       E = ClassDecl->field_end(); Field != E; ++Field) {
3375    if (Field->isUnnamedBitfield())
3376      continue;
3377
3378    PopulateKeysForFields(*Field, IdealInitKeys);
3379  }
3380
3381  unsigned NumIdealInits = IdealInitKeys.size();
3382  unsigned IdealIndex = 0;
3383
3384  CXXCtorInitializer *PrevInit = 0;
3385  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3386    CXXCtorInitializer *Init = Inits[InitIndex];
3387    void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3388
3389    // Scan forward to try to find this initializer in the idealized
3390    // initializers list.
3391    for (; IdealIndex != NumIdealInits; ++IdealIndex)
3392      if (InitKey == IdealInitKeys[IdealIndex])
3393        break;
3394
3395    // If we didn't find this initializer, it must be because we
3396    // scanned past it on a previous iteration.  That can only
3397    // happen if we're out of order;  emit a warning.
3398    if (IdealIndex == NumIdealInits && PrevInit) {
3399      Sema::SemaDiagnosticBuilder D =
3400        SemaRef.Diag(PrevInit->getSourceLocation(),
3401                     diag::warn_initializer_out_of_order);
3402
3403      if (PrevInit->isAnyMemberInitializer())
3404        D << 0 << PrevInit->getAnyMember()->getDeclName();
3405      else
3406        D << 1 << PrevInit->getTypeSourceInfo()->getType();
3407
3408      if (Init->isAnyMemberInitializer())
3409        D << 0 << Init->getAnyMember()->getDeclName();
3410      else
3411        D << 1 << Init->getTypeSourceInfo()->getType();
3412
3413      // Move back to the initializer's location in the ideal list.
3414      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3415        if (InitKey == IdealInitKeys[IdealIndex])
3416          break;
3417
3418      assert(IdealIndex != NumIdealInits &&
3419             "initializer not found in initializer list");
3420    }
3421
3422    PrevInit = Init;
3423  }
3424}
3425
3426namespace {
3427bool CheckRedundantInit(Sema &S,
3428                        CXXCtorInitializer *Init,
3429                        CXXCtorInitializer *&PrevInit) {
3430  if (!PrevInit) {
3431    PrevInit = Init;
3432    return false;
3433  }
3434
3435  if (FieldDecl *Field = Init->getAnyMember())
3436    S.Diag(Init->getSourceLocation(),
3437           diag::err_multiple_mem_initialization)
3438      << Field->getDeclName()
3439      << Init->getSourceRange();
3440  else {
3441    const Type *BaseClass = Init->getBaseClass();
3442    assert(BaseClass && "neither field nor base");
3443    S.Diag(Init->getSourceLocation(),
3444           diag::err_multiple_base_initialization)
3445      << QualType(BaseClass, 0)
3446      << Init->getSourceRange();
3447  }
3448  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3449    << 0 << PrevInit->getSourceRange();
3450
3451  return true;
3452}
3453
3454typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3455typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3456
3457bool CheckRedundantUnionInit(Sema &S,
3458                             CXXCtorInitializer *Init,
3459                             RedundantUnionMap &Unions) {
3460  FieldDecl *Field = Init->getAnyMember();
3461  RecordDecl *Parent = Field->getParent();
3462  NamedDecl *Child = Field;
3463
3464  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3465    if (Parent->isUnion()) {
3466      UnionEntry &En = Unions[Parent];
3467      if (En.first && En.first != Child) {
3468        S.Diag(Init->getSourceLocation(),
3469               diag::err_multiple_mem_union_initialization)
3470          << Field->getDeclName()
3471          << Init->getSourceRange();
3472        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3473          << 0 << En.second->getSourceRange();
3474        return true;
3475      }
3476      if (!En.first) {
3477        En.first = Child;
3478        En.second = Init;
3479      }
3480      if (!Parent->isAnonymousStructOrUnion())
3481        return false;
3482    }
3483
3484    Child = Parent;
3485    Parent = cast<RecordDecl>(Parent->getDeclContext());
3486  }
3487
3488  return false;
3489}
3490}
3491
3492/// ActOnMemInitializers - Handle the member initializers for a constructor.
3493void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3494                                SourceLocation ColonLoc,
3495                                ArrayRef<CXXCtorInitializer*> MemInits,
3496                                bool AnyErrors) {
3497  if (!ConstructorDecl)
3498    return;
3499
3500  AdjustDeclIfTemplate(ConstructorDecl);
3501
3502  CXXConstructorDecl *Constructor
3503    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3504
3505  if (!Constructor) {
3506    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3507    return;
3508  }
3509
3510  // Mapping for the duplicate initializers check.
3511  // For member initializers, this is keyed with a FieldDecl*.
3512  // For base initializers, this is keyed with a Type*.
3513  llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3514
3515  // Mapping for the inconsistent anonymous-union initializers check.
3516  RedundantUnionMap MemberUnions;
3517
3518  bool HadError = false;
3519  for (unsigned i = 0; i < MemInits.size(); i++) {
3520    CXXCtorInitializer *Init = MemInits[i];
3521
3522    // Set the source order index.
3523    Init->setSourceOrder(i);
3524
3525    if (Init->isAnyMemberInitializer()) {
3526      FieldDecl *Field = Init->getAnyMember();
3527      if (CheckRedundantInit(*this, Init, Members[Field]) ||
3528          CheckRedundantUnionInit(*this, Init, MemberUnions))
3529        HadError = true;
3530    } else if (Init->isBaseInitializer()) {
3531      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3532      if (CheckRedundantInit(*this, Init, Members[Key]))
3533        HadError = true;
3534    } else {
3535      assert(Init->isDelegatingInitializer());
3536      // This must be the only initializer
3537      if (MemInits.size() != 1) {
3538        Diag(Init->getSourceLocation(),
3539             diag::err_delegating_initializer_alone)
3540          << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3541        // We will treat this as being the only initializer.
3542      }
3543      SetDelegatingInitializer(Constructor, MemInits[i]);
3544      // Return immediately as the initializer is set.
3545      return;
3546    }
3547  }
3548
3549  if (HadError)
3550    return;
3551
3552  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
3553
3554  SetCtorInitializers(Constructor, AnyErrors, MemInits);
3555}
3556
3557void
3558Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3559                                             CXXRecordDecl *ClassDecl) {
3560  // Ignore dependent contexts. Also ignore unions, since their members never
3561  // have destructors implicitly called.
3562  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3563    return;
3564
3565  // FIXME: all the access-control diagnostics are positioned on the
3566  // field/base declaration.  That's probably good; that said, the
3567  // user might reasonably want to know why the destructor is being
3568  // emitted, and we currently don't say.
3569
3570  // Non-static data members.
3571  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3572       E = ClassDecl->field_end(); I != E; ++I) {
3573    FieldDecl *Field = *I;
3574    if (Field->isInvalidDecl())
3575      continue;
3576
3577    // Don't destroy incomplete or zero-length arrays.
3578    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3579      continue;
3580
3581    QualType FieldType = Context.getBaseElementType(Field->getType());
3582
3583    const RecordType* RT = FieldType->getAs<RecordType>();
3584    if (!RT)
3585      continue;
3586
3587    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3588    if (FieldClassDecl->isInvalidDecl())
3589      continue;
3590    if (FieldClassDecl->hasIrrelevantDestructor())
3591      continue;
3592    // The destructor for an implicit anonymous union member is never invoked.
3593    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3594      continue;
3595
3596    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3597    assert(Dtor && "No dtor found for FieldClassDecl!");
3598    CheckDestructorAccess(Field->getLocation(), Dtor,
3599                          PDiag(diag::err_access_dtor_field)
3600                            << Field->getDeclName()
3601                            << FieldType);
3602
3603    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3604    DiagnoseUseOfDecl(Dtor, Location);
3605  }
3606
3607  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3608
3609  // Bases.
3610  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3611       E = ClassDecl->bases_end(); Base != E; ++Base) {
3612    // Bases are always records in a well-formed non-dependent class.
3613    const RecordType *RT = Base->getType()->getAs<RecordType>();
3614
3615    // Remember direct virtual bases.
3616    if (Base->isVirtual())
3617      DirectVirtualBases.insert(RT);
3618
3619    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3620    // If our base class is invalid, we probably can't get its dtor anyway.
3621    if (BaseClassDecl->isInvalidDecl())
3622      continue;
3623    if (BaseClassDecl->hasIrrelevantDestructor())
3624      continue;
3625
3626    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3627    assert(Dtor && "No dtor found for BaseClassDecl!");
3628
3629    // FIXME: caret should be on the start of the class name
3630    CheckDestructorAccess(Base->getLocStart(), Dtor,
3631                          PDiag(diag::err_access_dtor_base)
3632                            << Base->getType()
3633                            << Base->getSourceRange(),
3634                          Context.getTypeDeclType(ClassDecl));
3635
3636    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3637    DiagnoseUseOfDecl(Dtor, Location);
3638  }
3639
3640  // Virtual bases.
3641  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3642       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3643
3644    // Bases are always records in a well-formed non-dependent class.
3645    const RecordType *RT = VBase->getType()->castAs<RecordType>();
3646
3647    // Ignore direct virtual bases.
3648    if (DirectVirtualBases.count(RT))
3649      continue;
3650
3651    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3652    // If our base class is invalid, we probably can't get its dtor anyway.
3653    if (BaseClassDecl->isInvalidDecl())
3654      continue;
3655    if (BaseClassDecl->hasIrrelevantDestructor())
3656      continue;
3657
3658    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3659    assert(Dtor && "No dtor found for BaseClassDecl!");
3660    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3661                          PDiag(diag::err_access_dtor_vbase)
3662                            << VBase->getType(),
3663                          Context.getTypeDeclType(ClassDecl));
3664
3665    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3666    DiagnoseUseOfDecl(Dtor, Location);
3667  }
3668}
3669
3670void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3671  if (!CDtorDecl)
3672    return;
3673
3674  if (CXXConstructorDecl *Constructor
3675      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3676    SetCtorInitializers(Constructor, /*AnyErrors=*/false);
3677}
3678
3679bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3680                                  unsigned DiagID, AbstractDiagSelID SelID) {
3681  class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3682    unsigned DiagID;
3683    AbstractDiagSelID SelID;
3684
3685  public:
3686    NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3687      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3688
3689    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3690      if (Suppressed) return;
3691      if (SelID == -1)
3692        S.Diag(Loc, DiagID) << T;
3693      else
3694        S.Diag(Loc, DiagID) << SelID << T;
3695    }
3696  } Diagnoser(DiagID, SelID);
3697
3698  return RequireNonAbstractType(Loc, T, Diagnoser);
3699}
3700
3701bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3702                                  TypeDiagnoser &Diagnoser) {
3703  if (!getLangOpts().CPlusPlus)
3704    return false;
3705
3706  if (const ArrayType *AT = Context.getAsArrayType(T))
3707    return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3708
3709  if (const PointerType *PT = T->getAs<PointerType>()) {
3710    // Find the innermost pointer type.
3711    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3712      PT = T;
3713
3714    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3715      return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3716  }
3717
3718  const RecordType *RT = T->getAs<RecordType>();
3719  if (!RT)
3720    return false;
3721
3722  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3723
3724  // We can't answer whether something is abstract until it has a
3725  // definition.  If it's currently being defined, we'll walk back
3726  // over all the declarations when we have a full definition.
3727  const CXXRecordDecl *Def = RD->getDefinition();
3728  if (!Def || Def->isBeingDefined())
3729    return false;
3730
3731  if (!RD->isAbstract())
3732    return false;
3733
3734  Diagnoser.diagnose(*this, Loc, T);
3735  DiagnoseAbstractType(RD);
3736
3737  return true;
3738}
3739
3740void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3741  // Check if we've already emitted the list of pure virtual functions
3742  // for this class.
3743  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3744    return;
3745
3746  CXXFinalOverriderMap FinalOverriders;
3747  RD->getFinalOverriders(FinalOverriders);
3748
3749  // Keep a set of seen pure methods so we won't diagnose the same method
3750  // more than once.
3751  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3752
3753  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3754                                   MEnd = FinalOverriders.end();
3755       M != MEnd;
3756       ++M) {
3757    for (OverridingMethods::iterator SO = M->second.begin(),
3758                                  SOEnd = M->second.end();
3759         SO != SOEnd; ++SO) {
3760      // C++ [class.abstract]p4:
3761      //   A class is abstract if it contains or inherits at least one
3762      //   pure virtual function for which the final overrider is pure
3763      //   virtual.
3764
3765      //
3766      if (SO->second.size() != 1)
3767        continue;
3768
3769      if (!SO->second.front().Method->isPure())
3770        continue;
3771
3772      if (!SeenPureMethods.insert(SO->second.front().Method))
3773        continue;
3774
3775      Diag(SO->second.front().Method->getLocation(),
3776           diag::note_pure_virtual_function)
3777        << SO->second.front().Method->getDeclName() << RD->getDeclName();
3778    }
3779  }
3780
3781  if (!PureVirtualClassDiagSet)
3782    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3783  PureVirtualClassDiagSet->insert(RD);
3784}
3785
3786namespace {
3787struct AbstractUsageInfo {
3788  Sema &S;
3789  CXXRecordDecl *Record;
3790  CanQualType AbstractType;
3791  bool Invalid;
3792
3793  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3794    : S(S), Record(Record),
3795      AbstractType(S.Context.getCanonicalType(
3796                   S.Context.getTypeDeclType(Record))),
3797      Invalid(false) {}
3798
3799  void DiagnoseAbstractType() {
3800    if (Invalid) return;
3801    S.DiagnoseAbstractType(Record);
3802    Invalid = true;
3803  }
3804
3805  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3806};
3807
3808struct CheckAbstractUsage {
3809  AbstractUsageInfo &Info;
3810  const NamedDecl *Ctx;
3811
3812  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3813    : Info(Info), Ctx(Ctx) {}
3814
3815  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3816    switch (TL.getTypeLocClass()) {
3817#define ABSTRACT_TYPELOC(CLASS, PARENT)
3818#define TYPELOC(CLASS, PARENT) \
3819    case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
3820#include "clang/AST/TypeLocNodes.def"
3821    }
3822  }
3823
3824  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3825    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3826    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3827      if (!TL.getArg(I))
3828        continue;
3829
3830      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3831      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3832    }
3833  }
3834
3835  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3836    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3837  }
3838
3839  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3840    // Visit the type parameters from a permissive context.
3841    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3842      TemplateArgumentLoc TAL = TL.getArgLoc(I);
3843      if (TAL.getArgument().getKind() == TemplateArgument::Type)
3844        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3845          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3846      // TODO: other template argument types?
3847    }
3848  }
3849
3850  // Visit pointee types from a permissive context.
3851#define CheckPolymorphic(Type) \
3852  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3853    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3854  }
3855  CheckPolymorphic(PointerTypeLoc)
3856  CheckPolymorphic(ReferenceTypeLoc)
3857  CheckPolymorphic(MemberPointerTypeLoc)
3858  CheckPolymorphic(BlockPointerTypeLoc)
3859  CheckPolymorphic(AtomicTypeLoc)
3860
3861  /// Handle all the types we haven't given a more specific
3862  /// implementation for above.
3863  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3864    // Every other kind of type that we haven't called out already
3865    // that has an inner type is either (1) sugar or (2) contains that
3866    // inner type in some way as a subobject.
3867    if (TypeLoc Next = TL.getNextTypeLoc())
3868      return Visit(Next, Sel);
3869
3870    // If there's no inner type and we're in a permissive context,
3871    // don't diagnose.
3872    if (Sel == Sema::AbstractNone) return;
3873
3874    // Check whether the type matches the abstract type.
3875    QualType T = TL.getType();
3876    if (T->isArrayType()) {
3877      Sel = Sema::AbstractArrayType;
3878      T = Info.S.Context.getBaseElementType(T);
3879    }
3880    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3881    if (CT != Info.AbstractType) return;
3882
3883    // It matched; do some magic.
3884    if (Sel == Sema::AbstractArrayType) {
3885      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3886        << T << TL.getSourceRange();
3887    } else {
3888      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3889        << Sel << T << TL.getSourceRange();
3890    }
3891    Info.DiagnoseAbstractType();
3892  }
3893};
3894
3895void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3896                                  Sema::AbstractDiagSelID Sel) {
3897  CheckAbstractUsage(*this, D).Visit(TL, Sel);
3898}
3899
3900}
3901
3902/// Check for invalid uses of an abstract type in a method declaration.
3903static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3904                                    CXXMethodDecl *MD) {
3905  // No need to do the check on definitions, which require that
3906  // the return/param types be complete.
3907  if (MD->doesThisDeclarationHaveABody())
3908    return;
3909
3910  // For safety's sake, just ignore it if we don't have type source
3911  // information.  This should never happen for non-implicit methods,
3912  // but...
3913  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3914    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3915}
3916
3917/// Check for invalid uses of an abstract type within a class definition.
3918static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3919                                    CXXRecordDecl *RD) {
3920  for (CXXRecordDecl::decl_iterator
3921         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3922    Decl *D = *I;
3923    if (D->isImplicit()) continue;
3924
3925    // Methods and method templates.
3926    if (isa<CXXMethodDecl>(D)) {
3927      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3928    } else if (isa<FunctionTemplateDecl>(D)) {
3929      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3930      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3931
3932    // Fields and static variables.
3933    } else if (isa<FieldDecl>(D)) {
3934      FieldDecl *FD = cast<FieldDecl>(D);
3935      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3936        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3937    } else if (isa<VarDecl>(D)) {
3938      VarDecl *VD = cast<VarDecl>(D);
3939      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3940        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3941
3942    // Nested classes and class templates.
3943    } else if (isa<CXXRecordDecl>(D)) {
3944      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3945    } else if (isa<ClassTemplateDecl>(D)) {
3946      CheckAbstractClassUsage(Info,
3947                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3948    }
3949  }
3950}
3951
3952/// \brief Perform semantic checks on a class definition that has been
3953/// completing, introducing implicitly-declared members, checking for
3954/// abstract types, etc.
3955void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3956  if (!Record)
3957    return;
3958
3959  if (Record->isAbstract() && !Record->isInvalidDecl()) {
3960    AbstractUsageInfo Info(*this, Record);
3961    CheckAbstractClassUsage(Info, Record);
3962  }
3963
3964  // If this is not an aggregate type and has no user-declared constructor,
3965  // complain about any non-static data members of reference or const scalar
3966  // type, since they will never get initializers.
3967  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3968      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3969      !Record->isLambda()) {
3970    bool Complained = false;
3971    for (RecordDecl::field_iterator F = Record->field_begin(),
3972                                 FEnd = Record->field_end();
3973         F != FEnd; ++F) {
3974      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
3975        continue;
3976
3977      if (F->getType()->isReferenceType() ||
3978          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3979        if (!Complained) {
3980          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3981            << Record->getTagKind() << Record;
3982          Complained = true;
3983        }
3984
3985        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3986          << F->getType()->isReferenceType()
3987          << F->getDeclName();
3988      }
3989    }
3990  }
3991
3992  if (Record->isDynamicClass() && !Record->isDependentType())
3993    DynamicClasses.push_back(Record);
3994
3995  if (Record->getIdentifier()) {
3996    // C++ [class.mem]p13:
3997    //   If T is the name of a class, then each of the following shall have a
3998    //   name different from T:
3999    //     - every member of every anonymous union that is a member of class T.
4000    //
4001    // C++ [class.mem]p14:
4002    //   In addition, if class T has a user-declared constructor (12.1), every
4003    //   non-static data member of class T shall have a name different from T.
4004    DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4005    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4006         ++I) {
4007      NamedDecl *D = *I;
4008      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4009          isa<IndirectFieldDecl>(D)) {
4010        Diag(D->getLocation(), diag::err_member_name_of_class)
4011          << D->getDeclName();
4012        break;
4013      }
4014    }
4015  }
4016
4017  // Warn if the class has virtual methods but non-virtual public destructor.
4018  if (Record->isPolymorphic() && !Record->isDependentType()) {
4019    CXXDestructorDecl *dtor = Record->getDestructor();
4020    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
4021      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4022           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4023  }
4024
4025  if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4026    Diag(Record->getLocation(), diag::warn_abstract_final_class);
4027    DiagnoseAbstractType(Record);
4028  }
4029
4030  if (!Record->isDependentType()) {
4031    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4032                                     MEnd = Record->method_end();
4033         M != MEnd; ++M) {
4034      // See if a method overloads virtual methods in a base
4035      // class without overriding any.
4036      if (!M->isStatic())
4037        DiagnoseHiddenVirtualMethods(Record, *M);
4038
4039      // Check whether the explicitly-defaulted special members are valid.
4040      if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4041        CheckExplicitlyDefaultedSpecialMember(*M);
4042
4043      // For an explicitly defaulted or deleted special member, we defer
4044      // determining triviality until the class is complete. That time is now!
4045      if (!M->isImplicit() && !M->isUserProvided()) {
4046        CXXSpecialMember CSM = getSpecialMember(*M);
4047        if (CSM != CXXInvalid) {
4048          M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4049
4050          // Inform the class that we've finished declaring this member.
4051          Record->finishedDefaultedOrDeletedMember(*M);
4052        }
4053      }
4054    }
4055  }
4056
4057  // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4058  // function that is not a constructor declares that member function to be
4059  // const. [...] The class of which that function is a member shall be
4060  // a literal type.
4061  //
4062  // If the class has virtual bases, any constexpr members will already have
4063  // been diagnosed by the checks performed on the member declaration, so
4064  // suppress this (less useful) diagnostic.
4065  //
4066  // We delay this until we know whether an explicitly-defaulted (or deleted)
4067  // destructor for the class is trivial.
4068  if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4069      !Record->isLiteral() && !Record->getNumVBases()) {
4070    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4071                                     MEnd = Record->method_end();
4072         M != MEnd; ++M) {
4073      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4074        switch (Record->getTemplateSpecializationKind()) {
4075        case TSK_ImplicitInstantiation:
4076        case TSK_ExplicitInstantiationDeclaration:
4077        case TSK_ExplicitInstantiationDefinition:
4078          // If a template instantiates to a non-literal type, but its members
4079          // instantiate to constexpr functions, the template is technically
4080          // ill-formed, but we allow it for sanity.
4081          continue;
4082
4083        case TSK_Undeclared:
4084        case TSK_ExplicitSpecialization:
4085          RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4086                             diag::err_constexpr_method_non_literal);
4087          break;
4088        }
4089
4090        // Only produce one error per class.
4091        break;
4092      }
4093    }
4094  }
4095
4096  // Declare inheriting constructors. We do this eagerly here because:
4097  // - The standard requires an eager diagnostic for conflicting inheriting
4098  //   constructors from different classes.
4099  // - The lazy declaration of the other implicit constructors is so as to not
4100  //   waste space and performance on classes that are not meant to be
4101  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4102  //   have inheriting constructors.
4103  DeclareInheritingConstructors(Record);
4104}
4105
4106/// Is the special member function which would be selected to perform the
4107/// specified operation on the specified class type a constexpr constructor?
4108static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4109                                     Sema::CXXSpecialMember CSM,
4110                                     bool ConstArg) {
4111  Sema::SpecialMemberOverloadResult *SMOR =
4112      S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4113                            false, false, false, false);
4114  if (!SMOR || !SMOR->getMethod())
4115    // A constructor we wouldn't select can't be "involved in initializing"
4116    // anything.
4117    return true;
4118  return SMOR->getMethod()->isConstexpr();
4119}
4120
4121/// Determine whether the specified special member function would be constexpr
4122/// if it were implicitly defined.
4123static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4124                                              Sema::CXXSpecialMember CSM,
4125                                              bool ConstArg) {
4126  if (!S.getLangOpts().CPlusPlus11)
4127    return false;
4128
4129  // C++11 [dcl.constexpr]p4:
4130  // In the definition of a constexpr constructor [...]
4131  switch (CSM) {
4132  case Sema::CXXDefaultConstructor:
4133    // Since default constructor lookup is essentially trivial (and cannot
4134    // involve, for instance, template instantiation), we compute whether a
4135    // defaulted default constructor is constexpr directly within CXXRecordDecl.
4136    //
4137    // This is important for performance; we need to know whether the default
4138    // constructor is constexpr to determine whether the type is a literal type.
4139    return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4140
4141  case Sema::CXXCopyConstructor:
4142  case Sema::CXXMoveConstructor:
4143    // For copy or move constructors, we need to perform overload resolution.
4144    break;
4145
4146  case Sema::CXXCopyAssignment:
4147  case Sema::CXXMoveAssignment:
4148  case Sema::CXXDestructor:
4149  case Sema::CXXInvalid:
4150    return false;
4151  }
4152
4153  //   -- if the class is a non-empty union, or for each non-empty anonymous
4154  //      union member of a non-union class, exactly one non-static data member
4155  //      shall be initialized; [DR1359]
4156  //
4157  // If we squint, this is guaranteed, since exactly one non-static data member
4158  // will be initialized (if the constructor isn't deleted), we just don't know
4159  // which one.
4160  if (ClassDecl->isUnion())
4161    return true;
4162
4163  //   -- the class shall not have any virtual base classes;
4164  if (ClassDecl->getNumVBases())
4165    return false;
4166
4167  //   -- every constructor involved in initializing [...] base class
4168  //      sub-objects shall be a constexpr constructor;
4169  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4170                                       BEnd = ClassDecl->bases_end();
4171       B != BEnd; ++B) {
4172    const RecordType *BaseType = B->getType()->getAs<RecordType>();
4173    if (!BaseType) continue;
4174
4175    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4176    if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4177      return false;
4178  }
4179
4180  //   -- every constructor involved in initializing non-static data members
4181  //      [...] shall be a constexpr constructor;
4182  //   -- every non-static data member and base class sub-object shall be
4183  //      initialized
4184  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4185                               FEnd = ClassDecl->field_end();
4186       F != FEnd; ++F) {
4187    if (F->isInvalidDecl())
4188      continue;
4189    if (const RecordType *RecordTy =
4190            S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4191      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4192      if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4193        return false;
4194    }
4195  }
4196
4197  // All OK, it's constexpr!
4198  return true;
4199}
4200
4201static Sema::ImplicitExceptionSpecification
4202computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4203  switch (S.getSpecialMember(MD)) {
4204  case Sema::CXXDefaultConstructor:
4205    return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4206  case Sema::CXXCopyConstructor:
4207    return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4208  case Sema::CXXCopyAssignment:
4209    return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4210  case Sema::CXXMoveConstructor:
4211    return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4212  case Sema::CXXMoveAssignment:
4213    return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4214  case Sema::CXXDestructor:
4215    return S.ComputeDefaultedDtorExceptionSpec(MD);
4216  case Sema::CXXInvalid:
4217    break;
4218  }
4219  assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4220         "only special members have implicit exception specs");
4221  return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4222}
4223
4224static void
4225updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4226                    const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4227  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4228  ExceptSpec.getEPI(EPI);
4229  const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4230      S.Context.getFunctionType(FPT->getResultType(), FPT->getArgTypes(), EPI));
4231  FD->setType(QualType(NewFPT, 0));
4232}
4233
4234void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4235  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4236  if (FPT->getExceptionSpecType() != EST_Unevaluated)
4237    return;
4238
4239  // Evaluate the exception specification.
4240  ImplicitExceptionSpecification ExceptSpec =
4241      computeImplicitExceptionSpec(*this, Loc, MD);
4242
4243  // Update the type of the special member to use it.
4244  updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4245
4246  // A user-provided destructor can be defined outside the class. When that
4247  // happens, be sure to update the exception specification on both
4248  // declarations.
4249  const FunctionProtoType *CanonicalFPT =
4250    MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4251  if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4252    updateExceptionSpec(*this, MD->getCanonicalDecl(),
4253                        CanonicalFPT, ExceptSpec);
4254}
4255
4256void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4257  CXXRecordDecl *RD = MD->getParent();
4258  CXXSpecialMember CSM = getSpecialMember(MD);
4259
4260  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4261         "not an explicitly-defaulted special member");
4262
4263  // Whether this was the first-declared instance of the constructor.
4264  // This affects whether we implicitly add an exception spec and constexpr.
4265  bool First = MD == MD->getCanonicalDecl();
4266
4267  bool HadError = false;
4268
4269  // C++11 [dcl.fct.def.default]p1:
4270  //   A function that is explicitly defaulted shall
4271  //     -- be a special member function (checked elsewhere),
4272  //     -- have the same type (except for ref-qualifiers, and except that a
4273  //        copy operation can take a non-const reference) as an implicit
4274  //        declaration, and
4275  //     -- not have default arguments.
4276  unsigned ExpectedParams = 1;
4277  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4278    ExpectedParams = 0;
4279  if (MD->getNumParams() != ExpectedParams) {
4280    // This also checks for default arguments: a copy or move constructor with a
4281    // default argument is classified as a default constructor, and assignment
4282    // operations and destructors can't have default arguments.
4283    Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4284      << CSM << MD->getSourceRange();
4285    HadError = true;
4286  } else if (MD->isVariadic()) {
4287    Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4288      << CSM << MD->getSourceRange();
4289    HadError = true;
4290  }
4291
4292  const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4293
4294  bool CanHaveConstParam = false;
4295  if (CSM == CXXCopyConstructor)
4296    CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4297  else if (CSM == CXXCopyAssignment)
4298    CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4299
4300  QualType ReturnType = Context.VoidTy;
4301  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4302    // Check for return type matching.
4303    ReturnType = Type->getResultType();
4304    QualType ExpectedReturnType =
4305        Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4306    if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4307      Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4308        << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4309      HadError = true;
4310    }
4311
4312    // A defaulted special member cannot have cv-qualifiers.
4313    if (Type->getTypeQuals()) {
4314      Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4315        << (CSM == CXXMoveAssignment);
4316      HadError = true;
4317    }
4318  }
4319
4320  // Check for parameter type matching.
4321  QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4322  bool HasConstParam = false;
4323  if (ExpectedParams && ArgType->isReferenceType()) {
4324    // Argument must be reference to possibly-const T.
4325    QualType ReferentType = ArgType->getPointeeType();
4326    HasConstParam = ReferentType.isConstQualified();
4327
4328    if (ReferentType.isVolatileQualified()) {
4329      Diag(MD->getLocation(),
4330           diag::err_defaulted_special_member_volatile_param) << CSM;
4331      HadError = true;
4332    }
4333
4334    if (HasConstParam && !CanHaveConstParam) {
4335      if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4336        Diag(MD->getLocation(),
4337             diag::err_defaulted_special_member_copy_const_param)
4338          << (CSM == CXXCopyAssignment);
4339        // FIXME: Explain why this special member can't be const.
4340      } else {
4341        Diag(MD->getLocation(),
4342             diag::err_defaulted_special_member_move_const_param)
4343          << (CSM == CXXMoveAssignment);
4344      }
4345      HadError = true;
4346    }
4347  } else if (ExpectedParams) {
4348    // A copy assignment operator can take its argument by value, but a
4349    // defaulted one cannot.
4350    assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4351    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4352    HadError = true;
4353  }
4354
4355  // C++11 [dcl.fct.def.default]p2:
4356  //   An explicitly-defaulted function may be declared constexpr only if it
4357  //   would have been implicitly declared as constexpr,
4358  // Do not apply this rule to members of class templates, since core issue 1358
4359  // makes such functions always instantiate to constexpr functions. For
4360  // non-constructors, this is checked elsewhere.
4361  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4362                                                     HasConstParam);
4363  if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4364      MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4365    Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4366    // FIXME: Explain why the constructor can't be constexpr.
4367    HadError = true;
4368  }
4369
4370  //   and may have an explicit exception-specification only if it is compatible
4371  //   with the exception-specification on the implicit declaration.
4372  if (Type->hasExceptionSpec()) {
4373    // Delay the check if this is the first declaration of the special member,
4374    // since we may not have parsed some necessary in-class initializers yet.
4375    if (First)
4376      DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4377    else
4378      CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4379  }
4380
4381  //   If a function is explicitly defaulted on its first declaration,
4382  if (First) {
4383    //  -- it is implicitly considered to be constexpr if the implicit
4384    //     definition would be,
4385    MD->setConstexpr(Constexpr);
4386
4387    //  -- it is implicitly considered to have the same exception-specification
4388    //     as if it had been implicitly declared,
4389    FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4390    EPI.ExceptionSpecType = EST_Unevaluated;
4391    EPI.ExceptionSpecDecl = MD;
4392    MD->setType(Context.getFunctionType(ReturnType,
4393                                        ArrayRef<QualType>(&ArgType,
4394                                                           ExpectedParams),
4395                                        EPI));
4396  }
4397
4398  if (ShouldDeleteSpecialMember(MD, CSM)) {
4399    if (First) {
4400      MD->setDeletedAsWritten();
4401    } else {
4402      // C++11 [dcl.fct.def.default]p4:
4403      //   [For a] user-provided explicitly-defaulted function [...] if such a
4404      //   function is implicitly defined as deleted, the program is ill-formed.
4405      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4406      HadError = true;
4407    }
4408  }
4409
4410  if (HadError)
4411    MD->setInvalidDecl();
4412}
4413
4414/// Check whether the exception specification provided for an
4415/// explicitly-defaulted special member matches the exception specification
4416/// that would have been generated for an implicit special member, per
4417/// C++11 [dcl.fct.def.default]p2.
4418void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4419    CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4420  // Compute the implicit exception specification.
4421  FunctionProtoType::ExtProtoInfo EPI;
4422  computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4423  const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4424    Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI));
4425
4426  // Ensure that it matches.
4427  CheckEquivalentExceptionSpec(
4428    PDiag(diag::err_incorrect_defaulted_exception_spec)
4429      << getSpecialMember(MD), PDiag(),
4430    ImplicitType, SourceLocation(),
4431    SpecifiedType, MD->getLocation());
4432}
4433
4434void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4435  for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4436       I != N; ++I)
4437    CheckExplicitlyDefaultedMemberExceptionSpec(
4438      DelayedDefaultedMemberExceptionSpecs[I].first,
4439      DelayedDefaultedMemberExceptionSpecs[I].second);
4440
4441  DelayedDefaultedMemberExceptionSpecs.clear();
4442}
4443
4444namespace {
4445struct SpecialMemberDeletionInfo {
4446  Sema &S;
4447  CXXMethodDecl *MD;
4448  Sema::CXXSpecialMember CSM;
4449  bool Diagnose;
4450
4451  // Properties of the special member, computed for convenience.
4452  bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4453  SourceLocation Loc;
4454
4455  bool AllFieldsAreConst;
4456
4457  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4458                            Sema::CXXSpecialMember CSM, bool Diagnose)
4459    : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4460      IsConstructor(false), IsAssignment(false), IsMove(false),
4461      ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4462      AllFieldsAreConst(true) {
4463    switch (CSM) {
4464      case Sema::CXXDefaultConstructor:
4465      case Sema::CXXCopyConstructor:
4466        IsConstructor = true;
4467        break;
4468      case Sema::CXXMoveConstructor:
4469        IsConstructor = true;
4470        IsMove = true;
4471        break;
4472      case Sema::CXXCopyAssignment:
4473        IsAssignment = true;
4474        break;
4475      case Sema::CXXMoveAssignment:
4476        IsAssignment = true;
4477        IsMove = true;
4478        break;
4479      case Sema::CXXDestructor:
4480        break;
4481      case Sema::CXXInvalid:
4482        llvm_unreachable("invalid special member kind");
4483    }
4484
4485    if (MD->getNumParams()) {
4486      ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4487      VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4488    }
4489  }
4490
4491  bool inUnion() const { return MD->getParent()->isUnion(); }
4492
4493  /// Look up the corresponding special member in the given class.
4494  Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4495                                              unsigned Quals) {
4496    unsigned TQ = MD->getTypeQualifiers();
4497    // cv-qualifiers on class members don't affect default ctor / dtor calls.
4498    if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4499      Quals = 0;
4500    return S.LookupSpecialMember(Class, CSM,
4501                                 ConstArg || (Quals & Qualifiers::Const),
4502                                 VolatileArg || (Quals & Qualifiers::Volatile),
4503                                 MD->getRefQualifier() == RQ_RValue,
4504                                 TQ & Qualifiers::Const,
4505                                 TQ & Qualifiers::Volatile);
4506  }
4507
4508  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4509
4510  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4511  bool shouldDeleteForField(FieldDecl *FD);
4512  bool shouldDeleteForAllConstMembers();
4513
4514  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4515                                     unsigned Quals);
4516  bool shouldDeleteForSubobjectCall(Subobject Subobj,
4517                                    Sema::SpecialMemberOverloadResult *SMOR,
4518                                    bool IsDtorCallInCtor);
4519
4520  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4521};
4522}
4523
4524/// Is the given special member inaccessible when used on the given
4525/// sub-object.
4526bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4527                                             CXXMethodDecl *target) {
4528  /// If we're operating on a base class, the object type is the
4529  /// type of this special member.
4530  QualType objectTy;
4531  AccessSpecifier access = target->getAccess();
4532  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4533    objectTy = S.Context.getTypeDeclType(MD->getParent());
4534    access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4535
4536  // If we're operating on a field, the object type is the type of the field.
4537  } else {
4538    objectTy = S.Context.getTypeDeclType(target->getParent());
4539  }
4540
4541  return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4542}
4543
4544/// Check whether we should delete a special member due to the implicit
4545/// definition containing a call to a special member of a subobject.
4546bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4547    Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4548    bool IsDtorCallInCtor) {
4549  CXXMethodDecl *Decl = SMOR->getMethod();
4550  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4551
4552  int DiagKind = -1;
4553
4554  if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4555    DiagKind = !Decl ? 0 : 1;
4556  else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4557    DiagKind = 2;
4558  else if (!isAccessible(Subobj, Decl))
4559    DiagKind = 3;
4560  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4561           !Decl->isTrivial()) {
4562    // A member of a union must have a trivial corresponding special member.
4563    // As a weird special case, a destructor call from a union's constructor
4564    // must be accessible and non-deleted, but need not be trivial. Such a
4565    // destructor is never actually called, but is semantically checked as
4566    // if it were.
4567    DiagKind = 4;
4568  }
4569
4570  if (DiagKind == -1)
4571    return false;
4572
4573  if (Diagnose) {
4574    if (Field) {
4575      S.Diag(Field->getLocation(),
4576             diag::note_deleted_special_member_class_subobject)
4577        << CSM << MD->getParent() << /*IsField*/true
4578        << Field << DiagKind << IsDtorCallInCtor;
4579    } else {
4580      CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4581      S.Diag(Base->getLocStart(),
4582             diag::note_deleted_special_member_class_subobject)
4583        << CSM << MD->getParent() << /*IsField*/false
4584        << Base->getType() << DiagKind << IsDtorCallInCtor;
4585    }
4586
4587    if (DiagKind == 1)
4588      S.NoteDeletedFunction(Decl);
4589    // FIXME: Explain inaccessibility if DiagKind == 3.
4590  }
4591
4592  return true;
4593}
4594
4595/// Check whether we should delete a special member function due to having a
4596/// direct or virtual base class or non-static data member of class type M.
4597bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4598    CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
4599  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4600
4601  // C++11 [class.ctor]p5:
4602  // -- any direct or virtual base class, or non-static data member with no
4603  //    brace-or-equal-initializer, has class type M (or array thereof) and
4604  //    either M has no default constructor or overload resolution as applied
4605  //    to M's default constructor results in an ambiguity or in a function
4606  //    that is deleted or inaccessible
4607  // C++11 [class.copy]p11, C++11 [class.copy]p23:
4608  // -- a direct or virtual base class B that cannot be copied/moved because
4609  //    overload resolution, as applied to B's corresponding special member,
4610  //    results in an ambiguity or a function that is deleted or inaccessible
4611  //    from the defaulted special member
4612  // C++11 [class.dtor]p5:
4613  // -- any direct or virtual base class [...] has a type with a destructor
4614  //    that is deleted or inaccessible
4615  if (!(CSM == Sema::CXXDefaultConstructor &&
4616        Field && Field->hasInClassInitializer()) &&
4617      shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
4618    return true;
4619
4620  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4621  // -- any direct or virtual base class or non-static data member has a
4622  //    type with a destructor that is deleted or inaccessible
4623  if (IsConstructor) {
4624    Sema::SpecialMemberOverloadResult *SMOR =
4625        S.LookupSpecialMember(Class, Sema::CXXDestructor,
4626                              false, false, false, false, false);
4627    if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4628      return true;
4629  }
4630
4631  return false;
4632}
4633
4634/// Check whether we should delete a special member function due to the class
4635/// having a particular direct or virtual base class.
4636bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4637  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4638  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
4639}
4640
4641/// Check whether we should delete a special member function due to the class
4642/// having a particular non-static data member.
4643bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4644  QualType FieldType = S.Context.getBaseElementType(FD->getType());
4645  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4646
4647  if (CSM == Sema::CXXDefaultConstructor) {
4648    // For a default constructor, all references must be initialized in-class
4649    // and, if a union, it must have a non-const member.
4650    if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4651      if (Diagnose)
4652        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4653          << MD->getParent() << FD << FieldType << /*Reference*/0;
4654      return true;
4655    }
4656    // C++11 [class.ctor]p5: any non-variant non-static data member of
4657    // const-qualified type (or array thereof) with no
4658    // brace-or-equal-initializer does not have a user-provided default
4659    // constructor.
4660    if (!inUnion() && FieldType.isConstQualified() &&
4661        !FD->hasInClassInitializer() &&
4662        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4663      if (Diagnose)
4664        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4665          << MD->getParent() << FD << FD->getType() << /*Const*/1;
4666      return true;
4667    }
4668
4669    if (inUnion() && !FieldType.isConstQualified())
4670      AllFieldsAreConst = false;
4671  } else if (CSM == Sema::CXXCopyConstructor) {
4672    // For a copy constructor, data members must not be of rvalue reference
4673    // type.
4674    if (FieldType->isRValueReferenceType()) {
4675      if (Diagnose)
4676        S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4677          << MD->getParent() << FD << FieldType;
4678      return true;
4679    }
4680  } else if (IsAssignment) {
4681    // For an assignment operator, data members must not be of reference type.
4682    if (FieldType->isReferenceType()) {
4683      if (Diagnose)
4684        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4685          << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4686      return true;
4687    }
4688    if (!FieldRecord && FieldType.isConstQualified()) {
4689      // C++11 [class.copy]p23:
4690      // -- a non-static data member of const non-class type (or array thereof)
4691      if (Diagnose)
4692        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4693          << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
4694      return true;
4695    }
4696  }
4697
4698  if (FieldRecord) {
4699    // Some additional restrictions exist on the variant members.
4700    if (!inUnion() && FieldRecord->isUnion() &&
4701        FieldRecord->isAnonymousStructOrUnion()) {
4702      bool AllVariantFieldsAreConst = true;
4703
4704      // FIXME: Handle anonymous unions declared within anonymous unions.
4705      for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4706                                         UE = FieldRecord->field_end();
4707           UI != UE; ++UI) {
4708        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4709
4710        if (!UnionFieldType.isConstQualified())
4711          AllVariantFieldsAreConst = false;
4712
4713        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4714        if (UnionFieldRecord &&
4715            shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4716                                          UnionFieldType.getCVRQualifiers()))
4717          return true;
4718      }
4719
4720      // At least one member in each anonymous union must be non-const
4721      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4722          FieldRecord->field_begin() != FieldRecord->field_end()) {
4723        if (Diagnose)
4724          S.Diag(FieldRecord->getLocation(),
4725                 diag::note_deleted_default_ctor_all_const)
4726            << MD->getParent() << /*anonymous union*/1;
4727        return true;
4728      }
4729
4730      // Don't check the implicit member of the anonymous union type.
4731      // This is technically non-conformant, but sanity demands it.
4732      return false;
4733    }
4734
4735    if (shouldDeleteForClassSubobject(FieldRecord, FD,
4736                                      FieldType.getCVRQualifiers()))
4737      return true;
4738  }
4739
4740  return false;
4741}
4742
4743/// C++11 [class.ctor] p5:
4744///   A defaulted default constructor for a class X is defined as deleted if
4745/// X is a union and all of its variant members are of const-qualified type.
4746bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4747  // This is a silly definition, because it gives an empty union a deleted
4748  // default constructor. Don't do that.
4749  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4750      (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4751    if (Diagnose)
4752      S.Diag(MD->getParent()->getLocation(),
4753             diag::note_deleted_default_ctor_all_const)
4754        << MD->getParent() << /*not anonymous union*/0;
4755    return true;
4756  }
4757  return false;
4758}
4759
4760/// Determine whether a defaulted special member function should be defined as
4761/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4762/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
4763bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4764                                     bool Diagnose) {
4765  if (MD->isInvalidDecl())
4766    return false;
4767  CXXRecordDecl *RD = MD->getParent();
4768  assert(!RD->isDependentType() && "do deletion after instantiation");
4769  if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
4770    return false;
4771
4772  // C++11 [expr.lambda.prim]p19:
4773  //   The closure type associated with a lambda-expression has a
4774  //   deleted (8.4.3) default constructor and a deleted copy
4775  //   assignment operator.
4776  if (RD->isLambda() &&
4777      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4778    if (Diagnose)
4779      Diag(RD->getLocation(), diag::note_lambda_decl);
4780    return true;
4781  }
4782
4783  // For an anonymous struct or union, the copy and assignment special members
4784  // will never be used, so skip the check. For an anonymous union declared at
4785  // namespace scope, the constructor and destructor are used.
4786  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4787      RD->isAnonymousStructOrUnion())
4788    return false;
4789
4790  // C++11 [class.copy]p7, p18:
4791  //   If the class definition declares a move constructor or move assignment
4792  //   operator, an implicitly declared copy constructor or copy assignment
4793  //   operator is defined as deleted.
4794  if (MD->isImplicit() &&
4795      (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4796    CXXMethodDecl *UserDeclaredMove = 0;
4797
4798    // In Microsoft mode, a user-declared move only causes the deletion of the
4799    // corresponding copy operation, not both copy operations.
4800    if (RD->hasUserDeclaredMoveConstructor() &&
4801        (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4802      if (!Diagnose) return true;
4803
4804      // Find any user-declared move constructor.
4805      for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4806                                        E = RD->ctor_end(); I != E; ++I) {
4807        if (I->isMoveConstructor()) {
4808          UserDeclaredMove = *I;
4809          break;
4810        }
4811      }
4812      assert(UserDeclaredMove);
4813    } else if (RD->hasUserDeclaredMoveAssignment() &&
4814               (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4815      if (!Diagnose) return true;
4816
4817      // Find any user-declared move assignment operator.
4818      for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4819                                          E = RD->method_end(); I != E; ++I) {
4820        if (I->isMoveAssignmentOperator()) {
4821          UserDeclaredMove = *I;
4822          break;
4823        }
4824      }
4825      assert(UserDeclaredMove);
4826    }
4827
4828    if (UserDeclaredMove) {
4829      Diag(UserDeclaredMove->getLocation(),
4830           diag::note_deleted_copy_user_declared_move)
4831        << (CSM == CXXCopyAssignment) << RD
4832        << UserDeclaredMove->isMoveAssignmentOperator();
4833      return true;
4834    }
4835  }
4836
4837  // Do access control from the special member function
4838  ContextRAII MethodContext(*this, MD);
4839
4840  // C++11 [class.dtor]p5:
4841  // -- for a virtual destructor, lookup of the non-array deallocation function
4842  //    results in an ambiguity or in a function that is deleted or inaccessible
4843  if (CSM == CXXDestructor && MD->isVirtual()) {
4844    FunctionDecl *OperatorDelete = 0;
4845    DeclarationName Name =
4846      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4847    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
4848                                 OperatorDelete, false)) {
4849      if (Diagnose)
4850        Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
4851      return true;
4852    }
4853  }
4854
4855  SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
4856
4857  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4858                                          BE = RD->bases_end(); BI != BE; ++BI)
4859    if (!BI->isVirtual() &&
4860        SMI.shouldDeleteForBase(BI))
4861      return true;
4862
4863  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4864                                          BE = RD->vbases_end(); BI != BE; ++BI)
4865    if (SMI.shouldDeleteForBase(BI))
4866      return true;
4867
4868  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4869                                     FE = RD->field_end(); FI != FE; ++FI)
4870    if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4871        SMI.shouldDeleteForField(*FI))
4872      return true;
4873
4874  if (SMI.shouldDeleteForAllConstMembers())
4875    return true;
4876
4877  return false;
4878}
4879
4880/// Perform lookup for a special member of the specified kind, and determine
4881/// whether it is trivial. If the triviality can be determined without the
4882/// lookup, skip it. This is intended for use when determining whether a
4883/// special member of a containing object is trivial, and thus does not ever
4884/// perform overload resolution for default constructors.
4885///
4886/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4887/// member that was most likely to be intended to be trivial, if any.
4888static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4889                                     Sema::CXXSpecialMember CSM, unsigned Quals,
4890                                     CXXMethodDecl **Selected) {
4891  if (Selected)
4892    *Selected = 0;
4893
4894  switch (CSM) {
4895  case Sema::CXXInvalid:
4896    llvm_unreachable("not a special member");
4897
4898  case Sema::CXXDefaultConstructor:
4899    // C++11 [class.ctor]p5:
4900    //   A default constructor is trivial if:
4901    //    - all the [direct subobjects] have trivial default constructors
4902    //
4903    // Note, no overload resolution is performed in this case.
4904    if (RD->hasTrivialDefaultConstructor())
4905      return true;
4906
4907    if (Selected) {
4908      // If there's a default constructor which could have been trivial, dig it
4909      // out. Otherwise, if there's any user-provided default constructor, point
4910      // to that as an example of why there's not a trivial one.
4911      CXXConstructorDecl *DefCtor = 0;
4912      if (RD->needsImplicitDefaultConstructor())
4913        S.DeclareImplicitDefaultConstructor(RD);
4914      for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4915                                        CE = RD->ctor_end(); CI != CE; ++CI) {
4916        if (!CI->isDefaultConstructor())
4917          continue;
4918        DefCtor = *CI;
4919        if (!DefCtor->isUserProvided())
4920          break;
4921      }
4922
4923      *Selected = DefCtor;
4924    }
4925
4926    return false;
4927
4928  case Sema::CXXDestructor:
4929    // C++11 [class.dtor]p5:
4930    //   A destructor is trivial if:
4931    //    - all the direct [subobjects] have trivial destructors
4932    if (RD->hasTrivialDestructor())
4933      return true;
4934
4935    if (Selected) {
4936      if (RD->needsImplicitDestructor())
4937        S.DeclareImplicitDestructor(RD);
4938      *Selected = RD->getDestructor();
4939    }
4940
4941    return false;
4942
4943  case Sema::CXXCopyConstructor:
4944    // C++11 [class.copy]p12:
4945    //   A copy constructor is trivial if:
4946    //    - the constructor selected to copy each direct [subobject] is trivial
4947    if (RD->hasTrivialCopyConstructor()) {
4948      if (Quals == Qualifiers::Const)
4949        // We must either select the trivial copy constructor or reach an
4950        // ambiguity; no need to actually perform overload resolution.
4951        return true;
4952    } else if (!Selected) {
4953      return false;
4954    }
4955    // In C++98, we are not supposed to perform overload resolution here, but we
4956    // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4957    // cases like B as having a non-trivial copy constructor:
4958    //   struct A { template<typename T> A(T&); };
4959    //   struct B { mutable A a; };
4960    goto NeedOverloadResolution;
4961
4962  case Sema::CXXCopyAssignment:
4963    // C++11 [class.copy]p25:
4964    //   A copy assignment operator is trivial if:
4965    //    - the assignment operator selected to copy each direct [subobject] is
4966    //      trivial
4967    if (RD->hasTrivialCopyAssignment()) {
4968      if (Quals == Qualifiers::Const)
4969        return true;
4970    } else if (!Selected) {
4971      return false;
4972    }
4973    // In C++98, we are not supposed to perform overload resolution here, but we
4974    // treat that as a language defect.
4975    goto NeedOverloadResolution;
4976
4977  case Sema::CXXMoveConstructor:
4978  case Sema::CXXMoveAssignment:
4979  NeedOverloadResolution:
4980    Sema::SpecialMemberOverloadResult *SMOR =
4981      S.LookupSpecialMember(RD, CSM,
4982                            Quals & Qualifiers::Const,
4983                            Quals & Qualifiers::Volatile,
4984                            /*RValueThis*/false, /*ConstThis*/false,
4985                            /*VolatileThis*/false);
4986
4987    // The standard doesn't describe how to behave if the lookup is ambiguous.
4988    // We treat it as not making the member non-trivial, just like the standard
4989    // mandates for the default constructor. This should rarely matter, because
4990    // the member will also be deleted.
4991    if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4992      return true;
4993
4994    if (!SMOR->getMethod()) {
4995      assert(SMOR->getKind() ==
4996             Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
4997      return false;
4998    }
4999
5000    // We deliberately don't check if we found a deleted special member. We're
5001    // not supposed to!
5002    if (Selected)
5003      *Selected = SMOR->getMethod();
5004    return SMOR->getMethod()->isTrivial();
5005  }
5006
5007  llvm_unreachable("unknown special method kind");
5008}
5009
5010static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5011  for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5012       CI != CE; ++CI)
5013    if (!CI->isImplicit())
5014      return *CI;
5015
5016  // Look for constructor templates.
5017  typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5018  for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5019    if (CXXConstructorDecl *CD =
5020          dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5021      return CD;
5022  }
5023
5024  return 0;
5025}
5026
5027/// The kind of subobject we are checking for triviality. The values of this
5028/// enumeration are used in diagnostics.
5029enum TrivialSubobjectKind {
5030  /// The subobject is a base class.
5031  TSK_BaseClass,
5032  /// The subobject is a non-static data member.
5033  TSK_Field,
5034  /// The object is actually the complete object.
5035  TSK_CompleteObject
5036};
5037
5038/// Check whether the special member selected for a given type would be trivial.
5039static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5040                                      QualType SubType,
5041                                      Sema::CXXSpecialMember CSM,
5042                                      TrivialSubobjectKind Kind,
5043                                      bool Diagnose) {
5044  CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5045  if (!SubRD)
5046    return true;
5047
5048  CXXMethodDecl *Selected;
5049  if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5050                               Diagnose ? &Selected : 0))
5051    return true;
5052
5053  if (Diagnose) {
5054    if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5055      S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5056        << Kind << SubType.getUnqualifiedType();
5057      if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5058        S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5059    } else if (!Selected)
5060      S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5061        << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5062    else if (Selected->isUserProvided()) {
5063      if (Kind == TSK_CompleteObject)
5064        S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5065          << Kind << SubType.getUnqualifiedType() << CSM;
5066      else {
5067        S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5068          << Kind << SubType.getUnqualifiedType() << CSM;
5069        S.Diag(Selected->getLocation(), diag::note_declared_at);
5070      }
5071    } else {
5072      if (Kind != TSK_CompleteObject)
5073        S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5074          << Kind << SubType.getUnqualifiedType() << CSM;
5075
5076      // Explain why the defaulted or deleted special member isn't trivial.
5077      S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5078    }
5079  }
5080
5081  return false;
5082}
5083
5084/// Check whether the members of a class type allow a special member to be
5085/// trivial.
5086static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5087                                     Sema::CXXSpecialMember CSM,
5088                                     bool ConstArg, bool Diagnose) {
5089  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5090                                     FE = RD->field_end(); FI != FE; ++FI) {
5091    if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5092      continue;
5093
5094    QualType FieldType = S.Context.getBaseElementType(FI->getType());
5095
5096    // Pretend anonymous struct or union members are members of this class.
5097    if (FI->isAnonymousStructOrUnion()) {
5098      if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5099                                    CSM, ConstArg, Diagnose))
5100        return false;
5101      continue;
5102    }
5103
5104    // C++11 [class.ctor]p5:
5105    //   A default constructor is trivial if [...]
5106    //    -- no non-static data member of its class has a
5107    //       brace-or-equal-initializer
5108    if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5109      if (Diagnose)
5110        S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5111      return false;
5112    }
5113
5114    // Objective C ARC 4.3.5:
5115    //   [...] nontrivally ownership-qualified types are [...] not trivially
5116    //   default constructible, copy constructible, move constructible, copy
5117    //   assignable, move assignable, or destructible [...]
5118    if (S.getLangOpts().ObjCAutoRefCount &&
5119        FieldType.hasNonTrivialObjCLifetime()) {
5120      if (Diagnose)
5121        S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5122          << RD << FieldType.getObjCLifetime();
5123      return false;
5124    }
5125
5126    if (ConstArg && !FI->isMutable())
5127      FieldType.addConst();
5128    if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5129                                   TSK_Field, Diagnose))
5130      return false;
5131  }
5132
5133  return true;
5134}
5135
5136/// Diagnose why the specified class does not have a trivial special member of
5137/// the given kind.
5138void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5139  QualType Ty = Context.getRecordType(RD);
5140  if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5141    Ty.addConst();
5142
5143  checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5144                            TSK_CompleteObject, /*Diagnose*/true);
5145}
5146
5147/// Determine whether a defaulted or deleted special member function is trivial,
5148/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5149/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5150bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5151                                  bool Diagnose) {
5152  assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5153
5154  CXXRecordDecl *RD = MD->getParent();
5155
5156  bool ConstArg = false;
5157
5158  // C++11 [class.copy]p12, p25:
5159  //   A [special member] is trivial if its declared parameter type is the same
5160  //   as if it had been implicitly declared [...]
5161  switch (CSM) {
5162  case CXXDefaultConstructor:
5163  case CXXDestructor:
5164    // Trivial default constructors and destructors cannot have parameters.
5165    break;
5166
5167  case CXXCopyConstructor:
5168  case CXXCopyAssignment: {
5169    // Trivial copy operations always have const, non-volatile parameter types.
5170    ConstArg = true;
5171    const ParmVarDecl *Param0 = MD->getParamDecl(0);
5172    const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5173    if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5174      if (Diagnose)
5175        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5176          << Param0->getSourceRange() << Param0->getType()
5177          << Context.getLValueReferenceType(
5178               Context.getRecordType(RD).withConst());
5179      return false;
5180    }
5181    break;
5182  }
5183
5184  case CXXMoveConstructor:
5185  case CXXMoveAssignment: {
5186    // Trivial move operations always have non-cv-qualified parameters.
5187    const ParmVarDecl *Param0 = MD->getParamDecl(0);
5188    const RValueReferenceType *RT =
5189      Param0->getType()->getAs<RValueReferenceType>();
5190    if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5191      if (Diagnose)
5192        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5193          << Param0->getSourceRange() << Param0->getType()
5194          << Context.getRValueReferenceType(Context.getRecordType(RD));
5195      return false;
5196    }
5197    break;
5198  }
5199
5200  case CXXInvalid:
5201    llvm_unreachable("not a special member");
5202  }
5203
5204  // FIXME: We require that the parameter-declaration-clause is equivalent to
5205  // that of an implicit declaration, not just that the declared parameter type
5206  // matches, in order to prevent absuridities like a function simultaneously
5207  // being a trivial copy constructor and a non-trivial default constructor.
5208  // This issue has not yet been assigned a core issue number.
5209  if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5210    if (Diagnose)
5211      Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5212           diag::note_nontrivial_default_arg)
5213        << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5214    return false;
5215  }
5216  if (MD->isVariadic()) {
5217    if (Diagnose)
5218      Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5219    return false;
5220  }
5221
5222  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5223  //   A copy/move [constructor or assignment operator] is trivial if
5224  //    -- the [member] selected to copy/move each direct base class subobject
5225  //       is trivial
5226  //
5227  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5228  //   A [default constructor or destructor] is trivial if
5229  //    -- all the direct base classes have trivial [default constructors or
5230  //       destructors]
5231  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5232                                          BE = RD->bases_end(); BI != BE; ++BI)
5233    if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5234                                   ConstArg ? BI->getType().withConst()
5235                                            : BI->getType(),
5236                                   CSM, TSK_BaseClass, Diagnose))
5237      return false;
5238
5239  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5240  //   A copy/move [constructor or assignment operator] for a class X is
5241  //   trivial if
5242  //    -- for each non-static data member of X that is of class type (or array
5243  //       thereof), the constructor selected to copy/move that member is
5244  //       trivial
5245  //
5246  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5247  //   A [default constructor or destructor] is trivial if
5248  //    -- for all of the non-static data members of its class that are of class
5249  //       type (or array thereof), each such class has a trivial [default
5250  //       constructor or destructor]
5251  if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5252    return false;
5253
5254  // C++11 [class.dtor]p5:
5255  //   A destructor is trivial if [...]
5256  //    -- the destructor is not virtual
5257  if (CSM == CXXDestructor && MD->isVirtual()) {
5258    if (Diagnose)
5259      Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5260    return false;
5261  }
5262
5263  // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5264  //   A [special member] for class X is trivial if [...]
5265  //    -- class X has no virtual functions and no virtual base classes
5266  if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5267    if (!Diagnose)
5268      return false;
5269
5270    if (RD->getNumVBases()) {
5271      // Check for virtual bases. We already know that the corresponding
5272      // member in all bases is trivial, so vbases must all be direct.
5273      CXXBaseSpecifier &BS = *RD->vbases_begin();
5274      assert(BS.isVirtual());
5275      Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5276      return false;
5277    }
5278
5279    // Must have a virtual method.
5280    for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5281                                        ME = RD->method_end(); MI != ME; ++MI) {
5282      if (MI->isVirtual()) {
5283        SourceLocation MLoc = MI->getLocStart();
5284        Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5285        return false;
5286      }
5287    }
5288
5289    llvm_unreachable("dynamic class with no vbases and no virtual functions");
5290  }
5291
5292  // Looks like it's trivial!
5293  return true;
5294}
5295
5296/// \brief Data used with FindHiddenVirtualMethod
5297namespace {
5298  struct FindHiddenVirtualMethodData {
5299    Sema *S;
5300    CXXMethodDecl *Method;
5301    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5302    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5303  };
5304}
5305
5306/// \brief Check whether any most overriden method from MD in Methods
5307static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5308                   const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5309  if (MD->size_overridden_methods() == 0)
5310    return Methods.count(MD->getCanonicalDecl());
5311  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5312                                      E = MD->end_overridden_methods();
5313       I != E; ++I)
5314    if (CheckMostOverridenMethods(*I, Methods))
5315      return true;
5316  return false;
5317}
5318
5319/// \brief Member lookup function that determines whether a given C++
5320/// method overloads virtual methods in a base class without overriding any,
5321/// to be used with CXXRecordDecl::lookupInBases().
5322static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5323                                    CXXBasePath &Path,
5324                                    void *UserData) {
5325  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5326
5327  FindHiddenVirtualMethodData &Data
5328    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5329
5330  DeclarationName Name = Data.Method->getDeclName();
5331  assert(Name.getNameKind() == DeclarationName::Identifier);
5332
5333  bool foundSameNameMethod = false;
5334  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5335  for (Path.Decls = BaseRecord->lookup(Name);
5336       !Path.Decls.empty();
5337       Path.Decls = Path.Decls.slice(1)) {
5338    NamedDecl *D = Path.Decls.front();
5339    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5340      MD = MD->getCanonicalDecl();
5341      foundSameNameMethod = true;
5342      // Interested only in hidden virtual methods.
5343      if (!MD->isVirtual())
5344        continue;
5345      // If the method we are checking overrides a method from its base
5346      // don't warn about the other overloaded methods.
5347      if (!Data.S->IsOverload(Data.Method, MD, false))
5348        return true;
5349      // Collect the overload only if its hidden.
5350      if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5351        overloadedMethods.push_back(MD);
5352    }
5353  }
5354
5355  if (foundSameNameMethod)
5356    Data.OverloadedMethods.append(overloadedMethods.begin(),
5357                                   overloadedMethods.end());
5358  return foundSameNameMethod;
5359}
5360
5361/// \brief Add the most overriden methods from MD to Methods
5362static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5363                         llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5364  if (MD->size_overridden_methods() == 0)
5365    Methods.insert(MD->getCanonicalDecl());
5366  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5367                                      E = MD->end_overridden_methods();
5368       I != E; ++I)
5369    AddMostOverridenMethods(*I, Methods);
5370}
5371
5372/// \brief See if a method overloads virtual methods in a base class without
5373/// overriding any.
5374void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5375  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5376                               MD->getLocation()) == DiagnosticsEngine::Ignored)
5377    return;
5378  if (!MD->getDeclName().isIdentifier())
5379    return;
5380
5381  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5382                     /*bool RecordPaths=*/false,
5383                     /*bool DetectVirtual=*/false);
5384  FindHiddenVirtualMethodData Data;
5385  Data.Method = MD;
5386  Data.S = this;
5387
5388  // Keep the base methods that were overriden or introduced in the subclass
5389  // by 'using' in a set. A base method not in this set is hidden.
5390  DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5391  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5392    NamedDecl *ND = *I;
5393    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5394      ND = shad->getTargetDecl();
5395    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5396      AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5397  }
5398
5399  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5400      !Data.OverloadedMethods.empty()) {
5401    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5402      << MD << (Data.OverloadedMethods.size() > 1);
5403
5404    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5405      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5406      Diag(overloadedMD->getLocation(),
5407           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5408    }
5409  }
5410}
5411
5412void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5413                                             Decl *TagDecl,
5414                                             SourceLocation LBrac,
5415                                             SourceLocation RBrac,
5416                                             AttributeList *AttrList) {
5417  if (!TagDecl)
5418    return;
5419
5420  AdjustDeclIfTemplate(TagDecl);
5421
5422  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5423    if (l->getKind() != AttributeList::AT_Visibility)
5424      continue;
5425    l->setInvalid();
5426    Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5427      l->getName();
5428  }
5429
5430  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5431              // strict aliasing violation!
5432              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5433              FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5434
5435  CheckCompletedCXXClass(
5436                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5437}
5438
5439/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5440/// special functions, such as the default constructor, copy
5441/// constructor, or destructor, to the given C++ class (C++
5442/// [special]p1).  This routine can only be executed just before the
5443/// definition of the class is complete.
5444void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
5445  if (!ClassDecl->hasUserDeclaredConstructor())
5446    ++ASTContext::NumImplicitDefaultConstructors;
5447
5448  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
5449    ++ASTContext::NumImplicitCopyConstructors;
5450
5451    // If the properties or semantics of the copy constructor couldn't be
5452    // determined while the class was being declared, force a declaration
5453    // of it now.
5454    if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5455      DeclareImplicitCopyConstructor(ClassDecl);
5456  }
5457
5458  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
5459    ++ASTContext::NumImplicitMoveConstructors;
5460
5461    if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5462      DeclareImplicitMoveConstructor(ClassDecl);
5463  }
5464
5465  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5466    ++ASTContext::NumImplicitCopyAssignmentOperators;
5467
5468    // If we have a dynamic class, then the copy assignment operator may be
5469    // virtual, so we have to declare it immediately. This ensures that, e.g.,
5470    // it shows up in the right place in the vtable and that we diagnose
5471    // problems with the implicit exception specification.
5472    if (ClassDecl->isDynamicClass() ||
5473        ClassDecl->needsOverloadResolutionForCopyAssignment())
5474      DeclareImplicitCopyAssignment(ClassDecl);
5475  }
5476
5477  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
5478    ++ASTContext::NumImplicitMoveAssignmentOperators;
5479
5480    // Likewise for the move assignment operator.
5481    if (ClassDecl->isDynamicClass() ||
5482        ClassDecl->needsOverloadResolutionForMoveAssignment())
5483      DeclareImplicitMoveAssignment(ClassDecl);
5484  }
5485
5486  if (!ClassDecl->hasUserDeclaredDestructor()) {
5487    ++ASTContext::NumImplicitDestructors;
5488
5489    // If we have a dynamic class, then the destructor may be virtual, so we
5490    // have to declare the destructor immediately. This ensures that, e.g., it
5491    // shows up in the right place in the vtable and that we diagnose problems
5492    // with the implicit exception specification.
5493    if (ClassDecl->isDynamicClass() ||
5494        ClassDecl->needsOverloadResolutionForDestructor())
5495      DeclareImplicitDestructor(ClassDecl);
5496  }
5497}
5498
5499void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5500  if (!D)
5501    return;
5502
5503  int NumParamList = D->getNumTemplateParameterLists();
5504  for (int i = 0; i < NumParamList; i++) {
5505    TemplateParameterList* Params = D->getTemplateParameterList(i);
5506    for (TemplateParameterList::iterator Param = Params->begin(),
5507                                      ParamEnd = Params->end();
5508          Param != ParamEnd; ++Param) {
5509      NamedDecl *Named = cast<NamedDecl>(*Param);
5510      if (Named->getDeclName()) {
5511        S->AddDecl(Named);
5512        IdResolver.AddDecl(Named);
5513      }
5514    }
5515  }
5516}
5517
5518void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
5519  if (!D)
5520    return;
5521
5522  TemplateParameterList *Params = 0;
5523  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5524    Params = Template->getTemplateParameters();
5525  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5526           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5527    Params = PartialSpec->getTemplateParameters();
5528  else
5529    return;
5530
5531  for (TemplateParameterList::iterator Param = Params->begin(),
5532                                    ParamEnd = Params->end();
5533       Param != ParamEnd; ++Param) {
5534    NamedDecl *Named = cast<NamedDecl>(*Param);
5535    if (Named->getDeclName()) {
5536      S->AddDecl(Named);
5537      IdResolver.AddDecl(Named);
5538    }
5539  }
5540}
5541
5542void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5543  if (!RecordD) return;
5544  AdjustDeclIfTemplate(RecordD);
5545  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
5546  PushDeclContext(S, Record);
5547}
5548
5549void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5550  if (!RecordD) return;
5551  PopDeclContext();
5552}
5553
5554/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5555/// parsing a top-level (non-nested) C++ class, and we are now
5556/// parsing those parts of the given Method declaration that could
5557/// not be parsed earlier (C++ [class.mem]p2), such as default
5558/// arguments. This action should enter the scope of the given
5559/// Method declaration as if we had just parsed the qualified method
5560/// name. However, it should not bring the parameters into scope;
5561/// that will be performed by ActOnDelayedCXXMethodParameter.
5562void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5563}
5564
5565/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5566/// C++ method declaration. We're (re-)introducing the given
5567/// function parameter into scope for use in parsing later parts of
5568/// the method declaration. For example, we could see an
5569/// ActOnParamDefaultArgument event for this parameter.
5570void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
5571  if (!ParamD)
5572    return;
5573
5574  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
5575
5576  // If this parameter has an unparsed default argument, clear it out
5577  // to make way for the parsed default argument.
5578  if (Param->hasUnparsedDefaultArg())
5579    Param->setDefaultArg(0);
5580
5581  S->AddDecl(Param);
5582  if (Param->getDeclName())
5583    IdResolver.AddDecl(Param);
5584}
5585
5586/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5587/// processing the delayed method declaration for Method. The method
5588/// declaration is now considered finished. There may be a separate
5589/// ActOnStartOfFunctionDef action later (not necessarily
5590/// immediately!) for this method, if it was also defined inside the
5591/// class body.
5592void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5593  if (!MethodD)
5594    return;
5595
5596  AdjustDeclIfTemplate(MethodD);
5597
5598  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
5599
5600  // Now that we have our default arguments, check the constructor
5601  // again. It could produce additional diagnostics or affect whether
5602  // the class has implicitly-declared destructors, among other
5603  // things.
5604  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5605    CheckConstructor(Constructor);
5606
5607  // Check the default arguments, which we may have added.
5608  if (!Method->isInvalidDecl())
5609    CheckCXXDefaultArguments(Method);
5610}
5611
5612/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
5613/// the well-formedness of the constructor declarator @p D with type @p
5614/// R. If there are any errors in the declarator, this routine will
5615/// emit diagnostics and set the invalid bit to true.  In any case, the type
5616/// will be updated to reflect a well-formed type for the constructor and
5617/// returned.
5618QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
5619                                          StorageClass &SC) {
5620  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5621
5622  // C++ [class.ctor]p3:
5623  //   A constructor shall not be virtual (10.3) or static (9.4). A
5624  //   constructor can be invoked for a const, volatile or const
5625  //   volatile object. A constructor shall not be declared const,
5626  //   volatile, or const volatile (9.3.2).
5627  if (isVirtual) {
5628    if (!D.isInvalidType())
5629      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5630        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5631        << SourceRange(D.getIdentifierLoc());
5632    D.setInvalidType();
5633  }
5634  if (SC == SC_Static) {
5635    if (!D.isInvalidType())
5636      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5637        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5638        << SourceRange(D.getIdentifierLoc());
5639    D.setInvalidType();
5640    SC = SC_None;
5641  }
5642
5643  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5644  if (FTI.TypeQuals != 0) {
5645    if (FTI.TypeQuals & Qualifiers::Const)
5646      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5647        << "const" << SourceRange(D.getIdentifierLoc());
5648    if (FTI.TypeQuals & Qualifiers::Volatile)
5649      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5650        << "volatile" << SourceRange(D.getIdentifierLoc());
5651    if (FTI.TypeQuals & Qualifiers::Restrict)
5652      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5653        << "restrict" << SourceRange(D.getIdentifierLoc());
5654    D.setInvalidType();
5655  }
5656
5657  // C++0x [class.ctor]p4:
5658  //   A constructor shall not be declared with a ref-qualifier.
5659  if (FTI.hasRefQualifier()) {
5660    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5661      << FTI.RefQualifierIsLValueRef
5662      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5663    D.setInvalidType();
5664  }
5665
5666  // Rebuild the function type "R" without any type qualifiers (in
5667  // case any of the errors above fired) and with "void" as the
5668  // return type, since constructors don't have return types.
5669  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5670  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5671    return R;
5672
5673  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5674  EPI.TypeQuals = 0;
5675  EPI.RefQualifier = RQ_None;
5676
5677  return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
5678}
5679
5680/// CheckConstructor - Checks a fully-formed constructor for
5681/// well-formedness, issuing any diagnostics required. Returns true if
5682/// the constructor declarator is invalid.
5683void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5684  CXXRecordDecl *ClassDecl
5685    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5686  if (!ClassDecl)
5687    return Constructor->setInvalidDecl();
5688
5689  // C++ [class.copy]p3:
5690  //   A declaration of a constructor for a class X is ill-formed if
5691  //   its first parameter is of type (optionally cv-qualified) X and
5692  //   either there are no other parameters or else all other
5693  //   parameters have default arguments.
5694  if (!Constructor->isInvalidDecl() &&
5695      ((Constructor->getNumParams() == 1) ||
5696       (Constructor->getNumParams() > 1 &&
5697        Constructor->getParamDecl(1)->hasDefaultArg())) &&
5698      Constructor->getTemplateSpecializationKind()
5699                                              != TSK_ImplicitInstantiation) {
5700    QualType ParamType = Constructor->getParamDecl(0)->getType();
5701    QualType ClassTy = Context.getTagDeclType(ClassDecl);
5702    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5703      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5704      const char *ConstRef
5705        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5706                                                        : " const &";
5707      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5708        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5709
5710      // FIXME: Rather that making the constructor invalid, we should endeavor
5711      // to fix the type.
5712      Constructor->setInvalidDecl();
5713    }
5714  }
5715}
5716
5717/// CheckDestructor - Checks a fully-formed destructor definition for
5718/// well-formedness, issuing any diagnostics required.  Returns true
5719/// on error.
5720bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5721  CXXRecordDecl *RD = Destructor->getParent();
5722
5723  if (Destructor->isVirtual()) {
5724    SourceLocation Loc;
5725
5726    if (!Destructor->isImplicit())
5727      Loc = Destructor->getLocation();
5728    else
5729      Loc = RD->getLocation();
5730
5731    // If we have a virtual destructor, look up the deallocation function
5732    FunctionDecl *OperatorDelete = 0;
5733    DeclarationName Name =
5734    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5735    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5736      return true;
5737
5738    MarkFunctionReferenced(Loc, OperatorDelete);
5739
5740    Destructor->setOperatorDelete(OperatorDelete);
5741  }
5742
5743  return false;
5744}
5745
5746static inline bool
5747FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5748  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5749          FTI.ArgInfo[0].Param &&
5750          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5751}
5752
5753/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5754/// the well-formednes of the destructor declarator @p D with type @p
5755/// R. If there are any errors in the declarator, this routine will
5756/// emit diagnostics and set the declarator to invalid.  Even if this happens,
5757/// will be updated to reflect a well-formed type for the destructor and
5758/// returned.
5759QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5760                                         StorageClass& SC) {
5761  // C++ [class.dtor]p1:
5762  //   [...] A typedef-name that names a class is a class-name
5763  //   (7.1.3); however, a typedef-name that names a class shall not
5764  //   be used as the identifier in the declarator for a destructor
5765  //   declaration.
5766  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5767  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5768    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5769      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5770  else if (const TemplateSpecializationType *TST =
5771             DeclaratorType->getAs<TemplateSpecializationType>())
5772    if (TST->isTypeAlias())
5773      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5774        << DeclaratorType << 1;
5775
5776  // C++ [class.dtor]p2:
5777  //   A destructor is used to destroy objects of its class type. A
5778  //   destructor takes no parameters, and no return type can be
5779  //   specified for it (not even void). The address of a destructor
5780  //   shall not be taken. A destructor shall not be static. A
5781  //   destructor can be invoked for a const, volatile or const
5782  //   volatile object. A destructor shall not be declared const,
5783  //   volatile or const volatile (9.3.2).
5784  if (SC == SC_Static) {
5785    if (!D.isInvalidType())
5786      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5787        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5788        << SourceRange(D.getIdentifierLoc())
5789        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5790
5791    SC = SC_None;
5792  }
5793  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5794    // Destructors don't have return types, but the parser will
5795    // happily parse something like:
5796    //
5797    //   class X {
5798    //     float ~X();
5799    //   };
5800    //
5801    // The return type will be eliminated later.
5802    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5803      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5804      << SourceRange(D.getIdentifierLoc());
5805  }
5806
5807  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5808  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5809    if (FTI.TypeQuals & Qualifiers::Const)
5810      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5811        << "const" << SourceRange(D.getIdentifierLoc());
5812    if (FTI.TypeQuals & Qualifiers::Volatile)
5813      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5814        << "volatile" << SourceRange(D.getIdentifierLoc());
5815    if (FTI.TypeQuals & Qualifiers::Restrict)
5816      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5817        << "restrict" << SourceRange(D.getIdentifierLoc());
5818    D.setInvalidType();
5819  }
5820
5821  // C++0x [class.dtor]p2:
5822  //   A destructor shall not be declared with a ref-qualifier.
5823  if (FTI.hasRefQualifier()) {
5824    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5825      << FTI.RefQualifierIsLValueRef
5826      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5827    D.setInvalidType();
5828  }
5829
5830  // Make sure we don't have any parameters.
5831  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5832    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5833
5834    // Delete the parameters.
5835    FTI.freeArgs();
5836    D.setInvalidType();
5837  }
5838
5839  // Make sure the destructor isn't variadic.
5840  if (FTI.isVariadic) {
5841    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5842    D.setInvalidType();
5843  }
5844
5845  // Rebuild the function type "R" without any type qualifiers or
5846  // parameters (in case any of the errors above fired) and with
5847  // "void" as the return type, since destructors don't have return
5848  // types.
5849  if (!D.isInvalidType())
5850    return R;
5851
5852  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5853  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5854  EPI.Variadic = false;
5855  EPI.TypeQuals = 0;
5856  EPI.RefQualifier = RQ_None;
5857  return Context.getFunctionType(Context.VoidTy, ArrayRef<QualType>(), EPI);
5858}
5859
5860/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5861/// well-formednes of the conversion function declarator @p D with
5862/// type @p R. If there are any errors in the declarator, this routine
5863/// will emit diagnostics and return true. Otherwise, it will return
5864/// false. Either way, the type @p R will be updated to reflect a
5865/// well-formed type for the conversion operator.
5866void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
5867                                     StorageClass& SC) {
5868  // C++ [class.conv.fct]p1:
5869  //   Neither parameter types nor return type can be specified. The
5870  //   type of a conversion function (8.3.5) is "function taking no
5871  //   parameter returning conversion-type-id."
5872  if (SC == SC_Static) {
5873    if (!D.isInvalidType())
5874      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5875        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5876        << SourceRange(D.getIdentifierLoc());
5877    D.setInvalidType();
5878    SC = SC_None;
5879  }
5880
5881  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5882
5883  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5884    // Conversion functions don't have return types, but the parser will
5885    // happily parse something like:
5886    //
5887    //   class X {
5888    //     float operator bool();
5889    //   };
5890    //
5891    // The return type will be changed later anyway.
5892    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5893      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5894      << SourceRange(D.getIdentifierLoc());
5895    D.setInvalidType();
5896  }
5897
5898  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5899
5900  // Make sure we don't have any parameters.
5901  if (Proto->getNumArgs() > 0) {
5902    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5903
5904    // Delete the parameters.
5905    D.getFunctionTypeInfo().freeArgs();
5906    D.setInvalidType();
5907  } else if (Proto->isVariadic()) {
5908    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
5909    D.setInvalidType();
5910  }
5911
5912  // Diagnose "&operator bool()" and other such nonsense.  This
5913  // is actually a gcc extension which we don't support.
5914  if (Proto->getResultType() != ConvType) {
5915    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5916      << Proto->getResultType();
5917    D.setInvalidType();
5918    ConvType = Proto->getResultType();
5919  }
5920
5921  // C++ [class.conv.fct]p4:
5922  //   The conversion-type-id shall not represent a function type nor
5923  //   an array type.
5924  if (ConvType->isArrayType()) {
5925    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5926    ConvType = Context.getPointerType(ConvType);
5927    D.setInvalidType();
5928  } else if (ConvType->isFunctionType()) {
5929    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5930    ConvType = Context.getPointerType(ConvType);
5931    D.setInvalidType();
5932  }
5933
5934  // Rebuild the function type "R" without any parameters (in case any
5935  // of the errors above fired) and with the conversion type as the
5936  // return type.
5937  if (D.isInvalidType())
5938    R = Context.getFunctionType(ConvType, ArrayRef<QualType>(),
5939                                Proto->getExtProtoInfo());
5940
5941  // C++0x explicit conversion operators.
5942  if (D.getDeclSpec().isExplicitSpecified())
5943    Diag(D.getDeclSpec().getExplicitSpecLoc(),
5944         getLangOpts().CPlusPlus11 ?
5945           diag::warn_cxx98_compat_explicit_conversion_functions :
5946           diag::ext_explicit_conversion_functions)
5947      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
5948}
5949
5950/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5951/// the declaration of the given C++ conversion function. This routine
5952/// is responsible for recording the conversion function in the C++
5953/// class, if possible.
5954Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
5955  assert(Conversion && "Expected to receive a conversion function declaration");
5956
5957  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
5958
5959  // Make sure we aren't redeclaring the conversion function.
5960  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
5961
5962  // C++ [class.conv.fct]p1:
5963  //   [...] A conversion function is never used to convert a
5964  //   (possibly cv-qualified) object to the (possibly cv-qualified)
5965  //   same object type (or a reference to it), to a (possibly
5966  //   cv-qualified) base class of that type (or a reference to it),
5967  //   or to (possibly cv-qualified) void.
5968  // FIXME: Suppress this warning if the conversion function ends up being a
5969  // virtual function that overrides a virtual function in a base class.
5970  QualType ClassType
5971    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5972  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
5973    ConvType = ConvTypeRef->getPointeeType();
5974  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5975      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5976    /* Suppress diagnostics for instantiations. */;
5977  else if (ConvType->isRecordType()) {
5978    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5979    if (ConvType == ClassType)
5980      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
5981        << ClassType;
5982    else if (IsDerivedFrom(ClassType, ConvType))
5983      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
5984        <<  ClassType << ConvType;
5985  } else if (ConvType->isVoidType()) {
5986    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
5987      << ClassType << ConvType;
5988  }
5989
5990  if (FunctionTemplateDecl *ConversionTemplate
5991                                = Conversion->getDescribedFunctionTemplate())
5992    return ConversionTemplate;
5993
5994  return Conversion;
5995}
5996
5997//===----------------------------------------------------------------------===//
5998// Namespace Handling
5999//===----------------------------------------------------------------------===//
6000
6001/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6002/// reopened.
6003static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6004                                            SourceLocation Loc,
6005                                            IdentifierInfo *II, bool *IsInline,
6006                                            NamespaceDecl *PrevNS) {
6007  assert(*IsInline != PrevNS->isInline());
6008
6009  // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6010  // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6011  // inline namespaces, with the intention of bringing names into namespace std.
6012  //
6013  // We support this just well enough to get that case working; this is not
6014  // sufficient to support reopening namespaces as inline in general.
6015  if (*IsInline && II && II->getName().startswith("__atomic") &&
6016      S.getSourceManager().isInSystemHeader(Loc)) {
6017    // Mark all prior declarations of the namespace as inline.
6018    for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6019         NS = NS->getPreviousDecl())
6020      NS->setInline(*IsInline);
6021    // Patch up the lookup table for the containing namespace. This isn't really
6022    // correct, but it's good enough for this particular case.
6023    for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6024                                    E = PrevNS->decls_end(); I != E; ++I)
6025      if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6026        PrevNS->getParent()->makeDeclVisibleInContext(ND);
6027    return;
6028  }
6029
6030  if (PrevNS->isInline())
6031    // The user probably just forgot the 'inline', so suggest that it
6032    // be added back.
6033    S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6034      << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6035  else
6036    S.Diag(Loc, diag::err_inline_namespace_mismatch)
6037      << IsInline;
6038
6039  S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6040  *IsInline = PrevNS->isInline();
6041}
6042
6043/// ActOnStartNamespaceDef - This is called at the start of a namespace
6044/// definition.
6045Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6046                                   SourceLocation InlineLoc,
6047                                   SourceLocation NamespaceLoc,
6048                                   SourceLocation IdentLoc,
6049                                   IdentifierInfo *II,
6050                                   SourceLocation LBrace,
6051                                   AttributeList *AttrList) {
6052  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6053  // For anonymous namespace, take the location of the left brace.
6054  SourceLocation Loc = II ? IdentLoc : LBrace;
6055  bool IsInline = InlineLoc.isValid();
6056  bool IsInvalid = false;
6057  bool IsStd = false;
6058  bool AddToKnown = false;
6059  Scope *DeclRegionScope = NamespcScope->getParent();
6060
6061  NamespaceDecl *PrevNS = 0;
6062  if (II) {
6063    // C++ [namespace.def]p2:
6064    //   The identifier in an original-namespace-definition shall not
6065    //   have been previously defined in the declarative region in
6066    //   which the original-namespace-definition appears. The
6067    //   identifier in an original-namespace-definition is the name of
6068    //   the namespace. Subsequently in that declarative region, it is
6069    //   treated as an original-namespace-name.
6070    //
6071    // Since namespace names are unique in their scope, and we don't
6072    // look through using directives, just look for any ordinary names.
6073
6074    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6075    Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6076    Decl::IDNS_Namespace;
6077    NamedDecl *PrevDecl = 0;
6078    DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6079    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6080         ++I) {
6081      if ((*I)->getIdentifierNamespace() & IDNS) {
6082        PrevDecl = *I;
6083        break;
6084      }
6085    }
6086
6087    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6088
6089    if (PrevNS) {
6090      // This is an extended namespace definition.
6091      if (IsInline != PrevNS->isInline())
6092        DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6093                                        &IsInline, PrevNS);
6094    } else if (PrevDecl) {
6095      // This is an invalid name redefinition.
6096      Diag(Loc, diag::err_redefinition_different_kind)
6097        << II;
6098      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6099      IsInvalid = true;
6100      // Continue on to push Namespc as current DeclContext and return it.
6101    } else if (II->isStr("std") &&
6102               CurContext->getRedeclContext()->isTranslationUnit()) {
6103      // This is the first "real" definition of the namespace "std", so update
6104      // our cache of the "std" namespace to point at this definition.
6105      PrevNS = getStdNamespace();
6106      IsStd = true;
6107      AddToKnown = !IsInline;
6108    } else {
6109      // We've seen this namespace for the first time.
6110      AddToKnown = !IsInline;
6111    }
6112  } else {
6113    // Anonymous namespaces.
6114
6115    // Determine whether the parent already has an anonymous namespace.
6116    DeclContext *Parent = CurContext->getRedeclContext();
6117    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6118      PrevNS = TU->getAnonymousNamespace();
6119    } else {
6120      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6121      PrevNS = ND->getAnonymousNamespace();
6122    }
6123
6124    if (PrevNS && IsInline != PrevNS->isInline())
6125      DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6126                                      &IsInline, PrevNS);
6127  }
6128
6129  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6130                                                 StartLoc, Loc, II, PrevNS);
6131  if (IsInvalid)
6132    Namespc->setInvalidDecl();
6133
6134  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6135
6136  // FIXME: Should we be merging attributes?
6137  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6138    PushNamespaceVisibilityAttr(Attr, Loc);
6139
6140  if (IsStd)
6141    StdNamespace = Namespc;
6142  if (AddToKnown)
6143    KnownNamespaces[Namespc] = false;
6144
6145  if (II) {
6146    PushOnScopeChains(Namespc, DeclRegionScope);
6147  } else {
6148    // Link the anonymous namespace into its parent.
6149    DeclContext *Parent = CurContext->getRedeclContext();
6150    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6151      TU->setAnonymousNamespace(Namespc);
6152    } else {
6153      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6154    }
6155
6156    CurContext->addDecl(Namespc);
6157
6158    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6159    //   behaves as if it were replaced by
6160    //     namespace unique { /* empty body */ }
6161    //     using namespace unique;
6162    //     namespace unique { namespace-body }
6163    //   where all occurrences of 'unique' in a translation unit are
6164    //   replaced by the same identifier and this identifier differs
6165    //   from all other identifiers in the entire program.
6166
6167    // We just create the namespace with an empty name and then add an
6168    // implicit using declaration, just like the standard suggests.
6169    //
6170    // CodeGen enforces the "universally unique" aspect by giving all
6171    // declarations semantically contained within an anonymous
6172    // namespace internal linkage.
6173
6174    if (!PrevNS) {
6175      UsingDirectiveDecl* UD
6176        = UsingDirectiveDecl::Create(Context, Parent,
6177                                     /* 'using' */ LBrace,
6178                                     /* 'namespace' */ SourceLocation(),
6179                                     /* qualifier */ NestedNameSpecifierLoc(),
6180                                     /* identifier */ SourceLocation(),
6181                                     Namespc,
6182                                     /* Ancestor */ Parent);
6183      UD->setImplicit();
6184      Parent->addDecl(UD);
6185    }
6186  }
6187
6188  ActOnDocumentableDecl(Namespc);
6189
6190  // Although we could have an invalid decl (i.e. the namespace name is a
6191  // redefinition), push it as current DeclContext and try to continue parsing.
6192  // FIXME: We should be able to push Namespc here, so that the each DeclContext
6193  // for the namespace has the declarations that showed up in that particular
6194  // namespace definition.
6195  PushDeclContext(NamespcScope, Namespc);
6196  return Namespc;
6197}
6198
6199/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6200/// is a namespace alias, returns the namespace it points to.
6201static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6202  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6203    return AD->getNamespace();
6204  return dyn_cast_or_null<NamespaceDecl>(D);
6205}
6206
6207/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6208/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6209void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6210  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6211  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6212  Namespc->setRBraceLoc(RBrace);
6213  PopDeclContext();
6214  if (Namespc->hasAttr<VisibilityAttr>())
6215    PopPragmaVisibility(true, RBrace);
6216}
6217
6218CXXRecordDecl *Sema::getStdBadAlloc() const {
6219  return cast_or_null<CXXRecordDecl>(
6220                                  StdBadAlloc.get(Context.getExternalSource()));
6221}
6222
6223NamespaceDecl *Sema::getStdNamespace() const {
6224  return cast_or_null<NamespaceDecl>(
6225                                 StdNamespace.get(Context.getExternalSource()));
6226}
6227
6228/// \brief Retrieve the special "std" namespace, which may require us to
6229/// implicitly define the namespace.
6230NamespaceDecl *Sema::getOrCreateStdNamespace() {
6231  if (!StdNamespace) {
6232    // The "std" namespace has not yet been defined, so build one implicitly.
6233    StdNamespace = NamespaceDecl::Create(Context,
6234                                         Context.getTranslationUnitDecl(),
6235                                         /*Inline=*/false,
6236                                         SourceLocation(), SourceLocation(),
6237                                         &PP.getIdentifierTable().get("std"),
6238                                         /*PrevDecl=*/0);
6239    getStdNamespace()->setImplicit(true);
6240  }
6241
6242  return getStdNamespace();
6243}
6244
6245bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6246  assert(getLangOpts().CPlusPlus &&
6247         "Looking for std::initializer_list outside of C++.");
6248
6249  // We're looking for implicit instantiations of
6250  // template <typename E> class std::initializer_list.
6251
6252  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6253    return false;
6254
6255  ClassTemplateDecl *Template = 0;
6256  const TemplateArgument *Arguments = 0;
6257
6258  if (const RecordType *RT = Ty->getAs<RecordType>()) {
6259
6260    ClassTemplateSpecializationDecl *Specialization =
6261        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6262    if (!Specialization)
6263      return false;
6264
6265    Template = Specialization->getSpecializedTemplate();
6266    Arguments = Specialization->getTemplateArgs().data();
6267  } else if (const TemplateSpecializationType *TST =
6268                 Ty->getAs<TemplateSpecializationType>()) {
6269    Template = dyn_cast_or_null<ClassTemplateDecl>(
6270        TST->getTemplateName().getAsTemplateDecl());
6271    Arguments = TST->getArgs();
6272  }
6273  if (!Template)
6274    return false;
6275
6276  if (!StdInitializerList) {
6277    // Haven't recognized std::initializer_list yet, maybe this is it.
6278    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6279    if (TemplateClass->getIdentifier() !=
6280            &PP.getIdentifierTable().get("initializer_list") ||
6281        !getStdNamespace()->InEnclosingNamespaceSetOf(
6282            TemplateClass->getDeclContext()))
6283      return false;
6284    // This is a template called std::initializer_list, but is it the right
6285    // template?
6286    TemplateParameterList *Params = Template->getTemplateParameters();
6287    if (Params->getMinRequiredArguments() != 1)
6288      return false;
6289    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6290      return false;
6291
6292    // It's the right template.
6293    StdInitializerList = Template;
6294  }
6295
6296  if (Template != StdInitializerList)
6297    return false;
6298
6299  // This is an instance of std::initializer_list. Find the argument type.
6300  if (Element)
6301    *Element = Arguments[0].getAsType();
6302  return true;
6303}
6304
6305static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6306  NamespaceDecl *Std = S.getStdNamespace();
6307  if (!Std) {
6308    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6309    return 0;
6310  }
6311
6312  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6313                      Loc, Sema::LookupOrdinaryName);
6314  if (!S.LookupQualifiedName(Result, Std)) {
6315    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6316    return 0;
6317  }
6318  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6319  if (!Template) {
6320    Result.suppressDiagnostics();
6321    // We found something weird. Complain about the first thing we found.
6322    NamedDecl *Found = *Result.begin();
6323    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6324    return 0;
6325  }
6326
6327  // We found some template called std::initializer_list. Now verify that it's
6328  // correct.
6329  TemplateParameterList *Params = Template->getTemplateParameters();
6330  if (Params->getMinRequiredArguments() != 1 ||
6331      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6332    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6333    return 0;
6334  }
6335
6336  return Template;
6337}
6338
6339QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6340  if (!StdInitializerList) {
6341    StdInitializerList = LookupStdInitializerList(*this, Loc);
6342    if (!StdInitializerList)
6343      return QualType();
6344  }
6345
6346  TemplateArgumentListInfo Args(Loc, Loc);
6347  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6348                                       Context.getTrivialTypeSourceInfo(Element,
6349                                                                        Loc)));
6350  return Context.getCanonicalType(
6351      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6352}
6353
6354bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6355  // C++ [dcl.init.list]p2:
6356  //   A constructor is an initializer-list constructor if its first parameter
6357  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
6358  //   std::initializer_list<E> for some type E, and either there are no other
6359  //   parameters or else all other parameters have default arguments.
6360  if (Ctor->getNumParams() < 1 ||
6361      (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6362    return false;
6363
6364  QualType ArgType = Ctor->getParamDecl(0)->getType();
6365  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6366    ArgType = RT->getPointeeType().getUnqualifiedType();
6367
6368  return isStdInitializerList(ArgType, 0);
6369}
6370
6371/// \brief Determine whether a using statement is in a context where it will be
6372/// apply in all contexts.
6373static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6374  switch (CurContext->getDeclKind()) {
6375    case Decl::TranslationUnit:
6376      return true;
6377    case Decl::LinkageSpec:
6378      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6379    default:
6380      return false;
6381  }
6382}
6383
6384namespace {
6385
6386// Callback to only accept typo corrections that are namespaces.
6387class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6388 public:
6389  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6390    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6391      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6392    }
6393    return false;
6394  }
6395};
6396
6397}
6398
6399static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6400                                       CXXScopeSpec &SS,
6401                                       SourceLocation IdentLoc,
6402                                       IdentifierInfo *Ident) {
6403  NamespaceValidatorCCC Validator;
6404  R.clear();
6405  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6406                                               R.getLookupKind(), Sc, &SS,
6407                                               Validator)) {
6408    std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6409    std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
6410    if (DeclContext *DC = S.computeDeclContext(SS, false))
6411      S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6412        << Ident << DC << CorrectedQuotedStr << SS.getRange()
6413        << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6414                                        CorrectedStr);
6415    else
6416      S.Diag(IdentLoc, diag::err_using_directive_suggest)
6417        << Ident << CorrectedQuotedStr
6418        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
6419
6420    S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6421         diag::note_namespace_defined_here) << CorrectedQuotedStr;
6422
6423    R.addDecl(Corrected.getCorrectionDecl());
6424    return true;
6425  }
6426  return false;
6427}
6428
6429Decl *Sema::ActOnUsingDirective(Scope *S,
6430                                          SourceLocation UsingLoc,
6431                                          SourceLocation NamespcLoc,
6432                                          CXXScopeSpec &SS,
6433                                          SourceLocation IdentLoc,
6434                                          IdentifierInfo *NamespcName,
6435                                          AttributeList *AttrList) {
6436  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6437  assert(NamespcName && "Invalid NamespcName.");
6438  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
6439
6440  // This can only happen along a recovery path.
6441  while (S->getFlags() & Scope::TemplateParamScope)
6442    S = S->getParent();
6443  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6444
6445  UsingDirectiveDecl *UDir = 0;
6446  NestedNameSpecifier *Qualifier = 0;
6447  if (SS.isSet())
6448    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6449
6450  // Lookup namespace name.
6451  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6452  LookupParsedName(R, S, &SS);
6453  if (R.isAmbiguous())
6454    return 0;
6455
6456  if (R.empty()) {
6457    R.clear();
6458    // Allow "using namespace std;" or "using namespace ::std;" even if
6459    // "std" hasn't been defined yet, for GCC compatibility.
6460    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6461        NamespcName->isStr("std")) {
6462      Diag(IdentLoc, diag::ext_using_undefined_std);
6463      R.addDecl(getOrCreateStdNamespace());
6464      R.resolveKind();
6465    }
6466    // Otherwise, attempt typo correction.
6467    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
6468  }
6469
6470  if (!R.empty()) {
6471    NamedDecl *Named = R.getFoundDecl();
6472    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6473        && "expected namespace decl");
6474    // C++ [namespace.udir]p1:
6475    //   A using-directive specifies that the names in the nominated
6476    //   namespace can be used in the scope in which the
6477    //   using-directive appears after the using-directive. During
6478    //   unqualified name lookup (3.4.1), the names appear as if they
6479    //   were declared in the nearest enclosing namespace which
6480    //   contains both the using-directive and the nominated
6481    //   namespace. [Note: in this context, "contains" means "contains
6482    //   directly or indirectly". ]
6483
6484    // Find enclosing context containing both using-directive and
6485    // nominated namespace.
6486    NamespaceDecl *NS = getNamespaceDecl(Named);
6487    DeclContext *CommonAncestor = cast<DeclContext>(NS);
6488    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6489      CommonAncestor = CommonAncestor->getParent();
6490
6491    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
6492                                      SS.getWithLocInContext(Context),
6493                                      IdentLoc, Named, CommonAncestor);
6494
6495    if (IsUsingDirectiveInToplevelContext(CurContext) &&
6496        !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
6497      Diag(IdentLoc, diag::warn_using_directive_in_header);
6498    }
6499
6500    PushUsingDirective(S, UDir);
6501  } else {
6502    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6503  }
6504
6505  if (UDir)
6506    ProcessDeclAttributeList(S, UDir, AttrList);
6507
6508  return UDir;
6509}
6510
6511void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6512  // If the scope has an associated entity and the using directive is at
6513  // namespace or translation unit scope, add the UsingDirectiveDecl into
6514  // its lookup structure so qualified name lookup can find it.
6515  DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6516  if (Ctx && !Ctx->isFunctionOrMethod())
6517    Ctx->addDecl(UDir);
6518  else
6519    // Otherwise, it is at block sope. The using-directives will affect lookup
6520    // only to the end of the scope.
6521    S->PushUsingDirective(UDir);
6522}
6523
6524
6525Decl *Sema::ActOnUsingDeclaration(Scope *S,
6526                                  AccessSpecifier AS,
6527                                  bool HasUsingKeyword,
6528                                  SourceLocation UsingLoc,
6529                                  CXXScopeSpec &SS,
6530                                  UnqualifiedId &Name,
6531                                  AttributeList *AttrList,
6532                                  bool IsTypeName,
6533                                  SourceLocation TypenameLoc) {
6534  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6535
6536  switch (Name.getKind()) {
6537  case UnqualifiedId::IK_ImplicitSelfParam:
6538  case UnqualifiedId::IK_Identifier:
6539  case UnqualifiedId::IK_OperatorFunctionId:
6540  case UnqualifiedId::IK_LiteralOperatorId:
6541  case UnqualifiedId::IK_ConversionFunctionId:
6542    break;
6543
6544  case UnqualifiedId::IK_ConstructorName:
6545  case UnqualifiedId::IK_ConstructorTemplateId:
6546    // C++11 inheriting constructors.
6547    Diag(Name.getLocStart(),
6548         getLangOpts().CPlusPlus11 ?
6549           diag::warn_cxx98_compat_using_decl_constructor :
6550           diag::err_using_decl_constructor)
6551      << SS.getRange();
6552
6553    if (getLangOpts().CPlusPlus11) break;
6554
6555    return 0;
6556
6557  case UnqualifiedId::IK_DestructorName:
6558    Diag(Name.getLocStart(), diag::err_using_decl_destructor)
6559      << SS.getRange();
6560    return 0;
6561
6562  case UnqualifiedId::IK_TemplateId:
6563    Diag(Name.getLocStart(), diag::err_using_decl_template_id)
6564      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
6565    return 0;
6566  }
6567
6568  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6569  DeclarationName TargetName = TargetNameInfo.getName();
6570  if (!TargetName)
6571    return 0;
6572
6573  // Warn about access declarations.
6574  // TODO: store that the declaration was written without 'using' and
6575  // talk about access decls instead of using decls in the
6576  // diagnostics.
6577  if (!HasUsingKeyword) {
6578    UsingLoc = Name.getLocStart();
6579
6580    Diag(UsingLoc, diag::warn_access_decl_deprecated)
6581      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
6582  }
6583
6584  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6585      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6586    return 0;
6587
6588  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
6589                                        TargetNameInfo, AttrList,
6590                                        /* IsInstantiation */ false,
6591                                        IsTypeName, TypenameLoc);
6592  if (UD)
6593    PushOnScopeChains(UD, S, /*AddToContext*/ false);
6594
6595  return UD;
6596}
6597
6598/// \brief Determine whether a using declaration considers the given
6599/// declarations as "equivalent", e.g., if they are redeclarations of
6600/// the same entity or are both typedefs of the same type.
6601static bool
6602IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6603                         bool &SuppressRedeclaration) {
6604  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6605    SuppressRedeclaration = false;
6606    return true;
6607  }
6608
6609  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6610    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
6611      SuppressRedeclaration = true;
6612      return Context.hasSameType(TD1->getUnderlyingType(),
6613                                 TD2->getUnderlyingType());
6614    }
6615
6616  return false;
6617}
6618
6619
6620/// Determines whether to create a using shadow decl for a particular
6621/// decl, given the set of decls existing prior to this using lookup.
6622bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6623                                const LookupResult &Previous) {
6624  // Diagnose finding a decl which is not from a base class of the
6625  // current class.  We do this now because there are cases where this
6626  // function will silently decide not to build a shadow decl, which
6627  // will pre-empt further diagnostics.
6628  //
6629  // We don't need to do this in C++0x because we do the check once on
6630  // the qualifier.
6631  //
6632  // FIXME: diagnose the following if we care enough:
6633  //   struct A { int foo; };
6634  //   struct B : A { using A::foo; };
6635  //   template <class T> struct C : A {};
6636  //   template <class T> struct D : C<T> { using B::foo; } // <---
6637  // This is invalid (during instantiation) in C++03 because B::foo
6638  // resolves to the using decl in B, which is not a base class of D<T>.
6639  // We can't diagnose it immediately because C<T> is an unknown
6640  // specialization.  The UsingShadowDecl in D<T> then points directly
6641  // to A::foo, which will look well-formed when we instantiate.
6642  // The right solution is to not collapse the shadow-decl chain.
6643  if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
6644    DeclContext *OrigDC = Orig->getDeclContext();
6645
6646    // Handle enums and anonymous structs.
6647    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6648    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6649    while (OrigRec->isAnonymousStructOrUnion())
6650      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6651
6652    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6653      if (OrigDC == CurContext) {
6654        Diag(Using->getLocation(),
6655             diag::err_using_decl_nested_name_specifier_is_current_class)
6656          << Using->getQualifierLoc().getSourceRange();
6657        Diag(Orig->getLocation(), diag::note_using_decl_target);
6658        return true;
6659      }
6660
6661      Diag(Using->getQualifierLoc().getBeginLoc(),
6662           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6663        << Using->getQualifier()
6664        << cast<CXXRecordDecl>(CurContext)
6665        << Using->getQualifierLoc().getSourceRange();
6666      Diag(Orig->getLocation(), diag::note_using_decl_target);
6667      return true;
6668    }
6669  }
6670
6671  if (Previous.empty()) return false;
6672
6673  NamedDecl *Target = Orig;
6674  if (isa<UsingShadowDecl>(Target))
6675    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6676
6677  // If the target happens to be one of the previous declarations, we
6678  // don't have a conflict.
6679  //
6680  // FIXME: but we might be increasing its access, in which case we
6681  // should redeclare it.
6682  NamedDecl *NonTag = 0, *Tag = 0;
6683  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6684         I != E; ++I) {
6685    NamedDecl *D = (*I)->getUnderlyingDecl();
6686    bool Result;
6687    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6688      return Result;
6689
6690    (isa<TagDecl>(D) ? Tag : NonTag) = D;
6691  }
6692
6693  if (Target->isFunctionOrFunctionTemplate()) {
6694    FunctionDecl *FD;
6695    if (isa<FunctionTemplateDecl>(Target))
6696      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6697    else
6698      FD = cast<FunctionDecl>(Target);
6699
6700    NamedDecl *OldDecl = 0;
6701    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6702    case Ovl_Overload:
6703      return false;
6704
6705    case Ovl_NonFunction:
6706      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6707      break;
6708
6709    // We found a decl with the exact signature.
6710    case Ovl_Match:
6711      // If we're in a record, we want to hide the target, so we
6712      // return true (without a diagnostic) to tell the caller not to
6713      // build a shadow decl.
6714      if (CurContext->isRecord())
6715        return true;
6716
6717      // If we're not in a record, this is an error.
6718      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6719      break;
6720    }
6721
6722    Diag(Target->getLocation(), diag::note_using_decl_target);
6723    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6724    return true;
6725  }
6726
6727  // Target is not a function.
6728
6729  if (isa<TagDecl>(Target)) {
6730    // No conflict between a tag and a non-tag.
6731    if (!Tag) return false;
6732
6733    Diag(Using->getLocation(), diag::err_using_decl_conflict);
6734    Diag(Target->getLocation(), diag::note_using_decl_target);
6735    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6736    return true;
6737  }
6738
6739  // No conflict between a tag and a non-tag.
6740  if (!NonTag) return false;
6741
6742  Diag(Using->getLocation(), diag::err_using_decl_conflict);
6743  Diag(Target->getLocation(), diag::note_using_decl_target);
6744  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6745  return true;
6746}
6747
6748/// Builds a shadow declaration corresponding to a 'using' declaration.
6749UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6750                                            UsingDecl *UD,
6751                                            NamedDecl *Orig) {
6752
6753  // If we resolved to another shadow declaration, just coalesce them.
6754  NamedDecl *Target = Orig;
6755  if (isa<UsingShadowDecl>(Target)) {
6756    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6757    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6758  }
6759
6760  UsingShadowDecl *Shadow
6761    = UsingShadowDecl::Create(Context, CurContext,
6762                              UD->getLocation(), UD, Target);
6763  UD->addShadowDecl(Shadow);
6764
6765  Shadow->setAccess(UD->getAccess());
6766  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6767    Shadow->setInvalidDecl();
6768
6769  if (S)
6770    PushOnScopeChains(Shadow, S);
6771  else
6772    CurContext->addDecl(Shadow);
6773
6774
6775  return Shadow;
6776}
6777
6778/// Hides a using shadow declaration.  This is required by the current
6779/// using-decl implementation when a resolvable using declaration in a
6780/// class is followed by a declaration which would hide or override
6781/// one or more of the using decl's targets; for example:
6782///
6783///   struct Base { void foo(int); };
6784///   struct Derived : Base {
6785///     using Base::foo;
6786///     void foo(int);
6787///   };
6788///
6789/// The governing language is C++03 [namespace.udecl]p12:
6790///
6791///   When a using-declaration brings names from a base class into a
6792///   derived class scope, member functions in the derived class
6793///   override and/or hide member functions with the same name and
6794///   parameter types in a base class (rather than conflicting).
6795///
6796/// There are two ways to implement this:
6797///   (1) optimistically create shadow decls when they're not hidden
6798///       by existing declarations, or
6799///   (2) don't create any shadow decls (or at least don't make them
6800///       visible) until we've fully parsed/instantiated the class.
6801/// The problem with (1) is that we might have to retroactively remove
6802/// a shadow decl, which requires several O(n) operations because the
6803/// decl structures are (very reasonably) not designed for removal.
6804/// (2) avoids this but is very fiddly and phase-dependent.
6805void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6806  if (Shadow->getDeclName().getNameKind() ==
6807        DeclarationName::CXXConversionFunctionName)
6808    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6809
6810  // Remove it from the DeclContext...
6811  Shadow->getDeclContext()->removeDecl(Shadow);
6812
6813  // ...and the scope, if applicable...
6814  if (S) {
6815    S->RemoveDecl(Shadow);
6816    IdResolver.RemoveDecl(Shadow);
6817  }
6818
6819  // ...and the using decl.
6820  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6821
6822  // TODO: complain somehow if Shadow was used.  It shouldn't
6823  // be possible for this to happen, because...?
6824}
6825
6826/// Builds a using declaration.
6827///
6828/// \param IsInstantiation - Whether this call arises from an
6829///   instantiation of an unresolved using declaration.  We treat
6830///   the lookup differently for these declarations.
6831NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6832                                       SourceLocation UsingLoc,
6833                                       CXXScopeSpec &SS,
6834                                       const DeclarationNameInfo &NameInfo,
6835                                       AttributeList *AttrList,
6836                                       bool IsInstantiation,
6837                                       bool IsTypeName,
6838                                       SourceLocation TypenameLoc) {
6839  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6840  SourceLocation IdentLoc = NameInfo.getLoc();
6841  assert(IdentLoc.isValid() && "Invalid TargetName location.");
6842
6843  // FIXME: We ignore attributes for now.
6844
6845  if (SS.isEmpty()) {
6846    Diag(IdentLoc, diag::err_using_requires_qualname);
6847    return 0;
6848  }
6849
6850  // Do the redeclaration lookup in the current scope.
6851  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
6852                        ForRedeclaration);
6853  Previous.setHideTags(false);
6854  if (S) {
6855    LookupName(Previous, S);
6856
6857    // It is really dumb that we have to do this.
6858    LookupResult::Filter F = Previous.makeFilter();
6859    while (F.hasNext()) {
6860      NamedDecl *D = F.next();
6861      if (!isDeclInScope(D, CurContext, S))
6862        F.erase();
6863    }
6864    F.done();
6865  } else {
6866    assert(IsInstantiation && "no scope in non-instantiation");
6867    assert(CurContext->isRecord() && "scope not record in instantiation");
6868    LookupQualifiedName(Previous, CurContext);
6869  }
6870
6871  // Check for invalid redeclarations.
6872  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6873    return 0;
6874
6875  // Check for bad qualifiers.
6876  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6877    return 0;
6878
6879  DeclContext *LookupContext = computeDeclContext(SS);
6880  NamedDecl *D;
6881  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6882  if (!LookupContext) {
6883    if (IsTypeName) {
6884      // FIXME: not all declaration name kinds are legal here
6885      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6886                                              UsingLoc, TypenameLoc,
6887                                              QualifierLoc,
6888                                              IdentLoc, NameInfo.getName());
6889    } else {
6890      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6891                                           QualifierLoc, NameInfo);
6892    }
6893  } else {
6894    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6895                          NameInfo, IsTypeName);
6896  }
6897  D->setAccess(AS);
6898  CurContext->addDecl(D);
6899
6900  if (!LookupContext) return D;
6901  UsingDecl *UD = cast<UsingDecl>(D);
6902
6903  if (RequireCompleteDeclContext(SS, LookupContext)) {
6904    UD->setInvalidDecl();
6905    return UD;
6906  }
6907
6908  // The normal rules do not apply to inheriting constructor declarations.
6909  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
6910    if (CheckInheritingConstructorUsingDecl(UD))
6911      UD->setInvalidDecl();
6912    return UD;
6913  }
6914
6915  // Otherwise, look up the target name.
6916
6917  LookupResult R(*this, NameInfo, LookupOrdinaryName);
6918
6919  // Unlike most lookups, we don't always want to hide tag
6920  // declarations: tag names are visible through the using declaration
6921  // even if hidden by ordinary names, *except* in a dependent context
6922  // where it's important for the sanity of two-phase lookup.
6923  if (!IsInstantiation)
6924    R.setHideTags(false);
6925
6926  // For the purposes of this lookup, we have a base object type
6927  // equal to that of the current context.
6928  if (CurContext->isRecord()) {
6929    R.setBaseObjectType(
6930                   Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6931  }
6932
6933  LookupQualifiedName(R, LookupContext);
6934
6935  if (R.empty()) {
6936    Diag(IdentLoc, diag::err_no_member)
6937      << NameInfo.getName() << LookupContext << SS.getRange();
6938    UD->setInvalidDecl();
6939    return UD;
6940  }
6941
6942  if (R.isAmbiguous()) {
6943    UD->setInvalidDecl();
6944    return UD;
6945  }
6946
6947  if (IsTypeName) {
6948    // If we asked for a typename and got a non-type decl, error out.
6949    if (!R.getAsSingle<TypeDecl>()) {
6950      Diag(IdentLoc, diag::err_using_typename_non_type);
6951      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6952        Diag((*I)->getUnderlyingDecl()->getLocation(),
6953             diag::note_using_decl_target);
6954      UD->setInvalidDecl();
6955      return UD;
6956    }
6957  } else {
6958    // If we asked for a non-typename and we got a type, error out,
6959    // but only if this is an instantiation of an unresolved using
6960    // decl.  Otherwise just silently find the type name.
6961    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
6962      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6963      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
6964      UD->setInvalidDecl();
6965      return UD;
6966    }
6967  }
6968
6969  // C++0x N2914 [namespace.udecl]p6:
6970  // A using-declaration shall not name a namespace.
6971  if (R.getAsSingle<NamespaceDecl>()) {
6972    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6973      << SS.getRange();
6974    UD->setInvalidDecl();
6975    return UD;
6976  }
6977
6978  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6979    if (!CheckUsingShadowDecl(UD, *I, Previous))
6980      BuildUsingShadowDecl(S, UD, *I);
6981  }
6982
6983  return UD;
6984}
6985
6986/// Additional checks for a using declaration referring to a constructor name.
6987bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6988  assert(!UD->isTypeName() && "expecting a constructor name");
6989
6990  const Type *SourceType = UD->getQualifier()->getAsType();
6991  assert(SourceType &&
6992         "Using decl naming constructor doesn't have type in scope spec.");
6993  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6994
6995  // Check whether the named type is a direct base class.
6996  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6997  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6998  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6999       BaseIt != BaseE; ++BaseIt) {
7000    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7001    if (CanonicalSourceType == BaseType)
7002      break;
7003    if (BaseIt->getType()->isDependentType())
7004      break;
7005  }
7006
7007  if (BaseIt == BaseE) {
7008    // Did not find SourceType in the bases.
7009    Diag(UD->getUsingLocation(),
7010         diag::err_using_decl_constructor_not_in_direct_base)
7011      << UD->getNameInfo().getSourceRange()
7012      << QualType(SourceType, 0) << TargetClass;
7013    return true;
7014  }
7015
7016  if (!CurContext->isDependentContext())
7017    BaseIt->setInheritConstructors();
7018
7019  return false;
7020}
7021
7022/// Checks that the given using declaration is not an invalid
7023/// redeclaration.  Note that this is checking only for the using decl
7024/// itself, not for any ill-formedness among the UsingShadowDecls.
7025bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7026                                       bool isTypeName,
7027                                       const CXXScopeSpec &SS,
7028                                       SourceLocation NameLoc,
7029                                       const LookupResult &Prev) {
7030  // C++03 [namespace.udecl]p8:
7031  // C++0x [namespace.udecl]p10:
7032  //   A using-declaration is a declaration and can therefore be used
7033  //   repeatedly where (and only where) multiple declarations are
7034  //   allowed.
7035  //
7036  // That's in non-member contexts.
7037  if (!CurContext->getRedeclContext()->isRecord())
7038    return false;
7039
7040  NestedNameSpecifier *Qual
7041    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7042
7043  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7044    NamedDecl *D = *I;
7045
7046    bool DTypename;
7047    NestedNameSpecifier *DQual;
7048    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7049      DTypename = UD->isTypeName();
7050      DQual = UD->getQualifier();
7051    } else if (UnresolvedUsingValueDecl *UD
7052                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7053      DTypename = false;
7054      DQual = UD->getQualifier();
7055    } else if (UnresolvedUsingTypenameDecl *UD
7056                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7057      DTypename = true;
7058      DQual = UD->getQualifier();
7059    } else continue;
7060
7061    // using decls differ if one says 'typename' and the other doesn't.
7062    // FIXME: non-dependent using decls?
7063    if (isTypeName != DTypename) continue;
7064
7065    // using decls differ if they name different scopes (but note that
7066    // template instantiation can cause this check to trigger when it
7067    // didn't before instantiation).
7068    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7069        Context.getCanonicalNestedNameSpecifier(DQual))
7070      continue;
7071
7072    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7073    Diag(D->getLocation(), diag::note_using_decl) << 1;
7074    return true;
7075  }
7076
7077  return false;
7078}
7079
7080
7081/// Checks that the given nested-name qualifier used in a using decl
7082/// in the current context is appropriately related to the current
7083/// scope.  If an error is found, diagnoses it and returns true.
7084bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7085                                   const CXXScopeSpec &SS,
7086                                   SourceLocation NameLoc) {
7087  DeclContext *NamedContext = computeDeclContext(SS);
7088
7089  if (!CurContext->isRecord()) {
7090    // C++03 [namespace.udecl]p3:
7091    // C++0x [namespace.udecl]p8:
7092    //   A using-declaration for a class member shall be a member-declaration.
7093
7094    // If we weren't able to compute a valid scope, it must be a
7095    // dependent class scope.
7096    if (!NamedContext || NamedContext->isRecord()) {
7097      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7098        << SS.getRange();
7099      return true;
7100    }
7101
7102    // Otherwise, everything is known to be fine.
7103    return false;
7104  }
7105
7106  // The current scope is a record.
7107
7108  // If the named context is dependent, we can't decide much.
7109  if (!NamedContext) {
7110    // FIXME: in C++0x, we can diagnose if we can prove that the
7111    // nested-name-specifier does not refer to a base class, which is
7112    // still possible in some cases.
7113
7114    // Otherwise we have to conservatively report that things might be
7115    // okay.
7116    return false;
7117  }
7118
7119  if (!NamedContext->isRecord()) {
7120    // Ideally this would point at the last name in the specifier,
7121    // but we don't have that level of source info.
7122    Diag(SS.getRange().getBegin(),
7123         diag::err_using_decl_nested_name_specifier_is_not_class)
7124      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7125    return true;
7126  }
7127
7128  if (!NamedContext->isDependentContext() &&
7129      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7130    return true;
7131
7132  if (getLangOpts().CPlusPlus11) {
7133    // C++0x [namespace.udecl]p3:
7134    //   In a using-declaration used as a member-declaration, the
7135    //   nested-name-specifier shall name a base class of the class
7136    //   being defined.
7137
7138    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7139                                 cast<CXXRecordDecl>(NamedContext))) {
7140      if (CurContext == NamedContext) {
7141        Diag(NameLoc,
7142             diag::err_using_decl_nested_name_specifier_is_current_class)
7143          << SS.getRange();
7144        return true;
7145      }
7146
7147      Diag(SS.getRange().getBegin(),
7148           diag::err_using_decl_nested_name_specifier_is_not_base_class)
7149        << (NestedNameSpecifier*) SS.getScopeRep()
7150        << cast<CXXRecordDecl>(CurContext)
7151        << SS.getRange();
7152      return true;
7153    }
7154
7155    return false;
7156  }
7157
7158  // C++03 [namespace.udecl]p4:
7159  //   A using-declaration used as a member-declaration shall refer
7160  //   to a member of a base class of the class being defined [etc.].
7161
7162  // Salient point: SS doesn't have to name a base class as long as
7163  // lookup only finds members from base classes.  Therefore we can
7164  // diagnose here only if we can prove that that can't happen,
7165  // i.e. if the class hierarchies provably don't intersect.
7166
7167  // TODO: it would be nice if "definitely valid" results were cached
7168  // in the UsingDecl and UsingShadowDecl so that these checks didn't
7169  // need to be repeated.
7170
7171  struct UserData {
7172    llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7173
7174    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7175      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7176      Data->Bases.insert(Base);
7177      return true;
7178    }
7179
7180    bool hasDependentBases(const CXXRecordDecl *Class) {
7181      return !Class->forallBases(collect, this);
7182    }
7183
7184    /// Returns true if the base is dependent or is one of the
7185    /// accumulated base classes.
7186    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7187      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7188      return !Data->Bases.count(Base);
7189    }
7190
7191    bool mightShareBases(const CXXRecordDecl *Class) {
7192      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7193    }
7194  };
7195
7196  UserData Data;
7197
7198  // Returns false if we find a dependent base.
7199  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7200    return false;
7201
7202  // Returns false if the class has a dependent base or if it or one
7203  // of its bases is present in the base set of the current context.
7204  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7205    return false;
7206
7207  Diag(SS.getRange().getBegin(),
7208       diag::err_using_decl_nested_name_specifier_is_not_base_class)
7209    << (NestedNameSpecifier*) SS.getScopeRep()
7210    << cast<CXXRecordDecl>(CurContext)
7211    << SS.getRange();
7212
7213  return true;
7214}
7215
7216Decl *Sema::ActOnAliasDeclaration(Scope *S,
7217                                  AccessSpecifier AS,
7218                                  MultiTemplateParamsArg TemplateParamLists,
7219                                  SourceLocation UsingLoc,
7220                                  UnqualifiedId &Name,
7221                                  AttributeList *AttrList,
7222                                  TypeResult Type) {
7223  // Skip up to the relevant declaration scope.
7224  while (S->getFlags() & Scope::TemplateParamScope)
7225    S = S->getParent();
7226  assert((S->getFlags() & Scope::DeclScope) &&
7227         "got alias-declaration outside of declaration scope");
7228
7229  if (Type.isInvalid())
7230    return 0;
7231
7232  bool Invalid = false;
7233  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7234  TypeSourceInfo *TInfo = 0;
7235  GetTypeFromParser(Type.get(), &TInfo);
7236
7237  if (DiagnoseClassNameShadow(CurContext, NameInfo))
7238    return 0;
7239
7240  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7241                                      UPPC_DeclarationType)) {
7242    Invalid = true;
7243    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7244                                             TInfo->getTypeLoc().getBeginLoc());
7245  }
7246
7247  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7248  LookupName(Previous, S);
7249
7250  // Warn about shadowing the name of a template parameter.
7251  if (Previous.isSingleResult() &&
7252      Previous.getFoundDecl()->isTemplateParameter()) {
7253    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
7254    Previous.clear();
7255  }
7256
7257  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7258         "name in alias declaration must be an identifier");
7259  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7260                                               Name.StartLocation,
7261                                               Name.Identifier, TInfo);
7262
7263  NewTD->setAccess(AS);
7264
7265  if (Invalid)
7266    NewTD->setInvalidDecl();
7267
7268  ProcessDeclAttributeList(S, NewTD, AttrList);
7269
7270  CheckTypedefForVariablyModifiedType(S, NewTD);
7271  Invalid |= NewTD->isInvalidDecl();
7272
7273  bool Redeclaration = false;
7274
7275  NamedDecl *NewND;
7276  if (TemplateParamLists.size()) {
7277    TypeAliasTemplateDecl *OldDecl = 0;
7278    TemplateParameterList *OldTemplateParams = 0;
7279
7280    if (TemplateParamLists.size() != 1) {
7281      Diag(UsingLoc, diag::err_alias_template_extra_headers)
7282        << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7283         TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
7284    }
7285    TemplateParameterList *TemplateParams = TemplateParamLists[0];
7286
7287    // Only consider previous declarations in the same scope.
7288    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7289                         /*ExplicitInstantiationOrSpecialization*/false);
7290    if (!Previous.empty()) {
7291      Redeclaration = true;
7292
7293      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7294      if (!OldDecl && !Invalid) {
7295        Diag(UsingLoc, diag::err_redefinition_different_kind)
7296          << Name.Identifier;
7297
7298        NamedDecl *OldD = Previous.getRepresentativeDecl();
7299        if (OldD->getLocation().isValid())
7300          Diag(OldD->getLocation(), diag::note_previous_definition);
7301
7302        Invalid = true;
7303      }
7304
7305      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7306        if (TemplateParameterListsAreEqual(TemplateParams,
7307                                           OldDecl->getTemplateParameters(),
7308                                           /*Complain=*/true,
7309                                           TPL_TemplateMatch))
7310          OldTemplateParams = OldDecl->getTemplateParameters();
7311        else
7312          Invalid = true;
7313
7314        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7315        if (!Invalid &&
7316            !Context.hasSameType(OldTD->getUnderlyingType(),
7317                                 NewTD->getUnderlyingType())) {
7318          // FIXME: The C++0x standard does not clearly say this is ill-formed,
7319          // but we can't reasonably accept it.
7320          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7321            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7322          if (OldTD->getLocation().isValid())
7323            Diag(OldTD->getLocation(), diag::note_previous_definition);
7324          Invalid = true;
7325        }
7326      }
7327    }
7328
7329    // Merge any previous default template arguments into our parameters,
7330    // and check the parameter list.
7331    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7332                                   TPC_TypeAliasTemplate))
7333      return 0;
7334
7335    TypeAliasTemplateDecl *NewDecl =
7336      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7337                                    Name.Identifier, TemplateParams,
7338                                    NewTD);
7339
7340    NewDecl->setAccess(AS);
7341
7342    if (Invalid)
7343      NewDecl->setInvalidDecl();
7344    else if (OldDecl)
7345      NewDecl->setPreviousDeclaration(OldDecl);
7346
7347    NewND = NewDecl;
7348  } else {
7349    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7350    NewND = NewTD;
7351  }
7352
7353  if (!Redeclaration)
7354    PushOnScopeChains(NewND, S);
7355
7356  ActOnDocumentableDecl(NewND);
7357  return NewND;
7358}
7359
7360Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
7361                                             SourceLocation NamespaceLoc,
7362                                             SourceLocation AliasLoc,
7363                                             IdentifierInfo *Alias,
7364                                             CXXScopeSpec &SS,
7365                                             SourceLocation IdentLoc,
7366                                             IdentifierInfo *Ident) {
7367
7368  // Lookup the namespace name.
7369  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7370  LookupParsedName(R, S, &SS);
7371
7372  // Check if we have a previous declaration with the same name.
7373  NamedDecl *PrevDecl
7374    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7375                       ForRedeclaration);
7376  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7377    PrevDecl = 0;
7378
7379  if (PrevDecl) {
7380    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
7381      // We already have an alias with the same name that points to the same
7382      // namespace, so don't create a new one.
7383      // FIXME: At some point, we'll want to create the (redundant)
7384      // declaration to maintain better source information.
7385      if (!R.isAmbiguous() && !R.empty() &&
7386          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
7387        return 0;
7388    }
7389
7390    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7391      diag::err_redefinition_different_kind;
7392    Diag(AliasLoc, DiagID) << Alias;
7393    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7394    return 0;
7395  }
7396
7397  if (R.isAmbiguous())
7398    return 0;
7399
7400  if (R.empty()) {
7401    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
7402      Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7403      return 0;
7404    }
7405  }
7406
7407  NamespaceAliasDecl *AliasDecl =
7408    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
7409                               Alias, SS.getWithLocInContext(Context),
7410                               IdentLoc, R.getFoundDecl());
7411
7412  PushOnScopeChains(AliasDecl, S);
7413  return AliasDecl;
7414}
7415
7416Sema::ImplicitExceptionSpecification
7417Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7418                                               CXXMethodDecl *MD) {
7419  CXXRecordDecl *ClassDecl = MD->getParent();
7420
7421  // C++ [except.spec]p14:
7422  //   An implicitly declared special member function (Clause 12) shall have an
7423  //   exception-specification. [...]
7424  ImplicitExceptionSpecification ExceptSpec(*this);
7425  if (ClassDecl->isInvalidDecl())
7426    return ExceptSpec;
7427
7428  // Direct base-class constructors.
7429  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7430                                       BEnd = ClassDecl->bases_end();
7431       B != BEnd; ++B) {
7432    if (B->isVirtual()) // Handled below.
7433      continue;
7434
7435    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7436      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7437      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7438      // If this is a deleted function, add it anyway. This might be conformant
7439      // with the standard. This might not. I'm not sure. It might not matter.
7440      if (Constructor)
7441        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7442    }
7443  }
7444
7445  // Virtual base-class constructors.
7446  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7447                                       BEnd = ClassDecl->vbases_end();
7448       B != BEnd; ++B) {
7449    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7450      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7451      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7452      // If this is a deleted function, add it anyway. This might be conformant
7453      // with the standard. This might not. I'm not sure. It might not matter.
7454      if (Constructor)
7455        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7456    }
7457  }
7458
7459  // Field constructors.
7460  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7461                               FEnd = ClassDecl->field_end();
7462       F != FEnd; ++F) {
7463    if (F->hasInClassInitializer()) {
7464      if (Expr *E = F->getInClassInitializer())
7465        ExceptSpec.CalledExpr(E);
7466      else if (!F->isInvalidDecl())
7467        // DR1351:
7468        //   If the brace-or-equal-initializer of a non-static data member
7469        //   invokes a defaulted default constructor of its class or of an
7470        //   enclosing class in a potentially evaluated subexpression, the
7471        //   program is ill-formed.
7472        //
7473        // This resolution is unworkable: the exception specification of the
7474        // default constructor can be needed in an unevaluated context, in
7475        // particular, in the operand of a noexcept-expression, and we can be
7476        // unable to compute an exception specification for an enclosed class.
7477        //
7478        // We do not allow an in-class initializer to require the evaluation
7479        // of the exception specification for any in-class initializer whose
7480        // definition is not lexically complete.
7481        Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
7482    } else if (const RecordType *RecordTy
7483              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7484      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7485      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7486      // If this is a deleted function, add it anyway. This might be conformant
7487      // with the standard. This might not. I'm not sure. It might not matter.
7488      // In particular, the problem is that this function never gets called. It
7489      // might just be ill-formed because this function attempts to refer to
7490      // a deleted function here.
7491      if (Constructor)
7492        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7493    }
7494  }
7495
7496  return ExceptSpec;
7497}
7498
7499Sema::ImplicitExceptionSpecification
7500Sema::ComputeInheritingCtorExceptionSpec(CXXMethodDecl *MD) {
7501  ImplicitExceptionSpecification ExceptSpec(*this);
7502  // FIXME: Compute the exception spec.
7503  return ExceptSpec;
7504}
7505
7506namespace {
7507/// RAII object to register a special member as being currently declared.
7508struct DeclaringSpecialMember {
7509  Sema &S;
7510  Sema::SpecialMemberDecl D;
7511  bool WasAlreadyBeingDeclared;
7512
7513  DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7514    : S(S), D(RD, CSM) {
7515    WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7516    if (WasAlreadyBeingDeclared)
7517      // This almost never happens, but if it does, ensure that our cache
7518      // doesn't contain a stale result.
7519      S.SpecialMemberCache.clear();
7520
7521    // FIXME: Register a note to be produced if we encounter an error while
7522    // declaring the special member.
7523  }
7524  ~DeclaringSpecialMember() {
7525    if (!WasAlreadyBeingDeclared)
7526      S.SpecialMembersBeingDeclared.erase(D);
7527  }
7528
7529  /// \brief Are we already trying to declare this special member?
7530  bool isAlreadyBeingDeclared() const {
7531    return WasAlreadyBeingDeclared;
7532  }
7533};
7534}
7535
7536CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7537                                                     CXXRecordDecl *ClassDecl) {
7538  // C++ [class.ctor]p5:
7539  //   A default constructor for a class X is a constructor of class X
7540  //   that can be called without an argument. If there is no
7541  //   user-declared constructor for class X, a default constructor is
7542  //   implicitly declared. An implicitly-declared default constructor
7543  //   is an inline public member of its class.
7544  assert(ClassDecl->needsImplicitDefaultConstructor() &&
7545         "Should not build implicit default constructor!");
7546
7547  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7548  if (DSM.isAlreadyBeingDeclared())
7549    return 0;
7550
7551  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7552                                                     CXXDefaultConstructor,
7553                                                     false);
7554
7555  // Create the actual constructor declaration.
7556  CanQualType ClassType
7557    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7558  SourceLocation ClassLoc = ClassDecl->getLocation();
7559  DeclarationName Name
7560    = Context.DeclarationNames.getCXXConstructorName(ClassType);
7561  DeclarationNameInfo NameInfo(Name, ClassLoc);
7562  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7563      Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
7564      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7565      Constexpr);
7566  DefaultCon->setAccess(AS_public);
7567  DefaultCon->setDefaulted();
7568  DefaultCon->setImplicit();
7569
7570  // Build an exception specification pointing back at this constructor.
7571  FunctionProtoType::ExtProtoInfo EPI;
7572  EPI.ExceptionSpecType = EST_Unevaluated;
7573  EPI.ExceptionSpecDecl = DefaultCon;
7574  DefaultCon->setType(Context.getFunctionType(Context.VoidTy,
7575                                              ArrayRef<QualType>(),
7576                                              EPI));
7577
7578  // We don't need to use SpecialMemberIsTrivial here; triviality for default
7579  // constructors is easy to compute.
7580  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7581
7582  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7583    DefaultCon->setDeletedAsWritten();
7584
7585  // Note that we have declared this constructor.
7586  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7587
7588  if (Scope *S = getScopeForContext(ClassDecl))
7589    PushOnScopeChains(DefaultCon, S, false);
7590  ClassDecl->addDecl(DefaultCon);
7591
7592  return DefaultCon;
7593}
7594
7595void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7596                                            CXXConstructorDecl *Constructor) {
7597  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7598          !Constructor->doesThisDeclarationHaveABody() &&
7599          !Constructor->isDeleted()) &&
7600    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
7601
7602  CXXRecordDecl *ClassDecl = Constructor->getParent();
7603  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
7604
7605  SynthesizedFunctionScope Scope(*this, Constructor);
7606  DiagnosticErrorTrap Trap(Diags);
7607  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
7608      Trap.hasErrorOccurred()) {
7609    Diag(CurrentLocation, diag::note_member_synthesized_at)
7610      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
7611    Constructor->setInvalidDecl();
7612    return;
7613  }
7614
7615  SourceLocation Loc = Constructor->getLocation();
7616  Constructor->setBody(new (Context) CompoundStmt(Loc));
7617
7618  Constructor->setUsed();
7619  MarkVTableUsed(CurrentLocation, ClassDecl);
7620
7621  if (ASTMutationListener *L = getASTMutationListener()) {
7622    L->CompletedImplicitDefinition(Constructor);
7623  }
7624}
7625
7626void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7627  // Check that any explicitly-defaulted methods have exception specifications
7628  // compatible with their implicit exception specifications.
7629  CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
7630}
7631
7632void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
7633  // We start with an initial pass over the base classes to collect those that
7634  // inherit constructors from. If there are none, we can forgo all further
7635  // processing.
7636  typedef SmallVector<const RecordType *, 4> BasesVector;
7637  BasesVector BasesToInheritFrom;
7638  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7639                                          BaseE = ClassDecl->bases_end();
7640         BaseIt != BaseE; ++BaseIt) {
7641    if (BaseIt->getInheritConstructors()) {
7642      QualType Base = BaseIt->getType();
7643      if (Base->isDependentType()) {
7644        // If we inherit constructors from anything that is dependent, just
7645        // abort processing altogether. We'll get another chance for the
7646        // instantiations.
7647        // FIXME: We need to ensure that any call to a constructor of this class
7648        // is considered instantiation-dependent in this case.
7649        return;
7650      }
7651      BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7652    }
7653  }
7654  if (BasesToInheritFrom.empty())
7655    return;
7656
7657  // FIXME: Constructor templates.
7658
7659  // Now collect the constructors that we already have in the current class.
7660  // Those take precedence over inherited constructors.
7661  // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7662  //   unless there is a user-declared constructor with the same signature in
7663  //   the class where the using-declaration appears.
7664  llvm::SmallSet<const Type *, 8> ExistingConstructors;
7665  for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7666                                    CtorE = ClassDecl->ctor_end();
7667       CtorIt != CtorE; ++CtorIt)
7668    ExistingConstructors.insert(
7669        Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7670
7671  DeclarationName CreatedCtorName =
7672      Context.DeclarationNames.getCXXConstructorName(
7673          ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7674
7675  // Now comes the true work.
7676  // First, we keep a map from constructor types to the base that introduced
7677  // them. Needed for finding conflicting constructors. We also keep the
7678  // actually inserted declarations in there, for pretty diagnostics.
7679  typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7680  typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7681  ConstructorToSourceMap InheritedConstructors;
7682  for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7683                             BaseE = BasesToInheritFrom.end();
7684       BaseIt != BaseE; ++BaseIt) {
7685    const RecordType *Base = *BaseIt;
7686    CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7687    CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7688    for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7689                                      CtorE = BaseDecl->ctor_end();
7690         CtorIt != CtorE; ++CtorIt) {
7691      // Find the using declaration for inheriting this base's constructors.
7692      // FIXME: Don't perform name lookup just to obtain a source location!
7693      DeclarationName Name =
7694          Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7695      LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7696      LookupQualifiedName(Result, CurContext);
7697      UsingDecl *UD = Result.getAsSingle<UsingDecl>();
7698      SourceLocation UsingLoc = UD ? UD->getLocation() :
7699                                     ClassDecl->getLocation();
7700
7701      // C++11 [class.inhctor]p1:
7702      //   The candidate set of inherited constructors from the class X named in
7703      //   the using-declaration consists of actual constructors and notional
7704      //   constructors that result from the transformation of defaulted
7705      //   parameters as follows:
7706      //   - all non-template constructors of X, and
7707      //   - for each non-template constructor of X that has at least one
7708      //     parameter with a default argument, the set of constructors that
7709      //     results from omitting any ellipsis parameter specification and
7710      //     successively omitting parameters with a default argument from the
7711      //     end of the parameter-type-list, and
7712      // FIXME: ...also constructor templates.
7713      CXXConstructorDecl *BaseCtor = *CtorIt;
7714      bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7715      const FunctionProtoType *BaseCtorType =
7716          BaseCtor->getType()->getAs<FunctionProtoType>();
7717
7718      // Determine whether this would be a copy or move constructor for the
7719      // derived class.
7720      if (BaseCtorType->getNumArgs() >= 1 &&
7721          BaseCtorType->getArgType(0)->isReferenceType() &&
7722          Context.hasSameUnqualifiedType(
7723            BaseCtorType->getArgType(0)->getPointeeType(),
7724            Context.getTagDeclType(ClassDecl)))
7725        CanBeCopyOrMove = true;
7726
7727      ArrayRef<QualType> ArgTypes(BaseCtorType->getArgTypes());
7728      FunctionProtoType::ExtProtoInfo EPI = BaseCtorType->getExtProtoInfo();
7729      // Core issue (no number yet): the ellipsis is always discarded.
7730      if (EPI.Variadic) {
7731        Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7732        Diag(BaseCtor->getLocation(),
7733             diag::note_using_decl_constructor_ellipsis);
7734        EPI.Variadic = false;
7735      }
7736
7737      for (unsigned Params = BaseCtor->getMinRequiredArguments(),
7738                    MaxParams = BaseCtor->getNumParams();
7739           Params <= MaxParams; ++Params) {
7740        // Skip default constructors. They're never inherited.
7741        if (Params == 0)
7742          continue;
7743
7744        // Skip copy and move constructors for both base and derived class
7745        // for the same reason.
7746        if (CanBeCopyOrMove && Params == 1)
7747          continue;
7748
7749        // Build up a function type for this particular constructor.
7750        QualType NewCtorType =
7751            Context.getFunctionType(Context.VoidTy, ArgTypes.slice(0, Params),
7752                                    EPI);
7753        const Type *CanonicalNewCtorType =
7754            Context.getCanonicalType(NewCtorType).getTypePtr();
7755
7756        // C++11 [class.inhctor]p3:
7757        //   ... a constructor is implicitly declared with the same constructor
7758        //   characteristics unless there is a user-declared constructor with
7759        //   the same signature in the class where the using-declaration appears
7760        if (ExistingConstructors.count(CanonicalNewCtorType))
7761          continue;
7762
7763        // C++11 [class.inhctor]p7:
7764        //   If two using-declarations declare inheriting constructors with the
7765        //   same signature, the program is ill-formed
7766        std::pair<ConstructorToSourceMap::iterator, bool> result =
7767            InheritedConstructors.insert(std::make_pair(
7768                CanonicalNewCtorType,
7769                std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7770        if (!result.second) {
7771          // Already in the map. If it came from a different class, that's an
7772          // error. Not if it's from the same.
7773          CanQualType PreviousBase = result.first->second.first;
7774          if (CanonicalBase != PreviousBase) {
7775            const CXXConstructorDecl *PrevCtor = result.first->second.second;
7776            const CXXConstructorDecl *PrevBaseCtor =
7777                PrevCtor->getInheritedConstructor();
7778            assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7779
7780            Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7781            Diag(BaseCtor->getLocation(),
7782                 diag::note_using_decl_constructor_conflict_current_ctor);
7783            Diag(PrevBaseCtor->getLocation(),
7784                 diag::note_using_decl_constructor_conflict_previous_ctor);
7785            Diag(PrevCtor->getLocation(),
7786                 diag::note_using_decl_constructor_conflict_previous_using);
7787          } else {
7788            // Core issue (no number): if the same inheriting constructor is
7789            // produced by multiple base class constructors from the same base
7790            // class, the inheriting constructor is defined as deleted.
7791            result.first->second.second->setDeletedAsWritten();
7792          }
7793          continue;
7794        }
7795
7796        // OK, we're there, now add the constructor.
7797        DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7798        CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
7799            Context, ClassDecl, UsingLoc, DNI, NewCtorType,
7800            /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
7801            /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
7802        NewCtor->setAccess(BaseCtor->getAccess());
7803
7804        // Build an unevaluated exception specification for this constructor.
7805        EPI.ExceptionSpecType = EST_Unevaluated;
7806        EPI.ExceptionSpecDecl = NewCtor;
7807        NewCtor->setType(Context.getFunctionType(Context.VoidTy,
7808                                                 ArgTypes.slice(0, Params),
7809                                                 EPI));
7810
7811        // Build up the parameter decls and add them.
7812        SmallVector<ParmVarDecl *, 16> ParamDecls;
7813        for (unsigned i = 0; i < Params; ++i) {
7814          ParmVarDecl *PD = ParmVarDecl::Create(Context, NewCtor,
7815                                                UsingLoc, UsingLoc,
7816                                                /*IdentifierInfo=*/0,
7817                                                BaseCtorType->getArgType(i),
7818                                                /*TInfo=*/0, SC_None,
7819                                                SC_None, /*DefaultArg=*/0);
7820          PD->setScopeInfo(0, i);
7821          PD->setImplicit();
7822          ParamDecls.push_back(PD);
7823        }
7824        NewCtor->setParams(ParamDecls);
7825        NewCtor->setInheritedConstructor(BaseCtor);
7826        if (BaseCtor->isDeleted())
7827          NewCtor->setDeletedAsWritten();
7828
7829        ClassDecl->addDecl(NewCtor);
7830        result.first->second.second = NewCtor;
7831      }
7832    }
7833  }
7834}
7835
7836void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
7837                                       CXXConstructorDecl *Constructor) {
7838  CXXRecordDecl *ClassDecl = Constructor->getParent();
7839  assert(Constructor->getInheritedConstructor() &&
7840         !Constructor->doesThisDeclarationHaveABody() &&
7841         !Constructor->isDeleted());
7842
7843  SynthesizedFunctionScope Scope(*this, Constructor);
7844  DiagnosticErrorTrap Trap(Diags);
7845  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
7846      Trap.hasErrorOccurred()) {
7847    Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
7848      << Context.getTagDeclType(ClassDecl);
7849    Constructor->setInvalidDecl();
7850    return;
7851  }
7852
7853  SourceLocation Loc = Constructor->getLocation();
7854  Constructor->setBody(new (Context) CompoundStmt(Loc));
7855
7856  Constructor->setUsed();
7857  MarkVTableUsed(CurrentLocation, ClassDecl);
7858
7859  if (ASTMutationListener *L = getASTMutationListener()) {
7860    L->CompletedImplicitDefinition(Constructor);
7861  }
7862}
7863
7864
7865Sema::ImplicitExceptionSpecification
7866Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7867  CXXRecordDecl *ClassDecl = MD->getParent();
7868
7869  // C++ [except.spec]p14:
7870  //   An implicitly declared special member function (Clause 12) shall have
7871  //   an exception-specification.
7872  ImplicitExceptionSpecification ExceptSpec(*this);
7873  if (ClassDecl->isInvalidDecl())
7874    return ExceptSpec;
7875
7876  // Direct base-class destructors.
7877  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7878                                       BEnd = ClassDecl->bases_end();
7879       B != BEnd; ++B) {
7880    if (B->isVirtual()) // Handled below.
7881      continue;
7882
7883    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7884      ExceptSpec.CalledDecl(B->getLocStart(),
7885                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7886  }
7887
7888  // Virtual base-class destructors.
7889  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7890                                       BEnd = ClassDecl->vbases_end();
7891       B != BEnd; ++B) {
7892    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7893      ExceptSpec.CalledDecl(B->getLocStart(),
7894                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7895  }
7896
7897  // Field destructors.
7898  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7899                               FEnd = ClassDecl->field_end();
7900       F != FEnd; ++F) {
7901    if (const RecordType *RecordTy
7902        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7903      ExceptSpec.CalledDecl(F->getLocation(),
7904                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
7905  }
7906
7907  return ExceptSpec;
7908}
7909
7910CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7911  // C++ [class.dtor]p2:
7912  //   If a class has no user-declared destructor, a destructor is
7913  //   declared implicitly. An implicitly-declared destructor is an
7914  //   inline public member of its class.
7915  assert(ClassDecl->needsImplicitDestructor());
7916
7917  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7918  if (DSM.isAlreadyBeingDeclared())
7919    return 0;
7920
7921  // Create the actual destructor declaration.
7922  CanQualType ClassType
7923    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7924  SourceLocation ClassLoc = ClassDecl->getLocation();
7925  DeclarationName Name
7926    = Context.DeclarationNames.getCXXDestructorName(ClassType);
7927  DeclarationNameInfo NameInfo(Name, ClassLoc);
7928  CXXDestructorDecl *Destructor
7929      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7930                                  QualType(), 0, /*isInline=*/true,
7931                                  /*isImplicitlyDeclared=*/true);
7932  Destructor->setAccess(AS_public);
7933  Destructor->setDefaulted();
7934  Destructor->setImplicit();
7935
7936  // Build an exception specification pointing back at this destructor.
7937  FunctionProtoType::ExtProtoInfo EPI;
7938  EPI.ExceptionSpecType = EST_Unevaluated;
7939  EPI.ExceptionSpecDecl = Destructor;
7940  Destructor->setType(Context.getFunctionType(Context.VoidTy,
7941                                              ArrayRef<QualType>(),
7942                                              EPI));
7943
7944  AddOverriddenMethods(ClassDecl, Destructor);
7945
7946  // We don't need to use SpecialMemberIsTrivial here; triviality for
7947  // destructors is easy to compute.
7948  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7949
7950  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7951    Destructor->setDeletedAsWritten();
7952
7953  // Note that we have declared this destructor.
7954  ++ASTContext::NumImplicitDestructorsDeclared;
7955
7956  // Introduce this destructor into its scope.
7957  if (Scope *S = getScopeForContext(ClassDecl))
7958    PushOnScopeChains(Destructor, S, false);
7959  ClassDecl->addDecl(Destructor);
7960
7961  return Destructor;
7962}
7963
7964void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
7965                                    CXXDestructorDecl *Destructor) {
7966  assert((Destructor->isDefaulted() &&
7967          !Destructor->doesThisDeclarationHaveABody() &&
7968          !Destructor->isDeleted()) &&
7969         "DefineImplicitDestructor - call it for implicit default dtor");
7970  CXXRecordDecl *ClassDecl = Destructor->getParent();
7971  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
7972
7973  if (Destructor->isInvalidDecl())
7974    return;
7975
7976  SynthesizedFunctionScope Scope(*this, Destructor);
7977
7978  DiagnosticErrorTrap Trap(Diags);
7979  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7980                                         Destructor->getParent());
7981
7982  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
7983    Diag(CurrentLocation, diag::note_member_synthesized_at)
7984      << CXXDestructor << Context.getTagDeclType(ClassDecl);
7985
7986    Destructor->setInvalidDecl();
7987    return;
7988  }
7989
7990  SourceLocation Loc = Destructor->getLocation();
7991  Destructor->setBody(new (Context) CompoundStmt(Loc));
7992  Destructor->setImplicitlyDefined(true);
7993  Destructor->setUsed();
7994  MarkVTableUsed(CurrentLocation, ClassDecl);
7995
7996  if (ASTMutationListener *L = getASTMutationListener()) {
7997    L->CompletedImplicitDefinition(Destructor);
7998  }
7999}
8000
8001/// \brief Perform any semantic analysis which needs to be delayed until all
8002/// pending class member declarations have been parsed.
8003void Sema::ActOnFinishCXXMemberDecls() {
8004  // If the context is an invalid C++ class, just suppress these checks.
8005  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8006    if (Record->isInvalidDecl()) {
8007      DelayedDestructorExceptionSpecChecks.clear();
8008      return;
8009    }
8010  }
8011
8012  // Perform any deferred checking of exception specifications for virtual
8013  // destructors.
8014  for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8015       i != e; ++i) {
8016    const CXXDestructorDecl *Dtor =
8017        DelayedDestructorExceptionSpecChecks[i].first;
8018    assert(!Dtor->getParent()->isDependentType() &&
8019           "Should not ever add destructors of templates into the list.");
8020    CheckOverridingFunctionExceptionSpec(Dtor,
8021        DelayedDestructorExceptionSpecChecks[i].second);
8022  }
8023  DelayedDestructorExceptionSpecChecks.clear();
8024}
8025
8026void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8027                                         CXXDestructorDecl *Destructor) {
8028  assert(getLangOpts().CPlusPlus11 &&
8029         "adjusting dtor exception specs was introduced in c++11");
8030
8031  // C++11 [class.dtor]p3:
8032  //   A declaration of a destructor that does not have an exception-
8033  //   specification is implicitly considered to have the same exception-
8034  //   specification as an implicit declaration.
8035  const FunctionProtoType *DtorType = Destructor->getType()->
8036                                        getAs<FunctionProtoType>();
8037  if (DtorType->hasExceptionSpec())
8038    return;
8039
8040  // Replace the destructor's type, building off the existing one. Fortunately,
8041  // the only thing of interest in the destructor type is its extended info.
8042  // The return and arguments are fixed.
8043  FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8044  EPI.ExceptionSpecType = EST_Unevaluated;
8045  EPI.ExceptionSpecDecl = Destructor;
8046  Destructor->setType(Context.getFunctionType(Context.VoidTy,
8047                                              ArrayRef<QualType>(),
8048                                              EPI));
8049
8050  // FIXME: If the destructor has a body that could throw, and the newly created
8051  // spec doesn't allow exceptions, we should emit a warning, because this
8052  // change in behavior can break conforming C++03 programs at runtime.
8053  // However, we don't have a body or an exception specification yet, so it
8054  // needs to be done somewhere else.
8055}
8056
8057/// When generating a defaulted copy or move assignment operator, if a field
8058/// should be copied with __builtin_memcpy rather than via explicit assignments,
8059/// do so. This optimization only applies for arrays of scalars, and for arrays
8060/// of class type where the selected copy/move-assignment operator is trivial.
8061static StmtResult
8062buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8063                           Expr *To, Expr *From) {
8064  // Compute the size of the memory buffer to be copied.
8065  QualType SizeType = S.Context.getSizeType();
8066  llvm::APInt Size(S.Context.getTypeSize(SizeType),
8067                   S.Context.getTypeSizeInChars(T).getQuantity());
8068
8069  // Take the address of the field references for "from" and "to". We
8070  // directly construct UnaryOperators here because semantic analysis
8071  // does not permit us to take the address of an xvalue.
8072  From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8073                         S.Context.getPointerType(From->getType()),
8074                         VK_RValue, OK_Ordinary, Loc);
8075  To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8076                       S.Context.getPointerType(To->getType()),
8077                       VK_RValue, OK_Ordinary, Loc);
8078
8079  const Type *E = T->getBaseElementTypeUnsafe();
8080  bool NeedsCollectableMemCpy =
8081    E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8082
8083  // Create a reference to the __builtin_objc_memmove_collectable function
8084  StringRef MemCpyName = NeedsCollectableMemCpy ?
8085    "__builtin_objc_memmove_collectable" :
8086    "__builtin_memcpy";
8087  LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8088                 Sema::LookupOrdinaryName);
8089  S.LookupName(R, S.TUScope, true);
8090
8091  FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8092  if (!MemCpy)
8093    // Something went horribly wrong earlier, and we will have complained
8094    // about it.
8095    return StmtError();
8096
8097  ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8098                                            VK_RValue, Loc, 0);
8099  assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8100
8101  Expr *CallArgs[] = {
8102    To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8103  };
8104  ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8105                                    Loc, CallArgs, Loc);
8106
8107  assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8108  return S.Owned(Call.takeAs<Stmt>());
8109}
8110
8111/// \brief Builds a statement that copies/moves the given entity from \p From to
8112/// \c To.
8113///
8114/// This routine is used to copy/move the members of a class with an
8115/// implicitly-declared copy/move assignment operator. When the entities being
8116/// copied are arrays, this routine builds for loops to copy them.
8117///
8118/// \param S The Sema object used for type-checking.
8119///
8120/// \param Loc The location where the implicit copy/move is being generated.
8121///
8122/// \param T The type of the expressions being copied/moved. Both expressions
8123/// must have this type.
8124///
8125/// \param To The expression we are copying/moving to.
8126///
8127/// \param From The expression we are copying/moving from.
8128///
8129/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
8130/// Otherwise, it's a non-static member subobject.
8131///
8132/// \param Copying Whether we're copying or moving.
8133///
8134/// \param Depth Internal parameter recording the depth of the recursion.
8135///
8136/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8137/// if a memcpy should be used instead.
8138static StmtResult
8139buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8140                                 Expr *To, Expr *From,
8141                                 bool CopyingBaseSubobject, bool Copying,
8142                                 unsigned Depth = 0) {
8143  // C++11 [class.copy]p28:
8144  //   Each subobject is assigned in the manner appropriate to its type:
8145  //
8146  //     - if the subobject is of class type, as if by a call to operator= with
8147  //       the subobject as the object expression and the corresponding
8148  //       subobject of x as a single function argument (as if by explicit
8149  //       qualification; that is, ignoring any possible virtual overriding
8150  //       functions in more derived classes);
8151  //
8152  // C++03 [class.copy]p13:
8153  //     - if the subobject is of class type, the copy assignment operator for
8154  //       the class is used (as if by explicit qualification; that is,
8155  //       ignoring any possible virtual overriding functions in more derived
8156  //       classes);
8157  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8158    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8159
8160    // Look for operator=.
8161    DeclarationName Name
8162      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8163    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8164    S.LookupQualifiedName(OpLookup, ClassDecl, false);
8165
8166    // Prior to C++11, filter out any result that isn't a copy/move-assignment
8167    // operator.
8168    if (!S.getLangOpts().CPlusPlus11) {
8169      LookupResult::Filter F = OpLookup.makeFilter();
8170      while (F.hasNext()) {
8171        NamedDecl *D = F.next();
8172        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8173          if (Method->isCopyAssignmentOperator() ||
8174              (!Copying && Method->isMoveAssignmentOperator()))
8175            continue;
8176
8177        F.erase();
8178      }
8179      F.done();
8180    }
8181
8182    // Suppress the protected check (C++ [class.protected]) for each of the
8183    // assignment operators we found. This strange dance is required when
8184    // we're assigning via a base classes's copy-assignment operator. To
8185    // ensure that we're getting the right base class subobject (without
8186    // ambiguities), we need to cast "this" to that subobject type; to
8187    // ensure that we don't go through the virtual call mechanism, we need
8188    // to qualify the operator= name with the base class (see below). However,
8189    // this means that if the base class has a protected copy assignment
8190    // operator, the protected member access check will fail. So, we
8191    // rewrite "protected" access to "public" access in this case, since we
8192    // know by construction that we're calling from a derived class.
8193    if (CopyingBaseSubobject) {
8194      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8195           L != LEnd; ++L) {
8196        if (L.getAccess() == AS_protected)
8197          L.setAccess(AS_public);
8198      }
8199    }
8200
8201    // Create the nested-name-specifier that will be used to qualify the
8202    // reference to operator=; this is required to suppress the virtual
8203    // call mechanism.
8204    CXXScopeSpec SS;
8205    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
8206    SS.MakeTrivial(S.Context,
8207                   NestedNameSpecifier::Create(S.Context, 0, false,
8208                                               CanonicalT),
8209                   Loc);
8210
8211    // Create the reference to operator=.
8212    ExprResult OpEqualRef
8213      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
8214                                   /*TemplateKWLoc=*/SourceLocation(),
8215                                   /*FirstQualifierInScope=*/0,
8216                                   OpLookup,
8217                                   /*TemplateArgs=*/0,
8218                                   /*SuppressQualifierCheck=*/true);
8219    if (OpEqualRef.isInvalid())
8220      return StmtError();
8221
8222    // Build the call to the assignment operator.
8223
8224    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
8225                                                  OpEqualRef.takeAs<Expr>(),
8226                                                  Loc, &From, 1, Loc);
8227    if (Call.isInvalid())
8228      return StmtError();
8229
8230    // If we built a call to a trivial 'operator=' while copying an array,
8231    // bail out. We'll replace the whole shebang with a memcpy.
8232    CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8233    if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8234      return StmtResult((Stmt*)0);
8235
8236    // Convert to an expression-statement, and clean up any produced
8237    // temporaries.
8238    return S.ActOnExprStmt(Call);
8239  }
8240
8241  //     - if the subobject is of scalar type, the built-in assignment
8242  //       operator is used.
8243  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
8244  if (!ArrayTy) {
8245    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
8246    if (Assignment.isInvalid())
8247      return StmtError();
8248    return S.ActOnExprStmt(Assignment);
8249  }
8250
8251  //     - if the subobject is an array, each element is assigned, in the
8252  //       manner appropriate to the element type;
8253
8254  // Construct a loop over the array bounds, e.g.,
8255  //
8256  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8257  //
8258  // that will copy each of the array elements.
8259  QualType SizeType = S.Context.getSizeType();
8260
8261  // Create the iteration variable.
8262  IdentifierInfo *IterationVarName = 0;
8263  {
8264    SmallString<8> Str;
8265    llvm::raw_svector_ostream OS(Str);
8266    OS << "__i" << Depth;
8267    IterationVarName = &S.Context.Idents.get(OS.str());
8268  }
8269  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
8270                                          IterationVarName, SizeType,
8271                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
8272                                          SC_None, SC_None);
8273
8274  // Initialize the iteration variable to zero.
8275  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8276  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8277
8278  // Create a reference to the iteration variable; we'll use this several
8279  // times throughout.
8280  Expr *IterationVarRef
8281    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
8282  assert(IterationVarRef && "Reference to invented variable cannot fail!");
8283  Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8284  assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8285
8286  // Create the DeclStmt that holds the iteration variable.
8287  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
8288
8289  // Subscript the "from" and "to" expressions with the iteration variable.
8290  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
8291                                                         IterationVarRefRVal,
8292                                                         Loc));
8293  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
8294                                                       IterationVarRefRVal,
8295                                                       Loc));
8296  if (!Copying) // Cast to rvalue
8297    From = CastForMoving(S, From);
8298
8299  // Build the copy/move for an individual element of the array.
8300  StmtResult Copy =
8301    buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8302                                     To, From, CopyingBaseSubobject,
8303                                     Copying, Depth + 1);
8304  // Bail out if copying fails or if we determined that we should use memcpy.
8305  if (Copy.isInvalid() || !Copy.get())
8306    return Copy;
8307
8308  // Create the comparison against the array bound.
8309  llvm::APInt Upper
8310    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8311  Expr *Comparison
8312    = new (S.Context) BinaryOperator(IterationVarRefRVal,
8313                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8314                                     BO_NE, S.Context.BoolTy,
8315                                     VK_RValue, OK_Ordinary, Loc, false);
8316
8317  // Create the pre-increment of the iteration variable.
8318  Expr *Increment
8319    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8320                                    VK_LValue, OK_Ordinary, Loc);
8321
8322  // Construct the loop that copies all elements of this array.
8323  return S.ActOnForStmt(Loc, Loc, InitStmt,
8324                        S.MakeFullExpr(Comparison),
8325                        0, S.MakeFullDiscardedValueExpr(Increment),
8326                        Loc, Copy.take());
8327}
8328
8329static StmtResult
8330buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8331                      Expr *To, Expr *From,
8332                      bool CopyingBaseSubobject, bool Copying) {
8333  // Maybe we should use a memcpy?
8334  if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8335      T.isTriviallyCopyableType(S.Context))
8336    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8337
8338  StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8339                                                     CopyingBaseSubobject,
8340                                                     Copying, 0));
8341
8342  // If we ended up picking a trivial assignment operator for an array of a
8343  // non-trivially-copyable class type, just emit a memcpy.
8344  if (!Result.isInvalid() && !Result.get())
8345    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8346
8347  return Result;
8348}
8349
8350Sema::ImplicitExceptionSpecification
8351Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8352  CXXRecordDecl *ClassDecl = MD->getParent();
8353
8354  ImplicitExceptionSpecification ExceptSpec(*this);
8355  if (ClassDecl->isInvalidDecl())
8356    return ExceptSpec;
8357
8358  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8359  assert(T->getNumArgs() == 1 && "not a copy assignment op");
8360  unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8361
8362  // C++ [except.spec]p14:
8363  //   An implicitly declared special member function (Clause 12) shall have an
8364  //   exception-specification. [...]
8365
8366  // It is unspecified whether or not an implicit copy assignment operator
8367  // attempts to deduplicate calls to assignment operators of virtual bases are
8368  // made. As such, this exception specification is effectively unspecified.
8369  // Based on a similar decision made for constness in C++0x, we're erring on
8370  // the side of assuming such calls to be made regardless of whether they
8371  // actually happen.
8372  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8373                                       BaseEnd = ClassDecl->bases_end();
8374       Base != BaseEnd; ++Base) {
8375    if (Base->isVirtual())
8376      continue;
8377
8378    CXXRecordDecl *BaseClassDecl
8379      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8380    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8381                                                            ArgQuals, false, 0))
8382      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8383  }
8384
8385  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8386                                       BaseEnd = ClassDecl->vbases_end();
8387       Base != BaseEnd; ++Base) {
8388    CXXRecordDecl *BaseClassDecl
8389      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8390    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8391                                                            ArgQuals, false, 0))
8392      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8393  }
8394
8395  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8396                                  FieldEnd = ClassDecl->field_end();
8397       Field != FieldEnd;
8398       ++Field) {
8399    QualType FieldType = Context.getBaseElementType(Field->getType());
8400    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8401      if (CXXMethodDecl *CopyAssign =
8402          LookupCopyingAssignment(FieldClassDecl,
8403                                  ArgQuals | FieldType.getCVRQualifiers(),
8404                                  false, 0))
8405        ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
8406    }
8407  }
8408
8409  return ExceptSpec;
8410}
8411
8412CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8413  // Note: The following rules are largely analoguous to the copy
8414  // constructor rules. Note that virtual bases are not taken into account
8415  // for determining the argument type of the operator. Note also that
8416  // operators taking an object instead of a reference are allowed.
8417  assert(ClassDecl->needsImplicitCopyAssignment());
8418
8419  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8420  if (DSM.isAlreadyBeingDeclared())
8421    return 0;
8422
8423  QualType ArgType = Context.getTypeDeclType(ClassDecl);
8424  QualType RetType = Context.getLValueReferenceType(ArgType);
8425  if (ClassDecl->implicitCopyAssignmentHasConstParam())
8426    ArgType = ArgType.withConst();
8427  ArgType = Context.getLValueReferenceType(ArgType);
8428
8429  //   An implicitly-declared copy assignment operator is an inline public
8430  //   member of its class.
8431  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8432  SourceLocation ClassLoc = ClassDecl->getLocation();
8433  DeclarationNameInfo NameInfo(Name, ClassLoc);
8434  CXXMethodDecl *CopyAssignment
8435    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8436                            /*TInfo=*/0, /*isStatic=*/false,
8437                            /*StorageClassAsWritten=*/SC_None,
8438                            /*isInline=*/true, /*isConstexpr=*/false,
8439                            SourceLocation());
8440  CopyAssignment->setAccess(AS_public);
8441  CopyAssignment->setDefaulted();
8442  CopyAssignment->setImplicit();
8443
8444  // Build an exception specification pointing back at this member.
8445  FunctionProtoType::ExtProtoInfo EPI;
8446  EPI.ExceptionSpecType = EST_Unevaluated;
8447  EPI.ExceptionSpecDecl = CopyAssignment;
8448  CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
8449
8450  // Add the parameter to the operator.
8451  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
8452                                               ClassLoc, ClassLoc, /*Id=*/0,
8453                                               ArgType, /*TInfo=*/0,
8454                                               SC_None,
8455                                               SC_None, 0);
8456  CopyAssignment->setParams(FromParam);
8457
8458  AddOverriddenMethods(ClassDecl, CopyAssignment);
8459
8460  CopyAssignment->setTrivial(
8461    ClassDecl->needsOverloadResolutionForCopyAssignment()
8462      ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8463      : ClassDecl->hasTrivialCopyAssignment());
8464
8465  // C++0x [class.copy]p19:
8466  //   ....  If the class definition does not explicitly declare a copy
8467  //   assignment operator, there is no user-declared move constructor, and
8468  //   there is no user-declared move assignment operator, a copy assignment
8469  //   operator is implicitly declared as defaulted.
8470  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
8471    CopyAssignment->setDeletedAsWritten();
8472
8473  // Note that we have added this copy-assignment operator.
8474  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8475
8476  if (Scope *S = getScopeForContext(ClassDecl))
8477    PushOnScopeChains(CopyAssignment, S, false);
8478  ClassDecl->addDecl(CopyAssignment);
8479
8480  return CopyAssignment;
8481}
8482
8483void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8484                                        CXXMethodDecl *CopyAssignOperator) {
8485  assert((CopyAssignOperator->isDefaulted() &&
8486          CopyAssignOperator->isOverloadedOperator() &&
8487          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
8488          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8489          !CopyAssignOperator->isDeleted()) &&
8490         "DefineImplicitCopyAssignment called for wrong function");
8491
8492  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8493
8494  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8495    CopyAssignOperator->setInvalidDecl();
8496    return;
8497  }
8498
8499  CopyAssignOperator->setUsed();
8500
8501  SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
8502  DiagnosticErrorTrap Trap(Diags);
8503
8504  // C++0x [class.copy]p30:
8505  //   The implicitly-defined or explicitly-defaulted copy assignment operator
8506  //   for a non-union class X performs memberwise copy assignment of its
8507  //   subobjects. The direct base classes of X are assigned first, in the
8508  //   order of their declaration in the base-specifier-list, and then the
8509  //   immediate non-static data members of X are assigned, in the order in
8510  //   which they were declared in the class definition.
8511
8512  // The statements that form the synthesized function body.
8513  SmallVector<Stmt*, 8> Statements;
8514
8515  // The parameter for the "other" object, which we are copying from.
8516  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8517  Qualifiers OtherQuals = Other->getType().getQualifiers();
8518  QualType OtherRefType = Other->getType();
8519  if (const LValueReferenceType *OtherRef
8520                                = OtherRefType->getAs<LValueReferenceType>()) {
8521    OtherRefType = OtherRef->getPointeeType();
8522    OtherQuals = OtherRefType.getQualifiers();
8523  }
8524
8525  // Our location for everything implicitly-generated.
8526  SourceLocation Loc = CopyAssignOperator->getLocation();
8527
8528  // Construct a reference to the "other" object. We'll be using this
8529  // throughout the generated ASTs.
8530  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8531  assert(OtherRef && "Reference to parameter cannot fail!");
8532
8533  // Construct the "this" pointer. We'll be using this throughout the generated
8534  // ASTs.
8535  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8536  assert(This && "Reference to this cannot fail!");
8537
8538  // Assign base classes.
8539  bool Invalid = false;
8540  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8541       E = ClassDecl->bases_end(); Base != E; ++Base) {
8542    // Form the assignment:
8543    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8544    QualType BaseType = Base->getType().getUnqualifiedType();
8545    if (!BaseType->isRecordType()) {
8546      Invalid = true;
8547      continue;
8548    }
8549
8550    CXXCastPath BasePath;
8551    BasePath.push_back(Base);
8552
8553    // Construct the "from" expression, which is an implicit cast to the
8554    // appropriately-qualified base type.
8555    Expr *From = OtherRef;
8556    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8557                             CK_UncheckedDerivedToBase,
8558                             VK_LValue, &BasePath).take();
8559
8560    // Dereference "this".
8561    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8562
8563    // Implicitly cast "this" to the appropriately-qualified base type.
8564    To = ImpCastExprToType(To.take(),
8565                           Context.getCVRQualifiedType(BaseType,
8566                                     CopyAssignOperator->getTypeQualifiers()),
8567                           CK_UncheckedDerivedToBase,
8568                           VK_LValue, &BasePath);
8569
8570    // Build the copy.
8571    StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
8572                                            To.get(), From,
8573                                            /*CopyingBaseSubobject=*/true,
8574                                            /*Copying=*/true);
8575    if (Copy.isInvalid()) {
8576      Diag(CurrentLocation, diag::note_member_synthesized_at)
8577        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8578      CopyAssignOperator->setInvalidDecl();
8579      return;
8580    }
8581
8582    // Success! Record the copy.
8583    Statements.push_back(Copy.takeAs<Expr>());
8584  }
8585
8586  // Assign non-static members.
8587  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8588                                  FieldEnd = ClassDecl->field_end();
8589       Field != FieldEnd; ++Field) {
8590    if (Field->isUnnamedBitfield())
8591      continue;
8592
8593    // Check for members of reference type; we can't copy those.
8594    if (Field->getType()->isReferenceType()) {
8595      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8596        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8597      Diag(Field->getLocation(), diag::note_declared_at);
8598      Diag(CurrentLocation, diag::note_member_synthesized_at)
8599        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8600      Invalid = true;
8601      continue;
8602    }
8603
8604    // Check for members of const-qualified, non-class type.
8605    QualType BaseType = Context.getBaseElementType(Field->getType());
8606    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8607      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8608        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8609      Diag(Field->getLocation(), diag::note_declared_at);
8610      Diag(CurrentLocation, diag::note_member_synthesized_at)
8611        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8612      Invalid = true;
8613      continue;
8614    }
8615
8616    // Suppress assigning zero-width bitfields.
8617    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8618      continue;
8619
8620    QualType FieldType = Field->getType().getNonReferenceType();
8621    if (FieldType->isIncompleteArrayType()) {
8622      assert(ClassDecl->hasFlexibleArrayMember() &&
8623             "Incomplete array type is not valid");
8624      continue;
8625    }
8626
8627    // Build references to the field in the object we're copying from and to.
8628    CXXScopeSpec SS; // Intentionally empty
8629    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8630                              LookupMemberName);
8631    MemberLookup.addDecl(*Field);
8632    MemberLookup.resolveKind();
8633    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8634                                               Loc, /*IsArrow=*/false,
8635                                               SS, SourceLocation(), 0,
8636                                               MemberLookup, 0);
8637    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8638                                             Loc, /*IsArrow=*/true,
8639                                             SS, SourceLocation(), 0,
8640                                             MemberLookup, 0);
8641    assert(!From.isInvalid() && "Implicit field reference cannot fail");
8642    assert(!To.isInvalid() && "Implicit field reference cannot fail");
8643
8644    // Build the copy of this field.
8645    StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
8646                                            To.get(), From.get(),
8647                                            /*CopyingBaseSubobject=*/false,
8648                                            /*Copying=*/true);
8649    if (Copy.isInvalid()) {
8650      Diag(CurrentLocation, diag::note_member_synthesized_at)
8651        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8652      CopyAssignOperator->setInvalidDecl();
8653      return;
8654    }
8655
8656    // Success! Record the copy.
8657    Statements.push_back(Copy.takeAs<Stmt>());
8658  }
8659
8660  if (!Invalid) {
8661    // Add a "return *this;"
8662    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8663
8664    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8665    if (Return.isInvalid())
8666      Invalid = true;
8667    else {
8668      Statements.push_back(Return.takeAs<Stmt>());
8669
8670      if (Trap.hasErrorOccurred()) {
8671        Diag(CurrentLocation, diag::note_member_synthesized_at)
8672          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8673        Invalid = true;
8674      }
8675    }
8676  }
8677
8678  if (Invalid) {
8679    CopyAssignOperator->setInvalidDecl();
8680    return;
8681  }
8682
8683  StmtResult Body;
8684  {
8685    CompoundScopeRAII CompoundScope(*this);
8686    Body = ActOnCompoundStmt(Loc, Loc, Statements,
8687                             /*isStmtExpr=*/false);
8688    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8689  }
8690  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
8691
8692  if (ASTMutationListener *L = getASTMutationListener()) {
8693    L->CompletedImplicitDefinition(CopyAssignOperator);
8694  }
8695}
8696
8697Sema::ImplicitExceptionSpecification
8698Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8699  CXXRecordDecl *ClassDecl = MD->getParent();
8700
8701  ImplicitExceptionSpecification ExceptSpec(*this);
8702  if (ClassDecl->isInvalidDecl())
8703    return ExceptSpec;
8704
8705  // C++0x [except.spec]p14:
8706  //   An implicitly declared special member function (Clause 12) shall have an
8707  //   exception-specification. [...]
8708
8709  // It is unspecified whether or not an implicit move assignment operator
8710  // attempts to deduplicate calls to assignment operators of virtual bases are
8711  // made. As such, this exception specification is effectively unspecified.
8712  // Based on a similar decision made for constness in C++0x, we're erring on
8713  // the side of assuming such calls to be made regardless of whether they
8714  // actually happen.
8715  // Note that a move constructor is not implicitly declared when there are
8716  // virtual bases, but it can still be user-declared and explicitly defaulted.
8717  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8718                                       BaseEnd = ClassDecl->bases_end();
8719       Base != BaseEnd; ++Base) {
8720    if (Base->isVirtual())
8721      continue;
8722
8723    CXXRecordDecl *BaseClassDecl
8724      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8725    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8726                                                           0, false, 0))
8727      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8728  }
8729
8730  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8731                                       BaseEnd = ClassDecl->vbases_end();
8732       Base != BaseEnd; ++Base) {
8733    CXXRecordDecl *BaseClassDecl
8734      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8735    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8736                                                           0, false, 0))
8737      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8738  }
8739
8740  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8741                                  FieldEnd = ClassDecl->field_end();
8742       Field != FieldEnd;
8743       ++Field) {
8744    QualType FieldType = Context.getBaseElementType(Field->getType());
8745    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8746      if (CXXMethodDecl *MoveAssign =
8747              LookupMovingAssignment(FieldClassDecl,
8748                                     FieldType.getCVRQualifiers(),
8749                                     false, 0))
8750        ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
8751    }
8752  }
8753
8754  return ExceptSpec;
8755}
8756
8757/// Determine whether the class type has any direct or indirect virtual base
8758/// classes which have a non-trivial move assignment operator.
8759static bool
8760hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8761  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8762                                          BaseEnd = ClassDecl->vbases_end();
8763       Base != BaseEnd; ++Base) {
8764    CXXRecordDecl *BaseClass =
8765        cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8766
8767    // Try to declare the move assignment. If it would be deleted, then the
8768    // class does not have a non-trivial move assignment.
8769    if (BaseClass->needsImplicitMoveAssignment())
8770      S.DeclareImplicitMoveAssignment(BaseClass);
8771
8772    if (BaseClass->hasNonTrivialMoveAssignment())
8773      return true;
8774  }
8775
8776  return false;
8777}
8778
8779/// Determine whether the given type either has a move constructor or is
8780/// trivially copyable.
8781static bool
8782hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8783  Type = S.Context.getBaseElementType(Type);
8784
8785  // FIXME: Technically, non-trivially-copyable non-class types, such as
8786  // reference types, are supposed to return false here, but that appears
8787  // to be a standard defect.
8788  CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
8789  if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
8790    return true;
8791
8792  if (Type.isTriviallyCopyableType(S.Context))
8793    return true;
8794
8795  if (IsConstructor) {
8796    // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8797    // give the right answer.
8798    if (ClassDecl->needsImplicitMoveConstructor())
8799      S.DeclareImplicitMoveConstructor(ClassDecl);
8800    return ClassDecl->hasMoveConstructor();
8801  }
8802
8803  // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8804  // give the right answer.
8805  if (ClassDecl->needsImplicitMoveAssignment())
8806    S.DeclareImplicitMoveAssignment(ClassDecl);
8807  return ClassDecl->hasMoveAssignment();
8808}
8809
8810/// Determine whether all non-static data members and direct or virtual bases
8811/// of class \p ClassDecl have either a move operation, or are trivially
8812/// copyable.
8813static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8814                                            bool IsConstructor) {
8815  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8816                                          BaseEnd = ClassDecl->bases_end();
8817       Base != BaseEnd; ++Base) {
8818    if (Base->isVirtual())
8819      continue;
8820
8821    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8822      return false;
8823  }
8824
8825  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8826                                          BaseEnd = ClassDecl->vbases_end();
8827       Base != BaseEnd; ++Base) {
8828    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8829      return false;
8830  }
8831
8832  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8833                                     FieldEnd = ClassDecl->field_end();
8834       Field != FieldEnd; ++Field) {
8835    if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
8836      return false;
8837  }
8838
8839  return true;
8840}
8841
8842CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8843  // C++11 [class.copy]p20:
8844  //   If the definition of a class X does not explicitly declare a move
8845  //   assignment operator, one will be implicitly declared as defaulted
8846  //   if and only if:
8847  //
8848  //   - [first 4 bullets]
8849  assert(ClassDecl->needsImplicitMoveAssignment());
8850
8851  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8852  if (DSM.isAlreadyBeingDeclared())
8853    return 0;
8854
8855  // [Checked after we build the declaration]
8856  //   - the move assignment operator would not be implicitly defined as
8857  //     deleted,
8858
8859  // [DR1402]:
8860  //   - X has no direct or indirect virtual base class with a non-trivial
8861  //     move assignment operator, and
8862  //   - each of X's non-static data members and direct or virtual base classes
8863  //     has a type that either has a move assignment operator or is trivially
8864  //     copyable.
8865  if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8866      !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8867    ClassDecl->setFailedImplicitMoveAssignment();
8868    return 0;
8869  }
8870
8871  // Note: The following rules are largely analoguous to the move
8872  // constructor rules.
8873
8874  QualType ArgType = Context.getTypeDeclType(ClassDecl);
8875  QualType RetType = Context.getLValueReferenceType(ArgType);
8876  ArgType = Context.getRValueReferenceType(ArgType);
8877
8878  //   An implicitly-declared move assignment operator is an inline public
8879  //   member of its class.
8880  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8881  SourceLocation ClassLoc = ClassDecl->getLocation();
8882  DeclarationNameInfo NameInfo(Name, ClassLoc);
8883  CXXMethodDecl *MoveAssignment
8884    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8885                            /*TInfo=*/0, /*isStatic=*/false,
8886                            /*StorageClassAsWritten=*/SC_None,
8887                            /*isInline=*/true,
8888                            /*isConstexpr=*/false,
8889                            SourceLocation());
8890  MoveAssignment->setAccess(AS_public);
8891  MoveAssignment->setDefaulted();
8892  MoveAssignment->setImplicit();
8893
8894  // Build an exception specification pointing back at this member.
8895  FunctionProtoType::ExtProtoInfo EPI;
8896  EPI.ExceptionSpecType = EST_Unevaluated;
8897  EPI.ExceptionSpecDecl = MoveAssignment;
8898  MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
8899
8900  // Add the parameter to the operator.
8901  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8902                                               ClassLoc, ClassLoc, /*Id=*/0,
8903                                               ArgType, /*TInfo=*/0,
8904                                               SC_None,
8905                                               SC_None, 0);
8906  MoveAssignment->setParams(FromParam);
8907
8908  AddOverriddenMethods(ClassDecl, MoveAssignment);
8909
8910  MoveAssignment->setTrivial(
8911    ClassDecl->needsOverloadResolutionForMoveAssignment()
8912      ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8913      : ClassDecl->hasTrivialMoveAssignment());
8914
8915  // C++0x [class.copy]p9:
8916  //   If the definition of a class X does not explicitly declare a move
8917  //   assignment operator, one will be implicitly declared as defaulted if and
8918  //   only if:
8919  //   [...]
8920  //   - the move assignment operator would not be implicitly defined as
8921  //     deleted.
8922  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
8923    // Cache this result so that we don't try to generate this over and over
8924    // on every lookup, leaking memory and wasting time.
8925    ClassDecl->setFailedImplicitMoveAssignment();
8926    return 0;
8927  }
8928
8929  // Note that we have added this copy-assignment operator.
8930  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8931
8932  if (Scope *S = getScopeForContext(ClassDecl))
8933    PushOnScopeChains(MoveAssignment, S, false);
8934  ClassDecl->addDecl(MoveAssignment);
8935
8936  return MoveAssignment;
8937}
8938
8939void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8940                                        CXXMethodDecl *MoveAssignOperator) {
8941  assert((MoveAssignOperator->isDefaulted() &&
8942          MoveAssignOperator->isOverloadedOperator() &&
8943          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8944          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8945          !MoveAssignOperator->isDeleted()) &&
8946         "DefineImplicitMoveAssignment called for wrong function");
8947
8948  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8949
8950  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8951    MoveAssignOperator->setInvalidDecl();
8952    return;
8953  }
8954
8955  MoveAssignOperator->setUsed();
8956
8957  SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
8958  DiagnosticErrorTrap Trap(Diags);
8959
8960  // C++0x [class.copy]p28:
8961  //   The implicitly-defined or move assignment operator for a non-union class
8962  //   X performs memberwise move assignment of its subobjects. The direct base
8963  //   classes of X are assigned first, in the order of their declaration in the
8964  //   base-specifier-list, and then the immediate non-static data members of X
8965  //   are assigned, in the order in which they were declared in the class
8966  //   definition.
8967
8968  // The statements that form the synthesized function body.
8969  SmallVector<Stmt*, 8> Statements;
8970
8971  // The parameter for the "other" object, which we are move from.
8972  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8973  QualType OtherRefType = Other->getType()->
8974      getAs<RValueReferenceType>()->getPointeeType();
8975  assert(OtherRefType.getQualifiers() == 0 &&
8976         "Bad argument type of defaulted move assignment");
8977
8978  // Our location for everything implicitly-generated.
8979  SourceLocation Loc = MoveAssignOperator->getLocation();
8980
8981  // Construct a reference to the "other" object. We'll be using this
8982  // throughout the generated ASTs.
8983  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8984  assert(OtherRef && "Reference to parameter cannot fail!");
8985  // Cast to rvalue.
8986  OtherRef = CastForMoving(*this, OtherRef);
8987
8988  // Construct the "this" pointer. We'll be using this throughout the generated
8989  // ASTs.
8990  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8991  assert(This && "Reference to this cannot fail!");
8992
8993  // Assign base classes.
8994  bool Invalid = false;
8995  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8996       E = ClassDecl->bases_end(); Base != E; ++Base) {
8997    // Form the assignment:
8998    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8999    QualType BaseType = Base->getType().getUnqualifiedType();
9000    if (!BaseType->isRecordType()) {
9001      Invalid = true;
9002      continue;
9003    }
9004
9005    CXXCastPath BasePath;
9006    BasePath.push_back(Base);
9007
9008    // Construct the "from" expression, which is an implicit cast to the
9009    // appropriately-qualified base type.
9010    Expr *From = OtherRef;
9011    From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
9012                             VK_XValue, &BasePath).take();
9013
9014    // Dereference "this".
9015    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9016
9017    // Implicitly cast "this" to the appropriately-qualified base type.
9018    To = ImpCastExprToType(To.take(),
9019                           Context.getCVRQualifiedType(BaseType,
9020                                     MoveAssignOperator->getTypeQualifiers()),
9021                           CK_UncheckedDerivedToBase,
9022                           VK_LValue, &BasePath);
9023
9024    // Build the move.
9025    StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
9026                                            To.get(), From,
9027                                            /*CopyingBaseSubobject=*/true,
9028                                            /*Copying=*/false);
9029    if (Move.isInvalid()) {
9030      Diag(CurrentLocation, diag::note_member_synthesized_at)
9031        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9032      MoveAssignOperator->setInvalidDecl();
9033      return;
9034    }
9035
9036    // Success! Record the move.
9037    Statements.push_back(Move.takeAs<Expr>());
9038  }
9039
9040  // Assign non-static members.
9041  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9042                                  FieldEnd = ClassDecl->field_end();
9043       Field != FieldEnd; ++Field) {
9044    if (Field->isUnnamedBitfield())
9045      continue;
9046
9047    // Check for members of reference type; we can't move those.
9048    if (Field->getType()->isReferenceType()) {
9049      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9050        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9051      Diag(Field->getLocation(), diag::note_declared_at);
9052      Diag(CurrentLocation, diag::note_member_synthesized_at)
9053        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9054      Invalid = true;
9055      continue;
9056    }
9057
9058    // Check for members of const-qualified, non-class type.
9059    QualType BaseType = Context.getBaseElementType(Field->getType());
9060    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9061      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9062        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9063      Diag(Field->getLocation(), diag::note_declared_at);
9064      Diag(CurrentLocation, diag::note_member_synthesized_at)
9065        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9066      Invalid = true;
9067      continue;
9068    }
9069
9070    // Suppress assigning zero-width bitfields.
9071    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9072      continue;
9073
9074    QualType FieldType = Field->getType().getNonReferenceType();
9075    if (FieldType->isIncompleteArrayType()) {
9076      assert(ClassDecl->hasFlexibleArrayMember() &&
9077             "Incomplete array type is not valid");
9078      continue;
9079    }
9080
9081    // Build references to the field in the object we're copying from and to.
9082    CXXScopeSpec SS; // Intentionally empty
9083    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9084                              LookupMemberName);
9085    MemberLookup.addDecl(*Field);
9086    MemberLookup.resolveKind();
9087    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9088                                               Loc, /*IsArrow=*/false,
9089                                               SS, SourceLocation(), 0,
9090                                               MemberLookup, 0);
9091    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9092                                             Loc, /*IsArrow=*/true,
9093                                             SS, SourceLocation(), 0,
9094                                             MemberLookup, 0);
9095    assert(!From.isInvalid() && "Implicit field reference cannot fail");
9096    assert(!To.isInvalid() && "Implicit field reference cannot fail");
9097
9098    assert(!From.get()->isLValue() && // could be xvalue or prvalue
9099        "Member reference with rvalue base must be rvalue except for reference "
9100        "members, which aren't allowed for move assignment.");
9101
9102    // Build the move of this field.
9103    StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
9104                                            To.get(), From.get(),
9105                                            /*CopyingBaseSubobject=*/false,
9106                                            /*Copying=*/false);
9107    if (Move.isInvalid()) {
9108      Diag(CurrentLocation, diag::note_member_synthesized_at)
9109        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9110      MoveAssignOperator->setInvalidDecl();
9111      return;
9112    }
9113
9114    // Success! Record the copy.
9115    Statements.push_back(Move.takeAs<Stmt>());
9116  }
9117
9118  if (!Invalid) {
9119    // Add a "return *this;"
9120    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9121
9122    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9123    if (Return.isInvalid())
9124      Invalid = true;
9125    else {
9126      Statements.push_back(Return.takeAs<Stmt>());
9127
9128      if (Trap.hasErrorOccurred()) {
9129        Diag(CurrentLocation, diag::note_member_synthesized_at)
9130          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9131        Invalid = true;
9132      }
9133    }
9134  }
9135
9136  if (Invalid) {
9137    MoveAssignOperator->setInvalidDecl();
9138    return;
9139  }
9140
9141  StmtResult Body;
9142  {
9143    CompoundScopeRAII CompoundScope(*this);
9144    Body = ActOnCompoundStmt(Loc, Loc, Statements,
9145                             /*isStmtExpr=*/false);
9146    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9147  }
9148  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9149
9150  if (ASTMutationListener *L = getASTMutationListener()) {
9151    L->CompletedImplicitDefinition(MoveAssignOperator);
9152  }
9153}
9154
9155Sema::ImplicitExceptionSpecification
9156Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9157  CXXRecordDecl *ClassDecl = MD->getParent();
9158
9159  ImplicitExceptionSpecification ExceptSpec(*this);
9160  if (ClassDecl->isInvalidDecl())
9161    return ExceptSpec;
9162
9163  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9164  assert(T->getNumArgs() >= 1 && "not a copy ctor");
9165  unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9166
9167  // C++ [except.spec]p14:
9168  //   An implicitly declared special member function (Clause 12) shall have an
9169  //   exception-specification. [...]
9170  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9171                                       BaseEnd = ClassDecl->bases_end();
9172       Base != BaseEnd;
9173       ++Base) {
9174    // Virtual bases are handled below.
9175    if (Base->isVirtual())
9176      continue;
9177
9178    CXXRecordDecl *BaseClassDecl
9179      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9180    if (CXXConstructorDecl *CopyConstructor =
9181          LookupCopyingConstructor(BaseClassDecl, Quals))
9182      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9183  }
9184  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9185                                       BaseEnd = ClassDecl->vbases_end();
9186       Base != BaseEnd;
9187       ++Base) {
9188    CXXRecordDecl *BaseClassDecl
9189      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9190    if (CXXConstructorDecl *CopyConstructor =
9191          LookupCopyingConstructor(BaseClassDecl, Quals))
9192      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9193  }
9194  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9195                                  FieldEnd = ClassDecl->field_end();
9196       Field != FieldEnd;
9197       ++Field) {
9198    QualType FieldType = Context.getBaseElementType(Field->getType());
9199    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9200      if (CXXConstructorDecl *CopyConstructor =
9201              LookupCopyingConstructor(FieldClassDecl,
9202                                       Quals | FieldType.getCVRQualifiers()))
9203      ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
9204    }
9205  }
9206
9207  return ExceptSpec;
9208}
9209
9210CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9211                                                    CXXRecordDecl *ClassDecl) {
9212  // C++ [class.copy]p4:
9213  //   If the class definition does not explicitly declare a copy
9214  //   constructor, one is declared implicitly.
9215  assert(ClassDecl->needsImplicitCopyConstructor());
9216
9217  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9218  if (DSM.isAlreadyBeingDeclared())
9219    return 0;
9220
9221  QualType ClassType = Context.getTypeDeclType(ClassDecl);
9222  QualType ArgType = ClassType;
9223  bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
9224  if (Const)
9225    ArgType = ArgType.withConst();
9226  ArgType = Context.getLValueReferenceType(ArgType);
9227
9228  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9229                                                     CXXCopyConstructor,
9230                                                     Const);
9231
9232  DeclarationName Name
9233    = Context.DeclarationNames.getCXXConstructorName(
9234                                           Context.getCanonicalType(ClassType));
9235  SourceLocation ClassLoc = ClassDecl->getLocation();
9236  DeclarationNameInfo NameInfo(Name, ClassLoc);
9237
9238  //   An implicitly-declared copy constructor is an inline public
9239  //   member of its class.
9240  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
9241      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9242      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9243      Constexpr);
9244  CopyConstructor->setAccess(AS_public);
9245  CopyConstructor->setDefaulted();
9246
9247  // Build an exception specification pointing back at this member.
9248  FunctionProtoType::ExtProtoInfo EPI;
9249  EPI.ExceptionSpecType = EST_Unevaluated;
9250  EPI.ExceptionSpecDecl = CopyConstructor;
9251  CopyConstructor->setType(
9252      Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9253
9254  // Add the parameter to the constructor.
9255  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
9256                                               ClassLoc, ClassLoc,
9257                                               /*IdentifierInfo=*/0,
9258                                               ArgType, /*TInfo=*/0,
9259                                               SC_None,
9260                                               SC_None, 0);
9261  CopyConstructor->setParams(FromParam);
9262
9263  CopyConstructor->setTrivial(
9264    ClassDecl->needsOverloadResolutionForCopyConstructor()
9265      ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9266      : ClassDecl->hasTrivialCopyConstructor());
9267
9268  // C++11 [class.copy]p8:
9269  //   ... If the class definition does not explicitly declare a copy
9270  //   constructor, there is no user-declared move constructor, and there is no
9271  //   user-declared move assignment operator, a copy constructor is implicitly
9272  //   declared as defaulted.
9273  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
9274    CopyConstructor->setDeletedAsWritten();
9275
9276  // Note that we have declared this constructor.
9277  ++ASTContext::NumImplicitCopyConstructorsDeclared;
9278
9279  if (Scope *S = getScopeForContext(ClassDecl))
9280    PushOnScopeChains(CopyConstructor, S, false);
9281  ClassDecl->addDecl(CopyConstructor);
9282
9283  return CopyConstructor;
9284}
9285
9286void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
9287                                   CXXConstructorDecl *CopyConstructor) {
9288  assert((CopyConstructor->isDefaulted() &&
9289          CopyConstructor->isCopyConstructor() &&
9290          !CopyConstructor->doesThisDeclarationHaveABody() &&
9291          !CopyConstructor->isDeleted()) &&
9292         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
9293
9294  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
9295  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
9296
9297  SynthesizedFunctionScope Scope(*this, CopyConstructor);
9298  DiagnosticErrorTrap Trap(Diags);
9299
9300  if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
9301      Trap.hasErrorOccurred()) {
9302    Diag(CurrentLocation, diag::note_member_synthesized_at)
9303      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
9304    CopyConstructor->setInvalidDecl();
9305  }  else {
9306    Sema::CompoundScopeRAII CompoundScope(*this);
9307    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9308                                               CopyConstructor->getLocation(),
9309                                               MultiStmtArg(),
9310                                               /*isStmtExpr=*/false)
9311                                                              .takeAs<Stmt>());
9312    CopyConstructor->setImplicitlyDefined(true);
9313  }
9314
9315  CopyConstructor->setUsed();
9316  if (ASTMutationListener *L = getASTMutationListener()) {
9317    L->CompletedImplicitDefinition(CopyConstructor);
9318  }
9319}
9320
9321Sema::ImplicitExceptionSpecification
9322Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9323  CXXRecordDecl *ClassDecl = MD->getParent();
9324
9325  // C++ [except.spec]p14:
9326  //   An implicitly declared special member function (Clause 12) shall have an
9327  //   exception-specification. [...]
9328  ImplicitExceptionSpecification ExceptSpec(*this);
9329  if (ClassDecl->isInvalidDecl())
9330    return ExceptSpec;
9331
9332  // Direct base-class constructors.
9333  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9334                                       BEnd = ClassDecl->bases_end();
9335       B != BEnd; ++B) {
9336    if (B->isVirtual()) // Handled below.
9337      continue;
9338
9339    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9340      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9341      CXXConstructorDecl *Constructor =
9342          LookupMovingConstructor(BaseClassDecl, 0);
9343      // If this is a deleted function, add it anyway. This might be conformant
9344      // with the standard. This might not. I'm not sure. It might not matter.
9345      if (Constructor)
9346        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9347    }
9348  }
9349
9350  // Virtual base-class constructors.
9351  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9352                                       BEnd = ClassDecl->vbases_end();
9353       B != BEnd; ++B) {
9354    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9355      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9356      CXXConstructorDecl *Constructor =
9357          LookupMovingConstructor(BaseClassDecl, 0);
9358      // If this is a deleted function, add it anyway. This might be conformant
9359      // with the standard. This might not. I'm not sure. It might not matter.
9360      if (Constructor)
9361        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9362    }
9363  }
9364
9365  // Field constructors.
9366  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9367                               FEnd = ClassDecl->field_end();
9368       F != FEnd; ++F) {
9369    QualType FieldType = Context.getBaseElementType(F->getType());
9370    if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9371      CXXConstructorDecl *Constructor =
9372          LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
9373      // If this is a deleted function, add it anyway. This might be conformant
9374      // with the standard. This might not. I'm not sure. It might not matter.
9375      // In particular, the problem is that this function never gets called. It
9376      // might just be ill-formed because this function attempts to refer to
9377      // a deleted function here.
9378      if (Constructor)
9379        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9380    }
9381  }
9382
9383  return ExceptSpec;
9384}
9385
9386CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9387                                                    CXXRecordDecl *ClassDecl) {
9388  // C++11 [class.copy]p9:
9389  //   If the definition of a class X does not explicitly declare a move
9390  //   constructor, one will be implicitly declared as defaulted if and only if:
9391  //
9392  //   - [first 4 bullets]
9393  assert(ClassDecl->needsImplicitMoveConstructor());
9394
9395  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9396  if (DSM.isAlreadyBeingDeclared())
9397    return 0;
9398
9399  // [Checked after we build the declaration]
9400  //   - the move assignment operator would not be implicitly defined as
9401  //     deleted,
9402
9403  // [DR1402]:
9404  //   - each of X's non-static data members and direct or virtual base classes
9405  //     has a type that either has a move constructor or is trivially copyable.
9406  if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9407    ClassDecl->setFailedImplicitMoveConstructor();
9408    return 0;
9409  }
9410
9411  QualType ClassType = Context.getTypeDeclType(ClassDecl);
9412  QualType ArgType = Context.getRValueReferenceType(ClassType);
9413
9414  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9415                                                     CXXMoveConstructor,
9416                                                     false);
9417
9418  DeclarationName Name
9419    = Context.DeclarationNames.getCXXConstructorName(
9420                                           Context.getCanonicalType(ClassType));
9421  SourceLocation ClassLoc = ClassDecl->getLocation();
9422  DeclarationNameInfo NameInfo(Name, ClassLoc);
9423
9424  // C++0x [class.copy]p11:
9425  //   An implicitly-declared copy/move constructor is an inline public
9426  //   member of its class.
9427  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
9428      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9429      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9430      Constexpr);
9431  MoveConstructor->setAccess(AS_public);
9432  MoveConstructor->setDefaulted();
9433
9434  // Build an exception specification pointing back at this member.
9435  FunctionProtoType::ExtProtoInfo EPI;
9436  EPI.ExceptionSpecType = EST_Unevaluated;
9437  EPI.ExceptionSpecDecl = MoveConstructor;
9438  MoveConstructor->setType(
9439      Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9440
9441  // Add the parameter to the constructor.
9442  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9443                                               ClassLoc, ClassLoc,
9444                                               /*IdentifierInfo=*/0,
9445                                               ArgType, /*TInfo=*/0,
9446                                               SC_None,
9447                                               SC_None, 0);
9448  MoveConstructor->setParams(FromParam);
9449
9450  MoveConstructor->setTrivial(
9451    ClassDecl->needsOverloadResolutionForMoveConstructor()
9452      ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9453      : ClassDecl->hasTrivialMoveConstructor());
9454
9455  // C++0x [class.copy]p9:
9456  //   If the definition of a class X does not explicitly declare a move
9457  //   constructor, one will be implicitly declared as defaulted if and only if:
9458  //   [...]
9459  //   - the move constructor would not be implicitly defined as deleted.
9460  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
9461    // Cache this result so that we don't try to generate this over and over
9462    // on every lookup, leaking memory and wasting time.
9463    ClassDecl->setFailedImplicitMoveConstructor();
9464    return 0;
9465  }
9466
9467  // Note that we have declared this constructor.
9468  ++ASTContext::NumImplicitMoveConstructorsDeclared;
9469
9470  if (Scope *S = getScopeForContext(ClassDecl))
9471    PushOnScopeChains(MoveConstructor, S, false);
9472  ClassDecl->addDecl(MoveConstructor);
9473
9474  return MoveConstructor;
9475}
9476
9477void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9478                                   CXXConstructorDecl *MoveConstructor) {
9479  assert((MoveConstructor->isDefaulted() &&
9480          MoveConstructor->isMoveConstructor() &&
9481          !MoveConstructor->doesThisDeclarationHaveABody() &&
9482          !MoveConstructor->isDeleted()) &&
9483         "DefineImplicitMoveConstructor - call it for implicit move ctor");
9484
9485  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9486  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9487
9488  SynthesizedFunctionScope Scope(*this, MoveConstructor);
9489  DiagnosticErrorTrap Trap(Diags);
9490
9491  if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
9492      Trap.hasErrorOccurred()) {
9493    Diag(CurrentLocation, diag::note_member_synthesized_at)
9494      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9495    MoveConstructor->setInvalidDecl();
9496  }  else {
9497    Sema::CompoundScopeRAII CompoundScope(*this);
9498    MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9499                                               MoveConstructor->getLocation(),
9500                                               MultiStmtArg(),
9501                                               /*isStmtExpr=*/false)
9502                                                              .takeAs<Stmt>());
9503    MoveConstructor->setImplicitlyDefined(true);
9504  }
9505
9506  MoveConstructor->setUsed();
9507
9508  if (ASTMutationListener *L = getASTMutationListener()) {
9509    L->CompletedImplicitDefinition(MoveConstructor);
9510  }
9511}
9512
9513bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9514  return FD->isDeleted() &&
9515         (FD->isDefaulted() || FD->isImplicit()) &&
9516         isa<CXXMethodDecl>(FD);
9517}
9518
9519/// \brief Mark the call operator of the given lambda closure type as "used".
9520static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9521  CXXMethodDecl *CallOperator
9522    = cast<CXXMethodDecl>(
9523        Lambda->lookup(
9524          S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
9525  CallOperator->setReferenced();
9526  CallOperator->setUsed();
9527}
9528
9529void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9530       SourceLocation CurrentLocation,
9531       CXXConversionDecl *Conv)
9532{
9533  CXXRecordDecl *Lambda = Conv->getParent();
9534
9535  // Make sure that the lambda call operator is marked used.
9536  markLambdaCallOperatorUsed(*this, Lambda);
9537
9538  Conv->setUsed();
9539
9540  SynthesizedFunctionScope Scope(*this, Conv);
9541  DiagnosticErrorTrap Trap(Diags);
9542
9543  // Return the address of the __invoke function.
9544  DeclarationName InvokeName = &Context.Idents.get("__invoke");
9545  CXXMethodDecl *Invoke
9546    = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
9547  Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9548                                       VK_LValue, Conv->getLocation()).take();
9549  assert(FunctionRef && "Can't refer to __invoke function?");
9550  Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
9551  Conv->setBody(new (Context) CompoundStmt(Context, Return,
9552                                           Conv->getLocation(),
9553                                           Conv->getLocation()));
9554
9555  // Fill in the __invoke function with a dummy implementation. IR generation
9556  // will fill in the actual details.
9557  Invoke->setUsed();
9558  Invoke->setReferenced();
9559  Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
9560
9561  if (ASTMutationListener *L = getASTMutationListener()) {
9562    L->CompletedImplicitDefinition(Conv);
9563    L->CompletedImplicitDefinition(Invoke);
9564  }
9565}
9566
9567void Sema::DefineImplicitLambdaToBlockPointerConversion(
9568       SourceLocation CurrentLocation,
9569       CXXConversionDecl *Conv)
9570{
9571  Conv->setUsed();
9572
9573  SynthesizedFunctionScope Scope(*this, Conv);
9574  DiagnosticErrorTrap Trap(Diags);
9575
9576  // Copy-initialize the lambda object as needed to capture it.
9577  Expr *This = ActOnCXXThis(CurrentLocation).take();
9578  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
9579
9580  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9581                                                        Conv->getLocation(),
9582                                                        Conv, DerefThis);
9583
9584  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9585  // behavior.  Note that only the general conversion function does this
9586  // (since it's unusable otherwise); in the case where we inline the
9587  // block literal, it has block literal lifetime semantics.
9588  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
9589    BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9590                                          CK_CopyAndAutoreleaseBlockObject,
9591                                          BuildBlock.get(), 0, VK_RValue);
9592
9593  if (BuildBlock.isInvalid()) {
9594    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9595    Conv->setInvalidDecl();
9596    return;
9597  }
9598
9599  // Create the return statement that returns the block from the conversion
9600  // function.
9601  StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
9602  if (Return.isInvalid()) {
9603    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9604    Conv->setInvalidDecl();
9605    return;
9606  }
9607
9608  // Set the body of the conversion function.
9609  Stmt *ReturnS = Return.take();
9610  Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
9611                                           Conv->getLocation(),
9612                                           Conv->getLocation()));
9613
9614  // We're done; notify the mutation listener, if any.
9615  if (ASTMutationListener *L = getASTMutationListener()) {
9616    L->CompletedImplicitDefinition(Conv);
9617  }
9618}
9619
9620/// \brief Determine whether the given list arguments contains exactly one
9621/// "real" (non-default) argument.
9622static bool hasOneRealArgument(MultiExprArg Args) {
9623  switch (Args.size()) {
9624  case 0:
9625    return false;
9626
9627  default:
9628    if (!Args[1]->isDefaultArgument())
9629      return false;
9630
9631    // fall through
9632  case 1:
9633    return !Args[0]->isDefaultArgument();
9634  }
9635
9636  return false;
9637}
9638
9639ExprResult
9640Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9641                            CXXConstructorDecl *Constructor,
9642                            MultiExprArg ExprArgs,
9643                            bool HadMultipleCandidates,
9644                            bool IsListInitialization,
9645                            bool RequiresZeroInit,
9646                            unsigned ConstructKind,
9647                            SourceRange ParenRange) {
9648  bool Elidable = false;
9649
9650  // C++0x [class.copy]p34:
9651  //   When certain criteria are met, an implementation is allowed to
9652  //   omit the copy/move construction of a class object, even if the
9653  //   copy/move constructor and/or destructor for the object have
9654  //   side effects. [...]
9655  //     - when a temporary class object that has not been bound to a
9656  //       reference (12.2) would be copied/moved to a class object
9657  //       with the same cv-unqualified type, the copy/move operation
9658  //       can be omitted by constructing the temporary object
9659  //       directly into the target of the omitted copy/move
9660  if (ConstructKind == CXXConstructExpr::CK_Complete &&
9661      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
9662    Expr *SubExpr = ExprArgs[0];
9663    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
9664  }
9665
9666  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
9667                               Elidable, ExprArgs, HadMultipleCandidates,
9668                               IsListInitialization, RequiresZeroInit,
9669                               ConstructKind, ParenRange);
9670}
9671
9672/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9673/// including handling of its default argument expressions.
9674ExprResult
9675Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9676                            CXXConstructorDecl *Constructor, bool Elidable,
9677                            MultiExprArg ExprArgs,
9678                            bool HadMultipleCandidates,
9679                            bool IsListInitialization,
9680                            bool RequiresZeroInit,
9681                            unsigned ConstructKind,
9682                            SourceRange ParenRange) {
9683  MarkFunctionReferenced(ConstructLoc, Constructor);
9684  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
9685                                        Constructor, Elidable, ExprArgs,
9686                                        HadMultipleCandidates,
9687                                        IsListInitialization, RequiresZeroInit,
9688              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9689                                        ParenRange));
9690}
9691
9692void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
9693  if (VD->isInvalidDecl()) return;
9694
9695  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
9696  if (ClassDecl->isInvalidDecl()) return;
9697  if (ClassDecl->hasIrrelevantDestructor()) return;
9698  if (ClassDecl->isDependentContext()) return;
9699
9700  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9701  MarkFunctionReferenced(VD->getLocation(), Destructor);
9702  CheckDestructorAccess(VD->getLocation(), Destructor,
9703                        PDiag(diag::err_access_dtor_var)
9704                        << VD->getDeclName()
9705                        << VD->getType());
9706  DiagnoseUseOfDecl(Destructor, VD->getLocation());
9707
9708  if (!VD->hasGlobalStorage()) return;
9709
9710  // Emit warning for non-trivial dtor in global scope (a real global,
9711  // class-static, function-static).
9712  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9713
9714  // TODO: this should be re-enabled for static locals by !CXAAtExit
9715  if (!VD->isStaticLocal())
9716    Diag(VD->getLocation(), diag::warn_global_destructor);
9717}
9718
9719/// \brief Given a constructor and the set of arguments provided for the
9720/// constructor, convert the arguments and add any required default arguments
9721/// to form a proper call to this constructor.
9722///
9723/// \returns true if an error occurred, false otherwise.
9724bool
9725Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9726                              MultiExprArg ArgsPtr,
9727                              SourceLocation Loc,
9728                              SmallVectorImpl<Expr*> &ConvertedArgs,
9729                              bool AllowExplicit,
9730                              bool IsListInitialization) {
9731  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9732  unsigned NumArgs = ArgsPtr.size();
9733  Expr **Args = ArgsPtr.data();
9734
9735  const FunctionProtoType *Proto
9736    = Constructor->getType()->getAs<FunctionProtoType>();
9737  assert(Proto && "Constructor without a prototype?");
9738  unsigned NumArgsInProto = Proto->getNumArgs();
9739
9740  // If too few arguments are available, we'll fill in the rest with defaults.
9741  if (NumArgs < NumArgsInProto)
9742    ConvertedArgs.reserve(NumArgsInProto);
9743  else
9744    ConvertedArgs.reserve(NumArgs);
9745
9746  VariadicCallType CallType =
9747    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
9748  SmallVector<Expr *, 8> AllArgs;
9749  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9750                                        Proto, 0, Args, NumArgs, AllArgs,
9751                                        CallType, AllowExplicit,
9752                                        IsListInitialization);
9753  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
9754
9755  DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9756
9757  CheckConstructorCall(Constructor,
9758                       llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9759                                                        AllArgs.size()),
9760                       Proto, Loc);
9761
9762  return Invalid;
9763}
9764
9765static inline bool
9766CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9767                                       const FunctionDecl *FnDecl) {
9768  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
9769  if (isa<NamespaceDecl>(DC)) {
9770    return SemaRef.Diag(FnDecl->getLocation(),
9771                        diag::err_operator_new_delete_declared_in_namespace)
9772      << FnDecl->getDeclName();
9773  }
9774
9775  if (isa<TranslationUnitDecl>(DC) &&
9776      FnDecl->getStorageClass() == SC_Static) {
9777    return SemaRef.Diag(FnDecl->getLocation(),
9778                        diag::err_operator_new_delete_declared_static)
9779      << FnDecl->getDeclName();
9780  }
9781
9782  return false;
9783}
9784
9785static inline bool
9786CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9787                            CanQualType ExpectedResultType,
9788                            CanQualType ExpectedFirstParamType,
9789                            unsigned DependentParamTypeDiag,
9790                            unsigned InvalidParamTypeDiag) {
9791  QualType ResultType =
9792    FnDecl->getType()->getAs<FunctionType>()->getResultType();
9793
9794  // Check that the result type is not dependent.
9795  if (ResultType->isDependentType())
9796    return SemaRef.Diag(FnDecl->getLocation(),
9797                        diag::err_operator_new_delete_dependent_result_type)
9798    << FnDecl->getDeclName() << ExpectedResultType;
9799
9800  // Check that the result type is what we expect.
9801  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9802    return SemaRef.Diag(FnDecl->getLocation(),
9803                        diag::err_operator_new_delete_invalid_result_type)
9804    << FnDecl->getDeclName() << ExpectedResultType;
9805
9806  // A function template must have at least 2 parameters.
9807  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9808    return SemaRef.Diag(FnDecl->getLocation(),
9809                      diag::err_operator_new_delete_template_too_few_parameters)
9810        << FnDecl->getDeclName();
9811
9812  // The function decl must have at least 1 parameter.
9813  if (FnDecl->getNumParams() == 0)
9814    return SemaRef.Diag(FnDecl->getLocation(),
9815                        diag::err_operator_new_delete_too_few_parameters)
9816      << FnDecl->getDeclName();
9817
9818  // Check the first parameter type is not dependent.
9819  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9820  if (FirstParamType->isDependentType())
9821    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9822      << FnDecl->getDeclName() << ExpectedFirstParamType;
9823
9824  // Check that the first parameter type is what we expect.
9825  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
9826      ExpectedFirstParamType)
9827    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9828    << FnDecl->getDeclName() << ExpectedFirstParamType;
9829
9830  return false;
9831}
9832
9833static bool
9834CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9835  // C++ [basic.stc.dynamic.allocation]p1:
9836  //   A program is ill-formed if an allocation function is declared in a
9837  //   namespace scope other than global scope or declared static in global
9838  //   scope.
9839  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9840    return true;
9841
9842  CanQualType SizeTy =
9843    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9844
9845  // C++ [basic.stc.dynamic.allocation]p1:
9846  //  The return type shall be void*. The first parameter shall have type
9847  //  std::size_t.
9848  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9849                                  SizeTy,
9850                                  diag::err_operator_new_dependent_param_type,
9851                                  diag::err_operator_new_param_type))
9852    return true;
9853
9854  // C++ [basic.stc.dynamic.allocation]p1:
9855  //  The first parameter shall not have an associated default argument.
9856  if (FnDecl->getParamDecl(0)->hasDefaultArg())
9857    return SemaRef.Diag(FnDecl->getLocation(),
9858                        diag::err_operator_new_default_arg)
9859      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9860
9861  return false;
9862}
9863
9864static bool
9865CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
9866  // C++ [basic.stc.dynamic.deallocation]p1:
9867  //   A program is ill-formed if deallocation functions are declared in a
9868  //   namespace scope other than global scope or declared static in global
9869  //   scope.
9870  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9871    return true;
9872
9873  // C++ [basic.stc.dynamic.deallocation]p2:
9874  //   Each deallocation function shall return void and its first parameter
9875  //   shall be void*.
9876  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9877                                  SemaRef.Context.VoidPtrTy,
9878                                 diag::err_operator_delete_dependent_param_type,
9879                                 diag::err_operator_delete_param_type))
9880    return true;
9881
9882  return false;
9883}
9884
9885/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9886/// of this overloaded operator is well-formed. If so, returns false;
9887/// otherwise, emits appropriate diagnostics and returns true.
9888bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
9889  assert(FnDecl && FnDecl->isOverloadedOperator() &&
9890         "Expected an overloaded operator declaration");
9891
9892  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9893
9894  // C++ [over.oper]p5:
9895  //   The allocation and deallocation functions, operator new,
9896  //   operator new[], operator delete and operator delete[], are
9897  //   described completely in 3.7.3. The attributes and restrictions
9898  //   found in the rest of this subclause do not apply to them unless
9899  //   explicitly stated in 3.7.3.
9900  if (Op == OO_Delete || Op == OO_Array_Delete)
9901    return CheckOperatorDeleteDeclaration(*this, FnDecl);
9902
9903  if (Op == OO_New || Op == OO_Array_New)
9904    return CheckOperatorNewDeclaration(*this, FnDecl);
9905
9906  // C++ [over.oper]p6:
9907  //   An operator function shall either be a non-static member
9908  //   function or be a non-member function and have at least one
9909  //   parameter whose type is a class, a reference to a class, an
9910  //   enumeration, or a reference to an enumeration.
9911  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9912    if (MethodDecl->isStatic())
9913      return Diag(FnDecl->getLocation(),
9914                  diag::err_operator_overload_static) << FnDecl->getDeclName();
9915  } else {
9916    bool ClassOrEnumParam = false;
9917    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9918                                   ParamEnd = FnDecl->param_end();
9919         Param != ParamEnd; ++Param) {
9920      QualType ParamType = (*Param)->getType().getNonReferenceType();
9921      if (ParamType->isDependentType() || ParamType->isRecordType() ||
9922          ParamType->isEnumeralType()) {
9923        ClassOrEnumParam = true;
9924        break;
9925      }
9926    }
9927
9928    if (!ClassOrEnumParam)
9929      return Diag(FnDecl->getLocation(),
9930                  diag::err_operator_overload_needs_class_or_enum)
9931        << FnDecl->getDeclName();
9932  }
9933
9934  // C++ [over.oper]p8:
9935  //   An operator function cannot have default arguments (8.3.6),
9936  //   except where explicitly stated below.
9937  //
9938  // Only the function-call operator allows default arguments
9939  // (C++ [over.call]p1).
9940  if (Op != OO_Call) {
9941    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9942         Param != FnDecl->param_end(); ++Param) {
9943      if ((*Param)->hasDefaultArg())
9944        return Diag((*Param)->getLocation(),
9945                    diag::err_operator_overload_default_arg)
9946          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
9947    }
9948  }
9949
9950  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9951    { false, false, false }
9952#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9953    , { Unary, Binary, MemberOnly }
9954#include "clang/Basic/OperatorKinds.def"
9955  };
9956
9957  bool CanBeUnaryOperator = OperatorUses[Op][0];
9958  bool CanBeBinaryOperator = OperatorUses[Op][1];
9959  bool MustBeMemberOperator = OperatorUses[Op][2];
9960
9961  // C++ [over.oper]p8:
9962  //   [...] Operator functions cannot have more or fewer parameters
9963  //   than the number required for the corresponding operator, as
9964  //   described in the rest of this subclause.
9965  unsigned NumParams = FnDecl->getNumParams()
9966                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
9967  if (Op != OO_Call &&
9968      ((NumParams == 1 && !CanBeUnaryOperator) ||
9969       (NumParams == 2 && !CanBeBinaryOperator) ||
9970       (NumParams < 1) || (NumParams > 2))) {
9971    // We have the wrong number of parameters.
9972    unsigned ErrorKind;
9973    if (CanBeUnaryOperator && CanBeBinaryOperator) {
9974      ErrorKind = 2;  // 2 -> unary or binary.
9975    } else if (CanBeUnaryOperator) {
9976      ErrorKind = 0;  // 0 -> unary
9977    } else {
9978      assert(CanBeBinaryOperator &&
9979             "All non-call overloaded operators are unary or binary!");
9980      ErrorKind = 1;  // 1 -> binary
9981    }
9982
9983    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
9984      << FnDecl->getDeclName() << NumParams << ErrorKind;
9985  }
9986
9987  // Overloaded operators other than operator() cannot be variadic.
9988  if (Op != OO_Call &&
9989      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
9990    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
9991      << FnDecl->getDeclName();
9992  }
9993
9994  // Some operators must be non-static member functions.
9995  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9996    return Diag(FnDecl->getLocation(),
9997                diag::err_operator_overload_must_be_member)
9998      << FnDecl->getDeclName();
9999  }
10000
10001  // C++ [over.inc]p1:
10002  //   The user-defined function called operator++ implements the
10003  //   prefix and postfix ++ operator. If this function is a member
10004  //   function with no parameters, or a non-member function with one
10005  //   parameter of class or enumeration type, it defines the prefix
10006  //   increment operator ++ for objects of that type. If the function
10007  //   is a member function with one parameter (which shall be of type
10008  //   int) or a non-member function with two parameters (the second
10009  //   of which shall be of type int), it defines the postfix
10010  //   increment operator ++ for objects of that type.
10011  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10012    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10013    bool ParamIsInt = false;
10014    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
10015      ParamIsInt = BT->getKind() == BuiltinType::Int;
10016
10017    if (!ParamIsInt)
10018      return Diag(LastParam->getLocation(),
10019                  diag::err_operator_overload_post_incdec_must_be_int)
10020        << LastParam->getType() << (Op == OO_MinusMinus);
10021  }
10022
10023  return false;
10024}
10025
10026/// CheckLiteralOperatorDeclaration - Check whether the declaration
10027/// of this literal operator function is well-formed. If so, returns
10028/// false; otherwise, emits appropriate diagnostics and returns true.
10029bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
10030  if (isa<CXXMethodDecl>(FnDecl)) {
10031    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10032      << FnDecl->getDeclName();
10033    return true;
10034  }
10035
10036  if (FnDecl->isExternC()) {
10037    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10038    return true;
10039  }
10040
10041  bool Valid = false;
10042
10043  // This might be the definition of a literal operator template.
10044  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10045  // This might be a specialization of a literal operator template.
10046  if (!TpDecl)
10047    TpDecl = FnDecl->getPrimaryTemplate();
10048
10049  // template <char...> type operator "" name() is the only valid template
10050  // signature, and the only valid signature with no parameters.
10051  if (TpDecl) {
10052    if (FnDecl->param_size() == 0) {
10053      // Must have only one template parameter
10054      TemplateParameterList *Params = TpDecl->getTemplateParameters();
10055      if (Params->size() == 1) {
10056        NonTypeTemplateParmDecl *PmDecl =
10057          dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
10058
10059        // The template parameter must be a char parameter pack.
10060        if (PmDecl && PmDecl->isTemplateParameterPack() &&
10061            Context.hasSameType(PmDecl->getType(), Context.CharTy))
10062          Valid = true;
10063      }
10064    }
10065  } else if (FnDecl->param_size()) {
10066    // Check the first parameter
10067    FunctionDecl::param_iterator Param = FnDecl->param_begin();
10068
10069    QualType T = (*Param)->getType().getUnqualifiedType();
10070
10071    // unsigned long long int, long double, and any character type are allowed
10072    // as the only parameters.
10073    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10074        Context.hasSameType(T, Context.LongDoubleTy) ||
10075        Context.hasSameType(T, Context.CharTy) ||
10076        Context.hasSameType(T, Context.WCharTy) ||
10077        Context.hasSameType(T, Context.Char16Ty) ||
10078        Context.hasSameType(T, Context.Char32Ty)) {
10079      if (++Param == FnDecl->param_end())
10080        Valid = true;
10081      goto FinishedParams;
10082    }
10083
10084    // Otherwise it must be a pointer to const; let's strip those qualifiers.
10085    const PointerType *PT = T->getAs<PointerType>();
10086    if (!PT)
10087      goto FinishedParams;
10088    T = PT->getPointeeType();
10089    if (!T.isConstQualified() || T.isVolatileQualified())
10090      goto FinishedParams;
10091    T = T.getUnqualifiedType();
10092
10093    // Move on to the second parameter;
10094    ++Param;
10095
10096    // If there is no second parameter, the first must be a const char *
10097    if (Param == FnDecl->param_end()) {
10098      if (Context.hasSameType(T, Context.CharTy))
10099        Valid = true;
10100      goto FinishedParams;
10101    }
10102
10103    // const char *, const wchar_t*, const char16_t*, and const char32_t*
10104    // are allowed as the first parameter to a two-parameter function
10105    if (!(Context.hasSameType(T, Context.CharTy) ||
10106          Context.hasSameType(T, Context.WCharTy) ||
10107          Context.hasSameType(T, Context.Char16Ty) ||
10108          Context.hasSameType(T, Context.Char32Ty)))
10109      goto FinishedParams;
10110
10111    // The second and final parameter must be an std::size_t
10112    T = (*Param)->getType().getUnqualifiedType();
10113    if (Context.hasSameType(T, Context.getSizeType()) &&
10114        ++Param == FnDecl->param_end())
10115      Valid = true;
10116  }
10117
10118  // FIXME: This diagnostic is absolutely terrible.
10119FinishedParams:
10120  if (!Valid) {
10121    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10122      << FnDecl->getDeclName();
10123    return true;
10124  }
10125
10126  // A parameter-declaration-clause containing a default argument is not
10127  // equivalent to any of the permitted forms.
10128  for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10129                                    ParamEnd = FnDecl->param_end();
10130       Param != ParamEnd; ++Param) {
10131    if ((*Param)->hasDefaultArg()) {
10132      Diag((*Param)->getDefaultArgRange().getBegin(),
10133           diag::err_literal_operator_default_argument)
10134        << (*Param)->getDefaultArgRange();
10135      break;
10136    }
10137  }
10138
10139  StringRef LiteralName
10140    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10141  if (LiteralName[0] != '_') {
10142    // C++11 [usrlit.suffix]p1:
10143    //   Literal suffix identifiers that do not start with an underscore
10144    //   are reserved for future standardization.
10145    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
10146  }
10147
10148  return false;
10149}
10150
10151/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10152/// linkage specification, including the language and (if present)
10153/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10154/// the location of the language string literal, which is provided
10155/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10156/// the '{' brace. Otherwise, this linkage specification does not
10157/// have any braces.
10158Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10159                                           SourceLocation LangLoc,
10160                                           StringRef Lang,
10161                                           SourceLocation LBraceLoc) {
10162  LinkageSpecDecl::LanguageIDs Language;
10163  if (Lang == "\"C\"")
10164    Language = LinkageSpecDecl::lang_c;
10165  else if (Lang == "\"C++\"")
10166    Language = LinkageSpecDecl::lang_cxx;
10167  else {
10168    Diag(LangLoc, diag::err_bad_language);
10169    return 0;
10170  }
10171
10172  // FIXME: Add all the various semantics of linkage specifications
10173
10174  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
10175                                               ExternLoc, LangLoc, Language);
10176  CurContext->addDecl(D);
10177  PushDeclContext(S, D);
10178  return D;
10179}
10180
10181/// ActOnFinishLinkageSpecification - Complete the definition of
10182/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10183/// valid, it's the position of the closing '}' brace in a linkage
10184/// specification that uses braces.
10185Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
10186                                            Decl *LinkageSpec,
10187                                            SourceLocation RBraceLoc) {
10188  if (LinkageSpec) {
10189    if (RBraceLoc.isValid()) {
10190      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10191      LSDecl->setRBraceLoc(RBraceLoc);
10192    }
10193    PopDeclContext();
10194  }
10195  return LinkageSpec;
10196}
10197
10198Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10199                                  AttributeList *AttrList,
10200                                  SourceLocation SemiLoc) {
10201  Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10202  // Attribute declarations appertain to empty declaration so we handle
10203  // them here.
10204  if (AttrList)
10205    ProcessDeclAttributeList(S, ED, AttrList);
10206
10207  CurContext->addDecl(ED);
10208  return ED;
10209}
10210
10211/// \brief Perform semantic analysis for the variable declaration that
10212/// occurs within a C++ catch clause, returning the newly-created
10213/// variable.
10214VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
10215                                         TypeSourceInfo *TInfo,
10216                                         SourceLocation StartLoc,
10217                                         SourceLocation Loc,
10218                                         IdentifierInfo *Name) {
10219  bool Invalid = false;
10220  QualType ExDeclType = TInfo->getType();
10221
10222  // Arrays and functions decay.
10223  if (ExDeclType->isArrayType())
10224    ExDeclType = Context.getArrayDecayedType(ExDeclType);
10225  else if (ExDeclType->isFunctionType())
10226    ExDeclType = Context.getPointerType(ExDeclType);
10227
10228  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10229  // The exception-declaration shall not denote a pointer or reference to an
10230  // incomplete type, other than [cv] void*.
10231  // N2844 forbids rvalue references.
10232  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
10233    Diag(Loc, diag::err_catch_rvalue_ref);
10234    Invalid = true;
10235  }
10236
10237  QualType BaseType = ExDeclType;
10238  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
10239  unsigned DK = diag::err_catch_incomplete;
10240  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
10241    BaseType = Ptr->getPointeeType();
10242    Mode = 1;
10243    DK = diag::err_catch_incomplete_ptr;
10244  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
10245    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
10246    BaseType = Ref->getPointeeType();
10247    Mode = 2;
10248    DK = diag::err_catch_incomplete_ref;
10249  }
10250  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
10251      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
10252    Invalid = true;
10253
10254  if (!Invalid && !ExDeclType->isDependentType() &&
10255      RequireNonAbstractType(Loc, ExDeclType,
10256                             diag::err_abstract_type_in_decl,
10257                             AbstractVariableType))
10258    Invalid = true;
10259
10260  // Only the non-fragile NeXT runtime currently supports C++ catches
10261  // of ObjC types, and no runtime supports catching ObjC types by value.
10262  if (!Invalid && getLangOpts().ObjC1) {
10263    QualType T = ExDeclType;
10264    if (const ReferenceType *RT = T->getAs<ReferenceType>())
10265      T = RT->getPointeeType();
10266
10267    if (T->isObjCObjectType()) {
10268      Diag(Loc, diag::err_objc_object_catch);
10269      Invalid = true;
10270    } else if (T->isObjCObjectPointerType()) {
10271      // FIXME: should this be a test for macosx-fragile specifically?
10272      if (getLangOpts().ObjCRuntime.isFragile())
10273        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
10274    }
10275  }
10276
10277  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10278                                    ExDeclType, TInfo, SC_None, SC_None);
10279  ExDecl->setExceptionVariable(true);
10280
10281  // In ARC, infer 'retaining' for variables of retainable type.
10282  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
10283    Invalid = true;
10284
10285  if (!Invalid && !ExDeclType->isDependentType()) {
10286    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
10287      // Insulate this from anything else we might currently be parsing.
10288      EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10289
10290      // C++ [except.handle]p16:
10291      //   The object declared in an exception-declaration or, if the
10292      //   exception-declaration does not specify a name, a temporary (12.2) is
10293      //   copy-initialized (8.5) from the exception object. [...]
10294      //   The object is destroyed when the handler exits, after the destruction
10295      //   of any automatic objects initialized within the handler.
10296      //
10297      // We just pretend to initialize the object with itself, then make sure
10298      // it can be destroyed later.
10299      QualType initType = ExDeclType;
10300
10301      InitializedEntity entity =
10302        InitializedEntity::InitializeVariable(ExDecl);
10303      InitializationKind initKind =
10304        InitializationKind::CreateCopy(Loc, SourceLocation());
10305
10306      Expr *opaqueValue =
10307        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10308      InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10309      ExprResult result = sequence.Perform(*this, entity, initKind,
10310                                           MultiExprArg(&opaqueValue, 1));
10311      if (result.isInvalid())
10312        Invalid = true;
10313      else {
10314        // If the constructor used was non-trivial, set this as the
10315        // "initializer".
10316        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10317        if (!construct->getConstructor()->isTrivial()) {
10318          Expr *init = MaybeCreateExprWithCleanups(construct);
10319          ExDecl->setInit(init);
10320        }
10321
10322        // And make sure it's destructable.
10323        FinalizeVarWithDestructor(ExDecl, recordType);
10324      }
10325    }
10326  }
10327
10328  if (Invalid)
10329    ExDecl->setInvalidDecl();
10330
10331  return ExDecl;
10332}
10333
10334/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10335/// handler.
10336Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
10337  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10338  bool Invalid = D.isInvalidType();
10339
10340  // Check for unexpanded parameter packs.
10341  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10342                                      UPPC_ExceptionType)) {
10343    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10344                                             D.getIdentifierLoc());
10345    Invalid = true;
10346  }
10347
10348  IdentifierInfo *II = D.getIdentifier();
10349  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
10350                                             LookupOrdinaryName,
10351                                             ForRedeclaration)) {
10352    // The scope should be freshly made just for us. There is just no way
10353    // it contains any previous declaration.
10354    assert(!S->isDeclScope(PrevDecl));
10355    if (PrevDecl->isTemplateParameter()) {
10356      // Maybe we will complain about the shadowed template parameter.
10357      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10358      PrevDecl = 0;
10359    }
10360  }
10361
10362  if (D.getCXXScopeSpec().isSet() && !Invalid) {
10363    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10364      << D.getCXXScopeSpec().getRange();
10365    Invalid = true;
10366  }
10367
10368  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
10369                                              D.getLocStart(),
10370                                              D.getIdentifierLoc(),
10371                                              D.getIdentifier());
10372  if (Invalid)
10373    ExDecl->setInvalidDecl();
10374
10375  // Add the exception declaration into this scope.
10376  if (II)
10377    PushOnScopeChains(ExDecl, S);
10378  else
10379    CurContext->addDecl(ExDecl);
10380
10381  ProcessDeclAttributes(S, ExDecl, D);
10382  return ExDecl;
10383}
10384
10385Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10386                                         Expr *AssertExpr,
10387                                         Expr *AssertMessageExpr,
10388                                         SourceLocation RParenLoc) {
10389  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
10390
10391  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10392    return 0;
10393
10394  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10395                                      AssertMessage, RParenLoc, false);
10396}
10397
10398Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10399                                         Expr *AssertExpr,
10400                                         StringLiteral *AssertMessage,
10401                                         SourceLocation RParenLoc,
10402                                         bool Failed) {
10403  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10404      !Failed) {
10405    // In a static_assert-declaration, the constant-expression shall be a
10406    // constant expression that can be contextually converted to bool.
10407    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10408    if (Converted.isInvalid())
10409      Failed = true;
10410
10411    llvm::APSInt Cond;
10412    if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
10413          diag::err_static_assert_expression_is_not_constant,
10414          /*AllowFold=*/false).isInvalid())
10415      Failed = true;
10416
10417    if (!Failed && !Cond) {
10418      SmallString<256> MsgBuffer;
10419      llvm::raw_svector_ostream Msg(MsgBuffer);
10420      AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
10421      Diag(StaticAssertLoc, diag::err_static_assert_failed)
10422        << Msg.str() << AssertExpr->getSourceRange();
10423      Failed = true;
10424    }
10425  }
10426
10427  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
10428                                        AssertExpr, AssertMessage, RParenLoc,
10429                                        Failed);
10430
10431  CurContext->addDecl(Decl);
10432  return Decl;
10433}
10434
10435/// \brief Perform semantic analysis of the given friend type declaration.
10436///
10437/// \returns A friend declaration that.
10438FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
10439                                      SourceLocation FriendLoc,
10440                                      TypeSourceInfo *TSInfo) {
10441  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10442
10443  QualType T = TSInfo->getType();
10444  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
10445
10446  // C++03 [class.friend]p2:
10447  //   An elaborated-type-specifier shall be used in a friend declaration
10448  //   for a class.*
10449  //
10450  //   * The class-key of the elaborated-type-specifier is required.
10451  if (!ActiveTemplateInstantiations.empty()) {
10452    // Do not complain about the form of friend template types during
10453    // template instantiation; we will already have complained when the
10454    // template was declared.
10455  } else {
10456    if (!T->isElaboratedTypeSpecifier()) {
10457      // If we evaluated the type to a record type, suggest putting
10458      // a tag in front.
10459      if (const RecordType *RT = T->getAs<RecordType>()) {
10460        RecordDecl *RD = RT->getDecl();
10461
10462        std::string InsertionText = std::string(" ") + RD->getKindName();
10463
10464        Diag(TypeRange.getBegin(),
10465             getLangOpts().CPlusPlus11 ?
10466               diag::warn_cxx98_compat_unelaborated_friend_type :
10467               diag::ext_unelaborated_friend_type)
10468          << (unsigned) RD->getTagKind()
10469          << T
10470          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10471                                        InsertionText);
10472      } else {
10473        Diag(FriendLoc,
10474             getLangOpts().CPlusPlus11 ?
10475               diag::warn_cxx98_compat_nonclass_type_friend :
10476               diag::ext_nonclass_type_friend)
10477          << T
10478          << TypeRange;
10479      }
10480    } else if (T->getAs<EnumType>()) {
10481      Diag(FriendLoc,
10482           getLangOpts().CPlusPlus11 ?
10483             diag::warn_cxx98_compat_enum_friend :
10484             diag::ext_enum_friend)
10485        << T
10486        << TypeRange;
10487    }
10488
10489    // C++11 [class.friend]p3:
10490    //   A friend declaration that does not declare a function shall have one
10491    //   of the following forms:
10492    //     friend elaborated-type-specifier ;
10493    //     friend simple-type-specifier ;
10494    //     friend typename-specifier ;
10495    if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10496      Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10497  }
10498
10499  //   If the type specifier in a friend declaration designates a (possibly
10500  //   cv-qualified) class type, that class is declared as a friend; otherwise,
10501  //   the friend declaration is ignored.
10502  return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
10503}
10504
10505/// Handle a friend tag declaration where the scope specifier was
10506/// templated.
10507Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10508                                    unsigned TagSpec, SourceLocation TagLoc,
10509                                    CXXScopeSpec &SS,
10510                                    IdentifierInfo *Name,
10511                                    SourceLocation NameLoc,
10512                                    AttributeList *Attr,
10513                                    MultiTemplateParamsArg TempParamLists) {
10514  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10515
10516  bool isExplicitSpecialization = false;
10517  bool Invalid = false;
10518
10519  if (TemplateParameterList *TemplateParams
10520        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
10521                                                  TempParamLists.data(),
10522                                                  TempParamLists.size(),
10523                                                  /*friend*/ true,
10524                                                  isExplicitSpecialization,
10525                                                  Invalid)) {
10526    if (TemplateParams->size() > 0) {
10527      // This is a declaration of a class template.
10528      if (Invalid)
10529        return 0;
10530
10531      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10532                                SS, Name, NameLoc, Attr,
10533                                TemplateParams, AS_public,
10534                                /*ModulePrivateLoc=*/SourceLocation(),
10535                                TempParamLists.size() - 1,
10536                                TempParamLists.data()).take();
10537    } else {
10538      // The "template<>" header is extraneous.
10539      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10540        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10541      isExplicitSpecialization = true;
10542    }
10543  }
10544
10545  if (Invalid) return 0;
10546
10547  bool isAllExplicitSpecializations = true;
10548  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
10549    if (TempParamLists[I]->size()) {
10550      isAllExplicitSpecializations = false;
10551      break;
10552    }
10553  }
10554
10555  // FIXME: don't ignore attributes.
10556
10557  // If it's explicit specializations all the way down, just forget
10558  // about the template header and build an appropriate non-templated
10559  // friend.  TODO: for source fidelity, remember the headers.
10560  if (isAllExplicitSpecializations) {
10561    if (SS.isEmpty()) {
10562      bool Owned = false;
10563      bool IsDependent = false;
10564      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10565                      Attr, AS_public,
10566                      /*ModulePrivateLoc=*/SourceLocation(),
10567                      MultiTemplateParamsArg(), Owned, IsDependent,
10568                      /*ScopedEnumKWLoc=*/SourceLocation(),
10569                      /*ScopedEnumUsesClassTag=*/false,
10570                      /*UnderlyingType=*/TypeResult());
10571    }
10572
10573    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10574    ElaboratedTypeKeyword Keyword
10575      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10576    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
10577                                   *Name, NameLoc);
10578    if (T.isNull())
10579      return 0;
10580
10581    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10582    if (isa<DependentNameType>(T)) {
10583      DependentNameTypeLoc TL =
10584          TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
10585      TL.setElaboratedKeywordLoc(TagLoc);
10586      TL.setQualifierLoc(QualifierLoc);
10587      TL.setNameLoc(NameLoc);
10588    } else {
10589      ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
10590      TL.setElaboratedKeywordLoc(TagLoc);
10591      TL.setQualifierLoc(QualifierLoc);
10592      TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
10593    }
10594
10595    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10596                                            TSI, FriendLoc, TempParamLists);
10597    Friend->setAccess(AS_public);
10598    CurContext->addDecl(Friend);
10599    return Friend;
10600  }
10601
10602  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10603
10604
10605
10606  // Handle the case of a templated-scope friend class.  e.g.
10607  //   template <class T> class A<T>::B;
10608  // FIXME: we don't support these right now.
10609  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10610  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10611  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10612  DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
10613  TL.setElaboratedKeywordLoc(TagLoc);
10614  TL.setQualifierLoc(SS.getWithLocInContext(Context));
10615  TL.setNameLoc(NameLoc);
10616
10617  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10618                                          TSI, FriendLoc, TempParamLists);
10619  Friend->setAccess(AS_public);
10620  Friend->setUnsupportedFriend(true);
10621  CurContext->addDecl(Friend);
10622  return Friend;
10623}
10624
10625
10626/// Handle a friend type declaration.  This works in tandem with
10627/// ActOnTag.
10628///
10629/// Notes on friend class templates:
10630///
10631/// We generally treat friend class declarations as if they were
10632/// declaring a class.  So, for example, the elaborated type specifier
10633/// in a friend declaration is required to obey the restrictions of a
10634/// class-head (i.e. no typedefs in the scope chain), template
10635/// parameters are required to match up with simple template-ids, &c.
10636/// However, unlike when declaring a template specialization, it's
10637/// okay to refer to a template specialization without an empty
10638/// template parameter declaration, e.g.
10639///   friend class A<T>::B<unsigned>;
10640/// We permit this as a special case; if there are any template
10641/// parameters present at all, require proper matching, i.e.
10642///   template <> template \<class T> friend class A<int>::B;
10643Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
10644                                MultiTemplateParamsArg TempParams) {
10645  SourceLocation Loc = DS.getLocStart();
10646
10647  assert(DS.isFriendSpecified());
10648  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10649
10650  // Try to convert the decl specifier to a type.  This works for
10651  // friend templates because ActOnTag never produces a ClassTemplateDecl
10652  // for a TUK_Friend.
10653  Declarator TheDeclarator(DS, Declarator::MemberContext);
10654  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10655  QualType T = TSI->getType();
10656  if (TheDeclarator.isInvalidType())
10657    return 0;
10658
10659  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10660    return 0;
10661
10662  // This is definitely an error in C++98.  It's probably meant to
10663  // be forbidden in C++0x, too, but the specification is just
10664  // poorly written.
10665  //
10666  // The problem is with declarations like the following:
10667  //   template <T> friend A<T>::foo;
10668  // where deciding whether a class C is a friend or not now hinges
10669  // on whether there exists an instantiation of A that causes
10670  // 'foo' to equal C.  There are restrictions on class-heads
10671  // (which we declare (by fiat) elaborated friend declarations to
10672  // be) that makes this tractable.
10673  //
10674  // FIXME: handle "template <> friend class A<T>;", which
10675  // is possibly well-formed?  Who even knows?
10676  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
10677    Diag(Loc, diag::err_tagless_friend_type_template)
10678      << DS.getSourceRange();
10679    return 0;
10680  }
10681
10682  // C++98 [class.friend]p1: A friend of a class is a function
10683  //   or class that is not a member of the class . . .
10684  // This is fixed in DR77, which just barely didn't make the C++03
10685  // deadline.  It's also a very silly restriction that seriously
10686  // affects inner classes and which nobody else seems to implement;
10687  // thus we never diagnose it, not even in -pedantic.
10688  //
10689  // But note that we could warn about it: it's always useless to
10690  // friend one of your own members (it's not, however, worthless to
10691  // friend a member of an arbitrary specialization of your template).
10692
10693  Decl *D;
10694  if (unsigned NumTempParamLists = TempParams.size())
10695    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
10696                                   NumTempParamLists,
10697                                   TempParams.data(),
10698                                   TSI,
10699                                   DS.getFriendSpecLoc());
10700  else
10701    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
10702
10703  if (!D)
10704    return 0;
10705
10706  D->setAccess(AS_public);
10707  CurContext->addDecl(D);
10708
10709  return D;
10710}
10711
10712NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10713                                        MultiTemplateParamsArg TemplateParams) {
10714  const DeclSpec &DS = D.getDeclSpec();
10715
10716  assert(DS.isFriendSpecified());
10717  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10718
10719  SourceLocation Loc = D.getIdentifierLoc();
10720  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10721
10722  // C++ [class.friend]p1
10723  //   A friend of a class is a function or class....
10724  // Note that this sees through typedefs, which is intended.
10725  // It *doesn't* see through dependent types, which is correct
10726  // according to [temp.arg.type]p3:
10727  //   If a declaration acquires a function type through a
10728  //   type dependent on a template-parameter and this causes
10729  //   a declaration that does not use the syntactic form of a
10730  //   function declarator to have a function type, the program
10731  //   is ill-formed.
10732  if (!TInfo->getType()->isFunctionType()) {
10733    Diag(Loc, diag::err_unexpected_friend);
10734
10735    // It might be worthwhile to try to recover by creating an
10736    // appropriate declaration.
10737    return 0;
10738  }
10739
10740  // C++ [namespace.memdef]p3
10741  //  - If a friend declaration in a non-local class first declares a
10742  //    class or function, the friend class or function is a member
10743  //    of the innermost enclosing namespace.
10744  //  - The name of the friend is not found by simple name lookup
10745  //    until a matching declaration is provided in that namespace
10746  //    scope (either before or after the class declaration granting
10747  //    friendship).
10748  //  - If a friend function is called, its name may be found by the
10749  //    name lookup that considers functions from namespaces and
10750  //    classes associated with the types of the function arguments.
10751  //  - When looking for a prior declaration of a class or a function
10752  //    declared as a friend, scopes outside the innermost enclosing
10753  //    namespace scope are not considered.
10754
10755  CXXScopeSpec &SS = D.getCXXScopeSpec();
10756  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10757  DeclarationName Name = NameInfo.getName();
10758  assert(Name);
10759
10760  // Check for unexpanded parameter packs.
10761  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10762      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10763      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10764    return 0;
10765
10766  // The context we found the declaration in, or in which we should
10767  // create the declaration.
10768  DeclContext *DC;
10769  Scope *DCScope = S;
10770  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10771                        ForRedeclaration);
10772
10773  // FIXME: there are different rules in local classes
10774
10775  // There are four cases here.
10776  //   - There's no scope specifier, in which case we just go to the
10777  //     appropriate scope and look for a function or function template
10778  //     there as appropriate.
10779  // Recover from invalid scope qualifiers as if they just weren't there.
10780  if (SS.isInvalid() || !SS.isSet()) {
10781    // C++0x [namespace.memdef]p3:
10782    //   If the name in a friend declaration is neither qualified nor
10783    //   a template-id and the declaration is a function or an
10784    //   elaborated-type-specifier, the lookup to determine whether
10785    //   the entity has been previously declared shall not consider
10786    //   any scopes outside the innermost enclosing namespace.
10787    // C++0x [class.friend]p11:
10788    //   If a friend declaration appears in a local class and the name
10789    //   specified is an unqualified name, a prior declaration is
10790    //   looked up without considering scopes that are outside the
10791    //   innermost enclosing non-class scope. For a friend function
10792    //   declaration, if there is no prior declaration, the program is
10793    //   ill-formed.
10794    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
10795    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
10796
10797    // Find the appropriate context according to the above.
10798    DC = CurContext;
10799    while (true) {
10800      // Skip class contexts.  If someone can cite chapter and verse
10801      // for this behavior, that would be nice --- it's what GCC and
10802      // EDG do, and it seems like a reasonable intent, but the spec
10803      // really only says that checks for unqualified existing
10804      // declarations should stop at the nearest enclosing namespace,
10805      // not that they should only consider the nearest enclosing
10806      // namespace.
10807      while (DC->isRecord() || DC->isTransparentContext())
10808        DC = DC->getParent();
10809
10810      LookupQualifiedName(Previous, DC);
10811
10812      // TODO: decide what we think about using declarations.
10813      if (isLocal || !Previous.empty())
10814        break;
10815
10816      if (isTemplateId) {
10817        if (isa<TranslationUnitDecl>(DC)) break;
10818      } else {
10819        if (DC->isFileContext()) break;
10820      }
10821      DC = DC->getParent();
10822    }
10823
10824    DCScope = getScopeForDeclContext(S, DC);
10825
10826    // C++ [class.friend]p6:
10827    //   A function can be defined in a friend declaration of a class if and
10828    //   only if the class is a non-local class (9.8), the function name is
10829    //   unqualified, and the function has namespace scope.
10830    if (isLocal && D.isFunctionDefinition()) {
10831      Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10832    }
10833
10834  //   - There's a non-dependent scope specifier, in which case we
10835  //     compute it and do a previous lookup there for a function
10836  //     or function template.
10837  } else if (!SS.getScopeRep()->isDependent()) {
10838    DC = computeDeclContext(SS);
10839    if (!DC) return 0;
10840
10841    if (RequireCompleteDeclContext(SS, DC)) return 0;
10842
10843    LookupQualifiedName(Previous, DC);
10844
10845    // Ignore things found implicitly in the wrong scope.
10846    // TODO: better diagnostics for this case.  Suggesting the right
10847    // qualified scope would be nice...
10848    LookupResult::Filter F = Previous.makeFilter();
10849    while (F.hasNext()) {
10850      NamedDecl *D = F.next();
10851      if (!DC->InEnclosingNamespaceSetOf(
10852              D->getDeclContext()->getRedeclContext()))
10853        F.erase();
10854    }
10855    F.done();
10856
10857    if (Previous.empty()) {
10858      D.setInvalidType();
10859      Diag(Loc, diag::err_qualified_friend_not_found)
10860          << Name << TInfo->getType();
10861      return 0;
10862    }
10863
10864    // C++ [class.friend]p1: A friend of a class is a function or
10865    //   class that is not a member of the class . . .
10866    if (DC->Equals(CurContext))
10867      Diag(DS.getFriendSpecLoc(),
10868           getLangOpts().CPlusPlus11 ?
10869             diag::warn_cxx98_compat_friend_is_member :
10870             diag::err_friend_is_member);
10871
10872    if (D.isFunctionDefinition()) {
10873      // C++ [class.friend]p6:
10874      //   A function can be defined in a friend declaration of a class if and
10875      //   only if the class is a non-local class (9.8), the function name is
10876      //   unqualified, and the function has namespace scope.
10877      SemaDiagnosticBuilder DB
10878        = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10879
10880      DB << SS.getScopeRep();
10881      if (DC->isFileContext())
10882        DB << FixItHint::CreateRemoval(SS.getRange());
10883      SS.clear();
10884    }
10885
10886  //   - There's a scope specifier that does not match any template
10887  //     parameter lists, in which case we use some arbitrary context,
10888  //     create a method or method template, and wait for instantiation.
10889  //   - There's a scope specifier that does match some template
10890  //     parameter lists, which we don't handle right now.
10891  } else {
10892    if (D.isFunctionDefinition()) {
10893      // C++ [class.friend]p6:
10894      //   A function can be defined in a friend declaration of a class if and
10895      //   only if the class is a non-local class (9.8), the function name is
10896      //   unqualified, and the function has namespace scope.
10897      Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10898        << SS.getScopeRep();
10899    }
10900
10901    DC = CurContext;
10902    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
10903  }
10904
10905  if (!DC->isRecord()) {
10906    // This implies that it has to be an operator or function.
10907    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10908        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10909        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
10910      Diag(Loc, diag::err_introducing_special_friend) <<
10911        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10912         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
10913      return 0;
10914    }
10915  }
10916
10917  // FIXME: This is an egregious hack to cope with cases where the scope stack
10918  // does not contain the declaration context, i.e., in an out-of-line
10919  // definition of a class.
10920  Scope FakeDCScope(S, Scope::DeclScope, Diags);
10921  if (!DCScope) {
10922    FakeDCScope.setEntity(DC);
10923    DCScope = &FakeDCScope;
10924  }
10925
10926  bool AddToScope = true;
10927  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10928                                          TemplateParams, AddToScope);
10929  if (!ND) return 0;
10930
10931  assert(ND->getDeclContext() == DC);
10932  assert(ND->getLexicalDeclContext() == CurContext);
10933
10934  // Add the function declaration to the appropriate lookup tables,
10935  // adjusting the redeclarations list as necessary.  We don't
10936  // want to do this yet if the friending class is dependent.
10937  //
10938  // Also update the scope-based lookup if the target context's
10939  // lookup context is in lexical scope.
10940  if (!CurContext->isDependentContext()) {
10941    DC = DC->getRedeclContext();
10942    DC->makeDeclVisibleInContext(ND);
10943    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10944      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
10945  }
10946
10947  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
10948                                       D.getIdentifierLoc(), ND,
10949                                       DS.getFriendSpecLoc());
10950  FrD->setAccess(AS_public);
10951  CurContext->addDecl(FrD);
10952
10953  if (ND->isInvalidDecl()) {
10954    FrD->setInvalidDecl();
10955  } else {
10956    if (DC->isRecord()) CheckFriendAccess(ND);
10957
10958    FunctionDecl *FD;
10959    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10960      FD = FTD->getTemplatedDecl();
10961    else
10962      FD = cast<FunctionDecl>(ND);
10963
10964    // Mark templated-scope function declarations as unsupported.
10965    if (FD->getNumTemplateParameterLists())
10966      FrD->setUnsupportedFriend(true);
10967  }
10968
10969  return ND;
10970}
10971
10972void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10973  AdjustDeclIfTemplate(Dcl);
10974
10975  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
10976  if (!Fn) {
10977    Diag(DelLoc, diag::err_deleted_non_function);
10978    return;
10979  }
10980  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
10981    // Don't consider the implicit declaration we generate for explicit
10982    // specializations. FIXME: Do not generate these implicit declarations.
10983    if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10984        || Prev->getPreviousDecl()) && !Prev->isDefined()) {
10985      Diag(DelLoc, diag::err_deleted_decl_not_first);
10986      Diag(Prev->getLocation(), diag::note_previous_declaration);
10987    }
10988    // If the declaration wasn't the first, we delete the function anyway for
10989    // recovery.
10990  }
10991  Fn->setDeletedAsWritten();
10992}
10993
10994void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10995  CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
10996
10997  if (MD) {
10998    if (MD->getParent()->isDependentType()) {
10999      MD->setDefaulted();
11000      MD->setExplicitlyDefaulted();
11001      return;
11002    }
11003
11004    CXXSpecialMember Member = getSpecialMember(MD);
11005    if (Member == CXXInvalid) {
11006      Diag(DefaultLoc, diag::err_default_special_members);
11007      return;
11008    }
11009
11010    MD->setDefaulted();
11011    MD->setExplicitlyDefaulted();
11012
11013    // If this definition appears within the record, do the checking when
11014    // the record is complete.
11015    const FunctionDecl *Primary = MD;
11016    if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
11017      // Find the uninstantiated declaration that actually had the '= default'
11018      // on it.
11019      Pattern->isDefined(Primary);
11020
11021    if (Primary == Primary->getCanonicalDecl())
11022      return;
11023
11024    CheckExplicitlyDefaultedSpecialMember(MD);
11025
11026    // The exception specification is needed because we are defining the
11027    // function.
11028    ResolveExceptionSpec(DefaultLoc,
11029                         MD->getType()->castAs<FunctionProtoType>());
11030
11031    switch (Member) {
11032    case CXXDefaultConstructor: {
11033      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11034      if (!CD->isInvalidDecl())
11035        DefineImplicitDefaultConstructor(DefaultLoc, CD);
11036      break;
11037    }
11038
11039    case CXXCopyConstructor: {
11040      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11041      if (!CD->isInvalidDecl())
11042        DefineImplicitCopyConstructor(DefaultLoc, CD);
11043      break;
11044    }
11045
11046    case CXXCopyAssignment: {
11047      if (!MD->isInvalidDecl())
11048        DefineImplicitCopyAssignment(DefaultLoc, MD);
11049      break;
11050    }
11051
11052    case CXXDestructor: {
11053      CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
11054      if (!DD->isInvalidDecl())
11055        DefineImplicitDestructor(DefaultLoc, DD);
11056      break;
11057    }
11058
11059    case CXXMoveConstructor: {
11060      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11061      if (!CD->isInvalidDecl())
11062        DefineImplicitMoveConstructor(DefaultLoc, CD);
11063      break;
11064    }
11065
11066    case CXXMoveAssignment: {
11067      if (!MD->isInvalidDecl())
11068        DefineImplicitMoveAssignment(DefaultLoc, MD);
11069      break;
11070    }
11071
11072    case CXXInvalid:
11073      llvm_unreachable("Invalid special member.");
11074    }
11075  } else {
11076    Diag(DefaultLoc, diag::err_default_special_members);
11077  }
11078}
11079
11080static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
11081  for (Stmt::child_range CI = S->children(); CI; ++CI) {
11082    Stmt *SubStmt = *CI;
11083    if (!SubStmt)
11084      continue;
11085    if (isa<ReturnStmt>(SubStmt))
11086      Self.Diag(SubStmt->getLocStart(),
11087           diag::err_return_in_constructor_handler);
11088    if (!isa<Expr>(SubStmt))
11089      SearchForReturnInStmt(Self, SubStmt);
11090  }
11091}
11092
11093void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11094  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11095    CXXCatchStmt *Handler = TryBlock->getHandler(I);
11096    SearchForReturnInStmt(*this, Handler);
11097  }
11098}
11099
11100bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
11101                                             const CXXMethodDecl *Old) {
11102  const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11103  const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11104
11105  CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11106
11107  // If the calling conventions match, everything is fine
11108  if (NewCC == OldCC)
11109    return false;
11110
11111  // If either of the calling conventions are set to "default", we need to pick
11112  // something more sensible based on the target. This supports code where the
11113  // one method explicitly sets thiscall, and another has no explicit calling
11114  // convention.
11115  CallingConv Default =
11116    Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11117  if (NewCC == CC_Default)
11118    NewCC = Default;
11119  if (OldCC == CC_Default)
11120    OldCC = Default;
11121
11122  // If the calling conventions still don't match, then report the error
11123  if (NewCC != OldCC) {
11124    Diag(New->getLocation(),
11125         diag::err_conflicting_overriding_cc_attributes)
11126      << New->getDeclName() << New->getType() << Old->getType();
11127    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11128    return true;
11129  }
11130
11131  return false;
11132}
11133
11134bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
11135                                             const CXXMethodDecl *Old) {
11136  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11137  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
11138
11139  if (Context.hasSameType(NewTy, OldTy) ||
11140      NewTy->isDependentType() || OldTy->isDependentType())
11141    return false;
11142
11143  // Check if the return types are covariant
11144  QualType NewClassTy, OldClassTy;
11145
11146  /// Both types must be pointers or references to classes.
11147  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11148    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
11149      NewClassTy = NewPT->getPointeeType();
11150      OldClassTy = OldPT->getPointeeType();
11151    }
11152  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11153    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11154      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11155        NewClassTy = NewRT->getPointeeType();
11156        OldClassTy = OldRT->getPointeeType();
11157      }
11158    }
11159  }
11160
11161  // The return types aren't either both pointers or references to a class type.
11162  if (NewClassTy.isNull()) {
11163    Diag(New->getLocation(),
11164         diag::err_different_return_type_for_overriding_virtual_function)
11165      << New->getDeclName() << NewTy << OldTy;
11166    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11167
11168    return true;
11169  }
11170
11171  // C++ [class.virtual]p6:
11172  //   If the return type of D::f differs from the return type of B::f, the
11173  //   class type in the return type of D::f shall be complete at the point of
11174  //   declaration of D::f or shall be the class type D.
11175  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11176    if (!RT->isBeingDefined() &&
11177        RequireCompleteType(New->getLocation(), NewClassTy,
11178                            diag::err_covariant_return_incomplete,
11179                            New->getDeclName()))
11180    return true;
11181  }
11182
11183  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
11184    // Check if the new class derives from the old class.
11185    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11186      Diag(New->getLocation(),
11187           diag::err_covariant_return_not_derived)
11188      << New->getDeclName() << NewTy << OldTy;
11189      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11190      return true;
11191    }
11192
11193    // Check if we the conversion from derived to base is valid.
11194    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
11195                    diag::err_covariant_return_inaccessible_base,
11196                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
11197                    // FIXME: Should this point to the return type?
11198                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
11199      // FIXME: this note won't trigger for delayed access control
11200      // diagnostics, and it's impossible to get an undelayed error
11201      // here from access control during the original parse because
11202      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
11203      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11204      return true;
11205    }
11206  }
11207
11208  // The qualifiers of the return types must be the same.
11209  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
11210    Diag(New->getLocation(),
11211         diag::err_covariant_return_type_different_qualifications)
11212    << New->getDeclName() << NewTy << OldTy;
11213    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11214    return true;
11215  };
11216
11217
11218  // The new class type must have the same or less qualifiers as the old type.
11219  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11220    Diag(New->getLocation(),
11221         diag::err_covariant_return_type_class_type_more_qualified)
11222    << New->getDeclName() << NewTy << OldTy;
11223    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11224    return true;
11225  };
11226
11227  return false;
11228}
11229
11230/// \brief Mark the given method pure.
11231///
11232/// \param Method the method to be marked pure.
11233///
11234/// \param InitRange the source range that covers the "0" initializer.
11235bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
11236  SourceLocation EndLoc = InitRange.getEnd();
11237  if (EndLoc.isValid())
11238    Method->setRangeEnd(EndLoc);
11239
11240  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11241    Method->setPure();
11242    return false;
11243  }
11244
11245  if (!Method->isInvalidDecl())
11246    Diag(Method->getLocation(), diag::err_non_virtual_pure)
11247      << Method->getDeclName() << InitRange;
11248  return true;
11249}
11250
11251/// \brief Determine whether the given declaration is a static data member.
11252static bool isStaticDataMember(Decl *D) {
11253  VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11254  if (!Var)
11255    return false;
11256
11257  return Var->isStaticDataMember();
11258}
11259/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11260/// an initializer for the out-of-line declaration 'Dcl'.  The scope
11261/// is a fresh scope pushed for just this purpose.
11262///
11263/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11264/// static data member of class X, names should be looked up in the scope of
11265/// class X.
11266void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
11267  // If there is no declaration, there was an error parsing it.
11268  if (D == 0 || D->isInvalidDecl()) return;
11269
11270  // We should only get called for declarations with scope specifiers, like:
11271  //   int foo::bar;
11272  assert(D->isOutOfLine());
11273  EnterDeclaratorContext(S, D->getDeclContext());
11274
11275  // If we are parsing the initializer for a static data member, push a
11276  // new expression evaluation context that is associated with this static
11277  // data member.
11278  if (isStaticDataMember(D))
11279    PushExpressionEvaluationContext(PotentiallyEvaluated, D);
11280}
11281
11282/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
11283/// initializer for the out-of-line declaration 'D'.
11284void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
11285  // If there is no declaration, there was an error parsing it.
11286  if (D == 0 || D->isInvalidDecl()) return;
11287
11288  if (isStaticDataMember(D))
11289    PopExpressionEvaluationContext();
11290
11291  assert(D->isOutOfLine());
11292  ExitDeclaratorContext(S);
11293}
11294
11295/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11296/// C++ if/switch/while/for statement.
11297/// e.g: "if (int x = f()) {...}"
11298DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
11299  // C++ 6.4p2:
11300  // The declarator shall not specify a function or an array.
11301  // The type-specifier-seq shall not contain typedef and shall not declare a
11302  // new class or enumeration.
11303  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11304         "Parser allowed 'typedef' as storage class of condition decl.");
11305
11306  Decl *Dcl = ActOnDeclarator(S, D);
11307  if (!Dcl)
11308    return true;
11309
11310  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11311    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
11312      << D.getSourceRange();
11313    return true;
11314  }
11315
11316  return Dcl;
11317}
11318
11319void Sema::LoadExternalVTableUses() {
11320  if (!ExternalSource)
11321    return;
11322
11323  SmallVector<ExternalVTableUse, 4> VTables;
11324  ExternalSource->ReadUsedVTables(VTables);
11325  SmallVector<VTableUse, 4> NewUses;
11326  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11327    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11328      = VTablesUsed.find(VTables[I].Record);
11329    // Even if a definition wasn't required before, it may be required now.
11330    if (Pos != VTablesUsed.end()) {
11331      if (!Pos->second && VTables[I].DefinitionRequired)
11332        Pos->second = true;
11333      continue;
11334    }
11335
11336    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11337    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11338  }
11339
11340  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11341}
11342
11343void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11344                          bool DefinitionRequired) {
11345  // Ignore any vtable uses in unevaluated operands or for classes that do
11346  // not have a vtable.
11347  if (!Class->isDynamicClass() || Class->isDependentContext() ||
11348      CurContext->isDependentContext() ||
11349      ExprEvalContexts.back().Context == Unevaluated)
11350    return;
11351
11352  // Try to insert this class into the map.
11353  LoadExternalVTableUses();
11354  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11355  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11356    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11357  if (!Pos.second) {
11358    // If we already had an entry, check to see if we are promoting this vtable
11359    // to required a definition. If so, we need to reappend to the VTableUses
11360    // list, since we may have already processed the first entry.
11361    if (DefinitionRequired && !Pos.first->second) {
11362      Pos.first->second = true;
11363    } else {
11364      // Otherwise, we can early exit.
11365      return;
11366    }
11367  }
11368
11369  // Local classes need to have their virtual members marked
11370  // immediately. For all other classes, we mark their virtual members
11371  // at the end of the translation unit.
11372  if (Class->isLocalClass())
11373    MarkVirtualMembersReferenced(Loc, Class);
11374  else
11375    VTableUses.push_back(std::make_pair(Class, Loc));
11376}
11377
11378bool Sema::DefineUsedVTables() {
11379  LoadExternalVTableUses();
11380  if (VTableUses.empty())
11381    return false;
11382
11383  // Note: The VTableUses vector could grow as a result of marking
11384  // the members of a class as "used", so we check the size each
11385  // time through the loop and prefer indices (which are stable) to
11386  // iterators (which are not).
11387  bool DefinedAnything = false;
11388  for (unsigned I = 0; I != VTableUses.size(); ++I) {
11389    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
11390    if (!Class)
11391      continue;
11392
11393    SourceLocation Loc = VTableUses[I].second;
11394
11395    bool DefineVTable = true;
11396
11397    // If this class has a key function, but that key function is
11398    // defined in another translation unit, we don't need to emit the
11399    // vtable even though we're using it.
11400    const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
11401    if (KeyFunction && !KeyFunction->hasBody()) {
11402      switch (KeyFunction->getTemplateSpecializationKind()) {
11403      case TSK_Undeclared:
11404      case TSK_ExplicitSpecialization:
11405      case TSK_ExplicitInstantiationDeclaration:
11406        // The key function is in another translation unit.
11407        DefineVTable = false;
11408        break;
11409
11410      case TSK_ExplicitInstantiationDefinition:
11411      case TSK_ImplicitInstantiation:
11412        // We will be instantiating the key function.
11413        break;
11414      }
11415    } else if (!KeyFunction) {
11416      // If we have a class with no key function that is the subject
11417      // of an explicit instantiation declaration, suppress the
11418      // vtable; it will live with the explicit instantiation
11419      // definition.
11420      bool IsExplicitInstantiationDeclaration
11421        = Class->getTemplateSpecializationKind()
11422                                      == TSK_ExplicitInstantiationDeclaration;
11423      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11424                                 REnd = Class->redecls_end();
11425           R != REnd; ++R) {
11426        TemplateSpecializationKind TSK
11427          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11428        if (TSK == TSK_ExplicitInstantiationDeclaration)
11429          IsExplicitInstantiationDeclaration = true;
11430        else if (TSK == TSK_ExplicitInstantiationDefinition) {
11431          IsExplicitInstantiationDeclaration = false;
11432          break;
11433        }
11434      }
11435
11436      if (IsExplicitInstantiationDeclaration)
11437        DefineVTable = false;
11438    }
11439
11440    // The exception specifications for all virtual members may be needed even
11441    // if we are not providing an authoritative form of the vtable in this TU.
11442    // We may choose to emit it available_externally anyway.
11443    if (!DefineVTable) {
11444      MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11445      continue;
11446    }
11447
11448    // Mark all of the virtual members of this class as referenced, so
11449    // that we can build a vtable. Then, tell the AST consumer that a
11450    // vtable for this class is required.
11451    DefinedAnything = true;
11452    MarkVirtualMembersReferenced(Loc, Class);
11453    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11454    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11455
11456    // Optionally warn if we're emitting a weak vtable.
11457    if (Class->hasExternalLinkage() &&
11458        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
11459      const FunctionDecl *KeyFunctionDef = 0;
11460      if (!KeyFunction ||
11461          (KeyFunction->hasBody(KeyFunctionDef) &&
11462           KeyFunctionDef->isInlined()))
11463        Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11464             TSK_ExplicitInstantiationDefinition
11465             ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11466          << Class;
11467    }
11468  }
11469  VTableUses.clear();
11470
11471  return DefinedAnything;
11472}
11473
11474void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11475                                                 const CXXRecordDecl *RD) {
11476  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11477                                      E = RD->method_end(); I != E; ++I)
11478    if ((*I)->isVirtual() && !(*I)->isPure())
11479      ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11480}
11481
11482void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11483                                        const CXXRecordDecl *RD) {
11484  // Mark all functions which will appear in RD's vtable as used.
11485  CXXFinalOverriderMap FinalOverriders;
11486  RD->getFinalOverriders(FinalOverriders);
11487  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11488                                            E = FinalOverriders.end();
11489       I != E; ++I) {
11490    for (OverridingMethods::const_iterator OI = I->second.begin(),
11491                                           OE = I->second.end();
11492         OI != OE; ++OI) {
11493      assert(OI->second.size() > 0 && "no final overrider");
11494      CXXMethodDecl *Overrider = OI->second.front().Method;
11495
11496      // C++ [basic.def.odr]p2:
11497      //   [...] A virtual member function is used if it is not pure. [...]
11498      if (!Overrider->isPure())
11499        MarkFunctionReferenced(Loc, Overrider);
11500    }
11501  }
11502
11503  // Only classes that have virtual bases need a VTT.
11504  if (RD->getNumVBases() == 0)
11505    return;
11506
11507  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11508           e = RD->bases_end(); i != e; ++i) {
11509    const CXXRecordDecl *Base =
11510        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
11511    if (Base->getNumVBases() == 0)
11512      continue;
11513    MarkVirtualMembersReferenced(Loc, Base);
11514  }
11515}
11516
11517/// SetIvarInitializers - This routine builds initialization ASTs for the
11518/// Objective-C implementation whose ivars need be initialized.
11519void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
11520  if (!getLangOpts().CPlusPlus)
11521    return;
11522  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
11523    SmallVector<ObjCIvarDecl*, 8> ivars;
11524    CollectIvarsToConstructOrDestruct(OID, ivars);
11525    if (ivars.empty())
11526      return;
11527    SmallVector<CXXCtorInitializer*, 32> AllToInit;
11528    for (unsigned i = 0; i < ivars.size(); i++) {
11529      FieldDecl *Field = ivars[i];
11530      if (Field->isInvalidDecl())
11531        continue;
11532
11533      CXXCtorInitializer *Member;
11534      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11535      InitializationKind InitKind =
11536        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11537
11538      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
11539      ExprResult MemberInit =
11540        InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
11541      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
11542      // Note, MemberInit could actually come back empty if no initialization
11543      // is required (e.g., because it would call a trivial default constructor)
11544      if (!MemberInit.get() || MemberInit.isInvalid())
11545        continue;
11546
11547      Member =
11548        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11549                                         SourceLocation(),
11550                                         MemberInit.takeAs<Expr>(),
11551                                         SourceLocation());
11552      AllToInit.push_back(Member);
11553
11554      // Be sure that the destructor is accessible and is marked as referenced.
11555      if (const RecordType *RecordTy
11556                  = Context.getBaseElementType(Field->getType())
11557                                                        ->getAs<RecordType>()) {
11558                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
11559        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
11560          MarkFunctionReferenced(Field->getLocation(), Destructor);
11561          CheckDestructorAccess(Field->getLocation(), Destructor,
11562                            PDiag(diag::err_access_dtor_ivar)
11563                              << Context.getBaseElementType(Field->getType()));
11564        }
11565      }
11566    }
11567    ObjCImplementation->setIvarInitializers(Context,
11568                                            AllToInit.data(), AllToInit.size());
11569  }
11570}
11571
11572static
11573void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11574                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11575                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11576                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11577                           Sema &S) {
11578  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11579                                                   CE = Current.end();
11580  if (Ctor->isInvalidDecl())
11581    return;
11582
11583  CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11584
11585  // Target may not be determinable yet, for instance if this is a dependent
11586  // call in an uninstantiated template.
11587  if (Target) {
11588    const FunctionDecl *FNTarget = 0;
11589    (void)Target->hasBody(FNTarget);
11590    Target = const_cast<CXXConstructorDecl*>(
11591      cast_or_null<CXXConstructorDecl>(FNTarget));
11592  }
11593
11594  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11595                     // Avoid dereferencing a null pointer here.
11596                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11597
11598  if (!Current.insert(Canonical))
11599    return;
11600
11601  // We know that beyond here, we aren't chaining into a cycle.
11602  if (!Target || !Target->isDelegatingConstructor() ||
11603      Target->isInvalidDecl() || Valid.count(TCanonical)) {
11604    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11605      Valid.insert(*CI);
11606    Current.clear();
11607  // We've hit a cycle.
11608  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11609             Current.count(TCanonical)) {
11610    // If we haven't diagnosed this cycle yet, do so now.
11611    if (!Invalid.count(TCanonical)) {
11612      S.Diag((*Ctor->init_begin())->getSourceLocation(),
11613             diag::warn_delegating_ctor_cycle)
11614        << Ctor;
11615
11616      // Don't add a note for a function delegating directly to itself.
11617      if (TCanonical != Canonical)
11618        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11619
11620      CXXConstructorDecl *C = Target;
11621      while (C->getCanonicalDecl() != Canonical) {
11622        const FunctionDecl *FNTarget = 0;
11623        (void)C->getTargetConstructor()->hasBody(FNTarget);
11624        assert(FNTarget && "Ctor cycle through bodiless function");
11625
11626        C = const_cast<CXXConstructorDecl*>(
11627          cast<CXXConstructorDecl>(FNTarget));
11628        S.Diag(C->getLocation(), diag::note_which_delegates_to);
11629      }
11630    }
11631
11632    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11633      Invalid.insert(*CI);
11634    Current.clear();
11635  } else {
11636    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11637  }
11638}
11639
11640
11641void Sema::CheckDelegatingCtorCycles() {
11642  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11643
11644  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11645                                                   CE = Current.end();
11646
11647  for (DelegatingCtorDeclsType::iterator
11648         I = DelegatingCtorDecls.begin(ExternalSource),
11649         E = DelegatingCtorDecls.end();
11650       I != E; ++I)
11651    DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
11652
11653  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11654    (*CI)->setInvalidDecl();
11655}
11656
11657namespace {
11658  /// \brief AST visitor that finds references to the 'this' expression.
11659  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11660    Sema &S;
11661
11662  public:
11663    explicit FindCXXThisExpr(Sema &S) : S(S) { }
11664
11665    bool VisitCXXThisExpr(CXXThisExpr *E) {
11666      S.Diag(E->getLocation(), diag::err_this_static_member_func)
11667        << E->isImplicit();
11668      return false;
11669    }
11670  };
11671}
11672
11673bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11674  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11675  if (!TSInfo)
11676    return false;
11677
11678  TypeLoc TL = TSInfo->getTypeLoc();
11679  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
11680  if (!ProtoTL)
11681    return false;
11682
11683  // C++11 [expr.prim.general]p3:
11684  //   [The expression this] shall not appear before the optional
11685  //   cv-qualifier-seq and it shall not appear within the declaration of a
11686  //   static member function (although its type and value category are defined
11687  //   within a static member function as they are within a non-static member
11688  //   function). [ Note: this is because declaration matching does not occur
11689  //  until the complete declarator is known. - end note ]
11690  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
11691  FindCXXThisExpr Finder(*this);
11692
11693  // If the return type came after the cv-qualifier-seq, check it now.
11694  if (Proto->hasTrailingReturn() &&
11695      !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
11696    return true;
11697
11698  // Check the exception specification.
11699  if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11700    return true;
11701
11702  return checkThisInStaticMemberFunctionAttributes(Method);
11703}
11704
11705bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11706  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11707  if (!TSInfo)
11708    return false;
11709
11710  TypeLoc TL = TSInfo->getTypeLoc();
11711  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
11712  if (!ProtoTL)
11713    return false;
11714
11715  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
11716  FindCXXThisExpr Finder(*this);
11717
11718  switch (Proto->getExceptionSpecType()) {
11719  case EST_Uninstantiated:
11720  case EST_Unevaluated:
11721  case EST_BasicNoexcept:
11722  case EST_DynamicNone:
11723  case EST_MSAny:
11724  case EST_None:
11725    break;
11726
11727  case EST_ComputedNoexcept:
11728    if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11729      return true;
11730
11731  case EST_Dynamic:
11732    for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
11733         EEnd = Proto->exception_end();
11734         E != EEnd; ++E) {
11735      if (!Finder.TraverseType(*E))
11736        return true;
11737    }
11738    break;
11739  }
11740
11741  return false;
11742}
11743
11744bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11745  FindCXXThisExpr Finder(*this);
11746
11747  // Check attributes.
11748  for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11749       A != AEnd; ++A) {
11750    // FIXME: This should be emitted by tblgen.
11751    Expr *Arg = 0;
11752    ArrayRef<Expr *> Args;
11753    if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11754      Arg = G->getArg();
11755    else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11756      Arg = G->getArg();
11757    else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11758      Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11759    else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11760      Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11761    else if (ExclusiveLockFunctionAttr *ELF
11762               = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11763      Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11764    else if (SharedLockFunctionAttr *SLF
11765               = dyn_cast<SharedLockFunctionAttr>(*A))
11766      Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11767    else if (ExclusiveTrylockFunctionAttr *ETLF
11768               = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11769      Arg = ETLF->getSuccessValue();
11770      Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11771    } else if (SharedTrylockFunctionAttr *STLF
11772                 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11773      Arg = STLF->getSuccessValue();
11774      Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11775    } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11776      Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11777    else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11778      Arg = LR->getArg();
11779    else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11780      Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11781    else if (ExclusiveLocksRequiredAttr *ELR
11782               = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11783      Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11784    else if (SharedLocksRequiredAttr *SLR
11785               = dyn_cast<SharedLocksRequiredAttr>(*A))
11786      Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11787
11788    if (Arg && !Finder.TraverseStmt(Arg))
11789      return true;
11790
11791    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11792      if (!Finder.TraverseStmt(Args[I]))
11793        return true;
11794    }
11795  }
11796
11797  return false;
11798}
11799
11800void
11801Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11802                                  ArrayRef<ParsedType> DynamicExceptions,
11803                                  ArrayRef<SourceRange> DynamicExceptionRanges,
11804                                  Expr *NoexceptExpr,
11805                                  SmallVectorImpl<QualType> &Exceptions,
11806                                  FunctionProtoType::ExtProtoInfo &EPI) {
11807  Exceptions.clear();
11808  EPI.ExceptionSpecType = EST;
11809  if (EST == EST_Dynamic) {
11810    Exceptions.reserve(DynamicExceptions.size());
11811    for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11812      // FIXME: Preserve type source info.
11813      QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11814
11815      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11816      collectUnexpandedParameterPacks(ET, Unexpanded);
11817      if (!Unexpanded.empty()) {
11818        DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11819                                         UPPC_ExceptionType,
11820                                         Unexpanded);
11821        continue;
11822      }
11823
11824      // Check that the type is valid for an exception spec, and
11825      // drop it if not.
11826      if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11827        Exceptions.push_back(ET);
11828    }
11829    EPI.NumExceptions = Exceptions.size();
11830    EPI.Exceptions = Exceptions.data();
11831    return;
11832  }
11833
11834  if (EST == EST_ComputedNoexcept) {
11835    // If an error occurred, there's no expression here.
11836    if (NoexceptExpr) {
11837      assert((NoexceptExpr->isTypeDependent() ||
11838              NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11839              Context.BoolTy) &&
11840             "Parser should have made sure that the expression is boolean");
11841      if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11842        EPI.ExceptionSpecType = EST_BasicNoexcept;
11843        return;
11844      }
11845
11846      if (!NoexceptExpr->isValueDependent())
11847        NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
11848                         diag::err_noexcept_needs_constant_expression,
11849                         /*AllowFold*/ false).take();
11850      EPI.NoexceptExpr = NoexceptExpr;
11851    }
11852    return;
11853  }
11854}
11855
11856/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11857Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11858  // Implicitly declared functions (e.g. copy constructors) are
11859  // __host__ __device__
11860  if (D->isImplicit())
11861    return CFT_HostDevice;
11862
11863  if (D->hasAttr<CUDAGlobalAttr>())
11864    return CFT_Global;
11865
11866  if (D->hasAttr<CUDADeviceAttr>()) {
11867    if (D->hasAttr<CUDAHostAttr>())
11868      return CFT_HostDevice;
11869    else
11870      return CFT_Device;
11871  }
11872
11873  return CFT_Host;
11874}
11875
11876bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11877                           CUDAFunctionTarget CalleeTarget) {
11878  // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11879  // Callable from the device only."
11880  if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11881    return true;
11882
11883  // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11884  // Callable from the host only."
11885  // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11886  // Callable from the host only."
11887  if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11888      (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11889    return true;
11890
11891  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11892    return true;
11893
11894  return false;
11895}
11896