SemaDeclCXX.cpp revision 76398e5ad39ae719dcc650c7cddeb25379c02c34
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
15#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
17#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
19#include "clang/Sema/ScopeInfo.h"
20#include "clang/AST/ASTConsumer.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/ASTMutationListener.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/CXXInheritance.h"
25#include "clang/AST/DeclVisitor.h"
26#include "clang/AST/EvaluatedExprVisitor.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/RecordLayout.h"
29#include "clang/AST/RecursiveASTVisitor.h"
30#include "clang/AST/StmtVisitor.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/AST/TypeOrdering.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/ParsedTemplate.h"
35#include "clang/Basic/PartialDiagnostic.h"
36#include "clang/Lex/Preprocessor.h"
37#include "llvm/ADT/SmallString.h"
38#include "llvm/ADT/STLExtras.h"
39#include <map>
40#include <set>
41
42using namespace clang;
43
44//===----------------------------------------------------------------------===//
45// CheckDefaultArgumentVisitor
46//===----------------------------------------------------------------------===//
47
48namespace {
49  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
50  /// the default argument of a parameter to determine whether it
51  /// contains any ill-formed subexpressions. For example, this will
52  /// diagnose the use of local variables or parameters within the
53  /// default argument expression.
54  class CheckDefaultArgumentVisitor
55    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
56    Expr *DefaultArg;
57    Sema *S;
58
59  public:
60    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
61      : DefaultArg(defarg), S(s) {}
62
63    bool VisitExpr(Expr *Node);
64    bool VisitDeclRefExpr(DeclRefExpr *DRE);
65    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
66    bool VisitLambdaExpr(LambdaExpr *Lambda);
67  };
68
69  /// VisitExpr - Visit all of the children of this expression.
70  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
71    bool IsInvalid = false;
72    for (Stmt::child_range I = Node->children(); I; ++I)
73      IsInvalid |= Visit(*I);
74    return IsInvalid;
75  }
76
77  /// VisitDeclRefExpr - Visit a reference to a declaration, to
78  /// determine whether this declaration can be used in the default
79  /// argument expression.
80  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
81    NamedDecl *Decl = DRE->getDecl();
82    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
83      // C++ [dcl.fct.default]p9
84      //   Default arguments are evaluated each time the function is
85      //   called. The order of evaluation of function arguments is
86      //   unspecified. Consequently, parameters of a function shall not
87      //   be used in default argument expressions, even if they are not
88      //   evaluated. Parameters of a function declared before a default
89      //   argument expression are in scope and can hide namespace and
90      //   class member names.
91      return S->Diag(DRE->getLocStart(),
92                     diag::err_param_default_argument_references_param)
93         << Param->getDeclName() << DefaultArg->getSourceRange();
94    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
95      // C++ [dcl.fct.default]p7
96      //   Local variables shall not be used in default argument
97      //   expressions.
98      if (VDecl->isLocalVarDecl())
99        return S->Diag(DRE->getLocStart(),
100                       diag::err_param_default_argument_references_local)
101          << VDecl->getDeclName() << DefaultArg->getSourceRange();
102    }
103
104    return false;
105  }
106
107  /// VisitCXXThisExpr - Visit a C++ "this" expression.
108  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
109    // C++ [dcl.fct.default]p8:
110    //   The keyword this shall not be used in a default argument of a
111    //   member function.
112    return S->Diag(ThisE->getLocStart(),
113                   diag::err_param_default_argument_references_this)
114               << ThisE->getSourceRange();
115  }
116
117  bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
118    // C++11 [expr.lambda.prim]p13:
119    //   A lambda-expression appearing in a default argument shall not
120    //   implicitly or explicitly capture any entity.
121    if (Lambda->capture_begin() == Lambda->capture_end())
122      return false;
123
124    return S->Diag(Lambda->getLocStart(),
125                   diag::err_lambda_capture_default_arg);
126  }
127}
128
129void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
130                                                      CXXMethodDecl *Method) {
131  // If we have an MSAny spec already, don't bother.
132  if (!Method || ComputedEST == EST_MSAny)
133    return;
134
135  const FunctionProtoType *Proto
136    = Method->getType()->getAs<FunctionProtoType>();
137  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
138  if (!Proto)
139    return;
140
141  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
142
143  // If this function can throw any exceptions, make a note of that.
144  if (EST == EST_MSAny || EST == EST_None) {
145    ClearExceptions();
146    ComputedEST = EST;
147    return;
148  }
149
150  // FIXME: If the call to this decl is using any of its default arguments, we
151  // need to search them for potentially-throwing calls.
152
153  // If this function has a basic noexcept, it doesn't affect the outcome.
154  if (EST == EST_BasicNoexcept)
155    return;
156
157  // If we have a throw-all spec at this point, ignore the function.
158  if (ComputedEST == EST_None)
159    return;
160
161  // If we're still at noexcept(true) and there's a nothrow() callee,
162  // change to that specification.
163  if (EST == EST_DynamicNone) {
164    if (ComputedEST == EST_BasicNoexcept)
165      ComputedEST = EST_DynamicNone;
166    return;
167  }
168
169  // Check out noexcept specs.
170  if (EST == EST_ComputedNoexcept) {
171    FunctionProtoType::NoexceptResult NR =
172        Proto->getNoexceptSpec(Self->Context);
173    assert(NR != FunctionProtoType::NR_NoNoexcept &&
174           "Must have noexcept result for EST_ComputedNoexcept.");
175    assert(NR != FunctionProtoType::NR_Dependent &&
176           "Should not generate implicit declarations for dependent cases, "
177           "and don't know how to handle them anyway.");
178
179    // noexcept(false) -> no spec on the new function
180    if (NR == FunctionProtoType::NR_Throw) {
181      ClearExceptions();
182      ComputedEST = EST_None;
183    }
184    // noexcept(true) won't change anything either.
185    return;
186  }
187
188  assert(EST == EST_Dynamic && "EST case not considered earlier.");
189  assert(ComputedEST != EST_None &&
190         "Shouldn't collect exceptions when throw-all is guaranteed.");
191  ComputedEST = EST_Dynamic;
192  // Record the exceptions in this function's exception specification.
193  for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
194                                          EEnd = Proto->exception_end();
195       E != EEnd; ++E)
196    if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
197      Exceptions.push_back(*E);
198}
199
200void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
201  if (!E || ComputedEST == EST_MSAny)
202    return;
203
204  // FIXME:
205  //
206  // C++0x [except.spec]p14:
207  //   [An] implicit exception-specification specifies the type-id T if and
208  // only if T is allowed by the exception-specification of a function directly
209  // invoked by f's implicit definition; f shall allow all exceptions if any
210  // function it directly invokes allows all exceptions, and f shall allow no
211  // exceptions if every function it directly invokes allows no exceptions.
212  //
213  // Note in particular that if an implicit exception-specification is generated
214  // for a function containing a throw-expression, that specification can still
215  // be noexcept(true).
216  //
217  // Note also that 'directly invoked' is not defined in the standard, and there
218  // is no indication that we should only consider potentially-evaluated calls.
219  //
220  // Ultimately we should implement the intent of the standard: the exception
221  // specification should be the set of exceptions which can be thrown by the
222  // implicit definition. For now, we assume that any non-nothrow expression can
223  // throw any exception.
224
225  if (Self->canThrow(E))
226    ComputedEST = EST_None;
227}
228
229bool
230Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
231                              SourceLocation EqualLoc) {
232  if (RequireCompleteType(Param->getLocation(), Param->getType(),
233                          diag::err_typecheck_decl_incomplete_type)) {
234    Param->setInvalidDecl();
235    return true;
236  }
237
238  // C++ [dcl.fct.default]p5
239  //   A default argument expression is implicitly converted (clause
240  //   4) to the parameter type. The default argument expression has
241  //   the same semantic constraints as the initializer expression in
242  //   a declaration of a variable of the parameter type, using the
243  //   copy-initialization semantics (8.5).
244  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
245                                                                    Param);
246  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
247                                                           EqualLoc);
248  InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
249  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
250  if (Result.isInvalid())
251    return true;
252  Arg = Result.takeAs<Expr>();
253
254  CheckImplicitConversions(Arg, EqualLoc);
255  Arg = MaybeCreateExprWithCleanups(Arg);
256
257  // Okay: add the default argument to the parameter
258  Param->setDefaultArg(Arg);
259
260  // We have already instantiated this parameter; provide each of the
261  // instantiations with the uninstantiated default argument.
262  UnparsedDefaultArgInstantiationsMap::iterator InstPos
263    = UnparsedDefaultArgInstantiations.find(Param);
264  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
265    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
266      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
267
268    // We're done tracking this parameter's instantiations.
269    UnparsedDefaultArgInstantiations.erase(InstPos);
270  }
271
272  return false;
273}
274
275/// ActOnParamDefaultArgument - Check whether the default argument
276/// provided for a function parameter is well-formed. If so, attach it
277/// to the parameter declaration.
278void
279Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
280                                Expr *DefaultArg) {
281  if (!param || !DefaultArg)
282    return;
283
284  ParmVarDecl *Param = cast<ParmVarDecl>(param);
285  UnparsedDefaultArgLocs.erase(Param);
286
287  // Default arguments are only permitted in C++
288  if (!getLangOpts().CPlusPlus) {
289    Diag(EqualLoc, diag::err_param_default_argument)
290      << DefaultArg->getSourceRange();
291    Param->setInvalidDecl();
292    return;
293  }
294
295  // Check for unexpanded parameter packs.
296  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
297    Param->setInvalidDecl();
298    return;
299  }
300
301  // Check that the default argument is well-formed
302  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
303  if (DefaultArgChecker.Visit(DefaultArg)) {
304    Param->setInvalidDecl();
305    return;
306  }
307
308  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
309}
310
311/// ActOnParamUnparsedDefaultArgument - We've seen a default
312/// argument for a function parameter, but we can't parse it yet
313/// because we're inside a class definition. Note that this default
314/// argument will be parsed later.
315void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
316                                             SourceLocation EqualLoc,
317                                             SourceLocation ArgLoc) {
318  if (!param)
319    return;
320
321  ParmVarDecl *Param = cast<ParmVarDecl>(param);
322  if (Param)
323    Param->setUnparsedDefaultArg();
324
325  UnparsedDefaultArgLocs[Param] = ArgLoc;
326}
327
328/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
329/// the default argument for the parameter param failed.
330void Sema::ActOnParamDefaultArgumentError(Decl *param) {
331  if (!param)
332    return;
333
334  ParmVarDecl *Param = cast<ParmVarDecl>(param);
335
336  Param->setInvalidDecl();
337
338  UnparsedDefaultArgLocs.erase(Param);
339}
340
341/// CheckExtraCXXDefaultArguments - Check for any extra default
342/// arguments in the declarator, which is not a function declaration
343/// or definition and therefore is not permitted to have default
344/// arguments. This routine should be invoked for every declarator
345/// that is not a function declaration or definition.
346void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
347  // C++ [dcl.fct.default]p3
348  //   A default argument expression shall be specified only in the
349  //   parameter-declaration-clause of a function declaration or in a
350  //   template-parameter (14.1). It shall not be specified for a
351  //   parameter pack. If it is specified in a
352  //   parameter-declaration-clause, it shall not occur within a
353  //   declarator or abstract-declarator of a parameter-declaration.
354  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
355    DeclaratorChunk &chunk = D.getTypeObject(i);
356    if (chunk.Kind == DeclaratorChunk::Function) {
357      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
358        ParmVarDecl *Param =
359          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
360        if (Param->hasUnparsedDefaultArg()) {
361          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
362          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
363            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
364          delete Toks;
365          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
366        } else if (Param->getDefaultArg()) {
367          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
368            << Param->getDefaultArg()->getSourceRange();
369          Param->setDefaultArg(0);
370        }
371      }
372    }
373  }
374}
375
376/// MergeCXXFunctionDecl - Merge two declarations of the same C++
377/// function, once we already know that they have the same
378/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
379/// error, false otherwise.
380bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
381                                Scope *S) {
382  bool Invalid = false;
383
384  // C++ [dcl.fct.default]p4:
385  //   For non-template functions, default arguments can be added in
386  //   later declarations of a function in the same
387  //   scope. Declarations in different scopes have completely
388  //   distinct sets of default arguments. That is, declarations in
389  //   inner scopes do not acquire default arguments from
390  //   declarations in outer scopes, and vice versa. In a given
391  //   function declaration, all parameters subsequent to a
392  //   parameter with a default argument shall have default
393  //   arguments supplied in this or previous declarations. A
394  //   default argument shall not be redefined by a later
395  //   declaration (not even to the same value).
396  //
397  // C++ [dcl.fct.default]p6:
398  //   Except for member functions of class templates, the default arguments
399  //   in a member function definition that appears outside of the class
400  //   definition are added to the set of default arguments provided by the
401  //   member function declaration in the class definition.
402  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
403    ParmVarDecl *OldParam = Old->getParamDecl(p);
404    ParmVarDecl *NewParam = New->getParamDecl(p);
405
406    bool OldParamHasDfl = OldParam->hasDefaultArg();
407    bool NewParamHasDfl = NewParam->hasDefaultArg();
408
409    NamedDecl *ND = Old;
410    if (S && !isDeclInScope(ND, New->getDeclContext(), S))
411      // Ignore default parameters of old decl if they are not in
412      // the same scope.
413      OldParamHasDfl = false;
414
415    if (OldParamHasDfl && NewParamHasDfl) {
416
417      unsigned DiagDefaultParamID =
418        diag::err_param_default_argument_redefinition;
419
420      // MSVC accepts that default parameters be redefined for member functions
421      // of template class. The new default parameter's value is ignored.
422      Invalid = true;
423      if (getLangOpts().MicrosoftExt) {
424        CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
425        if (MD && MD->getParent()->getDescribedClassTemplate()) {
426          // Merge the old default argument into the new parameter.
427          NewParam->setHasInheritedDefaultArg();
428          if (OldParam->hasUninstantiatedDefaultArg())
429            NewParam->setUninstantiatedDefaultArg(
430                                      OldParam->getUninstantiatedDefaultArg());
431          else
432            NewParam->setDefaultArg(OldParam->getInit());
433          DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
434          Invalid = false;
435        }
436      }
437
438      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
439      // hint here. Alternatively, we could walk the type-source information
440      // for NewParam to find the last source location in the type... but it
441      // isn't worth the effort right now. This is the kind of test case that
442      // is hard to get right:
443      //   int f(int);
444      //   void g(int (*fp)(int) = f);
445      //   void g(int (*fp)(int) = &f);
446      Diag(NewParam->getLocation(), DiagDefaultParamID)
447        << NewParam->getDefaultArgRange();
448
449      // Look for the function declaration where the default argument was
450      // actually written, which may be a declaration prior to Old.
451      for (FunctionDecl *Older = Old->getPreviousDecl();
452           Older; Older = Older->getPreviousDecl()) {
453        if (!Older->getParamDecl(p)->hasDefaultArg())
454          break;
455
456        OldParam = Older->getParamDecl(p);
457      }
458
459      Diag(OldParam->getLocation(), diag::note_previous_definition)
460        << OldParam->getDefaultArgRange();
461    } else if (OldParamHasDfl) {
462      // Merge the old default argument into the new parameter.
463      // It's important to use getInit() here;  getDefaultArg()
464      // strips off any top-level ExprWithCleanups.
465      NewParam->setHasInheritedDefaultArg();
466      if (OldParam->hasUninstantiatedDefaultArg())
467        NewParam->setUninstantiatedDefaultArg(
468                                      OldParam->getUninstantiatedDefaultArg());
469      else
470        NewParam->setDefaultArg(OldParam->getInit());
471    } else if (NewParamHasDfl) {
472      if (New->getDescribedFunctionTemplate()) {
473        // Paragraph 4, quoted above, only applies to non-template functions.
474        Diag(NewParam->getLocation(),
475             diag::err_param_default_argument_template_redecl)
476          << NewParam->getDefaultArgRange();
477        Diag(Old->getLocation(), diag::note_template_prev_declaration)
478          << false;
479      } else if (New->getTemplateSpecializationKind()
480                   != TSK_ImplicitInstantiation &&
481                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
482        // C++ [temp.expr.spec]p21:
483        //   Default function arguments shall not be specified in a declaration
484        //   or a definition for one of the following explicit specializations:
485        //     - the explicit specialization of a function template;
486        //     - the explicit specialization of a member function template;
487        //     - the explicit specialization of a member function of a class
488        //       template where the class template specialization to which the
489        //       member function specialization belongs is implicitly
490        //       instantiated.
491        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
492          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
493          << New->getDeclName()
494          << NewParam->getDefaultArgRange();
495      } else if (New->getDeclContext()->isDependentContext()) {
496        // C++ [dcl.fct.default]p6 (DR217):
497        //   Default arguments for a member function of a class template shall
498        //   be specified on the initial declaration of the member function
499        //   within the class template.
500        //
501        // Reading the tea leaves a bit in DR217 and its reference to DR205
502        // leads me to the conclusion that one cannot add default function
503        // arguments for an out-of-line definition of a member function of a
504        // dependent type.
505        int WhichKind = 2;
506        if (CXXRecordDecl *Record
507              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
508          if (Record->getDescribedClassTemplate())
509            WhichKind = 0;
510          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
511            WhichKind = 1;
512          else
513            WhichKind = 2;
514        }
515
516        Diag(NewParam->getLocation(),
517             diag::err_param_default_argument_member_template_redecl)
518          << WhichKind
519          << NewParam->getDefaultArgRange();
520      } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
521        CXXSpecialMember NewSM = getSpecialMember(Ctor),
522                         OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
523        if (NewSM != OldSM) {
524          Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
525            << NewParam->getDefaultArgRange() << NewSM;
526          Diag(Old->getLocation(), diag::note_previous_declaration_special)
527            << OldSM;
528        }
529      }
530    }
531  }
532
533  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
534  // template has a constexpr specifier then all its declarations shall
535  // contain the constexpr specifier.
536  if (New->isConstexpr() != Old->isConstexpr()) {
537    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
538      << New << New->isConstexpr();
539    Diag(Old->getLocation(), diag::note_previous_declaration);
540    Invalid = true;
541  }
542
543  if (CheckEquivalentExceptionSpec(Old, New))
544    Invalid = true;
545
546  return Invalid;
547}
548
549/// \brief Merge the exception specifications of two variable declarations.
550///
551/// This is called when there's a redeclaration of a VarDecl. The function
552/// checks if the redeclaration might have an exception specification and
553/// validates compatibility and merges the specs if necessary.
554void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
555  // Shortcut if exceptions are disabled.
556  if (!getLangOpts().CXXExceptions)
557    return;
558
559  assert(Context.hasSameType(New->getType(), Old->getType()) &&
560         "Should only be called if types are otherwise the same.");
561
562  QualType NewType = New->getType();
563  QualType OldType = Old->getType();
564
565  // We're only interested in pointers and references to functions, as well
566  // as pointers to member functions.
567  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
568    NewType = R->getPointeeType();
569    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
570  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
571    NewType = P->getPointeeType();
572    OldType = OldType->getAs<PointerType>()->getPointeeType();
573  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
574    NewType = M->getPointeeType();
575    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
576  }
577
578  if (!NewType->isFunctionProtoType())
579    return;
580
581  // There's lots of special cases for functions. For function pointers, system
582  // libraries are hopefully not as broken so that we don't need these
583  // workarounds.
584  if (CheckEquivalentExceptionSpec(
585        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
586        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
587    New->setInvalidDecl();
588  }
589}
590
591/// CheckCXXDefaultArguments - Verify that the default arguments for a
592/// function declaration are well-formed according to C++
593/// [dcl.fct.default].
594void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
595  unsigned NumParams = FD->getNumParams();
596  unsigned p;
597
598  bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
599                  isa<CXXMethodDecl>(FD) &&
600                  cast<CXXMethodDecl>(FD)->getParent()->isLambda();
601
602  // Find first parameter with a default argument
603  for (p = 0; p < NumParams; ++p) {
604    ParmVarDecl *Param = FD->getParamDecl(p);
605    if (Param->hasDefaultArg()) {
606      // C++11 [expr.prim.lambda]p5:
607      //   [...] Default arguments (8.3.6) shall not be specified in the
608      //   parameter-declaration-clause of a lambda-declarator.
609      //
610      // FIXME: Core issue 974 strikes this sentence, we only provide an
611      // extension warning.
612      if (IsLambda)
613        Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
614          << Param->getDefaultArgRange();
615      break;
616    }
617  }
618
619  // C++ [dcl.fct.default]p4:
620  //   In a given function declaration, all parameters
621  //   subsequent to a parameter with a default argument shall
622  //   have default arguments supplied in this or previous
623  //   declarations. A default argument shall not be redefined
624  //   by a later declaration (not even to the same value).
625  unsigned LastMissingDefaultArg = 0;
626  for (; p < NumParams; ++p) {
627    ParmVarDecl *Param = FD->getParamDecl(p);
628    if (!Param->hasDefaultArg()) {
629      if (Param->isInvalidDecl())
630        /* We already complained about this parameter. */;
631      else if (Param->getIdentifier())
632        Diag(Param->getLocation(),
633             diag::err_param_default_argument_missing_name)
634          << Param->getIdentifier();
635      else
636        Diag(Param->getLocation(),
637             diag::err_param_default_argument_missing);
638
639      LastMissingDefaultArg = p;
640    }
641  }
642
643  if (LastMissingDefaultArg > 0) {
644    // Some default arguments were missing. Clear out all of the
645    // default arguments up to (and including) the last missing
646    // default argument, so that we leave the function parameters
647    // in a semantically valid state.
648    for (p = 0; p <= LastMissingDefaultArg; ++p) {
649      ParmVarDecl *Param = FD->getParamDecl(p);
650      if (Param->hasDefaultArg()) {
651        Param->setDefaultArg(0);
652      }
653    }
654  }
655}
656
657// CheckConstexprParameterTypes - Check whether a function's parameter types
658// are all literal types. If so, return true. If not, produce a suitable
659// diagnostic and return false.
660static bool CheckConstexprParameterTypes(Sema &SemaRef,
661                                         const FunctionDecl *FD) {
662  unsigned ArgIndex = 0;
663  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
664  for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
665       e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
666    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
667    SourceLocation ParamLoc = PD->getLocation();
668    if (!(*i)->isDependentType() &&
669        SemaRef.RequireLiteralType(ParamLoc, *i,
670                                   diag::err_constexpr_non_literal_param,
671                                   ArgIndex+1, PD->getSourceRange(),
672                                   isa<CXXConstructorDecl>(FD)))
673      return false;
674  }
675  return true;
676}
677
678/// \brief Get diagnostic %select index for tag kind for
679/// record diagnostic message.
680/// WARNING: Indexes apply to particular diagnostics only!
681///
682/// \returns diagnostic %select index.
683static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
684  switch (Tag) {
685  case TTK_Struct: return 0;
686  case TTK_Interface: return 1;
687  case TTK_Class:  return 2;
688  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
689  }
690}
691
692// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
693// the requirements of a constexpr function definition or a constexpr
694// constructor definition. If so, return true. If not, produce appropriate
695// diagnostics and return false.
696//
697// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
698bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
699  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
700  if (MD && MD->isInstance()) {
701    // C++11 [dcl.constexpr]p4:
702    //  The definition of a constexpr constructor shall satisfy the following
703    //  constraints:
704    //  - the class shall not have any virtual base classes;
705    const CXXRecordDecl *RD = MD->getParent();
706    if (RD->getNumVBases()) {
707      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
708        << isa<CXXConstructorDecl>(NewFD)
709        << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
710      for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
711             E = RD->vbases_end(); I != E; ++I)
712        Diag(I->getLocStart(),
713             diag::note_constexpr_virtual_base_here) << I->getSourceRange();
714      return false;
715    }
716  }
717
718  if (!isa<CXXConstructorDecl>(NewFD)) {
719    // C++11 [dcl.constexpr]p3:
720    //  The definition of a constexpr function shall satisfy the following
721    //  constraints:
722    // - it shall not be virtual;
723    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
724    if (Method && Method->isVirtual()) {
725      Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
726
727      // If it's not obvious why this function is virtual, find an overridden
728      // function which uses the 'virtual' keyword.
729      const CXXMethodDecl *WrittenVirtual = Method;
730      while (!WrittenVirtual->isVirtualAsWritten())
731        WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
732      if (WrittenVirtual != Method)
733        Diag(WrittenVirtual->getLocation(),
734             diag::note_overridden_virtual_function);
735      return false;
736    }
737
738    // - its return type shall be a literal type;
739    QualType RT = NewFD->getResultType();
740    if (!RT->isDependentType() &&
741        RequireLiteralType(NewFD->getLocation(), RT,
742                           diag::err_constexpr_non_literal_return))
743      return false;
744  }
745
746  // - each of its parameter types shall be a literal type;
747  if (!CheckConstexprParameterTypes(*this, NewFD))
748    return false;
749
750  return true;
751}
752
753/// Check the given declaration statement is legal within a constexpr function
754/// body. C++0x [dcl.constexpr]p3,p4.
755///
756/// \return true if the body is OK, false if we have diagnosed a problem.
757static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
758                                   DeclStmt *DS) {
759  // C++0x [dcl.constexpr]p3 and p4:
760  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
761  //  contain only
762  for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
763         DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
764    switch ((*DclIt)->getKind()) {
765    case Decl::StaticAssert:
766    case Decl::Using:
767    case Decl::UsingShadow:
768    case Decl::UsingDirective:
769    case Decl::UnresolvedUsingTypename:
770      //   - static_assert-declarations
771      //   - using-declarations,
772      //   - using-directives,
773      continue;
774
775    case Decl::Typedef:
776    case Decl::TypeAlias: {
777      //   - typedef declarations and alias-declarations that do not define
778      //     classes or enumerations,
779      TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
780      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
781        // Don't allow variably-modified types in constexpr functions.
782        TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
783        SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
784          << TL.getSourceRange() << TL.getType()
785          << isa<CXXConstructorDecl>(Dcl);
786        return false;
787      }
788      continue;
789    }
790
791    case Decl::Enum:
792    case Decl::CXXRecord:
793      // As an extension, we allow the declaration (but not the definition) of
794      // classes and enumerations in all declarations, not just in typedef and
795      // alias declarations.
796      if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
797        SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
798          << isa<CXXConstructorDecl>(Dcl);
799        return false;
800      }
801      continue;
802
803    case Decl::Var:
804      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
805        << isa<CXXConstructorDecl>(Dcl);
806      return false;
807
808    default:
809      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
810        << isa<CXXConstructorDecl>(Dcl);
811      return false;
812    }
813  }
814
815  return true;
816}
817
818/// Check that the given field is initialized within a constexpr constructor.
819///
820/// \param Dcl The constexpr constructor being checked.
821/// \param Field The field being checked. This may be a member of an anonymous
822///        struct or union nested within the class being checked.
823/// \param Inits All declarations, including anonymous struct/union members and
824///        indirect members, for which any initialization was provided.
825/// \param Diagnosed Set to true if an error is produced.
826static void CheckConstexprCtorInitializer(Sema &SemaRef,
827                                          const FunctionDecl *Dcl,
828                                          FieldDecl *Field,
829                                          llvm::SmallSet<Decl*, 16> &Inits,
830                                          bool &Diagnosed) {
831  if (Field->isUnnamedBitfield())
832    return;
833
834  if (Field->isAnonymousStructOrUnion() &&
835      Field->getType()->getAsCXXRecordDecl()->isEmpty())
836    return;
837
838  if (!Inits.count(Field)) {
839    if (!Diagnosed) {
840      SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
841      Diagnosed = true;
842    }
843    SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
844  } else if (Field->isAnonymousStructOrUnion()) {
845    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
846    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
847         I != E; ++I)
848      // If an anonymous union contains an anonymous struct of which any member
849      // is initialized, all members must be initialized.
850      if (!RD->isUnion() || Inits.count(*I))
851        CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
852  }
853}
854
855/// Check the body for the given constexpr function declaration only contains
856/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
857///
858/// \return true if the body is OK, false if we have diagnosed a problem.
859bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
860  if (isa<CXXTryStmt>(Body)) {
861    // C++11 [dcl.constexpr]p3:
862    //  The definition of a constexpr function shall satisfy the following
863    //  constraints: [...]
864    // - its function-body shall be = delete, = default, or a
865    //   compound-statement
866    //
867    // C++11 [dcl.constexpr]p4:
868    //  In the definition of a constexpr constructor, [...]
869    // - its function-body shall not be a function-try-block;
870    Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
871      << isa<CXXConstructorDecl>(Dcl);
872    return false;
873  }
874
875  // - its function-body shall be [...] a compound-statement that contains only
876  CompoundStmt *CompBody = cast<CompoundStmt>(Body);
877
878  llvm::SmallVector<SourceLocation, 4> ReturnStmts;
879  for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
880         BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
881    switch ((*BodyIt)->getStmtClass()) {
882    case Stmt::NullStmtClass:
883      //   - null statements,
884      continue;
885
886    case Stmt::DeclStmtClass:
887      //   - static_assert-declarations
888      //   - using-declarations,
889      //   - using-directives,
890      //   - typedef declarations and alias-declarations that do not define
891      //     classes or enumerations,
892      if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
893        return false;
894      continue;
895
896    case Stmt::ReturnStmtClass:
897      //   - and exactly one return statement;
898      if (isa<CXXConstructorDecl>(Dcl))
899        break;
900
901      ReturnStmts.push_back((*BodyIt)->getLocStart());
902      continue;
903
904    default:
905      break;
906    }
907
908    Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
909      << isa<CXXConstructorDecl>(Dcl);
910    return false;
911  }
912
913  if (const CXXConstructorDecl *Constructor
914        = dyn_cast<CXXConstructorDecl>(Dcl)) {
915    const CXXRecordDecl *RD = Constructor->getParent();
916    // DR1359:
917    // - every non-variant non-static data member and base class sub-object
918    //   shall be initialized;
919    // - if the class is a non-empty union, or for each non-empty anonymous
920    //   union member of a non-union class, exactly one non-static data member
921    //   shall be initialized;
922    if (RD->isUnion()) {
923      if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
924        Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
925        return false;
926      }
927    } else if (!Constructor->isDependentContext() &&
928               !Constructor->isDelegatingConstructor()) {
929      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
930
931      // Skip detailed checking if we have enough initializers, and we would
932      // allow at most one initializer per member.
933      bool AnyAnonStructUnionMembers = false;
934      unsigned Fields = 0;
935      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
936           E = RD->field_end(); I != E; ++I, ++Fields) {
937        if (I->isAnonymousStructOrUnion()) {
938          AnyAnonStructUnionMembers = true;
939          break;
940        }
941      }
942      if (AnyAnonStructUnionMembers ||
943          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
944        // Check initialization of non-static data members. Base classes are
945        // always initialized so do not need to be checked. Dependent bases
946        // might not have initializers in the member initializer list.
947        llvm::SmallSet<Decl*, 16> Inits;
948        for (CXXConstructorDecl::init_const_iterator
949               I = Constructor->init_begin(), E = Constructor->init_end();
950             I != E; ++I) {
951          if (FieldDecl *FD = (*I)->getMember())
952            Inits.insert(FD);
953          else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
954            Inits.insert(ID->chain_begin(), ID->chain_end());
955        }
956
957        bool Diagnosed = false;
958        for (CXXRecordDecl::field_iterator I = RD->field_begin(),
959             E = RD->field_end(); I != E; ++I)
960          CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
961        if (Diagnosed)
962          return false;
963      }
964    }
965  } else {
966    if (ReturnStmts.empty()) {
967      Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
968      return false;
969    }
970    if (ReturnStmts.size() > 1) {
971      Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
972      for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
973        Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
974      return false;
975    }
976  }
977
978  // C++11 [dcl.constexpr]p5:
979  //   if no function argument values exist such that the function invocation
980  //   substitution would produce a constant expression, the program is
981  //   ill-formed; no diagnostic required.
982  // C++11 [dcl.constexpr]p3:
983  //   - every constructor call and implicit conversion used in initializing the
984  //     return value shall be one of those allowed in a constant expression.
985  // C++11 [dcl.constexpr]p4:
986  //   - every constructor involved in initializing non-static data members and
987  //     base class sub-objects shall be a constexpr constructor.
988  llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
989  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
990    Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
991      << isa<CXXConstructorDecl>(Dcl);
992    for (size_t I = 0, N = Diags.size(); I != N; ++I)
993      Diag(Diags[I].first, Diags[I].second);
994    return false;
995  }
996
997  return true;
998}
999
1000/// isCurrentClassName - Determine whether the identifier II is the
1001/// name of the class type currently being defined. In the case of
1002/// nested classes, this will only return true if II is the name of
1003/// the innermost class.
1004bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1005                              const CXXScopeSpec *SS) {
1006  assert(getLangOpts().CPlusPlus && "No class names in C!");
1007
1008  CXXRecordDecl *CurDecl;
1009  if (SS && SS->isSet() && !SS->isInvalid()) {
1010    DeclContext *DC = computeDeclContext(*SS, true);
1011    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1012  } else
1013    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1014
1015  if (CurDecl && CurDecl->getIdentifier())
1016    return &II == CurDecl->getIdentifier();
1017  else
1018    return false;
1019}
1020
1021/// \brief Check the validity of a C++ base class specifier.
1022///
1023/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1024/// and returns NULL otherwise.
1025CXXBaseSpecifier *
1026Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1027                         SourceRange SpecifierRange,
1028                         bool Virtual, AccessSpecifier Access,
1029                         TypeSourceInfo *TInfo,
1030                         SourceLocation EllipsisLoc) {
1031  QualType BaseType = TInfo->getType();
1032
1033  // C++ [class.union]p1:
1034  //   A union shall not have base classes.
1035  if (Class->isUnion()) {
1036    Diag(Class->getLocation(), diag::err_base_clause_on_union)
1037      << SpecifierRange;
1038    return 0;
1039  }
1040
1041  if (EllipsisLoc.isValid() &&
1042      !TInfo->getType()->containsUnexpandedParameterPack()) {
1043    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1044      << TInfo->getTypeLoc().getSourceRange();
1045    EllipsisLoc = SourceLocation();
1046  }
1047
1048  if (BaseType->isDependentType())
1049    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1050                                          Class->getTagKind() == TTK_Class,
1051                                          Access, TInfo, EllipsisLoc);
1052
1053  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1054
1055  // Base specifiers must be record types.
1056  if (!BaseType->isRecordType()) {
1057    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1058    return 0;
1059  }
1060
1061  // C++ [class.union]p1:
1062  //   A union shall not be used as a base class.
1063  if (BaseType->isUnionType()) {
1064    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1065    return 0;
1066  }
1067
1068  // C++ [class.derived]p2:
1069  //   The class-name in a base-specifier shall not be an incompletely
1070  //   defined class.
1071  if (RequireCompleteType(BaseLoc, BaseType,
1072                          diag::err_incomplete_base_class, SpecifierRange)) {
1073    Class->setInvalidDecl();
1074    return 0;
1075  }
1076
1077  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1078  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1079  assert(BaseDecl && "Record type has no declaration");
1080  BaseDecl = BaseDecl->getDefinition();
1081  assert(BaseDecl && "Base type is not incomplete, but has no definition");
1082  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1083  assert(CXXBaseDecl && "Base type is not a C++ type");
1084
1085  // C++ [class]p3:
1086  //   If a class is marked final and it appears as a base-type-specifier in
1087  //   base-clause, the program is ill-formed.
1088  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1089    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1090      << CXXBaseDecl->getDeclName();
1091    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1092      << CXXBaseDecl->getDeclName();
1093    return 0;
1094  }
1095
1096  if (BaseDecl->isInvalidDecl())
1097    Class->setInvalidDecl();
1098
1099  // Create the base specifier.
1100  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1101                                        Class->getTagKind() == TTK_Class,
1102                                        Access, TInfo, EllipsisLoc);
1103}
1104
1105/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1106/// one entry in the base class list of a class specifier, for
1107/// example:
1108///    class foo : public bar, virtual private baz {
1109/// 'public bar' and 'virtual private baz' are each base-specifiers.
1110BaseResult
1111Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1112                         bool Virtual, AccessSpecifier Access,
1113                         ParsedType basetype, SourceLocation BaseLoc,
1114                         SourceLocation EllipsisLoc) {
1115  if (!classdecl)
1116    return true;
1117
1118  AdjustDeclIfTemplate(classdecl);
1119  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1120  if (!Class)
1121    return true;
1122
1123  TypeSourceInfo *TInfo = 0;
1124  GetTypeFromParser(basetype, &TInfo);
1125
1126  if (EllipsisLoc.isInvalid() &&
1127      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1128                                      UPPC_BaseType))
1129    return true;
1130
1131  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1132                                                      Virtual, Access, TInfo,
1133                                                      EllipsisLoc))
1134    return BaseSpec;
1135  else
1136    Class->setInvalidDecl();
1137
1138  return true;
1139}
1140
1141/// \brief Performs the actual work of attaching the given base class
1142/// specifiers to a C++ class.
1143bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1144                                unsigned NumBases) {
1145 if (NumBases == 0)
1146    return false;
1147
1148  // Used to keep track of which base types we have already seen, so
1149  // that we can properly diagnose redundant direct base types. Note
1150  // that the key is always the unqualified canonical type of the base
1151  // class.
1152  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1153
1154  // Copy non-redundant base specifiers into permanent storage.
1155  unsigned NumGoodBases = 0;
1156  bool Invalid = false;
1157  for (unsigned idx = 0; idx < NumBases; ++idx) {
1158    QualType NewBaseType
1159      = Context.getCanonicalType(Bases[idx]->getType());
1160    NewBaseType = NewBaseType.getLocalUnqualifiedType();
1161
1162    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1163    if (KnownBase) {
1164      // C++ [class.mi]p3:
1165      //   A class shall not be specified as a direct base class of a
1166      //   derived class more than once.
1167      Diag(Bases[idx]->getLocStart(),
1168           diag::err_duplicate_base_class)
1169        << KnownBase->getType()
1170        << Bases[idx]->getSourceRange();
1171
1172      // Delete the duplicate base class specifier; we're going to
1173      // overwrite its pointer later.
1174      Context.Deallocate(Bases[idx]);
1175
1176      Invalid = true;
1177    } else {
1178      // Okay, add this new base class.
1179      KnownBase = Bases[idx];
1180      Bases[NumGoodBases++] = Bases[idx];
1181      if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1182        const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1183        if (Class->isInterface() &&
1184              (!RD->isInterface() ||
1185               KnownBase->getAccessSpecifier() != AS_public)) {
1186          // The Microsoft extension __interface does not permit bases that
1187          // are not themselves public interfaces.
1188          Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1189            << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1190            << RD->getSourceRange();
1191          Invalid = true;
1192        }
1193        if (RD->hasAttr<WeakAttr>())
1194          Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1195      }
1196    }
1197  }
1198
1199  // Attach the remaining base class specifiers to the derived class.
1200  Class->setBases(Bases, NumGoodBases);
1201
1202  // Delete the remaining (good) base class specifiers, since their
1203  // data has been copied into the CXXRecordDecl.
1204  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1205    Context.Deallocate(Bases[idx]);
1206
1207  return Invalid;
1208}
1209
1210/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1211/// class, after checking whether there are any duplicate base
1212/// classes.
1213void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1214                               unsigned NumBases) {
1215  if (!ClassDecl || !Bases || !NumBases)
1216    return;
1217
1218  AdjustDeclIfTemplate(ClassDecl);
1219  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1220                       (CXXBaseSpecifier**)(Bases), NumBases);
1221}
1222
1223static CXXRecordDecl *GetClassForType(QualType T) {
1224  if (const RecordType *RT = T->getAs<RecordType>())
1225    return cast<CXXRecordDecl>(RT->getDecl());
1226  else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1227    return ICT->getDecl();
1228  else
1229    return 0;
1230}
1231
1232/// \brief Determine whether the type \p Derived is a C++ class that is
1233/// derived from the type \p Base.
1234bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1235  if (!getLangOpts().CPlusPlus)
1236    return false;
1237
1238  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1239  if (!DerivedRD)
1240    return false;
1241
1242  CXXRecordDecl *BaseRD = GetClassForType(Base);
1243  if (!BaseRD)
1244    return false;
1245
1246  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1247  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1248}
1249
1250/// \brief Determine whether the type \p Derived is a C++ class that is
1251/// derived from the type \p Base.
1252bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1253  if (!getLangOpts().CPlusPlus)
1254    return false;
1255
1256  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1257  if (!DerivedRD)
1258    return false;
1259
1260  CXXRecordDecl *BaseRD = GetClassForType(Base);
1261  if (!BaseRD)
1262    return false;
1263
1264  return DerivedRD->isDerivedFrom(BaseRD, Paths);
1265}
1266
1267void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1268                              CXXCastPath &BasePathArray) {
1269  assert(BasePathArray.empty() && "Base path array must be empty!");
1270  assert(Paths.isRecordingPaths() && "Must record paths!");
1271
1272  const CXXBasePath &Path = Paths.front();
1273
1274  // We first go backward and check if we have a virtual base.
1275  // FIXME: It would be better if CXXBasePath had the base specifier for
1276  // the nearest virtual base.
1277  unsigned Start = 0;
1278  for (unsigned I = Path.size(); I != 0; --I) {
1279    if (Path[I - 1].Base->isVirtual()) {
1280      Start = I - 1;
1281      break;
1282    }
1283  }
1284
1285  // Now add all bases.
1286  for (unsigned I = Start, E = Path.size(); I != E; ++I)
1287    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1288}
1289
1290/// \brief Determine whether the given base path includes a virtual
1291/// base class.
1292bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1293  for (CXXCastPath::const_iterator B = BasePath.begin(),
1294                                BEnd = BasePath.end();
1295       B != BEnd; ++B)
1296    if ((*B)->isVirtual())
1297      return true;
1298
1299  return false;
1300}
1301
1302/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1303/// conversion (where Derived and Base are class types) is
1304/// well-formed, meaning that the conversion is unambiguous (and
1305/// that all of the base classes are accessible). Returns true
1306/// and emits a diagnostic if the code is ill-formed, returns false
1307/// otherwise. Loc is the location where this routine should point to
1308/// if there is an error, and Range is the source range to highlight
1309/// if there is an error.
1310bool
1311Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1312                                   unsigned InaccessibleBaseID,
1313                                   unsigned AmbigiousBaseConvID,
1314                                   SourceLocation Loc, SourceRange Range,
1315                                   DeclarationName Name,
1316                                   CXXCastPath *BasePath) {
1317  // First, determine whether the path from Derived to Base is
1318  // ambiguous. This is slightly more expensive than checking whether
1319  // the Derived to Base conversion exists, because here we need to
1320  // explore multiple paths to determine if there is an ambiguity.
1321  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1322                     /*DetectVirtual=*/false);
1323  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1324  assert(DerivationOkay &&
1325         "Can only be used with a derived-to-base conversion");
1326  (void)DerivationOkay;
1327
1328  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1329    if (InaccessibleBaseID) {
1330      // Check that the base class can be accessed.
1331      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1332                                   InaccessibleBaseID)) {
1333        case AR_inaccessible:
1334          return true;
1335        case AR_accessible:
1336        case AR_dependent:
1337        case AR_delayed:
1338          break;
1339      }
1340    }
1341
1342    // Build a base path if necessary.
1343    if (BasePath)
1344      BuildBasePathArray(Paths, *BasePath);
1345    return false;
1346  }
1347
1348  // We know that the derived-to-base conversion is ambiguous, and
1349  // we're going to produce a diagnostic. Perform the derived-to-base
1350  // search just one more time to compute all of the possible paths so
1351  // that we can print them out. This is more expensive than any of
1352  // the previous derived-to-base checks we've done, but at this point
1353  // performance isn't as much of an issue.
1354  Paths.clear();
1355  Paths.setRecordingPaths(true);
1356  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1357  assert(StillOkay && "Can only be used with a derived-to-base conversion");
1358  (void)StillOkay;
1359
1360  // Build up a textual representation of the ambiguous paths, e.g.,
1361  // D -> B -> A, that will be used to illustrate the ambiguous
1362  // conversions in the diagnostic. We only print one of the paths
1363  // to each base class subobject.
1364  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1365
1366  Diag(Loc, AmbigiousBaseConvID)
1367  << Derived << Base << PathDisplayStr << Range << Name;
1368  return true;
1369}
1370
1371bool
1372Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1373                                   SourceLocation Loc, SourceRange Range,
1374                                   CXXCastPath *BasePath,
1375                                   bool IgnoreAccess) {
1376  return CheckDerivedToBaseConversion(Derived, Base,
1377                                      IgnoreAccess ? 0
1378                                       : diag::err_upcast_to_inaccessible_base,
1379                                      diag::err_ambiguous_derived_to_base_conv,
1380                                      Loc, Range, DeclarationName(),
1381                                      BasePath);
1382}
1383
1384
1385/// @brief Builds a string representing ambiguous paths from a
1386/// specific derived class to different subobjects of the same base
1387/// class.
1388///
1389/// This function builds a string that can be used in error messages
1390/// to show the different paths that one can take through the
1391/// inheritance hierarchy to go from the derived class to different
1392/// subobjects of a base class. The result looks something like this:
1393/// @code
1394/// struct D -> struct B -> struct A
1395/// struct D -> struct C -> struct A
1396/// @endcode
1397std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1398  std::string PathDisplayStr;
1399  std::set<unsigned> DisplayedPaths;
1400  for (CXXBasePaths::paths_iterator Path = Paths.begin();
1401       Path != Paths.end(); ++Path) {
1402    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1403      // We haven't displayed a path to this particular base
1404      // class subobject yet.
1405      PathDisplayStr += "\n    ";
1406      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1407      for (CXXBasePath::const_iterator Element = Path->begin();
1408           Element != Path->end(); ++Element)
1409        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1410    }
1411  }
1412
1413  return PathDisplayStr;
1414}
1415
1416//===----------------------------------------------------------------------===//
1417// C++ class member Handling
1418//===----------------------------------------------------------------------===//
1419
1420/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1421bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1422                                SourceLocation ASLoc,
1423                                SourceLocation ColonLoc,
1424                                AttributeList *Attrs) {
1425  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1426  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1427                                                  ASLoc, ColonLoc);
1428  CurContext->addHiddenDecl(ASDecl);
1429  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1430}
1431
1432/// CheckOverrideControl - Check C++11 override control semantics.
1433void Sema::CheckOverrideControl(Decl *D) {
1434  if (D->isInvalidDecl())
1435    return;
1436
1437  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1438
1439  // Do we know which functions this declaration might be overriding?
1440  bool OverridesAreKnown = !MD ||
1441      (!MD->getParent()->hasAnyDependentBases() &&
1442       !MD->getType()->isDependentType());
1443
1444  if (!MD || !MD->isVirtual()) {
1445    if (OverridesAreKnown) {
1446      if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1447        Diag(OA->getLocation(),
1448             diag::override_keyword_only_allowed_on_virtual_member_functions)
1449          << "override" << FixItHint::CreateRemoval(OA->getLocation());
1450        D->dropAttr<OverrideAttr>();
1451      }
1452      if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1453        Diag(FA->getLocation(),
1454             diag::override_keyword_only_allowed_on_virtual_member_functions)
1455          << "final" << FixItHint::CreateRemoval(FA->getLocation());
1456        D->dropAttr<FinalAttr>();
1457      }
1458    }
1459    return;
1460  }
1461
1462  if (!OverridesAreKnown)
1463    return;
1464
1465  // C++11 [class.virtual]p5:
1466  //   If a virtual function is marked with the virt-specifier override and
1467  //   does not override a member function of a base class, the program is
1468  //   ill-formed.
1469  bool HasOverriddenMethods =
1470    MD->begin_overridden_methods() != MD->end_overridden_methods();
1471  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1472    Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1473      << MD->getDeclName();
1474}
1475
1476/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1477/// function overrides a virtual member function marked 'final', according to
1478/// C++11 [class.virtual]p4.
1479bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1480                                                  const CXXMethodDecl *Old) {
1481  if (!Old->hasAttr<FinalAttr>())
1482    return false;
1483
1484  Diag(New->getLocation(), diag::err_final_function_overridden)
1485    << New->getDeclName();
1486  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1487  return true;
1488}
1489
1490static bool InitializationHasSideEffects(const FieldDecl &FD) {
1491  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1492  // FIXME: Destruction of ObjC lifetime types has side-effects.
1493  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1494    return !RD->isCompleteDefinition() ||
1495           !RD->hasTrivialDefaultConstructor() ||
1496           !RD->hasTrivialDestructor();
1497  return false;
1498}
1499
1500/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1501/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1502/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1503/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1504/// present (but parsing it has been deferred).
1505Decl *
1506Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1507                               MultiTemplateParamsArg TemplateParameterLists,
1508                               Expr *BW, const VirtSpecifiers &VS,
1509                               InClassInitStyle InitStyle) {
1510  const DeclSpec &DS = D.getDeclSpec();
1511  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1512  DeclarationName Name = NameInfo.getName();
1513  SourceLocation Loc = NameInfo.getLoc();
1514
1515  // For anonymous bitfields, the location should point to the type.
1516  if (Loc.isInvalid())
1517    Loc = D.getLocStart();
1518
1519  Expr *BitWidth = static_cast<Expr*>(BW);
1520
1521  assert(isa<CXXRecordDecl>(CurContext));
1522  assert(!DS.isFriendSpecified());
1523
1524  bool isFunc = D.isDeclarationOfFunction();
1525
1526  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1527    // The Microsoft extension __interface only permits public member functions
1528    // and prohibits constructors, destructors, operators, non-public member
1529    // functions, static methods and data members.
1530    unsigned InvalidDecl;
1531    bool ShowDeclName = true;
1532    if (!isFunc)
1533      InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1534    else if (AS != AS_public)
1535      InvalidDecl = 2;
1536    else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1537      InvalidDecl = 3;
1538    else switch (Name.getNameKind()) {
1539      case DeclarationName::CXXConstructorName:
1540        InvalidDecl = 4;
1541        ShowDeclName = false;
1542        break;
1543
1544      case DeclarationName::CXXDestructorName:
1545        InvalidDecl = 5;
1546        ShowDeclName = false;
1547        break;
1548
1549      case DeclarationName::CXXOperatorName:
1550      case DeclarationName::CXXConversionFunctionName:
1551        InvalidDecl = 6;
1552        break;
1553
1554      default:
1555        InvalidDecl = 0;
1556        break;
1557    }
1558
1559    if (InvalidDecl) {
1560      if (ShowDeclName)
1561        Diag(Loc, diag::err_invalid_member_in_interface)
1562          << (InvalidDecl-1) << Name;
1563      else
1564        Diag(Loc, diag::err_invalid_member_in_interface)
1565          << (InvalidDecl-1) << "";
1566      return 0;
1567    }
1568  }
1569
1570  // C++ 9.2p6: A member shall not be declared to have automatic storage
1571  // duration (auto, register) or with the extern storage-class-specifier.
1572  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1573  // data members and cannot be applied to names declared const or static,
1574  // and cannot be applied to reference members.
1575  switch (DS.getStorageClassSpec()) {
1576    case DeclSpec::SCS_unspecified:
1577    case DeclSpec::SCS_typedef:
1578    case DeclSpec::SCS_static:
1579      // FALL THROUGH.
1580      break;
1581    case DeclSpec::SCS_mutable:
1582      if (isFunc) {
1583        if (DS.getStorageClassSpecLoc().isValid())
1584          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1585        else
1586          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1587
1588        // FIXME: It would be nicer if the keyword was ignored only for this
1589        // declarator. Otherwise we could get follow-up errors.
1590        D.getMutableDeclSpec().ClearStorageClassSpecs();
1591      }
1592      break;
1593    default:
1594      if (DS.getStorageClassSpecLoc().isValid())
1595        Diag(DS.getStorageClassSpecLoc(),
1596             diag::err_storageclass_invalid_for_member);
1597      else
1598        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1599      D.getMutableDeclSpec().ClearStorageClassSpecs();
1600  }
1601
1602  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1603                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1604                      !isFunc);
1605
1606  Decl *Member;
1607  if (isInstField) {
1608    CXXScopeSpec &SS = D.getCXXScopeSpec();
1609
1610    // Data members must have identifiers for names.
1611    if (!Name.isIdentifier()) {
1612      Diag(Loc, diag::err_bad_variable_name)
1613        << Name;
1614      return 0;
1615    }
1616
1617    IdentifierInfo *II = Name.getAsIdentifierInfo();
1618
1619    // Member field could not be with "template" keyword.
1620    // So TemplateParameterLists should be empty in this case.
1621    if (TemplateParameterLists.size()) {
1622      TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1623      if (TemplateParams->size()) {
1624        // There is no such thing as a member field template.
1625        Diag(D.getIdentifierLoc(), diag::err_template_member)
1626            << II
1627            << SourceRange(TemplateParams->getTemplateLoc(),
1628                TemplateParams->getRAngleLoc());
1629      } else {
1630        // There is an extraneous 'template<>' for this member.
1631        Diag(TemplateParams->getTemplateLoc(),
1632            diag::err_template_member_noparams)
1633            << II
1634            << SourceRange(TemplateParams->getTemplateLoc(),
1635                TemplateParams->getRAngleLoc());
1636      }
1637      return 0;
1638    }
1639
1640    if (SS.isSet() && !SS.isInvalid()) {
1641      // The user provided a superfluous scope specifier inside a class
1642      // definition:
1643      //
1644      // class X {
1645      //   int X::member;
1646      // };
1647      if (DeclContext *DC = computeDeclContext(SS, false))
1648        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1649      else
1650        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1651          << Name << SS.getRange();
1652
1653      SS.clear();
1654    }
1655
1656    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1657                         InitStyle, AS);
1658    assert(Member && "HandleField never returns null");
1659  } else {
1660    assert(InitStyle == ICIS_NoInit);
1661
1662    Member = HandleDeclarator(S, D, TemplateParameterLists);
1663    if (!Member) {
1664      return 0;
1665    }
1666
1667    // Non-instance-fields can't have a bitfield.
1668    if (BitWidth) {
1669      if (Member->isInvalidDecl()) {
1670        // don't emit another diagnostic.
1671      } else if (isa<VarDecl>(Member)) {
1672        // C++ 9.6p3: A bit-field shall not be a static member.
1673        // "static member 'A' cannot be a bit-field"
1674        Diag(Loc, diag::err_static_not_bitfield)
1675          << Name << BitWidth->getSourceRange();
1676      } else if (isa<TypedefDecl>(Member)) {
1677        // "typedef member 'x' cannot be a bit-field"
1678        Diag(Loc, diag::err_typedef_not_bitfield)
1679          << Name << BitWidth->getSourceRange();
1680      } else {
1681        // A function typedef ("typedef int f(); f a;").
1682        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1683        Diag(Loc, diag::err_not_integral_type_bitfield)
1684          << Name << cast<ValueDecl>(Member)->getType()
1685          << BitWidth->getSourceRange();
1686      }
1687
1688      BitWidth = 0;
1689      Member->setInvalidDecl();
1690    }
1691
1692    Member->setAccess(AS);
1693
1694    // If we have declared a member function template, set the access of the
1695    // templated declaration as well.
1696    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1697      FunTmpl->getTemplatedDecl()->setAccess(AS);
1698  }
1699
1700  if (VS.isOverrideSpecified())
1701    Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1702  if (VS.isFinalSpecified())
1703    Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1704
1705  if (VS.getLastLocation().isValid()) {
1706    // Update the end location of a method that has a virt-specifiers.
1707    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1708      MD->setRangeEnd(VS.getLastLocation());
1709  }
1710
1711  CheckOverrideControl(Member);
1712
1713  assert((Name || isInstField) && "No identifier for non-field ?");
1714
1715  if (isInstField) {
1716    FieldDecl *FD = cast<FieldDecl>(Member);
1717    FieldCollector->Add(FD);
1718
1719    if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1720                                 FD->getLocation())
1721          != DiagnosticsEngine::Ignored) {
1722      // Remember all explicit private FieldDecls that have a name, no side
1723      // effects and are not part of a dependent type declaration.
1724      if (!FD->isImplicit() && FD->getDeclName() &&
1725          FD->getAccess() == AS_private &&
1726          !FD->hasAttr<UnusedAttr>() &&
1727          !FD->getParent()->isDependentContext() &&
1728          !InitializationHasSideEffects(*FD))
1729        UnusedPrivateFields.insert(FD);
1730    }
1731  }
1732
1733  return Member;
1734}
1735
1736namespace {
1737  class UninitializedFieldVisitor
1738      : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1739    Sema &S;
1740    ValueDecl *VD;
1741  public:
1742    typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1743    UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
1744                                                        S(S), VD(VD) {
1745    }
1746
1747    void HandleExpr(Expr *E) {
1748      if (!E) return;
1749
1750      // Expressions like x(x) sometimes lack the surrounding expressions
1751      // but need to be checked anyways.
1752      HandleValue(E);
1753      Visit(E);
1754    }
1755
1756    void HandleValue(Expr *E) {
1757      E = E->IgnoreParens();
1758
1759      if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1760        if (isa<EnumConstantDecl>(ME->getMemberDecl()))
1761            return;
1762        Expr *Base = E;
1763        while (isa<MemberExpr>(Base)) {
1764          ME = dyn_cast<MemberExpr>(Base);
1765          if (VarDecl *VarD = dyn_cast<VarDecl>(ME->getMemberDecl()))
1766            if (VarD->hasGlobalStorage())
1767              return;
1768          Base = ME->getBase();
1769        }
1770
1771        if (VD == ME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
1772          unsigned diag = VD->getType()->isReferenceType()
1773              ? diag::warn_reference_field_is_uninit
1774              : diag::warn_field_is_uninit;
1775          S.Diag(ME->getExprLoc(), diag) << ME->getMemberNameInfo().getName();
1776          return;
1777        }
1778      }
1779
1780      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1781        HandleValue(CO->getTrueExpr());
1782        HandleValue(CO->getFalseExpr());
1783        return;
1784      }
1785
1786      if (BinaryConditionalOperator *BCO =
1787              dyn_cast<BinaryConditionalOperator>(E)) {
1788        HandleValue(BCO->getCommon());
1789        HandleValue(BCO->getFalseExpr());
1790        return;
1791      }
1792
1793      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1794        switch (BO->getOpcode()) {
1795        default:
1796          return;
1797        case(BO_PtrMemD):
1798        case(BO_PtrMemI):
1799          HandleValue(BO->getLHS());
1800          return;
1801        case(BO_Comma):
1802          HandleValue(BO->getRHS());
1803          return;
1804        }
1805      }
1806    }
1807
1808    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1809      if (E->getCastKind() == CK_LValueToRValue)
1810        HandleValue(E->getSubExpr());
1811
1812      Inherited::VisitImplicitCastExpr(E);
1813    }
1814
1815    void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1816      Expr *Callee = E->getCallee();
1817      if (isa<MemberExpr>(Callee))
1818        HandleValue(Callee);
1819
1820      Inherited::VisitCXXMemberCallExpr(E);
1821    }
1822  };
1823  static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1824                                                       ValueDecl *VD) {
1825    UninitializedFieldVisitor(S, VD).HandleExpr(E);
1826  }
1827} // namespace
1828
1829/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1830/// in-class initializer for a non-static C++ class member, and after
1831/// instantiating an in-class initializer in a class template. Such actions
1832/// are deferred until the class is complete.
1833void
1834Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
1835                                       Expr *InitExpr) {
1836  FieldDecl *FD = cast<FieldDecl>(D);
1837  assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1838         "must set init style when field is created");
1839
1840  if (!InitExpr) {
1841    FD->setInvalidDecl();
1842    FD->removeInClassInitializer();
1843    return;
1844  }
1845
1846  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1847    FD->setInvalidDecl();
1848    FD->removeInClassInitializer();
1849    return;
1850  }
1851
1852  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1853      != DiagnosticsEngine::Ignored) {
1854    CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1855  }
1856
1857  ExprResult Init = InitExpr;
1858  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent() &&
1859      !FD->getDeclContext()->isDependentContext()) {
1860    // Note: We don't type-check when we're in a dependent context, because
1861    // the initialization-substitution code does not properly handle direct
1862    // list initialization. We have the same hackaround for ctor-initializers.
1863    if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
1864      Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
1865        << /*at end of ctor*/1 << InitExpr->getSourceRange();
1866    }
1867    Expr **Inits = &InitExpr;
1868    unsigned NumInits = 1;
1869    InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1870    InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
1871        ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1872        : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
1873    InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1874    Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
1875    if (Init.isInvalid()) {
1876      FD->setInvalidDecl();
1877      return;
1878    }
1879
1880    CheckImplicitConversions(Init.get(), InitLoc);
1881  }
1882
1883  // C++0x [class.base.init]p7:
1884  //   The initialization of each base and member constitutes a
1885  //   full-expression.
1886  Init = MaybeCreateExprWithCleanups(Init);
1887  if (Init.isInvalid()) {
1888    FD->setInvalidDecl();
1889    return;
1890  }
1891
1892  InitExpr = Init.release();
1893
1894  FD->setInClassInitializer(InitExpr);
1895}
1896
1897/// \brief Find the direct and/or virtual base specifiers that
1898/// correspond to the given base type, for use in base initialization
1899/// within a constructor.
1900static bool FindBaseInitializer(Sema &SemaRef,
1901                                CXXRecordDecl *ClassDecl,
1902                                QualType BaseType,
1903                                const CXXBaseSpecifier *&DirectBaseSpec,
1904                                const CXXBaseSpecifier *&VirtualBaseSpec) {
1905  // First, check for a direct base class.
1906  DirectBaseSpec = 0;
1907  for (CXXRecordDecl::base_class_const_iterator Base
1908         = ClassDecl->bases_begin();
1909       Base != ClassDecl->bases_end(); ++Base) {
1910    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1911      // We found a direct base of this type. That's what we're
1912      // initializing.
1913      DirectBaseSpec = &*Base;
1914      break;
1915    }
1916  }
1917
1918  // Check for a virtual base class.
1919  // FIXME: We might be able to short-circuit this if we know in advance that
1920  // there are no virtual bases.
1921  VirtualBaseSpec = 0;
1922  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1923    // We haven't found a base yet; search the class hierarchy for a
1924    // virtual base class.
1925    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1926                       /*DetectVirtual=*/false);
1927    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1928                              BaseType, Paths)) {
1929      for (CXXBasePaths::paths_iterator Path = Paths.begin();
1930           Path != Paths.end(); ++Path) {
1931        if (Path->back().Base->isVirtual()) {
1932          VirtualBaseSpec = Path->back().Base;
1933          break;
1934        }
1935      }
1936    }
1937  }
1938
1939  return DirectBaseSpec || VirtualBaseSpec;
1940}
1941
1942/// \brief Handle a C++ member initializer using braced-init-list syntax.
1943MemInitResult
1944Sema::ActOnMemInitializer(Decl *ConstructorD,
1945                          Scope *S,
1946                          CXXScopeSpec &SS,
1947                          IdentifierInfo *MemberOrBase,
1948                          ParsedType TemplateTypeTy,
1949                          const DeclSpec &DS,
1950                          SourceLocation IdLoc,
1951                          Expr *InitList,
1952                          SourceLocation EllipsisLoc) {
1953  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1954                             DS, IdLoc, InitList,
1955                             EllipsisLoc);
1956}
1957
1958/// \brief Handle a C++ member initializer using parentheses syntax.
1959MemInitResult
1960Sema::ActOnMemInitializer(Decl *ConstructorD,
1961                          Scope *S,
1962                          CXXScopeSpec &SS,
1963                          IdentifierInfo *MemberOrBase,
1964                          ParsedType TemplateTypeTy,
1965                          const DeclSpec &DS,
1966                          SourceLocation IdLoc,
1967                          SourceLocation LParenLoc,
1968                          Expr **Args, unsigned NumArgs,
1969                          SourceLocation RParenLoc,
1970                          SourceLocation EllipsisLoc) {
1971  Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
1972                                           llvm::makeArrayRef(Args, NumArgs),
1973                                           RParenLoc);
1974  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1975                             DS, IdLoc, List, EllipsisLoc);
1976}
1977
1978namespace {
1979
1980// Callback to only accept typo corrections that can be a valid C++ member
1981// intializer: either a non-static field member or a base class.
1982class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1983 public:
1984  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1985      : ClassDecl(ClassDecl) {}
1986
1987  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1988    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1989      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1990        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1991      else
1992        return isa<TypeDecl>(ND);
1993    }
1994    return false;
1995  }
1996
1997 private:
1998  CXXRecordDecl *ClassDecl;
1999};
2000
2001}
2002
2003/// \brief Handle a C++ member initializer.
2004MemInitResult
2005Sema::BuildMemInitializer(Decl *ConstructorD,
2006                          Scope *S,
2007                          CXXScopeSpec &SS,
2008                          IdentifierInfo *MemberOrBase,
2009                          ParsedType TemplateTypeTy,
2010                          const DeclSpec &DS,
2011                          SourceLocation IdLoc,
2012                          Expr *Init,
2013                          SourceLocation EllipsisLoc) {
2014  if (!ConstructorD)
2015    return true;
2016
2017  AdjustDeclIfTemplate(ConstructorD);
2018
2019  CXXConstructorDecl *Constructor
2020    = dyn_cast<CXXConstructorDecl>(ConstructorD);
2021  if (!Constructor) {
2022    // The user wrote a constructor initializer on a function that is
2023    // not a C++ constructor. Ignore the error for now, because we may
2024    // have more member initializers coming; we'll diagnose it just
2025    // once in ActOnMemInitializers.
2026    return true;
2027  }
2028
2029  CXXRecordDecl *ClassDecl = Constructor->getParent();
2030
2031  // C++ [class.base.init]p2:
2032  //   Names in a mem-initializer-id are looked up in the scope of the
2033  //   constructor's class and, if not found in that scope, are looked
2034  //   up in the scope containing the constructor's definition.
2035  //   [Note: if the constructor's class contains a member with the
2036  //   same name as a direct or virtual base class of the class, a
2037  //   mem-initializer-id naming the member or base class and composed
2038  //   of a single identifier refers to the class member. A
2039  //   mem-initializer-id for the hidden base class may be specified
2040  //   using a qualified name. ]
2041  if (!SS.getScopeRep() && !TemplateTypeTy) {
2042    // Look for a member, first.
2043    DeclContext::lookup_result Result
2044      = ClassDecl->lookup(MemberOrBase);
2045    if (Result.first != Result.second) {
2046      ValueDecl *Member;
2047      if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
2048          (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
2049        if (EllipsisLoc.isValid())
2050          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2051            << MemberOrBase
2052            << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2053
2054        return BuildMemberInitializer(Member, Init, IdLoc);
2055      }
2056    }
2057  }
2058  // It didn't name a member, so see if it names a class.
2059  QualType BaseType;
2060  TypeSourceInfo *TInfo = 0;
2061
2062  if (TemplateTypeTy) {
2063    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2064  } else if (DS.getTypeSpecType() == TST_decltype) {
2065    BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2066  } else {
2067    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2068    LookupParsedName(R, S, &SS);
2069
2070    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2071    if (!TyD) {
2072      if (R.isAmbiguous()) return true;
2073
2074      // We don't want access-control diagnostics here.
2075      R.suppressDiagnostics();
2076
2077      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2078        bool NotUnknownSpecialization = false;
2079        DeclContext *DC = computeDeclContext(SS, false);
2080        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2081          NotUnknownSpecialization = !Record->hasAnyDependentBases();
2082
2083        if (!NotUnknownSpecialization) {
2084          // When the scope specifier can refer to a member of an unknown
2085          // specialization, we take it as a type name.
2086          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2087                                       SS.getWithLocInContext(Context),
2088                                       *MemberOrBase, IdLoc);
2089          if (BaseType.isNull())
2090            return true;
2091
2092          R.clear();
2093          R.setLookupName(MemberOrBase);
2094        }
2095      }
2096
2097      // If no results were found, try to correct typos.
2098      TypoCorrection Corr;
2099      MemInitializerValidatorCCC Validator(ClassDecl);
2100      if (R.empty() && BaseType.isNull() &&
2101          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2102                              Validator, ClassDecl))) {
2103        std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2104        std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
2105        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2106          // We have found a non-static data member with a similar
2107          // name to what was typed; complain and initialize that
2108          // member.
2109          Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2110            << MemberOrBase << true << CorrectedQuotedStr
2111            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2112          Diag(Member->getLocation(), diag::note_previous_decl)
2113            << CorrectedQuotedStr;
2114
2115          return BuildMemberInitializer(Member, Init, IdLoc);
2116        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2117          const CXXBaseSpecifier *DirectBaseSpec;
2118          const CXXBaseSpecifier *VirtualBaseSpec;
2119          if (FindBaseInitializer(*this, ClassDecl,
2120                                  Context.getTypeDeclType(Type),
2121                                  DirectBaseSpec, VirtualBaseSpec)) {
2122            // We have found a direct or virtual base class with a
2123            // similar name to what was typed; complain and initialize
2124            // that base class.
2125            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2126              << MemberOrBase << false << CorrectedQuotedStr
2127              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2128
2129            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2130                                                             : VirtualBaseSpec;
2131            Diag(BaseSpec->getLocStart(),
2132                 diag::note_base_class_specified_here)
2133              << BaseSpec->getType()
2134              << BaseSpec->getSourceRange();
2135
2136            TyD = Type;
2137          }
2138        }
2139      }
2140
2141      if (!TyD && BaseType.isNull()) {
2142        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2143          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2144        return true;
2145      }
2146    }
2147
2148    if (BaseType.isNull()) {
2149      BaseType = Context.getTypeDeclType(TyD);
2150      if (SS.isSet()) {
2151        NestedNameSpecifier *Qualifier =
2152          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2153
2154        // FIXME: preserve source range information
2155        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
2156      }
2157    }
2158  }
2159
2160  if (!TInfo)
2161    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2162
2163  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2164}
2165
2166/// Checks a member initializer expression for cases where reference (or
2167/// pointer) members are bound to by-value parameters (or their addresses).
2168static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2169                                               Expr *Init,
2170                                               SourceLocation IdLoc) {
2171  QualType MemberTy = Member->getType();
2172
2173  // We only handle pointers and references currently.
2174  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2175  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2176    return;
2177
2178  const bool IsPointer = MemberTy->isPointerType();
2179  if (IsPointer) {
2180    if (const UnaryOperator *Op
2181          = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2182      // The only case we're worried about with pointers requires taking the
2183      // address.
2184      if (Op->getOpcode() != UO_AddrOf)
2185        return;
2186
2187      Init = Op->getSubExpr();
2188    } else {
2189      // We only handle address-of expression initializers for pointers.
2190      return;
2191    }
2192  }
2193
2194  if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2195    // Taking the address of a temporary will be diagnosed as a hard error.
2196    if (IsPointer)
2197      return;
2198
2199    S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2200      << Member << Init->getSourceRange();
2201  } else if (const DeclRefExpr *DRE
2202               = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2203    // We only warn when referring to a non-reference parameter declaration.
2204    const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2205    if (!Parameter || Parameter->getType()->isReferenceType())
2206      return;
2207
2208    S.Diag(Init->getExprLoc(),
2209           IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2210                     : diag::warn_bind_ref_member_to_parameter)
2211      << Member << Parameter << Init->getSourceRange();
2212  } else {
2213    // Other initializers are fine.
2214    return;
2215  }
2216
2217  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2218    << (unsigned)IsPointer;
2219}
2220
2221MemInitResult
2222Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2223                             SourceLocation IdLoc) {
2224  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2225  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2226  assert((DirectMember || IndirectMember) &&
2227         "Member must be a FieldDecl or IndirectFieldDecl");
2228
2229  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2230    return true;
2231
2232  if (Member->isInvalidDecl())
2233    return true;
2234
2235  // Diagnose value-uses of fields to initialize themselves, e.g.
2236  //   foo(foo)
2237  // where foo is not also a parameter to the constructor.
2238  // TODO: implement -Wuninitialized and fold this into that framework.
2239  Expr **Args;
2240  unsigned NumArgs;
2241  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2242    Args = ParenList->getExprs();
2243    NumArgs = ParenList->getNumExprs();
2244  } else {
2245    InitListExpr *InitList = cast<InitListExpr>(Init);
2246    Args = InitList->getInits();
2247    NumArgs = InitList->getNumInits();
2248  }
2249
2250  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2251        != DiagnosticsEngine::Ignored)
2252    for (unsigned i = 0; i < NumArgs; ++i)
2253      // FIXME: Warn about the case when other fields are used before being
2254      // initialized. For example, let this field be the i'th field. When
2255      // initializing the i'th field, throw a warning if any of the >= i'th
2256      // fields are used, as they are not yet initialized.
2257      // Right now we are only handling the case where the i'th field uses
2258      // itself in its initializer.
2259      // Also need to take into account that some fields may be initialized by
2260      // in-class initializers, see C++11 [class.base.init]p9.
2261      CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
2262
2263  SourceRange InitRange = Init->getSourceRange();
2264
2265  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2266    // Can't check initialization for a member of dependent type or when
2267    // any of the arguments are type-dependent expressions.
2268    DiscardCleanupsInEvaluationContext();
2269  } else {
2270    bool InitList = false;
2271    if (isa<InitListExpr>(Init)) {
2272      InitList = true;
2273      Args = &Init;
2274      NumArgs = 1;
2275
2276      if (isStdInitializerList(Member->getType(), 0)) {
2277        Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2278            << /*at end of ctor*/1 << InitRange;
2279      }
2280    }
2281
2282    // Initialize the member.
2283    InitializedEntity MemberEntity =
2284      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2285                   : InitializedEntity::InitializeMember(IndirectMember, 0);
2286    InitializationKind Kind =
2287      InitList ? InitializationKind::CreateDirectList(IdLoc)
2288               : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2289                                                  InitRange.getEnd());
2290
2291    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2292    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2293                                            MultiExprArg(Args, NumArgs),
2294                                            0);
2295    if (MemberInit.isInvalid())
2296      return true;
2297
2298    CheckImplicitConversions(MemberInit.get(),
2299                             InitRange.getBegin());
2300
2301    // C++0x [class.base.init]p7:
2302    //   The initialization of each base and member constitutes a
2303    //   full-expression.
2304    MemberInit = MaybeCreateExprWithCleanups(MemberInit);
2305    if (MemberInit.isInvalid())
2306      return true;
2307
2308    // If we are in a dependent context, template instantiation will
2309    // perform this type-checking again. Just save the arguments that we
2310    // received.
2311    // FIXME: This isn't quite ideal, since our ASTs don't capture all
2312    // of the information that we have about the member
2313    // initializer. However, deconstructing the ASTs is a dicey process,
2314    // and this approach is far more likely to get the corner cases right.
2315    if (CurContext->isDependentContext()) {
2316      // The existing Init will do fine.
2317    } else {
2318      Init = MemberInit.get();
2319      CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2320    }
2321  }
2322
2323  if (DirectMember) {
2324    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2325                                            InitRange.getBegin(), Init,
2326                                            InitRange.getEnd());
2327  } else {
2328    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2329                                            InitRange.getBegin(), Init,
2330                                            InitRange.getEnd());
2331  }
2332}
2333
2334MemInitResult
2335Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2336                                 CXXRecordDecl *ClassDecl) {
2337  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2338  if (!LangOpts.CPlusPlus0x)
2339    return Diag(NameLoc, diag::err_delegating_ctor)
2340      << TInfo->getTypeLoc().getLocalSourceRange();
2341  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2342
2343  bool InitList = true;
2344  Expr **Args = &Init;
2345  unsigned NumArgs = 1;
2346  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2347    InitList = false;
2348    Args = ParenList->getExprs();
2349    NumArgs = ParenList->getNumExprs();
2350  }
2351
2352  SourceRange InitRange = Init->getSourceRange();
2353  // Initialize the object.
2354  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2355                                     QualType(ClassDecl->getTypeForDecl(), 0));
2356  InitializationKind Kind =
2357    InitList ? InitializationKind::CreateDirectList(NameLoc)
2358             : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2359                                                InitRange.getEnd());
2360  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2361  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2362                                              MultiExprArg(Args, NumArgs),
2363                                              0);
2364  if (DelegationInit.isInvalid())
2365    return true;
2366
2367  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2368         "Delegating constructor with no target?");
2369
2370  CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
2371
2372  // C++0x [class.base.init]p7:
2373  //   The initialization of each base and member constitutes a
2374  //   full-expression.
2375  DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2376  if (DelegationInit.isInvalid())
2377    return true;
2378
2379  // If we are in a dependent context, template instantiation will
2380  // perform this type-checking again. Just save the arguments that we
2381  // received in a ParenListExpr.
2382  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2383  // of the information that we have about the base
2384  // initializer. However, deconstructing the ASTs is a dicey process,
2385  // and this approach is far more likely to get the corner cases right.
2386  if (CurContext->isDependentContext())
2387    DelegationInit = Owned(Init);
2388
2389  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2390                                          DelegationInit.takeAs<Expr>(),
2391                                          InitRange.getEnd());
2392}
2393
2394MemInitResult
2395Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2396                           Expr *Init, CXXRecordDecl *ClassDecl,
2397                           SourceLocation EllipsisLoc) {
2398  SourceLocation BaseLoc
2399    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2400
2401  if (!BaseType->isDependentType() && !BaseType->isRecordType())
2402    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2403             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2404
2405  // C++ [class.base.init]p2:
2406  //   [...] Unless the mem-initializer-id names a nonstatic data
2407  //   member of the constructor's class or a direct or virtual base
2408  //   of that class, the mem-initializer is ill-formed. A
2409  //   mem-initializer-list can initialize a base class using any
2410  //   name that denotes that base class type.
2411  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2412
2413  SourceRange InitRange = Init->getSourceRange();
2414  if (EllipsisLoc.isValid()) {
2415    // This is a pack expansion.
2416    if (!BaseType->containsUnexpandedParameterPack())  {
2417      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2418        << SourceRange(BaseLoc, InitRange.getEnd());
2419
2420      EllipsisLoc = SourceLocation();
2421    }
2422  } else {
2423    // Check for any unexpanded parameter packs.
2424    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2425      return true;
2426
2427    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2428      return true;
2429  }
2430
2431  // Check for direct and virtual base classes.
2432  const CXXBaseSpecifier *DirectBaseSpec = 0;
2433  const CXXBaseSpecifier *VirtualBaseSpec = 0;
2434  if (!Dependent) {
2435    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2436                                       BaseType))
2437      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2438
2439    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2440                        VirtualBaseSpec);
2441
2442    // C++ [base.class.init]p2:
2443    // Unless the mem-initializer-id names a nonstatic data member of the
2444    // constructor's class or a direct or virtual base of that class, the
2445    // mem-initializer is ill-formed.
2446    if (!DirectBaseSpec && !VirtualBaseSpec) {
2447      // If the class has any dependent bases, then it's possible that
2448      // one of those types will resolve to the same type as
2449      // BaseType. Therefore, just treat this as a dependent base
2450      // class initialization.  FIXME: Should we try to check the
2451      // initialization anyway? It seems odd.
2452      if (ClassDecl->hasAnyDependentBases())
2453        Dependent = true;
2454      else
2455        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2456          << BaseType << Context.getTypeDeclType(ClassDecl)
2457          << BaseTInfo->getTypeLoc().getLocalSourceRange();
2458    }
2459  }
2460
2461  if (Dependent) {
2462    DiscardCleanupsInEvaluationContext();
2463
2464    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2465                                            /*IsVirtual=*/false,
2466                                            InitRange.getBegin(), Init,
2467                                            InitRange.getEnd(), EllipsisLoc);
2468  }
2469
2470  // C++ [base.class.init]p2:
2471  //   If a mem-initializer-id is ambiguous because it designates both
2472  //   a direct non-virtual base class and an inherited virtual base
2473  //   class, the mem-initializer is ill-formed.
2474  if (DirectBaseSpec && VirtualBaseSpec)
2475    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2476      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2477
2478  CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2479  if (!BaseSpec)
2480    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2481
2482  // Initialize the base.
2483  bool InitList = true;
2484  Expr **Args = &Init;
2485  unsigned NumArgs = 1;
2486  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2487    InitList = false;
2488    Args = ParenList->getExprs();
2489    NumArgs = ParenList->getNumExprs();
2490  }
2491
2492  InitializedEntity BaseEntity =
2493    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2494  InitializationKind Kind =
2495    InitList ? InitializationKind::CreateDirectList(BaseLoc)
2496             : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2497                                                InitRange.getEnd());
2498  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2499  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2500                                        MultiExprArg(Args, NumArgs), 0);
2501  if (BaseInit.isInvalid())
2502    return true;
2503
2504  CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
2505
2506  // C++0x [class.base.init]p7:
2507  //   The initialization of each base and member constitutes a
2508  //   full-expression.
2509  BaseInit = MaybeCreateExprWithCleanups(BaseInit);
2510  if (BaseInit.isInvalid())
2511    return true;
2512
2513  // If we are in a dependent context, template instantiation will
2514  // perform this type-checking again. Just save the arguments that we
2515  // received in a ParenListExpr.
2516  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2517  // of the information that we have about the base
2518  // initializer. However, deconstructing the ASTs is a dicey process,
2519  // and this approach is far more likely to get the corner cases right.
2520  if (CurContext->isDependentContext())
2521    BaseInit = Owned(Init);
2522
2523  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2524                                          BaseSpec->isVirtual(),
2525                                          InitRange.getBegin(),
2526                                          BaseInit.takeAs<Expr>(),
2527                                          InitRange.getEnd(), EllipsisLoc);
2528}
2529
2530// Create a static_cast\<T&&>(expr).
2531static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2532  QualType ExprType = E->getType();
2533  QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2534  SourceLocation ExprLoc = E->getLocStart();
2535  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2536      TargetType, ExprLoc);
2537
2538  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2539                                   SourceRange(ExprLoc, ExprLoc),
2540                                   E->getSourceRange()).take();
2541}
2542
2543/// ImplicitInitializerKind - How an implicit base or member initializer should
2544/// initialize its base or member.
2545enum ImplicitInitializerKind {
2546  IIK_Default,
2547  IIK_Copy,
2548  IIK_Move
2549};
2550
2551static bool
2552BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2553                             ImplicitInitializerKind ImplicitInitKind,
2554                             CXXBaseSpecifier *BaseSpec,
2555                             bool IsInheritedVirtualBase,
2556                             CXXCtorInitializer *&CXXBaseInit) {
2557  InitializedEntity InitEntity
2558    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2559                                        IsInheritedVirtualBase);
2560
2561  ExprResult BaseInit;
2562
2563  switch (ImplicitInitKind) {
2564  case IIK_Default: {
2565    InitializationKind InitKind
2566      = InitializationKind::CreateDefault(Constructor->getLocation());
2567    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2568    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2569    break;
2570  }
2571
2572  case IIK_Move:
2573  case IIK_Copy: {
2574    bool Moving = ImplicitInitKind == IIK_Move;
2575    ParmVarDecl *Param = Constructor->getParamDecl(0);
2576    QualType ParamType = Param->getType().getNonReferenceType();
2577
2578    Expr *CopyCtorArg =
2579      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2580                          SourceLocation(), Param, false,
2581                          Constructor->getLocation(), ParamType,
2582                          VK_LValue, 0);
2583
2584    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2585
2586    // Cast to the base class to avoid ambiguities.
2587    QualType ArgTy =
2588      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2589                                       ParamType.getQualifiers());
2590
2591    if (Moving) {
2592      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2593    }
2594
2595    CXXCastPath BasePath;
2596    BasePath.push_back(BaseSpec);
2597    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2598                                            CK_UncheckedDerivedToBase,
2599                                            Moving ? VK_XValue : VK_LValue,
2600                                            &BasePath).take();
2601
2602    InitializationKind InitKind
2603      = InitializationKind::CreateDirect(Constructor->getLocation(),
2604                                         SourceLocation(), SourceLocation());
2605    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2606                                   &CopyCtorArg, 1);
2607    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2608                               MultiExprArg(&CopyCtorArg, 1));
2609    break;
2610  }
2611  }
2612
2613  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2614  if (BaseInit.isInvalid())
2615    return true;
2616
2617  CXXBaseInit =
2618    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2619               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2620                                                        SourceLocation()),
2621                                             BaseSpec->isVirtual(),
2622                                             SourceLocation(),
2623                                             BaseInit.takeAs<Expr>(),
2624                                             SourceLocation(),
2625                                             SourceLocation());
2626
2627  return false;
2628}
2629
2630static bool RefersToRValueRef(Expr *MemRef) {
2631  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2632  return Referenced->getType()->isRValueReferenceType();
2633}
2634
2635static bool
2636BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2637                               ImplicitInitializerKind ImplicitInitKind,
2638                               FieldDecl *Field, IndirectFieldDecl *Indirect,
2639                               CXXCtorInitializer *&CXXMemberInit) {
2640  if (Field->isInvalidDecl())
2641    return true;
2642
2643  SourceLocation Loc = Constructor->getLocation();
2644
2645  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2646    bool Moving = ImplicitInitKind == IIK_Move;
2647    ParmVarDecl *Param = Constructor->getParamDecl(0);
2648    QualType ParamType = Param->getType().getNonReferenceType();
2649
2650    // Suppress copying zero-width bitfields.
2651    if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2652      return false;
2653
2654    Expr *MemberExprBase =
2655      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2656                          SourceLocation(), Param, false,
2657                          Loc, ParamType, VK_LValue, 0);
2658
2659    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2660
2661    if (Moving) {
2662      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2663    }
2664
2665    // Build a reference to this field within the parameter.
2666    CXXScopeSpec SS;
2667    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2668                              Sema::LookupMemberName);
2669    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2670                                  : cast<ValueDecl>(Field), AS_public);
2671    MemberLookup.resolveKind();
2672    ExprResult CtorArg
2673      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2674                                         ParamType, Loc,
2675                                         /*IsArrow=*/false,
2676                                         SS,
2677                                         /*TemplateKWLoc=*/SourceLocation(),
2678                                         /*FirstQualifierInScope=*/0,
2679                                         MemberLookup,
2680                                         /*TemplateArgs=*/0);
2681    if (CtorArg.isInvalid())
2682      return true;
2683
2684    // C++11 [class.copy]p15:
2685    //   - if a member m has rvalue reference type T&&, it is direct-initialized
2686    //     with static_cast<T&&>(x.m);
2687    if (RefersToRValueRef(CtorArg.get())) {
2688      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2689    }
2690
2691    // When the field we are copying is an array, create index variables for
2692    // each dimension of the array. We use these index variables to subscript
2693    // the source array, and other clients (e.g., CodeGen) will perform the
2694    // necessary iteration with these index variables.
2695    SmallVector<VarDecl *, 4> IndexVariables;
2696    QualType BaseType = Field->getType();
2697    QualType SizeType = SemaRef.Context.getSizeType();
2698    bool InitializingArray = false;
2699    while (const ConstantArrayType *Array
2700                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2701      InitializingArray = true;
2702      // Create the iteration variable for this array index.
2703      IdentifierInfo *IterationVarName = 0;
2704      {
2705        SmallString<8> Str;
2706        llvm::raw_svector_ostream OS(Str);
2707        OS << "__i" << IndexVariables.size();
2708        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2709      }
2710      VarDecl *IterationVar
2711        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2712                          IterationVarName, SizeType,
2713                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2714                          SC_None, SC_None);
2715      IndexVariables.push_back(IterationVar);
2716
2717      // Create a reference to the iteration variable.
2718      ExprResult IterationVarRef
2719        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
2720      assert(!IterationVarRef.isInvalid() &&
2721             "Reference to invented variable cannot fail!");
2722      IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2723      assert(!IterationVarRef.isInvalid() &&
2724             "Conversion of invented variable cannot fail!");
2725
2726      // Subscript the array with this iteration variable.
2727      CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
2728                                                        IterationVarRef.take(),
2729                                                        Loc);
2730      if (CtorArg.isInvalid())
2731        return true;
2732
2733      BaseType = Array->getElementType();
2734    }
2735
2736    // The array subscript expression is an lvalue, which is wrong for moving.
2737    if (Moving && InitializingArray)
2738      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2739
2740    // Construct the entity that we will be initializing. For an array, this
2741    // will be first element in the array, which may require several levels
2742    // of array-subscript entities.
2743    SmallVector<InitializedEntity, 4> Entities;
2744    Entities.reserve(1 + IndexVariables.size());
2745    if (Indirect)
2746      Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2747    else
2748      Entities.push_back(InitializedEntity::InitializeMember(Field));
2749    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2750      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2751                                                              0,
2752                                                              Entities.back()));
2753
2754    // Direct-initialize to use the copy constructor.
2755    InitializationKind InitKind =
2756      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2757
2758    Expr *CtorArgE = CtorArg.takeAs<Expr>();
2759    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2760                                   &CtorArgE, 1);
2761
2762    ExprResult MemberInit
2763      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2764                        MultiExprArg(&CtorArgE, 1));
2765    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2766    if (MemberInit.isInvalid())
2767      return true;
2768
2769    if (Indirect) {
2770      assert(IndexVariables.size() == 0 &&
2771             "Indirect field improperly initialized");
2772      CXXMemberInit
2773        = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2774                                                   Loc, Loc,
2775                                                   MemberInit.takeAs<Expr>(),
2776                                                   Loc);
2777    } else
2778      CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2779                                                 Loc, MemberInit.takeAs<Expr>(),
2780                                                 Loc,
2781                                                 IndexVariables.data(),
2782                                                 IndexVariables.size());
2783    return false;
2784  }
2785
2786  assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2787
2788  QualType FieldBaseElementType =
2789    SemaRef.Context.getBaseElementType(Field->getType());
2790
2791  if (FieldBaseElementType->isRecordType()) {
2792    InitializedEntity InitEntity
2793      = Indirect? InitializedEntity::InitializeMember(Indirect)
2794                : InitializedEntity::InitializeMember(Field);
2795    InitializationKind InitKind =
2796      InitializationKind::CreateDefault(Loc);
2797
2798    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2799    ExprResult MemberInit =
2800      InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2801
2802    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2803    if (MemberInit.isInvalid())
2804      return true;
2805
2806    if (Indirect)
2807      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2808                                                               Indirect, Loc,
2809                                                               Loc,
2810                                                               MemberInit.get(),
2811                                                               Loc);
2812    else
2813      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2814                                                               Field, Loc, Loc,
2815                                                               MemberInit.get(),
2816                                                               Loc);
2817    return false;
2818  }
2819
2820  if (!Field->getParent()->isUnion()) {
2821    if (FieldBaseElementType->isReferenceType()) {
2822      SemaRef.Diag(Constructor->getLocation(),
2823                   diag::err_uninitialized_member_in_ctor)
2824      << (int)Constructor->isImplicit()
2825      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2826      << 0 << Field->getDeclName();
2827      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2828      return true;
2829    }
2830
2831    if (FieldBaseElementType.isConstQualified()) {
2832      SemaRef.Diag(Constructor->getLocation(),
2833                   diag::err_uninitialized_member_in_ctor)
2834      << (int)Constructor->isImplicit()
2835      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2836      << 1 << Field->getDeclName();
2837      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2838      return true;
2839    }
2840  }
2841
2842  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2843      FieldBaseElementType->isObjCRetainableType() &&
2844      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2845      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2846    // ARC:
2847    //   Default-initialize Objective-C pointers to NULL.
2848    CXXMemberInit
2849      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2850                                                 Loc, Loc,
2851                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2852                                                 Loc);
2853    return false;
2854  }
2855
2856  // Nothing to initialize.
2857  CXXMemberInit = 0;
2858  return false;
2859}
2860
2861namespace {
2862struct BaseAndFieldInfo {
2863  Sema &S;
2864  CXXConstructorDecl *Ctor;
2865  bool AnyErrorsInInits;
2866  ImplicitInitializerKind IIK;
2867  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2868  SmallVector<CXXCtorInitializer*, 8> AllToInit;
2869
2870  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2871    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2872    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2873    if (Generated && Ctor->isCopyConstructor())
2874      IIK = IIK_Copy;
2875    else if (Generated && Ctor->isMoveConstructor())
2876      IIK = IIK_Move;
2877    else
2878      IIK = IIK_Default;
2879  }
2880
2881  bool isImplicitCopyOrMove() const {
2882    switch (IIK) {
2883    case IIK_Copy:
2884    case IIK_Move:
2885      return true;
2886
2887    case IIK_Default:
2888      return false;
2889    }
2890
2891    llvm_unreachable("Invalid ImplicitInitializerKind!");
2892  }
2893
2894  bool addFieldInitializer(CXXCtorInitializer *Init) {
2895    AllToInit.push_back(Init);
2896
2897    // Check whether this initializer makes the field "used".
2898    if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2899      S.UnusedPrivateFields.remove(Init->getAnyMember());
2900
2901    return false;
2902  }
2903};
2904}
2905
2906/// \brief Determine whether the given indirect field declaration is somewhere
2907/// within an anonymous union.
2908static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2909  for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2910                                      CEnd = F->chain_end();
2911       C != CEnd; ++C)
2912    if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2913      if (Record->isUnion())
2914        return true;
2915
2916  return false;
2917}
2918
2919/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2920/// array type.
2921static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2922  if (T->isIncompleteArrayType())
2923    return true;
2924
2925  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2926    if (!ArrayT->getSize())
2927      return true;
2928
2929    T = ArrayT->getElementType();
2930  }
2931
2932  return false;
2933}
2934
2935static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
2936                                    FieldDecl *Field,
2937                                    IndirectFieldDecl *Indirect = 0) {
2938
2939  // Overwhelmingly common case: we have a direct initializer for this field.
2940  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
2941    return Info.addFieldInitializer(Init);
2942
2943  // C++11 [class.base.init]p8: if the entity is a non-static data member that
2944  // has a brace-or-equal-initializer, the entity is initialized as specified
2945  // in [dcl.init].
2946  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
2947    CXXCtorInitializer *Init;
2948    if (Indirect)
2949      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2950                                                      SourceLocation(),
2951                                                      SourceLocation(), 0,
2952                                                      SourceLocation());
2953    else
2954      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2955                                                      SourceLocation(),
2956                                                      SourceLocation(), 0,
2957                                                      SourceLocation());
2958    return Info.addFieldInitializer(Init);
2959  }
2960
2961  // Don't build an implicit initializer for union members if none was
2962  // explicitly specified.
2963  if (Field->getParent()->isUnion() ||
2964      (Indirect && isWithinAnonymousUnion(Indirect)))
2965    return false;
2966
2967  // Don't initialize incomplete or zero-length arrays.
2968  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2969    return false;
2970
2971  // Don't try to build an implicit initializer if there were semantic
2972  // errors in any of the initializers (and therefore we might be
2973  // missing some that the user actually wrote).
2974  if (Info.AnyErrorsInInits || Field->isInvalidDecl())
2975    return false;
2976
2977  CXXCtorInitializer *Init = 0;
2978  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2979                                     Indirect, Init))
2980    return true;
2981
2982  if (!Init)
2983    return false;
2984
2985  return Info.addFieldInitializer(Init);
2986}
2987
2988bool
2989Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2990                               CXXCtorInitializer *Initializer) {
2991  assert(Initializer->isDelegatingInitializer());
2992  Constructor->setNumCtorInitializers(1);
2993  CXXCtorInitializer **initializer =
2994    new (Context) CXXCtorInitializer*[1];
2995  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2996  Constructor->setCtorInitializers(initializer);
2997
2998  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2999    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3000    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3001  }
3002
3003  DelegatingCtorDecls.push_back(Constructor);
3004
3005  return false;
3006}
3007
3008bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
3009                               CXXCtorInitializer **Initializers,
3010                               unsigned NumInitializers,
3011                               bool AnyErrors) {
3012  if (Constructor->isDependentContext()) {
3013    // Just store the initializers as written, they will be checked during
3014    // instantiation.
3015    if (NumInitializers > 0) {
3016      Constructor->setNumCtorInitializers(NumInitializers);
3017      CXXCtorInitializer **baseOrMemberInitializers =
3018        new (Context) CXXCtorInitializer*[NumInitializers];
3019      memcpy(baseOrMemberInitializers, Initializers,
3020             NumInitializers * sizeof(CXXCtorInitializer*));
3021      Constructor->setCtorInitializers(baseOrMemberInitializers);
3022    }
3023
3024    // Let template instantiation know whether we had errors.
3025    if (AnyErrors)
3026      Constructor->setInvalidDecl();
3027
3028    return false;
3029  }
3030
3031  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3032
3033  // We need to build the initializer AST according to order of construction
3034  // and not what user specified in the Initializers list.
3035  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3036  if (!ClassDecl)
3037    return true;
3038
3039  bool HadError = false;
3040
3041  for (unsigned i = 0; i < NumInitializers; i++) {
3042    CXXCtorInitializer *Member = Initializers[i];
3043
3044    if (Member->isBaseInitializer())
3045      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3046    else
3047      Info.AllBaseFields[Member->getAnyMember()] = Member;
3048  }
3049
3050  // Keep track of the direct virtual bases.
3051  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3052  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3053       E = ClassDecl->bases_end(); I != E; ++I) {
3054    if (I->isVirtual())
3055      DirectVBases.insert(I);
3056  }
3057
3058  // Push virtual bases before others.
3059  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3060       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3061
3062    if (CXXCtorInitializer *Value
3063        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3064      Info.AllToInit.push_back(Value);
3065    } else if (!AnyErrors) {
3066      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3067      CXXCtorInitializer *CXXBaseInit;
3068      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3069                                       VBase, IsInheritedVirtualBase,
3070                                       CXXBaseInit)) {
3071        HadError = true;
3072        continue;
3073      }
3074
3075      Info.AllToInit.push_back(CXXBaseInit);
3076    }
3077  }
3078
3079  // Non-virtual bases.
3080  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3081       E = ClassDecl->bases_end(); Base != E; ++Base) {
3082    // Virtuals are in the virtual base list and already constructed.
3083    if (Base->isVirtual())
3084      continue;
3085
3086    if (CXXCtorInitializer *Value
3087          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3088      Info.AllToInit.push_back(Value);
3089    } else if (!AnyErrors) {
3090      CXXCtorInitializer *CXXBaseInit;
3091      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3092                                       Base, /*IsInheritedVirtualBase=*/false,
3093                                       CXXBaseInit)) {
3094        HadError = true;
3095        continue;
3096      }
3097
3098      Info.AllToInit.push_back(CXXBaseInit);
3099    }
3100  }
3101
3102  // Fields.
3103  for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3104                               MemEnd = ClassDecl->decls_end();
3105       Mem != MemEnd; ++Mem) {
3106    if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3107      // C++ [class.bit]p2:
3108      //   A declaration for a bit-field that omits the identifier declares an
3109      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3110      //   initialized.
3111      if (F->isUnnamedBitfield())
3112        continue;
3113
3114      // If we're not generating the implicit copy/move constructor, then we'll
3115      // handle anonymous struct/union fields based on their individual
3116      // indirect fields.
3117      if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3118        continue;
3119
3120      if (CollectFieldInitializer(*this, Info, F))
3121        HadError = true;
3122      continue;
3123    }
3124
3125    // Beyond this point, we only consider default initialization.
3126    if (Info.IIK != IIK_Default)
3127      continue;
3128
3129    if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3130      if (F->getType()->isIncompleteArrayType()) {
3131        assert(ClassDecl->hasFlexibleArrayMember() &&
3132               "Incomplete array type is not valid");
3133        continue;
3134      }
3135
3136      // Initialize each field of an anonymous struct individually.
3137      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3138        HadError = true;
3139
3140      continue;
3141    }
3142  }
3143
3144  NumInitializers = Info.AllToInit.size();
3145  if (NumInitializers > 0) {
3146    Constructor->setNumCtorInitializers(NumInitializers);
3147    CXXCtorInitializer **baseOrMemberInitializers =
3148      new (Context) CXXCtorInitializer*[NumInitializers];
3149    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3150           NumInitializers * sizeof(CXXCtorInitializer*));
3151    Constructor->setCtorInitializers(baseOrMemberInitializers);
3152
3153    // Constructors implicitly reference the base and member
3154    // destructors.
3155    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3156                                           Constructor->getParent());
3157  }
3158
3159  return HadError;
3160}
3161
3162static void *GetKeyForTopLevelField(FieldDecl *Field) {
3163  // For anonymous unions, use the class declaration as the key.
3164  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3165    if (RT->getDecl()->isAnonymousStructOrUnion())
3166      return static_cast<void *>(RT->getDecl());
3167  }
3168  return static_cast<void *>(Field);
3169}
3170
3171static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3172  return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3173}
3174
3175static void *GetKeyForMember(ASTContext &Context,
3176                             CXXCtorInitializer *Member) {
3177  if (!Member->isAnyMemberInitializer())
3178    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3179
3180  // For fields injected into the class via declaration of an anonymous union,
3181  // use its anonymous union class declaration as the unique key.
3182  FieldDecl *Field = Member->getAnyMember();
3183
3184  // If the field is a member of an anonymous struct or union, our key
3185  // is the anonymous record decl that's a direct child of the class.
3186  RecordDecl *RD = Field->getParent();
3187  if (RD->isAnonymousStructOrUnion()) {
3188    while (true) {
3189      RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3190      if (Parent->isAnonymousStructOrUnion())
3191        RD = Parent;
3192      else
3193        break;
3194    }
3195
3196    return static_cast<void *>(RD);
3197  }
3198
3199  return static_cast<void *>(Field);
3200}
3201
3202static void
3203DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
3204                                  const CXXConstructorDecl *Constructor,
3205                                  CXXCtorInitializer **Inits,
3206                                  unsigned NumInits) {
3207  if (Constructor->getDeclContext()->isDependentContext())
3208    return;
3209
3210  // Don't check initializers order unless the warning is enabled at the
3211  // location of at least one initializer.
3212  bool ShouldCheckOrder = false;
3213  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3214    CXXCtorInitializer *Init = Inits[InitIndex];
3215    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3216                                         Init->getSourceLocation())
3217          != DiagnosticsEngine::Ignored) {
3218      ShouldCheckOrder = true;
3219      break;
3220    }
3221  }
3222  if (!ShouldCheckOrder)
3223    return;
3224
3225  // Build the list of bases and members in the order that they'll
3226  // actually be initialized.  The explicit initializers should be in
3227  // this same order but may be missing things.
3228  SmallVector<const void*, 32> IdealInitKeys;
3229
3230  const CXXRecordDecl *ClassDecl = Constructor->getParent();
3231
3232  // 1. Virtual bases.
3233  for (CXXRecordDecl::base_class_const_iterator VBase =
3234       ClassDecl->vbases_begin(),
3235       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3236    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3237
3238  // 2. Non-virtual bases.
3239  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3240       E = ClassDecl->bases_end(); Base != E; ++Base) {
3241    if (Base->isVirtual())
3242      continue;
3243    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3244  }
3245
3246  // 3. Direct fields.
3247  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3248       E = ClassDecl->field_end(); Field != E; ++Field) {
3249    if (Field->isUnnamedBitfield())
3250      continue;
3251
3252    IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
3253  }
3254
3255  unsigned NumIdealInits = IdealInitKeys.size();
3256  unsigned IdealIndex = 0;
3257
3258  CXXCtorInitializer *PrevInit = 0;
3259  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3260    CXXCtorInitializer *Init = Inits[InitIndex];
3261    void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3262
3263    // Scan forward to try to find this initializer in the idealized
3264    // initializers list.
3265    for (; IdealIndex != NumIdealInits; ++IdealIndex)
3266      if (InitKey == IdealInitKeys[IdealIndex])
3267        break;
3268
3269    // If we didn't find this initializer, it must be because we
3270    // scanned past it on a previous iteration.  That can only
3271    // happen if we're out of order;  emit a warning.
3272    if (IdealIndex == NumIdealInits && PrevInit) {
3273      Sema::SemaDiagnosticBuilder D =
3274        SemaRef.Diag(PrevInit->getSourceLocation(),
3275                     diag::warn_initializer_out_of_order);
3276
3277      if (PrevInit->isAnyMemberInitializer())
3278        D << 0 << PrevInit->getAnyMember()->getDeclName();
3279      else
3280        D << 1 << PrevInit->getTypeSourceInfo()->getType();
3281
3282      if (Init->isAnyMemberInitializer())
3283        D << 0 << Init->getAnyMember()->getDeclName();
3284      else
3285        D << 1 << Init->getTypeSourceInfo()->getType();
3286
3287      // Move back to the initializer's location in the ideal list.
3288      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3289        if (InitKey == IdealInitKeys[IdealIndex])
3290          break;
3291
3292      assert(IdealIndex != NumIdealInits &&
3293             "initializer not found in initializer list");
3294    }
3295
3296    PrevInit = Init;
3297  }
3298}
3299
3300namespace {
3301bool CheckRedundantInit(Sema &S,
3302                        CXXCtorInitializer *Init,
3303                        CXXCtorInitializer *&PrevInit) {
3304  if (!PrevInit) {
3305    PrevInit = Init;
3306    return false;
3307  }
3308
3309  if (FieldDecl *Field = Init->getMember())
3310    S.Diag(Init->getSourceLocation(),
3311           diag::err_multiple_mem_initialization)
3312      << Field->getDeclName()
3313      << Init->getSourceRange();
3314  else {
3315    const Type *BaseClass = Init->getBaseClass();
3316    assert(BaseClass && "neither field nor base");
3317    S.Diag(Init->getSourceLocation(),
3318           diag::err_multiple_base_initialization)
3319      << QualType(BaseClass, 0)
3320      << Init->getSourceRange();
3321  }
3322  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3323    << 0 << PrevInit->getSourceRange();
3324
3325  return true;
3326}
3327
3328typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3329typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3330
3331bool CheckRedundantUnionInit(Sema &S,
3332                             CXXCtorInitializer *Init,
3333                             RedundantUnionMap &Unions) {
3334  FieldDecl *Field = Init->getAnyMember();
3335  RecordDecl *Parent = Field->getParent();
3336  NamedDecl *Child = Field;
3337
3338  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3339    if (Parent->isUnion()) {
3340      UnionEntry &En = Unions[Parent];
3341      if (En.first && En.first != Child) {
3342        S.Diag(Init->getSourceLocation(),
3343               diag::err_multiple_mem_union_initialization)
3344          << Field->getDeclName()
3345          << Init->getSourceRange();
3346        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3347          << 0 << En.second->getSourceRange();
3348        return true;
3349      }
3350      if (!En.first) {
3351        En.first = Child;
3352        En.second = Init;
3353      }
3354      if (!Parent->isAnonymousStructOrUnion())
3355        return false;
3356    }
3357
3358    Child = Parent;
3359    Parent = cast<RecordDecl>(Parent->getDeclContext());
3360  }
3361
3362  return false;
3363}
3364}
3365
3366/// ActOnMemInitializers - Handle the member initializers for a constructor.
3367void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3368                                SourceLocation ColonLoc,
3369                                CXXCtorInitializer **meminits,
3370                                unsigned NumMemInits,
3371                                bool AnyErrors) {
3372  if (!ConstructorDecl)
3373    return;
3374
3375  AdjustDeclIfTemplate(ConstructorDecl);
3376
3377  CXXConstructorDecl *Constructor
3378    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3379
3380  if (!Constructor) {
3381    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3382    return;
3383  }
3384
3385  CXXCtorInitializer **MemInits =
3386    reinterpret_cast<CXXCtorInitializer **>(meminits);
3387
3388  // Mapping for the duplicate initializers check.
3389  // For member initializers, this is keyed with a FieldDecl*.
3390  // For base initializers, this is keyed with a Type*.
3391  llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3392
3393  // Mapping for the inconsistent anonymous-union initializers check.
3394  RedundantUnionMap MemberUnions;
3395
3396  bool HadError = false;
3397  for (unsigned i = 0; i < NumMemInits; i++) {
3398    CXXCtorInitializer *Init = MemInits[i];
3399
3400    // Set the source order index.
3401    Init->setSourceOrder(i);
3402
3403    if (Init->isAnyMemberInitializer()) {
3404      FieldDecl *Field = Init->getAnyMember();
3405      if (CheckRedundantInit(*this, Init, Members[Field]) ||
3406          CheckRedundantUnionInit(*this, Init, MemberUnions))
3407        HadError = true;
3408    } else if (Init->isBaseInitializer()) {
3409      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3410      if (CheckRedundantInit(*this, Init, Members[Key]))
3411        HadError = true;
3412    } else {
3413      assert(Init->isDelegatingInitializer());
3414      // This must be the only initializer
3415      if (NumMemInits != 1) {
3416        Diag(Init->getSourceLocation(),
3417             diag::err_delegating_initializer_alone)
3418          << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3419        // We will treat this as being the only initializer.
3420      }
3421      SetDelegatingInitializer(Constructor, MemInits[i]);
3422      // Return immediately as the initializer is set.
3423      return;
3424    }
3425  }
3426
3427  if (HadError)
3428    return;
3429
3430  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
3431
3432  SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
3433}
3434
3435void
3436Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3437                                             CXXRecordDecl *ClassDecl) {
3438  // Ignore dependent contexts. Also ignore unions, since their members never
3439  // have destructors implicitly called.
3440  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3441    return;
3442
3443  // FIXME: all the access-control diagnostics are positioned on the
3444  // field/base declaration.  That's probably good; that said, the
3445  // user might reasonably want to know why the destructor is being
3446  // emitted, and we currently don't say.
3447
3448  // Non-static data members.
3449  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3450       E = ClassDecl->field_end(); I != E; ++I) {
3451    FieldDecl *Field = *I;
3452    if (Field->isInvalidDecl())
3453      continue;
3454
3455    // Don't destroy incomplete or zero-length arrays.
3456    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3457      continue;
3458
3459    QualType FieldType = Context.getBaseElementType(Field->getType());
3460
3461    const RecordType* RT = FieldType->getAs<RecordType>();
3462    if (!RT)
3463      continue;
3464
3465    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3466    if (FieldClassDecl->isInvalidDecl())
3467      continue;
3468    if (FieldClassDecl->hasIrrelevantDestructor())
3469      continue;
3470    // The destructor for an implicit anonymous union member is never invoked.
3471    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3472      continue;
3473
3474    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3475    assert(Dtor && "No dtor found for FieldClassDecl!");
3476    CheckDestructorAccess(Field->getLocation(), Dtor,
3477                          PDiag(diag::err_access_dtor_field)
3478                            << Field->getDeclName()
3479                            << FieldType);
3480
3481    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3482    DiagnoseUseOfDecl(Dtor, Location);
3483  }
3484
3485  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3486
3487  // Bases.
3488  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3489       E = ClassDecl->bases_end(); Base != E; ++Base) {
3490    // Bases are always records in a well-formed non-dependent class.
3491    const RecordType *RT = Base->getType()->getAs<RecordType>();
3492
3493    // Remember direct virtual bases.
3494    if (Base->isVirtual())
3495      DirectVirtualBases.insert(RT);
3496
3497    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3498    // If our base class is invalid, we probably can't get its dtor anyway.
3499    if (BaseClassDecl->isInvalidDecl())
3500      continue;
3501    if (BaseClassDecl->hasIrrelevantDestructor())
3502      continue;
3503
3504    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3505    assert(Dtor && "No dtor found for BaseClassDecl!");
3506
3507    // FIXME: caret should be on the start of the class name
3508    CheckDestructorAccess(Base->getLocStart(), Dtor,
3509                          PDiag(diag::err_access_dtor_base)
3510                            << Base->getType()
3511                            << Base->getSourceRange(),
3512                          Context.getTypeDeclType(ClassDecl));
3513
3514    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3515    DiagnoseUseOfDecl(Dtor, Location);
3516  }
3517
3518  // Virtual bases.
3519  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3520       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3521
3522    // Bases are always records in a well-formed non-dependent class.
3523    const RecordType *RT = VBase->getType()->castAs<RecordType>();
3524
3525    // Ignore direct virtual bases.
3526    if (DirectVirtualBases.count(RT))
3527      continue;
3528
3529    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3530    // If our base class is invalid, we probably can't get its dtor anyway.
3531    if (BaseClassDecl->isInvalidDecl())
3532      continue;
3533    if (BaseClassDecl->hasIrrelevantDestructor())
3534      continue;
3535
3536    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3537    assert(Dtor && "No dtor found for BaseClassDecl!");
3538    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3539                          PDiag(diag::err_access_dtor_vbase)
3540                            << VBase->getType(),
3541                          Context.getTypeDeclType(ClassDecl));
3542
3543    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3544    DiagnoseUseOfDecl(Dtor, Location);
3545  }
3546}
3547
3548void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3549  if (!CDtorDecl)
3550    return;
3551
3552  if (CXXConstructorDecl *Constructor
3553      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3554    SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
3555}
3556
3557bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3558                                  unsigned DiagID, AbstractDiagSelID SelID) {
3559  class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3560    unsigned DiagID;
3561    AbstractDiagSelID SelID;
3562
3563  public:
3564    NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3565      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3566
3567    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3568      if (Suppressed) return;
3569      if (SelID == -1)
3570        S.Diag(Loc, DiagID) << T;
3571      else
3572        S.Diag(Loc, DiagID) << SelID << T;
3573    }
3574  } Diagnoser(DiagID, SelID);
3575
3576  return RequireNonAbstractType(Loc, T, Diagnoser);
3577}
3578
3579bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3580                                  TypeDiagnoser &Diagnoser) {
3581  if (!getLangOpts().CPlusPlus)
3582    return false;
3583
3584  if (const ArrayType *AT = Context.getAsArrayType(T))
3585    return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3586
3587  if (const PointerType *PT = T->getAs<PointerType>()) {
3588    // Find the innermost pointer type.
3589    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3590      PT = T;
3591
3592    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3593      return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3594  }
3595
3596  const RecordType *RT = T->getAs<RecordType>();
3597  if (!RT)
3598    return false;
3599
3600  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3601
3602  // We can't answer whether something is abstract until it has a
3603  // definition.  If it's currently being defined, we'll walk back
3604  // over all the declarations when we have a full definition.
3605  const CXXRecordDecl *Def = RD->getDefinition();
3606  if (!Def || Def->isBeingDefined())
3607    return false;
3608
3609  if (!RD->isAbstract())
3610    return false;
3611
3612  Diagnoser.diagnose(*this, Loc, T);
3613  DiagnoseAbstractType(RD);
3614
3615  return true;
3616}
3617
3618void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3619  // Check if we've already emitted the list of pure virtual functions
3620  // for this class.
3621  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3622    return;
3623
3624  CXXFinalOverriderMap FinalOverriders;
3625  RD->getFinalOverriders(FinalOverriders);
3626
3627  // Keep a set of seen pure methods so we won't diagnose the same method
3628  // more than once.
3629  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3630
3631  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3632                                   MEnd = FinalOverriders.end();
3633       M != MEnd;
3634       ++M) {
3635    for (OverridingMethods::iterator SO = M->second.begin(),
3636                                  SOEnd = M->second.end();
3637         SO != SOEnd; ++SO) {
3638      // C++ [class.abstract]p4:
3639      //   A class is abstract if it contains or inherits at least one
3640      //   pure virtual function for which the final overrider is pure
3641      //   virtual.
3642
3643      //
3644      if (SO->second.size() != 1)
3645        continue;
3646
3647      if (!SO->second.front().Method->isPure())
3648        continue;
3649
3650      if (!SeenPureMethods.insert(SO->second.front().Method))
3651        continue;
3652
3653      Diag(SO->second.front().Method->getLocation(),
3654           diag::note_pure_virtual_function)
3655        << SO->second.front().Method->getDeclName() << RD->getDeclName();
3656    }
3657  }
3658
3659  if (!PureVirtualClassDiagSet)
3660    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3661  PureVirtualClassDiagSet->insert(RD);
3662}
3663
3664namespace {
3665struct AbstractUsageInfo {
3666  Sema &S;
3667  CXXRecordDecl *Record;
3668  CanQualType AbstractType;
3669  bool Invalid;
3670
3671  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3672    : S(S), Record(Record),
3673      AbstractType(S.Context.getCanonicalType(
3674                   S.Context.getTypeDeclType(Record))),
3675      Invalid(false) {}
3676
3677  void DiagnoseAbstractType() {
3678    if (Invalid) return;
3679    S.DiagnoseAbstractType(Record);
3680    Invalid = true;
3681  }
3682
3683  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3684};
3685
3686struct CheckAbstractUsage {
3687  AbstractUsageInfo &Info;
3688  const NamedDecl *Ctx;
3689
3690  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3691    : Info(Info), Ctx(Ctx) {}
3692
3693  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3694    switch (TL.getTypeLocClass()) {
3695#define ABSTRACT_TYPELOC(CLASS, PARENT)
3696#define TYPELOC(CLASS, PARENT) \
3697    case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3698#include "clang/AST/TypeLocNodes.def"
3699    }
3700  }
3701
3702  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3703    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3704    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3705      if (!TL.getArg(I))
3706        continue;
3707
3708      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3709      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3710    }
3711  }
3712
3713  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3714    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3715  }
3716
3717  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3718    // Visit the type parameters from a permissive context.
3719    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3720      TemplateArgumentLoc TAL = TL.getArgLoc(I);
3721      if (TAL.getArgument().getKind() == TemplateArgument::Type)
3722        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3723          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3724      // TODO: other template argument types?
3725    }
3726  }
3727
3728  // Visit pointee types from a permissive context.
3729#define CheckPolymorphic(Type) \
3730  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3731    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3732  }
3733  CheckPolymorphic(PointerTypeLoc)
3734  CheckPolymorphic(ReferenceTypeLoc)
3735  CheckPolymorphic(MemberPointerTypeLoc)
3736  CheckPolymorphic(BlockPointerTypeLoc)
3737  CheckPolymorphic(AtomicTypeLoc)
3738
3739  /// Handle all the types we haven't given a more specific
3740  /// implementation for above.
3741  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3742    // Every other kind of type that we haven't called out already
3743    // that has an inner type is either (1) sugar or (2) contains that
3744    // inner type in some way as a subobject.
3745    if (TypeLoc Next = TL.getNextTypeLoc())
3746      return Visit(Next, Sel);
3747
3748    // If there's no inner type and we're in a permissive context,
3749    // don't diagnose.
3750    if (Sel == Sema::AbstractNone) return;
3751
3752    // Check whether the type matches the abstract type.
3753    QualType T = TL.getType();
3754    if (T->isArrayType()) {
3755      Sel = Sema::AbstractArrayType;
3756      T = Info.S.Context.getBaseElementType(T);
3757    }
3758    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3759    if (CT != Info.AbstractType) return;
3760
3761    // It matched; do some magic.
3762    if (Sel == Sema::AbstractArrayType) {
3763      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3764        << T << TL.getSourceRange();
3765    } else {
3766      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3767        << Sel << T << TL.getSourceRange();
3768    }
3769    Info.DiagnoseAbstractType();
3770  }
3771};
3772
3773void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3774                                  Sema::AbstractDiagSelID Sel) {
3775  CheckAbstractUsage(*this, D).Visit(TL, Sel);
3776}
3777
3778}
3779
3780/// Check for invalid uses of an abstract type in a method declaration.
3781static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3782                                    CXXMethodDecl *MD) {
3783  // No need to do the check on definitions, which require that
3784  // the return/param types be complete.
3785  if (MD->doesThisDeclarationHaveABody())
3786    return;
3787
3788  // For safety's sake, just ignore it if we don't have type source
3789  // information.  This should never happen for non-implicit methods,
3790  // but...
3791  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3792    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3793}
3794
3795/// Check for invalid uses of an abstract type within a class definition.
3796static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3797                                    CXXRecordDecl *RD) {
3798  for (CXXRecordDecl::decl_iterator
3799         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3800    Decl *D = *I;
3801    if (D->isImplicit()) continue;
3802
3803    // Methods and method templates.
3804    if (isa<CXXMethodDecl>(D)) {
3805      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3806    } else if (isa<FunctionTemplateDecl>(D)) {
3807      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3808      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3809
3810    // Fields and static variables.
3811    } else if (isa<FieldDecl>(D)) {
3812      FieldDecl *FD = cast<FieldDecl>(D);
3813      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3814        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3815    } else if (isa<VarDecl>(D)) {
3816      VarDecl *VD = cast<VarDecl>(D);
3817      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3818        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3819
3820    // Nested classes and class templates.
3821    } else if (isa<CXXRecordDecl>(D)) {
3822      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3823    } else if (isa<ClassTemplateDecl>(D)) {
3824      CheckAbstractClassUsage(Info,
3825                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3826    }
3827  }
3828}
3829
3830/// \brief Perform semantic checks on a class definition that has been
3831/// completing, introducing implicitly-declared members, checking for
3832/// abstract types, etc.
3833void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3834  if (!Record)
3835    return;
3836
3837  if (Record->isAbstract() && !Record->isInvalidDecl()) {
3838    AbstractUsageInfo Info(*this, Record);
3839    CheckAbstractClassUsage(Info, Record);
3840  }
3841
3842  // If this is not an aggregate type and has no user-declared constructor,
3843  // complain about any non-static data members of reference or const scalar
3844  // type, since they will never get initializers.
3845  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3846      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3847      !Record->isLambda()) {
3848    bool Complained = false;
3849    for (RecordDecl::field_iterator F = Record->field_begin(),
3850                                 FEnd = Record->field_end();
3851         F != FEnd; ++F) {
3852      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
3853        continue;
3854
3855      if (F->getType()->isReferenceType() ||
3856          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3857        if (!Complained) {
3858          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3859            << Record->getTagKind() << Record;
3860          Complained = true;
3861        }
3862
3863        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3864          << F->getType()->isReferenceType()
3865          << F->getDeclName();
3866      }
3867    }
3868  }
3869
3870  if (Record->isDynamicClass() && !Record->isDependentType())
3871    DynamicClasses.push_back(Record);
3872
3873  if (Record->getIdentifier()) {
3874    // C++ [class.mem]p13:
3875    //   If T is the name of a class, then each of the following shall have a
3876    //   name different from T:
3877    //     - every member of every anonymous union that is a member of class T.
3878    //
3879    // C++ [class.mem]p14:
3880    //   In addition, if class T has a user-declared constructor (12.1), every
3881    //   non-static data member of class T shall have a name different from T.
3882    for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3883         R.first != R.second; ++R.first) {
3884      NamedDecl *D = *R.first;
3885      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3886          isa<IndirectFieldDecl>(D)) {
3887        Diag(D->getLocation(), diag::err_member_name_of_class)
3888          << D->getDeclName();
3889        break;
3890      }
3891    }
3892  }
3893
3894  // Warn if the class has virtual methods but non-virtual public destructor.
3895  if (Record->isPolymorphic() && !Record->isDependentType()) {
3896    CXXDestructorDecl *dtor = Record->getDestructor();
3897    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3898      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3899           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3900  }
3901
3902  if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
3903    Diag(Record->getLocation(), diag::warn_abstract_final_class);
3904    DiagnoseAbstractType(Record);
3905  }
3906
3907  // See if a method overloads virtual methods in a base
3908  /// class without overriding any.
3909  if (!Record->isDependentType()) {
3910    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3911                                     MEnd = Record->method_end();
3912         M != MEnd; ++M) {
3913      if (!M->isStatic())
3914        DiagnoseHiddenVirtualMethods(Record, *M);
3915    }
3916  }
3917
3918  // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3919  // function that is not a constructor declares that member function to be
3920  // const. [...] The class of which that function is a member shall be
3921  // a literal type.
3922  //
3923  // If the class has virtual bases, any constexpr members will already have
3924  // been diagnosed by the checks performed on the member declaration, so
3925  // suppress this (less useful) diagnostic.
3926  if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3927      !Record->isLiteral() && !Record->getNumVBases()) {
3928    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3929                                     MEnd = Record->method_end();
3930         M != MEnd; ++M) {
3931      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
3932        switch (Record->getTemplateSpecializationKind()) {
3933        case TSK_ImplicitInstantiation:
3934        case TSK_ExplicitInstantiationDeclaration:
3935        case TSK_ExplicitInstantiationDefinition:
3936          // If a template instantiates to a non-literal type, but its members
3937          // instantiate to constexpr functions, the template is technically
3938          // ill-formed, but we allow it for sanity.
3939          continue;
3940
3941        case TSK_Undeclared:
3942        case TSK_ExplicitSpecialization:
3943          RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
3944                             diag::err_constexpr_method_non_literal);
3945          break;
3946        }
3947
3948        // Only produce one error per class.
3949        break;
3950      }
3951    }
3952  }
3953
3954  // Declare inherited constructors. We do this eagerly here because:
3955  // - The standard requires an eager diagnostic for conflicting inherited
3956  //   constructors from different classes.
3957  // - The lazy declaration of the other implicit constructors is so as to not
3958  //   waste space and performance on classes that are not meant to be
3959  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
3960  //   have inherited constructors.
3961  DeclareInheritedConstructors(Record);
3962}
3963
3964void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3965  for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3966                                      ME = Record->method_end();
3967       MI != ME; ++MI)
3968    if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
3969      CheckExplicitlyDefaultedSpecialMember(*MI);
3970}
3971
3972/// Is the special member function which would be selected to perform the
3973/// specified operation on the specified class type a constexpr constructor?
3974static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3975                                     Sema::CXXSpecialMember CSM,
3976                                     bool ConstArg) {
3977  Sema::SpecialMemberOverloadResult *SMOR =
3978      S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
3979                            false, false, false, false);
3980  if (!SMOR || !SMOR->getMethod())
3981    // A constructor we wouldn't select can't be "involved in initializing"
3982    // anything.
3983    return true;
3984  return SMOR->getMethod()->isConstexpr();
3985}
3986
3987/// Determine whether the specified special member function would be constexpr
3988/// if it were implicitly defined.
3989static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3990                                              Sema::CXXSpecialMember CSM,
3991                                              bool ConstArg) {
3992  if (!S.getLangOpts().CPlusPlus0x)
3993    return false;
3994
3995  // C++11 [dcl.constexpr]p4:
3996  // In the definition of a constexpr constructor [...]
3997  switch (CSM) {
3998  case Sema::CXXDefaultConstructor:
3999    // Since default constructor lookup is essentially trivial (and cannot
4000    // involve, for instance, template instantiation), we compute whether a
4001    // defaulted default constructor is constexpr directly within CXXRecordDecl.
4002    //
4003    // This is important for performance; we need to know whether the default
4004    // constructor is constexpr to determine whether the type is a literal type.
4005    return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4006
4007  case Sema::CXXCopyConstructor:
4008  case Sema::CXXMoveConstructor:
4009    // For copy or move constructors, we need to perform overload resolution.
4010    break;
4011
4012  case Sema::CXXCopyAssignment:
4013  case Sema::CXXMoveAssignment:
4014  case Sema::CXXDestructor:
4015  case Sema::CXXInvalid:
4016    return false;
4017  }
4018
4019  //   -- if the class is a non-empty union, or for each non-empty anonymous
4020  //      union member of a non-union class, exactly one non-static data member
4021  //      shall be initialized; [DR1359]
4022  //
4023  // If we squint, this is guaranteed, since exactly one non-static data member
4024  // will be initialized (if the constructor isn't deleted), we just don't know
4025  // which one.
4026  if (ClassDecl->isUnion())
4027    return true;
4028
4029  //   -- the class shall not have any virtual base classes;
4030  if (ClassDecl->getNumVBases())
4031    return false;
4032
4033  //   -- every constructor involved in initializing [...] base class
4034  //      sub-objects shall be a constexpr constructor;
4035  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4036                                       BEnd = ClassDecl->bases_end();
4037       B != BEnd; ++B) {
4038    const RecordType *BaseType = B->getType()->getAs<RecordType>();
4039    if (!BaseType) continue;
4040
4041    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4042    if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4043      return false;
4044  }
4045
4046  //   -- every constructor involved in initializing non-static data members
4047  //      [...] shall be a constexpr constructor;
4048  //   -- every non-static data member and base class sub-object shall be
4049  //      initialized
4050  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4051                               FEnd = ClassDecl->field_end();
4052       F != FEnd; ++F) {
4053    if (F->isInvalidDecl())
4054      continue;
4055    if (const RecordType *RecordTy =
4056            S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4057      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4058      if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4059        return false;
4060    }
4061  }
4062
4063  // All OK, it's constexpr!
4064  return true;
4065}
4066
4067static Sema::ImplicitExceptionSpecification
4068computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4069  switch (S.getSpecialMember(MD)) {
4070  case Sema::CXXDefaultConstructor:
4071    return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4072  case Sema::CXXCopyConstructor:
4073    return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4074  case Sema::CXXCopyAssignment:
4075    return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4076  case Sema::CXXMoveConstructor:
4077    return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4078  case Sema::CXXMoveAssignment:
4079    return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4080  case Sema::CXXDestructor:
4081    return S.ComputeDefaultedDtorExceptionSpec(MD);
4082  case Sema::CXXInvalid:
4083    break;
4084  }
4085  llvm_unreachable("only special members have implicit exception specs");
4086}
4087
4088static void
4089updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4090                    const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4091  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4092  ExceptSpec.getEPI(EPI);
4093  const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4094    S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4095                              FPT->getNumArgs(), EPI));
4096  FD->setType(QualType(NewFPT, 0));
4097}
4098
4099void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4100  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4101  if (FPT->getExceptionSpecType() != EST_Unevaluated)
4102    return;
4103
4104  // Evaluate the exception specification.
4105  ImplicitExceptionSpecification ExceptSpec =
4106      computeImplicitExceptionSpec(*this, Loc, MD);
4107
4108  // Update the type of the special member to use it.
4109  updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4110
4111  // A user-provided destructor can be defined outside the class. When that
4112  // happens, be sure to update the exception specification on both
4113  // declarations.
4114  const FunctionProtoType *CanonicalFPT =
4115    MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4116  if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4117    updateExceptionSpec(*this, MD->getCanonicalDecl(),
4118                        CanonicalFPT, ExceptSpec);
4119}
4120
4121static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4122static bool isImplicitCopyAssignmentArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4123
4124void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4125  CXXRecordDecl *RD = MD->getParent();
4126  CXXSpecialMember CSM = getSpecialMember(MD);
4127
4128  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4129         "not an explicitly-defaulted special member");
4130
4131  // Whether this was the first-declared instance of the constructor.
4132  // This affects whether we implicitly add an exception spec and constexpr.
4133  bool First = MD == MD->getCanonicalDecl();
4134
4135  bool HadError = false;
4136
4137  // C++11 [dcl.fct.def.default]p1:
4138  //   A function that is explicitly defaulted shall
4139  //     -- be a special member function (checked elsewhere),
4140  //     -- have the same type (except for ref-qualifiers, and except that a
4141  //        copy operation can take a non-const reference) as an implicit
4142  //        declaration, and
4143  //     -- not have default arguments.
4144  unsigned ExpectedParams = 1;
4145  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4146    ExpectedParams = 0;
4147  if (MD->getNumParams() != ExpectedParams) {
4148    // This also checks for default arguments: a copy or move constructor with a
4149    // default argument is classified as a default constructor, and assignment
4150    // operations and destructors can't have default arguments.
4151    Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4152      << CSM << MD->getSourceRange();
4153    HadError = true;
4154  }
4155
4156  const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4157
4158  // Compute argument constness, constexpr, and triviality.
4159  bool CanHaveConstParam = false;
4160  bool Trivial = false;
4161  switch (CSM) {
4162  case CXXDefaultConstructor:
4163    Trivial = RD->hasTrivialDefaultConstructor();
4164    break;
4165  case CXXCopyConstructor:
4166    CanHaveConstParam = isImplicitCopyCtorArgConst(*this, RD);
4167    Trivial = RD->hasTrivialCopyConstructor();
4168    break;
4169  case CXXCopyAssignment:
4170    CanHaveConstParam = isImplicitCopyAssignmentArgConst(*this, RD);
4171    Trivial = RD->hasTrivialCopyAssignment();
4172    break;
4173  case CXXMoveConstructor:
4174    Trivial = RD->hasTrivialMoveConstructor();
4175    break;
4176  case CXXMoveAssignment:
4177    Trivial = RD->hasTrivialMoveAssignment();
4178    break;
4179  case CXXDestructor:
4180    Trivial = RD->hasTrivialDestructor();
4181    break;
4182  case CXXInvalid:
4183    llvm_unreachable("non-special member explicitly defaulted!");
4184  }
4185
4186  QualType ReturnType = Context.VoidTy;
4187  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4188    // Check for return type matching.
4189    ReturnType = Type->getResultType();
4190    QualType ExpectedReturnType =
4191        Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4192    if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4193      Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4194        << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4195      HadError = true;
4196    }
4197
4198    // A defaulted special member cannot have cv-qualifiers.
4199    if (Type->getTypeQuals()) {
4200      Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4201        << (CSM == CXXMoveAssignment);
4202      HadError = true;
4203    }
4204  }
4205
4206  // Check for parameter type matching.
4207  QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4208  bool HasConstParam = false;
4209  if (ExpectedParams && ArgType->isReferenceType()) {
4210    // Argument must be reference to possibly-const T.
4211    QualType ReferentType = ArgType->getPointeeType();
4212    HasConstParam = ReferentType.isConstQualified();
4213
4214    if (ReferentType.isVolatileQualified()) {
4215      Diag(MD->getLocation(),
4216           diag::err_defaulted_special_member_volatile_param) << CSM;
4217      HadError = true;
4218    }
4219
4220    if (HasConstParam && !CanHaveConstParam) {
4221      if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4222        Diag(MD->getLocation(),
4223             diag::err_defaulted_special_member_copy_const_param)
4224          << (CSM == CXXCopyAssignment);
4225        // FIXME: Explain why this special member can't be const.
4226      } else {
4227        Diag(MD->getLocation(),
4228             diag::err_defaulted_special_member_move_const_param)
4229          << (CSM == CXXMoveAssignment);
4230      }
4231      HadError = true;
4232    }
4233
4234    // If a function is explicitly defaulted on its first declaration, it shall
4235    // have the same parameter type as if it had been implicitly declared.
4236    // (Presumably this is to prevent it from being trivial?)
4237    if (!HasConstParam && CanHaveConstParam && First)
4238      Diag(MD->getLocation(),
4239           diag::err_defaulted_special_member_copy_non_const_param)
4240        << (CSM == CXXCopyAssignment);
4241  } else if (ExpectedParams) {
4242    // A copy assignment operator can take its argument by value, but a
4243    // defaulted one cannot.
4244    assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4245    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4246    HadError = true;
4247  }
4248
4249  // Rebuild the type with the implicit exception specification added, if we
4250  // are going to need it.
4251  const FunctionProtoType *ImplicitType = 0;
4252  if (First || Type->hasExceptionSpec()) {
4253    FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4254    computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4255    ImplicitType = cast<FunctionProtoType>(
4256      Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
4257  }
4258
4259  // C++11 [dcl.fct.def.default]p2:
4260  //   An explicitly-defaulted function may be declared constexpr only if it
4261  //   would have been implicitly declared as constexpr,
4262  // Do not apply this rule to members of class templates, since core issue 1358
4263  // makes such functions always instantiate to constexpr functions. For
4264  // non-constructors, this is checked elsewhere.
4265  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4266                                                     HasConstParam);
4267  if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4268      MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4269    Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4270    // FIXME: Explain why the constructor can't be constexpr.
4271    HadError = true;
4272  }
4273  //   and may have an explicit exception-specification only if it is compatible
4274  //   with the exception-specification on the implicit declaration.
4275  if (Type->hasExceptionSpec() &&
4276      CheckEquivalentExceptionSpec(
4277        PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
4278        PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
4279    HadError = true;
4280
4281  //   If a function is explicitly defaulted on its first declaration,
4282  if (First) {
4283    //  -- it is implicitly considered to be constexpr if the implicit
4284    //     definition would be,
4285    MD->setConstexpr(Constexpr);
4286
4287    //  -- it is implicitly considered to have the same exception-specification
4288    //     as if it had been implicitly declared,
4289    MD->setType(QualType(ImplicitType, 0));
4290
4291    // Such a function is also trivial if the implicitly-declared function
4292    // would have been.
4293    MD->setTrivial(Trivial);
4294  }
4295
4296  if (ShouldDeleteSpecialMember(MD, CSM)) {
4297    if (First) {
4298      MD->setDeletedAsWritten();
4299    } else {
4300      // C++11 [dcl.fct.def.default]p4:
4301      //   [For a] user-provided explicitly-defaulted function [...] if such a
4302      //   function is implicitly defined as deleted, the program is ill-formed.
4303      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4304      HadError = true;
4305    }
4306  }
4307
4308  if (HadError)
4309    MD->setInvalidDecl();
4310}
4311
4312namespace {
4313struct SpecialMemberDeletionInfo {
4314  Sema &S;
4315  CXXMethodDecl *MD;
4316  Sema::CXXSpecialMember CSM;
4317  bool Diagnose;
4318
4319  // Properties of the special member, computed for convenience.
4320  bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4321  SourceLocation Loc;
4322
4323  bool AllFieldsAreConst;
4324
4325  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4326                            Sema::CXXSpecialMember CSM, bool Diagnose)
4327    : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4328      IsConstructor(false), IsAssignment(false), IsMove(false),
4329      ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4330      AllFieldsAreConst(true) {
4331    switch (CSM) {
4332      case Sema::CXXDefaultConstructor:
4333      case Sema::CXXCopyConstructor:
4334        IsConstructor = true;
4335        break;
4336      case Sema::CXXMoveConstructor:
4337        IsConstructor = true;
4338        IsMove = true;
4339        break;
4340      case Sema::CXXCopyAssignment:
4341        IsAssignment = true;
4342        break;
4343      case Sema::CXXMoveAssignment:
4344        IsAssignment = true;
4345        IsMove = true;
4346        break;
4347      case Sema::CXXDestructor:
4348        break;
4349      case Sema::CXXInvalid:
4350        llvm_unreachable("invalid special member kind");
4351    }
4352
4353    if (MD->getNumParams()) {
4354      ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4355      VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4356    }
4357  }
4358
4359  bool inUnion() const { return MD->getParent()->isUnion(); }
4360
4361  /// Look up the corresponding special member in the given class.
4362  Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4363                                              unsigned Quals) {
4364    unsigned TQ = MD->getTypeQualifiers();
4365    // cv-qualifiers on class members don't affect default ctor / dtor calls.
4366    if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4367      Quals = 0;
4368    return S.LookupSpecialMember(Class, CSM,
4369                                 ConstArg || (Quals & Qualifiers::Const),
4370                                 VolatileArg || (Quals & Qualifiers::Volatile),
4371                                 MD->getRefQualifier() == RQ_RValue,
4372                                 TQ & Qualifiers::Const,
4373                                 TQ & Qualifiers::Volatile);
4374  }
4375
4376  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4377
4378  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4379  bool shouldDeleteForField(FieldDecl *FD);
4380  bool shouldDeleteForAllConstMembers();
4381
4382  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4383                                     unsigned Quals);
4384  bool shouldDeleteForSubobjectCall(Subobject Subobj,
4385                                    Sema::SpecialMemberOverloadResult *SMOR,
4386                                    bool IsDtorCallInCtor);
4387
4388  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4389};
4390}
4391
4392/// Is the given special member inaccessible when used on the given
4393/// sub-object.
4394bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4395                                             CXXMethodDecl *target) {
4396  /// If we're operating on a base class, the object type is the
4397  /// type of this special member.
4398  QualType objectTy;
4399  AccessSpecifier access = target->getAccess();
4400  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4401    objectTy = S.Context.getTypeDeclType(MD->getParent());
4402    access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4403
4404  // If we're operating on a field, the object type is the type of the field.
4405  } else {
4406    objectTy = S.Context.getTypeDeclType(target->getParent());
4407  }
4408
4409  return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4410}
4411
4412/// Check whether we should delete a special member due to the implicit
4413/// definition containing a call to a special member of a subobject.
4414bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4415    Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4416    bool IsDtorCallInCtor) {
4417  CXXMethodDecl *Decl = SMOR->getMethod();
4418  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4419
4420  int DiagKind = -1;
4421
4422  if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4423    DiagKind = !Decl ? 0 : 1;
4424  else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4425    DiagKind = 2;
4426  else if (!isAccessible(Subobj, Decl))
4427    DiagKind = 3;
4428  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4429           !Decl->isTrivial()) {
4430    // A member of a union must have a trivial corresponding special member.
4431    // As a weird special case, a destructor call from a union's constructor
4432    // must be accessible and non-deleted, but need not be trivial. Such a
4433    // destructor is never actually called, but is semantically checked as
4434    // if it were.
4435    DiagKind = 4;
4436  }
4437
4438  if (DiagKind == -1)
4439    return false;
4440
4441  if (Diagnose) {
4442    if (Field) {
4443      S.Diag(Field->getLocation(),
4444             diag::note_deleted_special_member_class_subobject)
4445        << CSM << MD->getParent() << /*IsField*/true
4446        << Field << DiagKind << IsDtorCallInCtor;
4447    } else {
4448      CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4449      S.Diag(Base->getLocStart(),
4450             diag::note_deleted_special_member_class_subobject)
4451        << CSM << MD->getParent() << /*IsField*/false
4452        << Base->getType() << DiagKind << IsDtorCallInCtor;
4453    }
4454
4455    if (DiagKind == 1)
4456      S.NoteDeletedFunction(Decl);
4457    // FIXME: Explain inaccessibility if DiagKind == 3.
4458  }
4459
4460  return true;
4461}
4462
4463/// Check whether we should delete a special member function due to having a
4464/// direct or virtual base class or non-static data member of class type M.
4465bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4466    CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
4467  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4468
4469  // C++11 [class.ctor]p5:
4470  // -- any direct or virtual base class, or non-static data member with no
4471  //    brace-or-equal-initializer, has class type M (or array thereof) and
4472  //    either M has no default constructor or overload resolution as applied
4473  //    to M's default constructor results in an ambiguity or in a function
4474  //    that is deleted or inaccessible
4475  // C++11 [class.copy]p11, C++11 [class.copy]p23:
4476  // -- a direct or virtual base class B that cannot be copied/moved because
4477  //    overload resolution, as applied to B's corresponding special member,
4478  //    results in an ambiguity or a function that is deleted or inaccessible
4479  //    from the defaulted special member
4480  // C++11 [class.dtor]p5:
4481  // -- any direct or virtual base class [...] has a type with a destructor
4482  //    that is deleted or inaccessible
4483  if (!(CSM == Sema::CXXDefaultConstructor &&
4484        Field && Field->hasInClassInitializer()) &&
4485      shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
4486    return true;
4487
4488  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4489  // -- any direct or virtual base class or non-static data member has a
4490  //    type with a destructor that is deleted or inaccessible
4491  if (IsConstructor) {
4492    Sema::SpecialMemberOverloadResult *SMOR =
4493        S.LookupSpecialMember(Class, Sema::CXXDestructor,
4494                              false, false, false, false, false);
4495    if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4496      return true;
4497  }
4498
4499  return false;
4500}
4501
4502/// Check whether we should delete a special member function due to the class
4503/// having a particular direct or virtual base class.
4504bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4505  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4506  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
4507}
4508
4509/// Check whether we should delete a special member function due to the class
4510/// having a particular non-static data member.
4511bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4512  QualType FieldType = S.Context.getBaseElementType(FD->getType());
4513  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4514
4515  if (CSM == Sema::CXXDefaultConstructor) {
4516    // For a default constructor, all references must be initialized in-class
4517    // and, if a union, it must have a non-const member.
4518    if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4519      if (Diagnose)
4520        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4521          << MD->getParent() << FD << FieldType << /*Reference*/0;
4522      return true;
4523    }
4524    // C++11 [class.ctor]p5: any non-variant non-static data member of
4525    // const-qualified type (or array thereof) with no
4526    // brace-or-equal-initializer does not have a user-provided default
4527    // constructor.
4528    if (!inUnion() && FieldType.isConstQualified() &&
4529        !FD->hasInClassInitializer() &&
4530        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4531      if (Diagnose)
4532        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4533          << MD->getParent() << FD << FD->getType() << /*Const*/1;
4534      return true;
4535    }
4536
4537    if (inUnion() && !FieldType.isConstQualified())
4538      AllFieldsAreConst = false;
4539  } else if (CSM == Sema::CXXCopyConstructor) {
4540    // For a copy constructor, data members must not be of rvalue reference
4541    // type.
4542    if (FieldType->isRValueReferenceType()) {
4543      if (Diagnose)
4544        S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4545          << MD->getParent() << FD << FieldType;
4546      return true;
4547    }
4548  } else if (IsAssignment) {
4549    // For an assignment operator, data members must not be of reference type.
4550    if (FieldType->isReferenceType()) {
4551      if (Diagnose)
4552        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4553          << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4554      return true;
4555    }
4556    if (!FieldRecord && FieldType.isConstQualified()) {
4557      // C++11 [class.copy]p23:
4558      // -- a non-static data member of const non-class type (or array thereof)
4559      if (Diagnose)
4560        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4561          << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
4562      return true;
4563    }
4564  }
4565
4566  if (FieldRecord) {
4567    // Some additional restrictions exist on the variant members.
4568    if (!inUnion() && FieldRecord->isUnion() &&
4569        FieldRecord->isAnonymousStructOrUnion()) {
4570      bool AllVariantFieldsAreConst = true;
4571
4572      // FIXME: Handle anonymous unions declared within anonymous unions.
4573      for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4574                                         UE = FieldRecord->field_end();
4575           UI != UE; ++UI) {
4576        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4577
4578        if (!UnionFieldType.isConstQualified())
4579          AllVariantFieldsAreConst = false;
4580
4581        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4582        if (UnionFieldRecord &&
4583            shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4584                                          UnionFieldType.getCVRQualifiers()))
4585          return true;
4586      }
4587
4588      // At least one member in each anonymous union must be non-const
4589      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4590          FieldRecord->field_begin() != FieldRecord->field_end()) {
4591        if (Diagnose)
4592          S.Diag(FieldRecord->getLocation(),
4593                 diag::note_deleted_default_ctor_all_const)
4594            << MD->getParent() << /*anonymous union*/1;
4595        return true;
4596      }
4597
4598      // Don't check the implicit member of the anonymous union type.
4599      // This is technically non-conformant, but sanity demands it.
4600      return false;
4601    }
4602
4603    if (shouldDeleteForClassSubobject(FieldRecord, FD,
4604                                      FieldType.getCVRQualifiers()))
4605      return true;
4606  }
4607
4608  return false;
4609}
4610
4611/// C++11 [class.ctor] p5:
4612///   A defaulted default constructor for a class X is defined as deleted if
4613/// X is a union and all of its variant members are of const-qualified type.
4614bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4615  // This is a silly definition, because it gives an empty union a deleted
4616  // default constructor. Don't do that.
4617  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4618      (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4619    if (Diagnose)
4620      S.Diag(MD->getParent()->getLocation(),
4621             diag::note_deleted_default_ctor_all_const)
4622        << MD->getParent() << /*not anonymous union*/0;
4623    return true;
4624  }
4625  return false;
4626}
4627
4628/// Determine whether a defaulted special member function should be defined as
4629/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4630/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
4631bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4632                                     bool Diagnose) {
4633  if (MD->isInvalidDecl())
4634    return false;
4635  CXXRecordDecl *RD = MD->getParent();
4636  assert(!RD->isDependentType() && "do deletion after instantiation");
4637  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4638    return false;
4639
4640  // C++11 [expr.lambda.prim]p19:
4641  //   The closure type associated with a lambda-expression has a
4642  //   deleted (8.4.3) default constructor and a deleted copy
4643  //   assignment operator.
4644  if (RD->isLambda() &&
4645      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4646    if (Diagnose)
4647      Diag(RD->getLocation(), diag::note_lambda_decl);
4648    return true;
4649  }
4650
4651  // For an anonymous struct or union, the copy and assignment special members
4652  // will never be used, so skip the check. For an anonymous union declared at
4653  // namespace scope, the constructor and destructor are used.
4654  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4655      RD->isAnonymousStructOrUnion())
4656    return false;
4657
4658  // C++11 [class.copy]p7, p18:
4659  //   If the class definition declares a move constructor or move assignment
4660  //   operator, an implicitly declared copy constructor or copy assignment
4661  //   operator is defined as deleted.
4662  if (MD->isImplicit() &&
4663      (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4664    CXXMethodDecl *UserDeclaredMove = 0;
4665
4666    // In Microsoft mode, a user-declared move only causes the deletion of the
4667    // corresponding copy operation, not both copy operations.
4668    if (RD->hasUserDeclaredMoveConstructor() &&
4669        (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4670      if (!Diagnose) return true;
4671      UserDeclaredMove = RD->getMoveConstructor();
4672      assert(UserDeclaredMove);
4673    } else if (RD->hasUserDeclaredMoveAssignment() &&
4674               (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4675      if (!Diagnose) return true;
4676      UserDeclaredMove = RD->getMoveAssignmentOperator();
4677      assert(UserDeclaredMove);
4678    }
4679
4680    if (UserDeclaredMove) {
4681      Diag(UserDeclaredMove->getLocation(),
4682           diag::note_deleted_copy_user_declared_move)
4683        << (CSM == CXXCopyAssignment) << RD
4684        << UserDeclaredMove->isMoveAssignmentOperator();
4685      return true;
4686    }
4687  }
4688
4689  // Do access control from the special member function
4690  ContextRAII MethodContext(*this, MD);
4691
4692  // C++11 [class.dtor]p5:
4693  // -- for a virtual destructor, lookup of the non-array deallocation function
4694  //    results in an ambiguity or in a function that is deleted or inaccessible
4695  if (CSM == CXXDestructor && MD->isVirtual()) {
4696    FunctionDecl *OperatorDelete = 0;
4697    DeclarationName Name =
4698      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4699    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
4700                                 OperatorDelete, false)) {
4701      if (Diagnose)
4702        Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
4703      return true;
4704    }
4705  }
4706
4707  SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
4708
4709  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4710                                          BE = RD->bases_end(); BI != BE; ++BI)
4711    if (!BI->isVirtual() &&
4712        SMI.shouldDeleteForBase(BI))
4713      return true;
4714
4715  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4716                                          BE = RD->vbases_end(); BI != BE; ++BI)
4717    if (SMI.shouldDeleteForBase(BI))
4718      return true;
4719
4720  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4721                                     FE = RD->field_end(); FI != FE; ++FI)
4722    if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4723        SMI.shouldDeleteForField(*FI))
4724      return true;
4725
4726  if (SMI.shouldDeleteForAllConstMembers())
4727    return true;
4728
4729  return false;
4730}
4731
4732/// \brief Data used with FindHiddenVirtualMethod
4733namespace {
4734  struct FindHiddenVirtualMethodData {
4735    Sema *S;
4736    CXXMethodDecl *Method;
4737    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4738    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4739  };
4740}
4741
4742/// \brief Member lookup function that determines whether a given C++
4743/// method overloads virtual methods in a base class without overriding any,
4744/// to be used with CXXRecordDecl::lookupInBases().
4745static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4746                                    CXXBasePath &Path,
4747                                    void *UserData) {
4748  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4749
4750  FindHiddenVirtualMethodData &Data
4751    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4752
4753  DeclarationName Name = Data.Method->getDeclName();
4754  assert(Name.getNameKind() == DeclarationName::Identifier);
4755
4756  bool foundSameNameMethod = false;
4757  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4758  for (Path.Decls = BaseRecord->lookup(Name);
4759       Path.Decls.first != Path.Decls.second;
4760       ++Path.Decls.first) {
4761    NamedDecl *D = *Path.Decls.first;
4762    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4763      MD = MD->getCanonicalDecl();
4764      foundSameNameMethod = true;
4765      // Interested only in hidden virtual methods.
4766      if (!MD->isVirtual())
4767        continue;
4768      // If the method we are checking overrides a method from its base
4769      // don't warn about the other overloaded methods.
4770      if (!Data.S->IsOverload(Data.Method, MD, false))
4771        return true;
4772      // Collect the overload only if its hidden.
4773      bool Using = Data.OverridenAndUsingBaseMethods.count(MD);
4774      for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4775                                          E = MD->end_overridden_methods();
4776           I != E && !Using; ++I)
4777        Using = Data.OverridenAndUsingBaseMethods.count(*I);
4778      if (!Using)
4779        overloadedMethods.push_back(MD);
4780    }
4781  }
4782
4783  if (foundSameNameMethod)
4784    Data.OverloadedMethods.append(overloadedMethods.begin(),
4785                                   overloadedMethods.end());
4786  return foundSameNameMethod;
4787}
4788
4789/// \brief See if a method overloads virtual methods in a base class without
4790/// overriding any.
4791void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4792  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4793                               MD->getLocation()) == DiagnosticsEngine::Ignored)
4794    return;
4795  if (!MD->getDeclName().isIdentifier())
4796    return;
4797
4798  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4799                     /*bool RecordPaths=*/false,
4800                     /*bool DetectVirtual=*/false);
4801  FindHiddenVirtualMethodData Data;
4802  Data.Method = MD;
4803  Data.S = this;
4804
4805  // Keep the base methods that were overriden or introduced in the subclass
4806  // by 'using' in a set. A base method not in this set is hidden.
4807  for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4808       res.first != res.second; ++res.first) {
4809    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4810      for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4811                                          E = MD->end_overridden_methods();
4812           I != E; ++I)
4813        Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
4814    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4815      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
4816        Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
4817  }
4818
4819  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4820      !Data.OverloadedMethods.empty()) {
4821    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4822      << MD << (Data.OverloadedMethods.size() > 1);
4823
4824    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4825      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4826      Diag(overloadedMD->getLocation(),
4827           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4828    }
4829  }
4830}
4831
4832void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4833                                             Decl *TagDecl,
4834                                             SourceLocation LBrac,
4835                                             SourceLocation RBrac,
4836                                             AttributeList *AttrList) {
4837  if (!TagDecl)
4838    return;
4839
4840  AdjustDeclIfTemplate(TagDecl);
4841
4842  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4843    if (l->getKind() != AttributeList::AT_Visibility)
4844      continue;
4845    l->setInvalid();
4846    Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
4847      l->getName();
4848  }
4849
4850  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
4851              // strict aliasing violation!
4852              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
4853              FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
4854
4855  CheckCompletedCXXClass(
4856                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
4857}
4858
4859/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4860/// special functions, such as the default constructor, copy
4861/// constructor, or destructor, to the given C++ class (C++
4862/// [special]p1).  This routine can only be executed just before the
4863/// definition of the class is complete.
4864void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
4865  if (!ClassDecl->hasUserDeclaredConstructor())
4866    ++ASTContext::NumImplicitDefaultConstructors;
4867
4868  if (!ClassDecl->hasUserDeclaredCopyConstructor())
4869    ++ASTContext::NumImplicitCopyConstructors;
4870
4871  if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
4872    ++ASTContext::NumImplicitMoveConstructors;
4873
4874  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4875    ++ASTContext::NumImplicitCopyAssignmentOperators;
4876
4877    // If we have a dynamic class, then the copy assignment operator may be
4878    // virtual, so we have to declare it immediately. This ensures that, e.g.,
4879    // it shows up in the right place in the vtable and that we diagnose
4880    // problems with the implicit exception specification.
4881    if (ClassDecl->isDynamicClass())
4882      DeclareImplicitCopyAssignment(ClassDecl);
4883  }
4884
4885  if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
4886    ++ASTContext::NumImplicitMoveAssignmentOperators;
4887
4888    // Likewise for the move assignment operator.
4889    if (ClassDecl->isDynamicClass())
4890      DeclareImplicitMoveAssignment(ClassDecl);
4891  }
4892
4893  if (!ClassDecl->hasUserDeclaredDestructor()) {
4894    ++ASTContext::NumImplicitDestructors;
4895
4896    // If we have a dynamic class, then the destructor may be virtual, so we
4897    // have to declare the destructor immediately. This ensures that, e.g., it
4898    // shows up in the right place in the vtable and that we diagnose problems
4899    // with the implicit exception specification.
4900    if (ClassDecl->isDynamicClass())
4901      DeclareImplicitDestructor(ClassDecl);
4902  }
4903}
4904
4905void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4906  if (!D)
4907    return;
4908
4909  int NumParamList = D->getNumTemplateParameterLists();
4910  for (int i = 0; i < NumParamList; i++) {
4911    TemplateParameterList* Params = D->getTemplateParameterList(i);
4912    for (TemplateParameterList::iterator Param = Params->begin(),
4913                                      ParamEnd = Params->end();
4914          Param != ParamEnd; ++Param) {
4915      NamedDecl *Named = cast<NamedDecl>(*Param);
4916      if (Named->getDeclName()) {
4917        S->AddDecl(Named);
4918        IdResolver.AddDecl(Named);
4919      }
4920    }
4921  }
4922}
4923
4924void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
4925  if (!D)
4926    return;
4927
4928  TemplateParameterList *Params = 0;
4929  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4930    Params = Template->getTemplateParameters();
4931  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4932           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4933    Params = PartialSpec->getTemplateParameters();
4934  else
4935    return;
4936
4937  for (TemplateParameterList::iterator Param = Params->begin(),
4938                                    ParamEnd = Params->end();
4939       Param != ParamEnd; ++Param) {
4940    NamedDecl *Named = cast<NamedDecl>(*Param);
4941    if (Named->getDeclName()) {
4942      S->AddDecl(Named);
4943      IdResolver.AddDecl(Named);
4944    }
4945  }
4946}
4947
4948void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4949  if (!RecordD) return;
4950  AdjustDeclIfTemplate(RecordD);
4951  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
4952  PushDeclContext(S, Record);
4953}
4954
4955void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4956  if (!RecordD) return;
4957  PopDeclContext();
4958}
4959
4960/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4961/// parsing a top-level (non-nested) C++ class, and we are now
4962/// parsing those parts of the given Method declaration that could
4963/// not be parsed earlier (C++ [class.mem]p2), such as default
4964/// arguments. This action should enter the scope of the given
4965/// Method declaration as if we had just parsed the qualified method
4966/// name. However, it should not bring the parameters into scope;
4967/// that will be performed by ActOnDelayedCXXMethodParameter.
4968void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4969}
4970
4971/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4972/// C++ method declaration. We're (re-)introducing the given
4973/// function parameter into scope for use in parsing later parts of
4974/// the method declaration. For example, we could see an
4975/// ActOnParamDefaultArgument event for this parameter.
4976void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
4977  if (!ParamD)
4978    return;
4979
4980  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
4981
4982  // If this parameter has an unparsed default argument, clear it out
4983  // to make way for the parsed default argument.
4984  if (Param->hasUnparsedDefaultArg())
4985    Param->setDefaultArg(0);
4986
4987  S->AddDecl(Param);
4988  if (Param->getDeclName())
4989    IdResolver.AddDecl(Param);
4990}
4991
4992/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4993/// processing the delayed method declaration for Method. The method
4994/// declaration is now considered finished. There may be a separate
4995/// ActOnStartOfFunctionDef action later (not necessarily
4996/// immediately!) for this method, if it was also defined inside the
4997/// class body.
4998void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4999  if (!MethodD)
5000    return;
5001
5002  AdjustDeclIfTemplate(MethodD);
5003
5004  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
5005
5006  // Now that we have our default arguments, check the constructor
5007  // again. It could produce additional diagnostics or affect whether
5008  // the class has implicitly-declared destructors, among other
5009  // things.
5010  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5011    CheckConstructor(Constructor);
5012
5013  // Check the default arguments, which we may have added.
5014  if (!Method->isInvalidDecl())
5015    CheckCXXDefaultArguments(Method);
5016}
5017
5018/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
5019/// the well-formedness of the constructor declarator @p D with type @p
5020/// R. If there are any errors in the declarator, this routine will
5021/// emit diagnostics and set the invalid bit to true.  In any case, the type
5022/// will be updated to reflect a well-formed type for the constructor and
5023/// returned.
5024QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
5025                                          StorageClass &SC) {
5026  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5027
5028  // C++ [class.ctor]p3:
5029  //   A constructor shall not be virtual (10.3) or static (9.4). A
5030  //   constructor can be invoked for a const, volatile or const
5031  //   volatile object. A constructor shall not be declared const,
5032  //   volatile, or const volatile (9.3.2).
5033  if (isVirtual) {
5034    if (!D.isInvalidType())
5035      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5036        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5037        << SourceRange(D.getIdentifierLoc());
5038    D.setInvalidType();
5039  }
5040  if (SC == SC_Static) {
5041    if (!D.isInvalidType())
5042      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5043        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5044        << SourceRange(D.getIdentifierLoc());
5045    D.setInvalidType();
5046    SC = SC_None;
5047  }
5048
5049  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5050  if (FTI.TypeQuals != 0) {
5051    if (FTI.TypeQuals & Qualifiers::Const)
5052      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5053        << "const" << SourceRange(D.getIdentifierLoc());
5054    if (FTI.TypeQuals & Qualifiers::Volatile)
5055      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5056        << "volatile" << SourceRange(D.getIdentifierLoc());
5057    if (FTI.TypeQuals & Qualifiers::Restrict)
5058      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5059        << "restrict" << SourceRange(D.getIdentifierLoc());
5060    D.setInvalidType();
5061  }
5062
5063  // C++0x [class.ctor]p4:
5064  //   A constructor shall not be declared with a ref-qualifier.
5065  if (FTI.hasRefQualifier()) {
5066    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5067      << FTI.RefQualifierIsLValueRef
5068      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5069    D.setInvalidType();
5070  }
5071
5072  // Rebuild the function type "R" without any type qualifiers (in
5073  // case any of the errors above fired) and with "void" as the
5074  // return type, since constructors don't have return types.
5075  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5076  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5077    return R;
5078
5079  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5080  EPI.TypeQuals = 0;
5081  EPI.RefQualifier = RQ_None;
5082
5083  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
5084                                 Proto->getNumArgs(), EPI);
5085}
5086
5087/// CheckConstructor - Checks a fully-formed constructor for
5088/// well-formedness, issuing any diagnostics required. Returns true if
5089/// the constructor declarator is invalid.
5090void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5091  CXXRecordDecl *ClassDecl
5092    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5093  if (!ClassDecl)
5094    return Constructor->setInvalidDecl();
5095
5096  // C++ [class.copy]p3:
5097  //   A declaration of a constructor for a class X is ill-formed if
5098  //   its first parameter is of type (optionally cv-qualified) X and
5099  //   either there are no other parameters or else all other
5100  //   parameters have default arguments.
5101  if (!Constructor->isInvalidDecl() &&
5102      ((Constructor->getNumParams() == 1) ||
5103       (Constructor->getNumParams() > 1 &&
5104        Constructor->getParamDecl(1)->hasDefaultArg())) &&
5105      Constructor->getTemplateSpecializationKind()
5106                                              != TSK_ImplicitInstantiation) {
5107    QualType ParamType = Constructor->getParamDecl(0)->getType();
5108    QualType ClassTy = Context.getTagDeclType(ClassDecl);
5109    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5110      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5111      const char *ConstRef
5112        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5113                                                        : " const &";
5114      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5115        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5116
5117      // FIXME: Rather that making the constructor invalid, we should endeavor
5118      // to fix the type.
5119      Constructor->setInvalidDecl();
5120    }
5121  }
5122}
5123
5124/// CheckDestructor - Checks a fully-formed destructor definition for
5125/// well-formedness, issuing any diagnostics required.  Returns true
5126/// on error.
5127bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5128  CXXRecordDecl *RD = Destructor->getParent();
5129
5130  if (Destructor->isVirtual()) {
5131    SourceLocation Loc;
5132
5133    if (!Destructor->isImplicit())
5134      Loc = Destructor->getLocation();
5135    else
5136      Loc = RD->getLocation();
5137
5138    // If we have a virtual destructor, look up the deallocation function
5139    FunctionDecl *OperatorDelete = 0;
5140    DeclarationName Name =
5141    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5142    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5143      return true;
5144
5145    MarkFunctionReferenced(Loc, OperatorDelete);
5146
5147    Destructor->setOperatorDelete(OperatorDelete);
5148  }
5149
5150  return false;
5151}
5152
5153static inline bool
5154FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5155  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5156          FTI.ArgInfo[0].Param &&
5157          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5158}
5159
5160/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5161/// the well-formednes of the destructor declarator @p D with type @p
5162/// R. If there are any errors in the declarator, this routine will
5163/// emit diagnostics and set the declarator to invalid.  Even if this happens,
5164/// will be updated to reflect a well-formed type for the destructor and
5165/// returned.
5166QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5167                                         StorageClass& SC) {
5168  // C++ [class.dtor]p1:
5169  //   [...] A typedef-name that names a class is a class-name
5170  //   (7.1.3); however, a typedef-name that names a class shall not
5171  //   be used as the identifier in the declarator for a destructor
5172  //   declaration.
5173  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5174  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5175    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5176      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5177  else if (const TemplateSpecializationType *TST =
5178             DeclaratorType->getAs<TemplateSpecializationType>())
5179    if (TST->isTypeAlias())
5180      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5181        << DeclaratorType << 1;
5182
5183  // C++ [class.dtor]p2:
5184  //   A destructor is used to destroy objects of its class type. A
5185  //   destructor takes no parameters, and no return type can be
5186  //   specified for it (not even void). The address of a destructor
5187  //   shall not be taken. A destructor shall not be static. A
5188  //   destructor can be invoked for a const, volatile or const
5189  //   volatile object. A destructor shall not be declared const,
5190  //   volatile or const volatile (9.3.2).
5191  if (SC == SC_Static) {
5192    if (!D.isInvalidType())
5193      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5194        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5195        << SourceRange(D.getIdentifierLoc())
5196        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5197
5198    SC = SC_None;
5199  }
5200  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5201    // Destructors don't have return types, but the parser will
5202    // happily parse something like:
5203    //
5204    //   class X {
5205    //     float ~X();
5206    //   };
5207    //
5208    // The return type will be eliminated later.
5209    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5210      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5211      << SourceRange(D.getIdentifierLoc());
5212  }
5213
5214  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5215  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5216    if (FTI.TypeQuals & Qualifiers::Const)
5217      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5218        << "const" << SourceRange(D.getIdentifierLoc());
5219    if (FTI.TypeQuals & Qualifiers::Volatile)
5220      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5221        << "volatile" << SourceRange(D.getIdentifierLoc());
5222    if (FTI.TypeQuals & Qualifiers::Restrict)
5223      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5224        << "restrict" << SourceRange(D.getIdentifierLoc());
5225    D.setInvalidType();
5226  }
5227
5228  // C++0x [class.dtor]p2:
5229  //   A destructor shall not be declared with a ref-qualifier.
5230  if (FTI.hasRefQualifier()) {
5231    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5232      << FTI.RefQualifierIsLValueRef
5233      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5234    D.setInvalidType();
5235  }
5236
5237  // Make sure we don't have any parameters.
5238  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5239    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5240
5241    // Delete the parameters.
5242    FTI.freeArgs();
5243    D.setInvalidType();
5244  }
5245
5246  // Make sure the destructor isn't variadic.
5247  if (FTI.isVariadic) {
5248    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5249    D.setInvalidType();
5250  }
5251
5252  // Rebuild the function type "R" without any type qualifiers or
5253  // parameters (in case any of the errors above fired) and with
5254  // "void" as the return type, since destructors don't have return
5255  // types.
5256  if (!D.isInvalidType())
5257    return R;
5258
5259  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5260  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5261  EPI.Variadic = false;
5262  EPI.TypeQuals = 0;
5263  EPI.RefQualifier = RQ_None;
5264  return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
5265}
5266
5267/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5268/// well-formednes of the conversion function declarator @p D with
5269/// type @p R. If there are any errors in the declarator, this routine
5270/// will emit diagnostics and return true. Otherwise, it will return
5271/// false. Either way, the type @p R will be updated to reflect a
5272/// well-formed type for the conversion operator.
5273void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
5274                                     StorageClass& SC) {
5275  // C++ [class.conv.fct]p1:
5276  //   Neither parameter types nor return type can be specified. The
5277  //   type of a conversion function (8.3.5) is "function taking no
5278  //   parameter returning conversion-type-id."
5279  if (SC == SC_Static) {
5280    if (!D.isInvalidType())
5281      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5282        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5283        << SourceRange(D.getIdentifierLoc());
5284    D.setInvalidType();
5285    SC = SC_None;
5286  }
5287
5288  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5289
5290  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5291    // Conversion functions don't have return types, but the parser will
5292    // happily parse something like:
5293    //
5294    //   class X {
5295    //     float operator bool();
5296    //   };
5297    //
5298    // The return type will be changed later anyway.
5299    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5300      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5301      << SourceRange(D.getIdentifierLoc());
5302    D.setInvalidType();
5303  }
5304
5305  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5306
5307  // Make sure we don't have any parameters.
5308  if (Proto->getNumArgs() > 0) {
5309    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5310
5311    // Delete the parameters.
5312    D.getFunctionTypeInfo().freeArgs();
5313    D.setInvalidType();
5314  } else if (Proto->isVariadic()) {
5315    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
5316    D.setInvalidType();
5317  }
5318
5319  // Diagnose "&operator bool()" and other such nonsense.  This
5320  // is actually a gcc extension which we don't support.
5321  if (Proto->getResultType() != ConvType) {
5322    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5323      << Proto->getResultType();
5324    D.setInvalidType();
5325    ConvType = Proto->getResultType();
5326  }
5327
5328  // C++ [class.conv.fct]p4:
5329  //   The conversion-type-id shall not represent a function type nor
5330  //   an array type.
5331  if (ConvType->isArrayType()) {
5332    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5333    ConvType = Context.getPointerType(ConvType);
5334    D.setInvalidType();
5335  } else if (ConvType->isFunctionType()) {
5336    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5337    ConvType = Context.getPointerType(ConvType);
5338    D.setInvalidType();
5339  }
5340
5341  // Rebuild the function type "R" without any parameters (in case any
5342  // of the errors above fired) and with the conversion type as the
5343  // return type.
5344  if (D.isInvalidType())
5345    R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
5346
5347  // C++0x explicit conversion operators.
5348  if (D.getDeclSpec().isExplicitSpecified())
5349    Diag(D.getDeclSpec().getExplicitSpecLoc(),
5350         getLangOpts().CPlusPlus0x ?
5351           diag::warn_cxx98_compat_explicit_conversion_functions :
5352           diag::ext_explicit_conversion_functions)
5353      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
5354}
5355
5356/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5357/// the declaration of the given C++ conversion function. This routine
5358/// is responsible for recording the conversion function in the C++
5359/// class, if possible.
5360Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
5361  assert(Conversion && "Expected to receive a conversion function declaration");
5362
5363  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
5364
5365  // Make sure we aren't redeclaring the conversion function.
5366  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
5367
5368  // C++ [class.conv.fct]p1:
5369  //   [...] A conversion function is never used to convert a
5370  //   (possibly cv-qualified) object to the (possibly cv-qualified)
5371  //   same object type (or a reference to it), to a (possibly
5372  //   cv-qualified) base class of that type (or a reference to it),
5373  //   or to (possibly cv-qualified) void.
5374  // FIXME: Suppress this warning if the conversion function ends up being a
5375  // virtual function that overrides a virtual function in a base class.
5376  QualType ClassType
5377    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5378  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
5379    ConvType = ConvTypeRef->getPointeeType();
5380  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5381      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5382    /* Suppress diagnostics for instantiations. */;
5383  else if (ConvType->isRecordType()) {
5384    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5385    if (ConvType == ClassType)
5386      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
5387        << ClassType;
5388    else if (IsDerivedFrom(ClassType, ConvType))
5389      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
5390        <<  ClassType << ConvType;
5391  } else if (ConvType->isVoidType()) {
5392    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
5393      << ClassType << ConvType;
5394  }
5395
5396  if (FunctionTemplateDecl *ConversionTemplate
5397                                = Conversion->getDescribedFunctionTemplate())
5398    return ConversionTemplate;
5399
5400  return Conversion;
5401}
5402
5403//===----------------------------------------------------------------------===//
5404// Namespace Handling
5405//===----------------------------------------------------------------------===//
5406
5407/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
5408/// reopened.
5409static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
5410                                            SourceLocation Loc,
5411                                            IdentifierInfo *II, bool *IsInline,
5412                                            NamespaceDecl *PrevNS) {
5413  assert(*IsInline != PrevNS->isInline());
5414
5415  // HACK: Work around a bug in libstdc++4.6's <atomic>, where
5416  // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
5417  // inline namespaces, with the intention of bringing names into namespace std.
5418  //
5419  // We support this just well enough to get that case working; this is not
5420  // sufficient to support reopening namespaces as inline in general.
5421  if (*IsInline && II && II->getName().startswith("__atomic") &&
5422      S.getSourceManager().isInSystemHeader(Loc)) {
5423    // Mark all prior declarations of the namespace as inline.
5424    for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
5425         NS = NS->getPreviousDecl())
5426      NS->setInline(*IsInline);
5427    // Patch up the lookup table for the containing namespace. This isn't really
5428    // correct, but it's good enough for this particular case.
5429    for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
5430                                    E = PrevNS->decls_end(); I != E; ++I)
5431      if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
5432        PrevNS->getParent()->makeDeclVisibleInContext(ND);
5433    return;
5434  }
5435
5436  if (PrevNS->isInline())
5437    // The user probably just forgot the 'inline', so suggest that it
5438    // be added back.
5439    S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5440      << FixItHint::CreateInsertion(KeywordLoc, "inline ");
5441  else
5442    S.Diag(Loc, diag::err_inline_namespace_mismatch)
5443      << IsInline;
5444
5445  S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
5446  *IsInline = PrevNS->isInline();
5447}
5448
5449/// ActOnStartNamespaceDef - This is called at the start of a namespace
5450/// definition.
5451Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
5452                                   SourceLocation InlineLoc,
5453                                   SourceLocation NamespaceLoc,
5454                                   SourceLocation IdentLoc,
5455                                   IdentifierInfo *II,
5456                                   SourceLocation LBrace,
5457                                   AttributeList *AttrList) {
5458  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5459  // For anonymous namespace, take the location of the left brace.
5460  SourceLocation Loc = II ? IdentLoc : LBrace;
5461  bool IsInline = InlineLoc.isValid();
5462  bool IsInvalid = false;
5463  bool IsStd = false;
5464  bool AddToKnown = false;
5465  Scope *DeclRegionScope = NamespcScope->getParent();
5466
5467  NamespaceDecl *PrevNS = 0;
5468  if (II) {
5469    // C++ [namespace.def]p2:
5470    //   The identifier in an original-namespace-definition shall not
5471    //   have been previously defined in the declarative region in
5472    //   which the original-namespace-definition appears. The
5473    //   identifier in an original-namespace-definition is the name of
5474    //   the namespace. Subsequently in that declarative region, it is
5475    //   treated as an original-namespace-name.
5476    //
5477    // Since namespace names are unique in their scope, and we don't
5478    // look through using directives, just look for any ordinary names.
5479
5480    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5481    Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5482    Decl::IDNS_Namespace;
5483    NamedDecl *PrevDecl = 0;
5484    for (DeclContext::lookup_result R
5485         = CurContext->getRedeclContext()->lookup(II);
5486         R.first != R.second; ++R.first) {
5487      if ((*R.first)->getIdentifierNamespace() & IDNS) {
5488        PrevDecl = *R.first;
5489        break;
5490      }
5491    }
5492
5493    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5494
5495    if (PrevNS) {
5496      // This is an extended namespace definition.
5497      if (IsInline != PrevNS->isInline())
5498        DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
5499                                        &IsInline, PrevNS);
5500    } else if (PrevDecl) {
5501      // This is an invalid name redefinition.
5502      Diag(Loc, diag::err_redefinition_different_kind)
5503        << II;
5504      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5505      IsInvalid = true;
5506      // Continue on to push Namespc as current DeclContext and return it.
5507    } else if (II->isStr("std") &&
5508               CurContext->getRedeclContext()->isTranslationUnit()) {
5509      // This is the first "real" definition of the namespace "std", so update
5510      // our cache of the "std" namespace to point at this definition.
5511      PrevNS = getStdNamespace();
5512      IsStd = true;
5513      AddToKnown = !IsInline;
5514    } else {
5515      // We've seen this namespace for the first time.
5516      AddToKnown = !IsInline;
5517    }
5518  } else {
5519    // Anonymous namespaces.
5520
5521    // Determine whether the parent already has an anonymous namespace.
5522    DeclContext *Parent = CurContext->getRedeclContext();
5523    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5524      PrevNS = TU->getAnonymousNamespace();
5525    } else {
5526      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5527      PrevNS = ND->getAnonymousNamespace();
5528    }
5529
5530    if (PrevNS && IsInline != PrevNS->isInline())
5531      DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
5532                                      &IsInline, PrevNS);
5533  }
5534
5535  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5536                                                 StartLoc, Loc, II, PrevNS);
5537  if (IsInvalid)
5538    Namespc->setInvalidDecl();
5539
5540  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5541
5542  // FIXME: Should we be merging attributes?
5543  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5544    PushNamespaceVisibilityAttr(Attr, Loc);
5545
5546  if (IsStd)
5547    StdNamespace = Namespc;
5548  if (AddToKnown)
5549    KnownNamespaces[Namespc] = false;
5550
5551  if (II) {
5552    PushOnScopeChains(Namespc, DeclRegionScope);
5553  } else {
5554    // Link the anonymous namespace into its parent.
5555    DeclContext *Parent = CurContext->getRedeclContext();
5556    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5557      TU->setAnonymousNamespace(Namespc);
5558    } else {
5559      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
5560    }
5561
5562    CurContext->addDecl(Namespc);
5563
5564    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
5565    //   behaves as if it were replaced by
5566    //     namespace unique { /* empty body */ }
5567    //     using namespace unique;
5568    //     namespace unique { namespace-body }
5569    //   where all occurrences of 'unique' in a translation unit are
5570    //   replaced by the same identifier and this identifier differs
5571    //   from all other identifiers in the entire program.
5572
5573    // We just create the namespace with an empty name and then add an
5574    // implicit using declaration, just like the standard suggests.
5575    //
5576    // CodeGen enforces the "universally unique" aspect by giving all
5577    // declarations semantically contained within an anonymous
5578    // namespace internal linkage.
5579
5580    if (!PrevNS) {
5581      UsingDirectiveDecl* UD
5582        = UsingDirectiveDecl::Create(Context, CurContext,
5583                                     /* 'using' */ LBrace,
5584                                     /* 'namespace' */ SourceLocation(),
5585                                     /* qualifier */ NestedNameSpecifierLoc(),
5586                                     /* identifier */ SourceLocation(),
5587                                     Namespc,
5588                                     /* Ancestor */ CurContext);
5589      UD->setImplicit();
5590      CurContext->addDecl(UD);
5591    }
5592  }
5593
5594  ActOnDocumentableDecl(Namespc);
5595
5596  // Although we could have an invalid decl (i.e. the namespace name is a
5597  // redefinition), push it as current DeclContext and try to continue parsing.
5598  // FIXME: We should be able to push Namespc here, so that the each DeclContext
5599  // for the namespace has the declarations that showed up in that particular
5600  // namespace definition.
5601  PushDeclContext(NamespcScope, Namespc);
5602  return Namespc;
5603}
5604
5605/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5606/// is a namespace alias, returns the namespace it points to.
5607static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5608  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5609    return AD->getNamespace();
5610  return dyn_cast_or_null<NamespaceDecl>(D);
5611}
5612
5613/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5614/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5615void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
5616  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5617  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
5618  Namespc->setRBraceLoc(RBrace);
5619  PopDeclContext();
5620  if (Namespc->hasAttr<VisibilityAttr>())
5621    PopPragmaVisibility(true, RBrace);
5622}
5623
5624CXXRecordDecl *Sema::getStdBadAlloc() const {
5625  return cast_or_null<CXXRecordDecl>(
5626                                  StdBadAlloc.get(Context.getExternalSource()));
5627}
5628
5629NamespaceDecl *Sema::getStdNamespace() const {
5630  return cast_or_null<NamespaceDecl>(
5631                                 StdNamespace.get(Context.getExternalSource()));
5632}
5633
5634/// \brief Retrieve the special "std" namespace, which may require us to
5635/// implicitly define the namespace.
5636NamespaceDecl *Sema::getOrCreateStdNamespace() {
5637  if (!StdNamespace) {
5638    // The "std" namespace has not yet been defined, so build one implicitly.
5639    StdNamespace = NamespaceDecl::Create(Context,
5640                                         Context.getTranslationUnitDecl(),
5641                                         /*Inline=*/false,
5642                                         SourceLocation(), SourceLocation(),
5643                                         &PP.getIdentifierTable().get("std"),
5644                                         /*PrevDecl=*/0);
5645    getStdNamespace()->setImplicit(true);
5646  }
5647
5648  return getStdNamespace();
5649}
5650
5651bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5652  assert(getLangOpts().CPlusPlus &&
5653         "Looking for std::initializer_list outside of C++.");
5654
5655  // We're looking for implicit instantiations of
5656  // template <typename E> class std::initializer_list.
5657
5658  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5659    return false;
5660
5661  ClassTemplateDecl *Template = 0;
5662  const TemplateArgument *Arguments = 0;
5663
5664  if (const RecordType *RT = Ty->getAs<RecordType>()) {
5665
5666    ClassTemplateSpecializationDecl *Specialization =
5667        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5668    if (!Specialization)
5669      return false;
5670
5671    Template = Specialization->getSpecializedTemplate();
5672    Arguments = Specialization->getTemplateArgs().data();
5673  } else if (const TemplateSpecializationType *TST =
5674                 Ty->getAs<TemplateSpecializationType>()) {
5675    Template = dyn_cast_or_null<ClassTemplateDecl>(
5676        TST->getTemplateName().getAsTemplateDecl());
5677    Arguments = TST->getArgs();
5678  }
5679  if (!Template)
5680    return false;
5681
5682  if (!StdInitializerList) {
5683    // Haven't recognized std::initializer_list yet, maybe this is it.
5684    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5685    if (TemplateClass->getIdentifier() !=
5686            &PP.getIdentifierTable().get("initializer_list") ||
5687        !getStdNamespace()->InEnclosingNamespaceSetOf(
5688            TemplateClass->getDeclContext()))
5689      return false;
5690    // This is a template called std::initializer_list, but is it the right
5691    // template?
5692    TemplateParameterList *Params = Template->getTemplateParameters();
5693    if (Params->getMinRequiredArguments() != 1)
5694      return false;
5695    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5696      return false;
5697
5698    // It's the right template.
5699    StdInitializerList = Template;
5700  }
5701
5702  if (Template != StdInitializerList)
5703    return false;
5704
5705  // This is an instance of std::initializer_list. Find the argument type.
5706  if (Element)
5707    *Element = Arguments[0].getAsType();
5708  return true;
5709}
5710
5711static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5712  NamespaceDecl *Std = S.getStdNamespace();
5713  if (!Std) {
5714    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5715    return 0;
5716  }
5717
5718  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5719                      Loc, Sema::LookupOrdinaryName);
5720  if (!S.LookupQualifiedName(Result, Std)) {
5721    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5722    return 0;
5723  }
5724  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5725  if (!Template) {
5726    Result.suppressDiagnostics();
5727    // We found something weird. Complain about the first thing we found.
5728    NamedDecl *Found = *Result.begin();
5729    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5730    return 0;
5731  }
5732
5733  // We found some template called std::initializer_list. Now verify that it's
5734  // correct.
5735  TemplateParameterList *Params = Template->getTemplateParameters();
5736  if (Params->getMinRequiredArguments() != 1 ||
5737      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5738    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5739    return 0;
5740  }
5741
5742  return Template;
5743}
5744
5745QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5746  if (!StdInitializerList) {
5747    StdInitializerList = LookupStdInitializerList(*this, Loc);
5748    if (!StdInitializerList)
5749      return QualType();
5750  }
5751
5752  TemplateArgumentListInfo Args(Loc, Loc);
5753  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5754                                       Context.getTrivialTypeSourceInfo(Element,
5755                                                                        Loc)));
5756  return Context.getCanonicalType(
5757      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5758}
5759
5760bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5761  // C++ [dcl.init.list]p2:
5762  //   A constructor is an initializer-list constructor if its first parameter
5763  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
5764  //   std::initializer_list<E> for some type E, and either there are no other
5765  //   parameters or else all other parameters have default arguments.
5766  if (Ctor->getNumParams() < 1 ||
5767      (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5768    return false;
5769
5770  QualType ArgType = Ctor->getParamDecl(0)->getType();
5771  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5772    ArgType = RT->getPointeeType().getUnqualifiedType();
5773
5774  return isStdInitializerList(ArgType, 0);
5775}
5776
5777/// \brief Determine whether a using statement is in a context where it will be
5778/// apply in all contexts.
5779static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5780  switch (CurContext->getDeclKind()) {
5781    case Decl::TranslationUnit:
5782      return true;
5783    case Decl::LinkageSpec:
5784      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5785    default:
5786      return false;
5787  }
5788}
5789
5790namespace {
5791
5792// Callback to only accept typo corrections that are namespaces.
5793class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5794 public:
5795  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5796    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5797      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5798    }
5799    return false;
5800  }
5801};
5802
5803}
5804
5805static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5806                                       CXXScopeSpec &SS,
5807                                       SourceLocation IdentLoc,
5808                                       IdentifierInfo *Ident) {
5809  NamespaceValidatorCCC Validator;
5810  R.clear();
5811  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5812                                               R.getLookupKind(), Sc, &SS,
5813                                               Validator)) {
5814    std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5815    std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
5816    if (DeclContext *DC = S.computeDeclContext(SS, false))
5817      S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5818        << Ident << DC << CorrectedQuotedStr << SS.getRange()
5819        << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
5820                                        CorrectedStr);
5821    else
5822      S.Diag(IdentLoc, diag::err_using_directive_suggest)
5823        << Ident << CorrectedQuotedStr
5824        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5825
5826    S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5827         diag::note_namespace_defined_here) << CorrectedQuotedStr;
5828
5829    R.addDecl(Corrected.getCorrectionDecl());
5830    return true;
5831  }
5832  return false;
5833}
5834
5835Decl *Sema::ActOnUsingDirective(Scope *S,
5836                                          SourceLocation UsingLoc,
5837                                          SourceLocation NamespcLoc,
5838                                          CXXScopeSpec &SS,
5839                                          SourceLocation IdentLoc,
5840                                          IdentifierInfo *NamespcName,
5841                                          AttributeList *AttrList) {
5842  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5843  assert(NamespcName && "Invalid NamespcName.");
5844  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
5845
5846  // This can only happen along a recovery path.
5847  while (S->getFlags() & Scope::TemplateParamScope)
5848    S = S->getParent();
5849  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5850
5851  UsingDirectiveDecl *UDir = 0;
5852  NestedNameSpecifier *Qualifier = 0;
5853  if (SS.isSet())
5854    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5855
5856  // Lookup namespace name.
5857  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5858  LookupParsedName(R, S, &SS);
5859  if (R.isAmbiguous())
5860    return 0;
5861
5862  if (R.empty()) {
5863    R.clear();
5864    // Allow "using namespace std;" or "using namespace ::std;" even if
5865    // "std" hasn't been defined yet, for GCC compatibility.
5866    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5867        NamespcName->isStr("std")) {
5868      Diag(IdentLoc, diag::ext_using_undefined_std);
5869      R.addDecl(getOrCreateStdNamespace());
5870      R.resolveKind();
5871    }
5872    // Otherwise, attempt typo correction.
5873    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
5874  }
5875
5876  if (!R.empty()) {
5877    NamedDecl *Named = R.getFoundDecl();
5878    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5879        && "expected namespace decl");
5880    // C++ [namespace.udir]p1:
5881    //   A using-directive specifies that the names in the nominated
5882    //   namespace can be used in the scope in which the
5883    //   using-directive appears after the using-directive. During
5884    //   unqualified name lookup (3.4.1), the names appear as if they
5885    //   were declared in the nearest enclosing namespace which
5886    //   contains both the using-directive and the nominated
5887    //   namespace. [Note: in this context, "contains" means "contains
5888    //   directly or indirectly". ]
5889
5890    // Find enclosing context containing both using-directive and
5891    // nominated namespace.
5892    NamespaceDecl *NS = getNamespaceDecl(Named);
5893    DeclContext *CommonAncestor = cast<DeclContext>(NS);
5894    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5895      CommonAncestor = CommonAncestor->getParent();
5896
5897    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
5898                                      SS.getWithLocInContext(Context),
5899                                      IdentLoc, Named, CommonAncestor);
5900
5901    if (IsUsingDirectiveInToplevelContext(CurContext) &&
5902        !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
5903      Diag(IdentLoc, diag::warn_using_directive_in_header);
5904    }
5905
5906    PushUsingDirective(S, UDir);
5907  } else {
5908    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
5909  }
5910
5911  // FIXME: We ignore attributes for now.
5912  return UDir;
5913}
5914
5915void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5916  // If the scope has an associated entity and the using directive is at
5917  // namespace or translation unit scope, add the UsingDirectiveDecl into
5918  // its lookup structure so qualified name lookup can find it.
5919  DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5920  if (Ctx && !Ctx->isFunctionOrMethod())
5921    Ctx->addDecl(UDir);
5922  else
5923    // Otherwise, it is at block sope. The using-directives will affect lookup
5924    // only to the end of the scope.
5925    S->PushUsingDirective(UDir);
5926}
5927
5928
5929Decl *Sema::ActOnUsingDeclaration(Scope *S,
5930                                  AccessSpecifier AS,
5931                                  bool HasUsingKeyword,
5932                                  SourceLocation UsingLoc,
5933                                  CXXScopeSpec &SS,
5934                                  UnqualifiedId &Name,
5935                                  AttributeList *AttrList,
5936                                  bool IsTypeName,
5937                                  SourceLocation TypenameLoc) {
5938  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5939
5940  switch (Name.getKind()) {
5941  case UnqualifiedId::IK_ImplicitSelfParam:
5942  case UnqualifiedId::IK_Identifier:
5943  case UnqualifiedId::IK_OperatorFunctionId:
5944  case UnqualifiedId::IK_LiteralOperatorId:
5945  case UnqualifiedId::IK_ConversionFunctionId:
5946    break;
5947
5948  case UnqualifiedId::IK_ConstructorName:
5949  case UnqualifiedId::IK_ConstructorTemplateId:
5950    // C++11 inheriting constructors.
5951    Diag(Name.getLocStart(),
5952         getLangOpts().CPlusPlus0x ?
5953           // FIXME: Produce warn_cxx98_compat_using_decl_constructor
5954           //        instead once inheriting constructors work.
5955           diag::err_using_decl_constructor_unsupported :
5956           diag::err_using_decl_constructor)
5957      << SS.getRange();
5958
5959    if (getLangOpts().CPlusPlus0x) break;
5960
5961    return 0;
5962
5963  case UnqualifiedId::IK_DestructorName:
5964    Diag(Name.getLocStart(), diag::err_using_decl_destructor)
5965      << SS.getRange();
5966    return 0;
5967
5968  case UnqualifiedId::IK_TemplateId:
5969    Diag(Name.getLocStart(), diag::err_using_decl_template_id)
5970      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
5971    return 0;
5972  }
5973
5974  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5975  DeclarationName TargetName = TargetNameInfo.getName();
5976  if (!TargetName)
5977    return 0;
5978
5979  // Warn about using declarations.
5980  // TODO: store that the declaration was written without 'using' and
5981  // talk about access decls instead of using decls in the
5982  // diagnostics.
5983  if (!HasUsingKeyword) {
5984    UsingLoc = Name.getLocStart();
5985
5986    Diag(UsingLoc, diag::warn_access_decl_deprecated)
5987      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
5988  }
5989
5990  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5991      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5992    return 0;
5993
5994  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
5995                                        TargetNameInfo, AttrList,
5996                                        /* IsInstantiation */ false,
5997                                        IsTypeName, TypenameLoc);
5998  if (UD)
5999    PushOnScopeChains(UD, S, /*AddToContext*/ false);
6000
6001  return UD;
6002}
6003
6004/// \brief Determine whether a using declaration considers the given
6005/// declarations as "equivalent", e.g., if they are redeclarations of
6006/// the same entity or are both typedefs of the same type.
6007static bool
6008IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6009                         bool &SuppressRedeclaration) {
6010  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6011    SuppressRedeclaration = false;
6012    return true;
6013  }
6014
6015  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6016    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
6017      SuppressRedeclaration = true;
6018      return Context.hasSameType(TD1->getUnderlyingType(),
6019                                 TD2->getUnderlyingType());
6020    }
6021
6022  return false;
6023}
6024
6025
6026/// Determines whether to create a using shadow decl for a particular
6027/// decl, given the set of decls existing prior to this using lookup.
6028bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6029                                const LookupResult &Previous) {
6030  // Diagnose finding a decl which is not from a base class of the
6031  // current class.  We do this now because there are cases where this
6032  // function will silently decide not to build a shadow decl, which
6033  // will pre-empt further diagnostics.
6034  //
6035  // We don't need to do this in C++0x because we do the check once on
6036  // the qualifier.
6037  //
6038  // FIXME: diagnose the following if we care enough:
6039  //   struct A { int foo; };
6040  //   struct B : A { using A::foo; };
6041  //   template <class T> struct C : A {};
6042  //   template <class T> struct D : C<T> { using B::foo; } // <---
6043  // This is invalid (during instantiation) in C++03 because B::foo
6044  // resolves to the using decl in B, which is not a base class of D<T>.
6045  // We can't diagnose it immediately because C<T> is an unknown
6046  // specialization.  The UsingShadowDecl in D<T> then points directly
6047  // to A::foo, which will look well-formed when we instantiate.
6048  // The right solution is to not collapse the shadow-decl chain.
6049  if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
6050    DeclContext *OrigDC = Orig->getDeclContext();
6051
6052    // Handle enums and anonymous structs.
6053    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6054    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6055    while (OrigRec->isAnonymousStructOrUnion())
6056      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6057
6058    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6059      if (OrigDC == CurContext) {
6060        Diag(Using->getLocation(),
6061             diag::err_using_decl_nested_name_specifier_is_current_class)
6062          << Using->getQualifierLoc().getSourceRange();
6063        Diag(Orig->getLocation(), diag::note_using_decl_target);
6064        return true;
6065      }
6066
6067      Diag(Using->getQualifierLoc().getBeginLoc(),
6068           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6069        << Using->getQualifier()
6070        << cast<CXXRecordDecl>(CurContext)
6071        << Using->getQualifierLoc().getSourceRange();
6072      Diag(Orig->getLocation(), diag::note_using_decl_target);
6073      return true;
6074    }
6075  }
6076
6077  if (Previous.empty()) return false;
6078
6079  NamedDecl *Target = Orig;
6080  if (isa<UsingShadowDecl>(Target))
6081    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6082
6083  // If the target happens to be one of the previous declarations, we
6084  // don't have a conflict.
6085  //
6086  // FIXME: but we might be increasing its access, in which case we
6087  // should redeclare it.
6088  NamedDecl *NonTag = 0, *Tag = 0;
6089  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6090         I != E; ++I) {
6091    NamedDecl *D = (*I)->getUnderlyingDecl();
6092    bool Result;
6093    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6094      return Result;
6095
6096    (isa<TagDecl>(D) ? Tag : NonTag) = D;
6097  }
6098
6099  if (Target->isFunctionOrFunctionTemplate()) {
6100    FunctionDecl *FD;
6101    if (isa<FunctionTemplateDecl>(Target))
6102      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6103    else
6104      FD = cast<FunctionDecl>(Target);
6105
6106    NamedDecl *OldDecl = 0;
6107    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6108    case Ovl_Overload:
6109      return false;
6110
6111    case Ovl_NonFunction:
6112      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6113      break;
6114
6115    // We found a decl with the exact signature.
6116    case Ovl_Match:
6117      // If we're in a record, we want to hide the target, so we
6118      // return true (without a diagnostic) to tell the caller not to
6119      // build a shadow decl.
6120      if (CurContext->isRecord())
6121        return true;
6122
6123      // If we're not in a record, this is an error.
6124      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6125      break;
6126    }
6127
6128    Diag(Target->getLocation(), diag::note_using_decl_target);
6129    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6130    return true;
6131  }
6132
6133  // Target is not a function.
6134
6135  if (isa<TagDecl>(Target)) {
6136    // No conflict between a tag and a non-tag.
6137    if (!Tag) return false;
6138
6139    Diag(Using->getLocation(), diag::err_using_decl_conflict);
6140    Diag(Target->getLocation(), diag::note_using_decl_target);
6141    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6142    return true;
6143  }
6144
6145  // No conflict between a tag and a non-tag.
6146  if (!NonTag) return false;
6147
6148  Diag(Using->getLocation(), diag::err_using_decl_conflict);
6149  Diag(Target->getLocation(), diag::note_using_decl_target);
6150  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6151  return true;
6152}
6153
6154/// Builds a shadow declaration corresponding to a 'using' declaration.
6155UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6156                                            UsingDecl *UD,
6157                                            NamedDecl *Orig) {
6158
6159  // If we resolved to another shadow declaration, just coalesce them.
6160  NamedDecl *Target = Orig;
6161  if (isa<UsingShadowDecl>(Target)) {
6162    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6163    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6164  }
6165
6166  UsingShadowDecl *Shadow
6167    = UsingShadowDecl::Create(Context, CurContext,
6168                              UD->getLocation(), UD, Target);
6169  UD->addShadowDecl(Shadow);
6170
6171  Shadow->setAccess(UD->getAccess());
6172  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6173    Shadow->setInvalidDecl();
6174
6175  if (S)
6176    PushOnScopeChains(Shadow, S);
6177  else
6178    CurContext->addDecl(Shadow);
6179
6180
6181  return Shadow;
6182}
6183
6184/// Hides a using shadow declaration.  This is required by the current
6185/// using-decl implementation when a resolvable using declaration in a
6186/// class is followed by a declaration which would hide or override
6187/// one or more of the using decl's targets; for example:
6188///
6189///   struct Base { void foo(int); };
6190///   struct Derived : Base {
6191///     using Base::foo;
6192///     void foo(int);
6193///   };
6194///
6195/// The governing language is C++03 [namespace.udecl]p12:
6196///
6197///   When a using-declaration brings names from a base class into a
6198///   derived class scope, member functions in the derived class
6199///   override and/or hide member functions with the same name and
6200///   parameter types in a base class (rather than conflicting).
6201///
6202/// There are two ways to implement this:
6203///   (1) optimistically create shadow decls when they're not hidden
6204///       by existing declarations, or
6205///   (2) don't create any shadow decls (or at least don't make them
6206///       visible) until we've fully parsed/instantiated the class.
6207/// The problem with (1) is that we might have to retroactively remove
6208/// a shadow decl, which requires several O(n) operations because the
6209/// decl structures are (very reasonably) not designed for removal.
6210/// (2) avoids this but is very fiddly and phase-dependent.
6211void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6212  if (Shadow->getDeclName().getNameKind() ==
6213        DeclarationName::CXXConversionFunctionName)
6214    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6215
6216  // Remove it from the DeclContext...
6217  Shadow->getDeclContext()->removeDecl(Shadow);
6218
6219  // ...and the scope, if applicable...
6220  if (S) {
6221    S->RemoveDecl(Shadow);
6222    IdResolver.RemoveDecl(Shadow);
6223  }
6224
6225  // ...and the using decl.
6226  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6227
6228  // TODO: complain somehow if Shadow was used.  It shouldn't
6229  // be possible for this to happen, because...?
6230}
6231
6232/// Builds a using declaration.
6233///
6234/// \param IsInstantiation - Whether this call arises from an
6235///   instantiation of an unresolved using declaration.  We treat
6236///   the lookup differently for these declarations.
6237NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6238                                       SourceLocation UsingLoc,
6239                                       CXXScopeSpec &SS,
6240                                       const DeclarationNameInfo &NameInfo,
6241                                       AttributeList *AttrList,
6242                                       bool IsInstantiation,
6243                                       bool IsTypeName,
6244                                       SourceLocation TypenameLoc) {
6245  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6246  SourceLocation IdentLoc = NameInfo.getLoc();
6247  assert(IdentLoc.isValid() && "Invalid TargetName location.");
6248
6249  // FIXME: We ignore attributes for now.
6250
6251  if (SS.isEmpty()) {
6252    Diag(IdentLoc, diag::err_using_requires_qualname);
6253    return 0;
6254  }
6255
6256  // Do the redeclaration lookup in the current scope.
6257  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
6258                        ForRedeclaration);
6259  Previous.setHideTags(false);
6260  if (S) {
6261    LookupName(Previous, S);
6262
6263    // It is really dumb that we have to do this.
6264    LookupResult::Filter F = Previous.makeFilter();
6265    while (F.hasNext()) {
6266      NamedDecl *D = F.next();
6267      if (!isDeclInScope(D, CurContext, S))
6268        F.erase();
6269    }
6270    F.done();
6271  } else {
6272    assert(IsInstantiation && "no scope in non-instantiation");
6273    assert(CurContext->isRecord() && "scope not record in instantiation");
6274    LookupQualifiedName(Previous, CurContext);
6275  }
6276
6277  // Check for invalid redeclarations.
6278  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6279    return 0;
6280
6281  // Check for bad qualifiers.
6282  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6283    return 0;
6284
6285  DeclContext *LookupContext = computeDeclContext(SS);
6286  NamedDecl *D;
6287  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6288  if (!LookupContext) {
6289    if (IsTypeName) {
6290      // FIXME: not all declaration name kinds are legal here
6291      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6292                                              UsingLoc, TypenameLoc,
6293                                              QualifierLoc,
6294                                              IdentLoc, NameInfo.getName());
6295    } else {
6296      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6297                                           QualifierLoc, NameInfo);
6298    }
6299  } else {
6300    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6301                          NameInfo, IsTypeName);
6302  }
6303  D->setAccess(AS);
6304  CurContext->addDecl(D);
6305
6306  if (!LookupContext) return D;
6307  UsingDecl *UD = cast<UsingDecl>(D);
6308
6309  if (RequireCompleteDeclContext(SS, LookupContext)) {
6310    UD->setInvalidDecl();
6311    return UD;
6312  }
6313
6314  // The normal rules do not apply to inheriting constructor declarations.
6315  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
6316    if (CheckInheritingConstructorUsingDecl(UD))
6317      UD->setInvalidDecl();
6318    return UD;
6319  }
6320
6321  // Otherwise, look up the target name.
6322
6323  LookupResult R(*this, NameInfo, LookupOrdinaryName);
6324
6325  // Unlike most lookups, we don't always want to hide tag
6326  // declarations: tag names are visible through the using declaration
6327  // even if hidden by ordinary names, *except* in a dependent context
6328  // where it's important for the sanity of two-phase lookup.
6329  if (!IsInstantiation)
6330    R.setHideTags(false);
6331
6332  // For the purposes of this lookup, we have a base object type
6333  // equal to that of the current context.
6334  if (CurContext->isRecord()) {
6335    R.setBaseObjectType(
6336                   Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6337  }
6338
6339  LookupQualifiedName(R, LookupContext);
6340
6341  if (R.empty()) {
6342    Diag(IdentLoc, diag::err_no_member)
6343      << NameInfo.getName() << LookupContext << SS.getRange();
6344    UD->setInvalidDecl();
6345    return UD;
6346  }
6347
6348  if (R.isAmbiguous()) {
6349    UD->setInvalidDecl();
6350    return UD;
6351  }
6352
6353  if (IsTypeName) {
6354    // If we asked for a typename and got a non-type decl, error out.
6355    if (!R.getAsSingle<TypeDecl>()) {
6356      Diag(IdentLoc, diag::err_using_typename_non_type);
6357      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6358        Diag((*I)->getUnderlyingDecl()->getLocation(),
6359             diag::note_using_decl_target);
6360      UD->setInvalidDecl();
6361      return UD;
6362    }
6363  } else {
6364    // If we asked for a non-typename and we got a type, error out,
6365    // but only if this is an instantiation of an unresolved using
6366    // decl.  Otherwise just silently find the type name.
6367    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
6368      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6369      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
6370      UD->setInvalidDecl();
6371      return UD;
6372    }
6373  }
6374
6375  // C++0x N2914 [namespace.udecl]p6:
6376  // A using-declaration shall not name a namespace.
6377  if (R.getAsSingle<NamespaceDecl>()) {
6378    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6379      << SS.getRange();
6380    UD->setInvalidDecl();
6381    return UD;
6382  }
6383
6384  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6385    if (!CheckUsingShadowDecl(UD, *I, Previous))
6386      BuildUsingShadowDecl(S, UD, *I);
6387  }
6388
6389  return UD;
6390}
6391
6392/// Additional checks for a using declaration referring to a constructor name.
6393bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6394  assert(!UD->isTypeName() && "expecting a constructor name");
6395
6396  const Type *SourceType = UD->getQualifier()->getAsType();
6397  assert(SourceType &&
6398         "Using decl naming constructor doesn't have type in scope spec.");
6399  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6400
6401  // Check whether the named type is a direct base class.
6402  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6403  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6404  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6405       BaseIt != BaseE; ++BaseIt) {
6406    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6407    if (CanonicalSourceType == BaseType)
6408      break;
6409    if (BaseIt->getType()->isDependentType())
6410      break;
6411  }
6412
6413  if (BaseIt == BaseE) {
6414    // Did not find SourceType in the bases.
6415    Diag(UD->getUsingLocation(),
6416         diag::err_using_decl_constructor_not_in_direct_base)
6417      << UD->getNameInfo().getSourceRange()
6418      << QualType(SourceType, 0) << TargetClass;
6419    return true;
6420  }
6421
6422  if (!CurContext->isDependentContext())
6423    BaseIt->setInheritConstructors();
6424
6425  return false;
6426}
6427
6428/// Checks that the given using declaration is not an invalid
6429/// redeclaration.  Note that this is checking only for the using decl
6430/// itself, not for any ill-formedness among the UsingShadowDecls.
6431bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6432                                       bool isTypeName,
6433                                       const CXXScopeSpec &SS,
6434                                       SourceLocation NameLoc,
6435                                       const LookupResult &Prev) {
6436  // C++03 [namespace.udecl]p8:
6437  // C++0x [namespace.udecl]p10:
6438  //   A using-declaration is a declaration and can therefore be used
6439  //   repeatedly where (and only where) multiple declarations are
6440  //   allowed.
6441  //
6442  // That's in non-member contexts.
6443  if (!CurContext->getRedeclContext()->isRecord())
6444    return false;
6445
6446  NestedNameSpecifier *Qual
6447    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6448
6449  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6450    NamedDecl *D = *I;
6451
6452    bool DTypename;
6453    NestedNameSpecifier *DQual;
6454    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6455      DTypename = UD->isTypeName();
6456      DQual = UD->getQualifier();
6457    } else if (UnresolvedUsingValueDecl *UD
6458                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6459      DTypename = false;
6460      DQual = UD->getQualifier();
6461    } else if (UnresolvedUsingTypenameDecl *UD
6462                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6463      DTypename = true;
6464      DQual = UD->getQualifier();
6465    } else continue;
6466
6467    // using decls differ if one says 'typename' and the other doesn't.
6468    // FIXME: non-dependent using decls?
6469    if (isTypeName != DTypename) continue;
6470
6471    // using decls differ if they name different scopes (but note that
6472    // template instantiation can cause this check to trigger when it
6473    // didn't before instantiation).
6474    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6475        Context.getCanonicalNestedNameSpecifier(DQual))
6476      continue;
6477
6478    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
6479    Diag(D->getLocation(), diag::note_using_decl) << 1;
6480    return true;
6481  }
6482
6483  return false;
6484}
6485
6486
6487/// Checks that the given nested-name qualifier used in a using decl
6488/// in the current context is appropriately related to the current
6489/// scope.  If an error is found, diagnoses it and returns true.
6490bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6491                                   const CXXScopeSpec &SS,
6492                                   SourceLocation NameLoc) {
6493  DeclContext *NamedContext = computeDeclContext(SS);
6494
6495  if (!CurContext->isRecord()) {
6496    // C++03 [namespace.udecl]p3:
6497    // C++0x [namespace.udecl]p8:
6498    //   A using-declaration for a class member shall be a member-declaration.
6499
6500    // If we weren't able to compute a valid scope, it must be a
6501    // dependent class scope.
6502    if (!NamedContext || NamedContext->isRecord()) {
6503      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6504        << SS.getRange();
6505      return true;
6506    }
6507
6508    // Otherwise, everything is known to be fine.
6509    return false;
6510  }
6511
6512  // The current scope is a record.
6513
6514  // If the named context is dependent, we can't decide much.
6515  if (!NamedContext) {
6516    // FIXME: in C++0x, we can diagnose if we can prove that the
6517    // nested-name-specifier does not refer to a base class, which is
6518    // still possible in some cases.
6519
6520    // Otherwise we have to conservatively report that things might be
6521    // okay.
6522    return false;
6523  }
6524
6525  if (!NamedContext->isRecord()) {
6526    // Ideally this would point at the last name in the specifier,
6527    // but we don't have that level of source info.
6528    Diag(SS.getRange().getBegin(),
6529         diag::err_using_decl_nested_name_specifier_is_not_class)
6530      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6531    return true;
6532  }
6533
6534  if (!NamedContext->isDependentContext() &&
6535      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6536    return true;
6537
6538  if (getLangOpts().CPlusPlus0x) {
6539    // C++0x [namespace.udecl]p3:
6540    //   In a using-declaration used as a member-declaration, the
6541    //   nested-name-specifier shall name a base class of the class
6542    //   being defined.
6543
6544    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6545                                 cast<CXXRecordDecl>(NamedContext))) {
6546      if (CurContext == NamedContext) {
6547        Diag(NameLoc,
6548             diag::err_using_decl_nested_name_specifier_is_current_class)
6549          << SS.getRange();
6550        return true;
6551      }
6552
6553      Diag(SS.getRange().getBegin(),
6554           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6555        << (NestedNameSpecifier*) SS.getScopeRep()
6556        << cast<CXXRecordDecl>(CurContext)
6557        << SS.getRange();
6558      return true;
6559    }
6560
6561    return false;
6562  }
6563
6564  // C++03 [namespace.udecl]p4:
6565  //   A using-declaration used as a member-declaration shall refer
6566  //   to a member of a base class of the class being defined [etc.].
6567
6568  // Salient point: SS doesn't have to name a base class as long as
6569  // lookup only finds members from base classes.  Therefore we can
6570  // diagnose here only if we can prove that that can't happen,
6571  // i.e. if the class hierarchies provably don't intersect.
6572
6573  // TODO: it would be nice if "definitely valid" results were cached
6574  // in the UsingDecl and UsingShadowDecl so that these checks didn't
6575  // need to be repeated.
6576
6577  struct UserData {
6578    llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
6579
6580    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6581      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6582      Data->Bases.insert(Base);
6583      return true;
6584    }
6585
6586    bool hasDependentBases(const CXXRecordDecl *Class) {
6587      return !Class->forallBases(collect, this);
6588    }
6589
6590    /// Returns true if the base is dependent or is one of the
6591    /// accumulated base classes.
6592    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6593      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6594      return !Data->Bases.count(Base);
6595    }
6596
6597    bool mightShareBases(const CXXRecordDecl *Class) {
6598      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6599    }
6600  };
6601
6602  UserData Data;
6603
6604  // Returns false if we find a dependent base.
6605  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6606    return false;
6607
6608  // Returns false if the class has a dependent base or if it or one
6609  // of its bases is present in the base set of the current context.
6610  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6611    return false;
6612
6613  Diag(SS.getRange().getBegin(),
6614       diag::err_using_decl_nested_name_specifier_is_not_base_class)
6615    << (NestedNameSpecifier*) SS.getScopeRep()
6616    << cast<CXXRecordDecl>(CurContext)
6617    << SS.getRange();
6618
6619  return true;
6620}
6621
6622Decl *Sema::ActOnAliasDeclaration(Scope *S,
6623                                  AccessSpecifier AS,
6624                                  MultiTemplateParamsArg TemplateParamLists,
6625                                  SourceLocation UsingLoc,
6626                                  UnqualifiedId &Name,
6627                                  TypeResult Type) {
6628  // Skip up to the relevant declaration scope.
6629  while (S->getFlags() & Scope::TemplateParamScope)
6630    S = S->getParent();
6631  assert((S->getFlags() & Scope::DeclScope) &&
6632         "got alias-declaration outside of declaration scope");
6633
6634  if (Type.isInvalid())
6635    return 0;
6636
6637  bool Invalid = false;
6638  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6639  TypeSourceInfo *TInfo = 0;
6640  GetTypeFromParser(Type.get(), &TInfo);
6641
6642  if (DiagnoseClassNameShadow(CurContext, NameInfo))
6643    return 0;
6644
6645  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
6646                                      UPPC_DeclarationType)) {
6647    Invalid = true;
6648    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6649                                             TInfo->getTypeLoc().getBeginLoc());
6650  }
6651
6652  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6653  LookupName(Previous, S);
6654
6655  // Warn about shadowing the name of a template parameter.
6656  if (Previous.isSingleResult() &&
6657      Previous.getFoundDecl()->isTemplateParameter()) {
6658    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
6659    Previous.clear();
6660  }
6661
6662  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6663         "name in alias declaration must be an identifier");
6664  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6665                                               Name.StartLocation,
6666                                               Name.Identifier, TInfo);
6667
6668  NewTD->setAccess(AS);
6669
6670  if (Invalid)
6671    NewTD->setInvalidDecl();
6672
6673  CheckTypedefForVariablyModifiedType(S, NewTD);
6674  Invalid |= NewTD->isInvalidDecl();
6675
6676  bool Redeclaration = false;
6677
6678  NamedDecl *NewND;
6679  if (TemplateParamLists.size()) {
6680    TypeAliasTemplateDecl *OldDecl = 0;
6681    TemplateParameterList *OldTemplateParams = 0;
6682
6683    if (TemplateParamLists.size() != 1) {
6684      Diag(UsingLoc, diag::err_alias_template_extra_headers)
6685        << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
6686         TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
6687    }
6688    TemplateParameterList *TemplateParams = TemplateParamLists[0];
6689
6690    // Only consider previous declarations in the same scope.
6691    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6692                         /*ExplicitInstantiationOrSpecialization*/false);
6693    if (!Previous.empty()) {
6694      Redeclaration = true;
6695
6696      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6697      if (!OldDecl && !Invalid) {
6698        Diag(UsingLoc, diag::err_redefinition_different_kind)
6699          << Name.Identifier;
6700
6701        NamedDecl *OldD = Previous.getRepresentativeDecl();
6702        if (OldD->getLocation().isValid())
6703          Diag(OldD->getLocation(), diag::note_previous_definition);
6704
6705        Invalid = true;
6706      }
6707
6708      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6709        if (TemplateParameterListsAreEqual(TemplateParams,
6710                                           OldDecl->getTemplateParameters(),
6711                                           /*Complain=*/true,
6712                                           TPL_TemplateMatch))
6713          OldTemplateParams = OldDecl->getTemplateParameters();
6714        else
6715          Invalid = true;
6716
6717        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6718        if (!Invalid &&
6719            !Context.hasSameType(OldTD->getUnderlyingType(),
6720                                 NewTD->getUnderlyingType())) {
6721          // FIXME: The C++0x standard does not clearly say this is ill-formed,
6722          // but we can't reasonably accept it.
6723          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6724            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6725          if (OldTD->getLocation().isValid())
6726            Diag(OldTD->getLocation(), diag::note_previous_definition);
6727          Invalid = true;
6728        }
6729      }
6730    }
6731
6732    // Merge any previous default template arguments into our parameters,
6733    // and check the parameter list.
6734    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6735                                   TPC_TypeAliasTemplate))
6736      return 0;
6737
6738    TypeAliasTemplateDecl *NewDecl =
6739      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6740                                    Name.Identifier, TemplateParams,
6741                                    NewTD);
6742
6743    NewDecl->setAccess(AS);
6744
6745    if (Invalid)
6746      NewDecl->setInvalidDecl();
6747    else if (OldDecl)
6748      NewDecl->setPreviousDeclaration(OldDecl);
6749
6750    NewND = NewDecl;
6751  } else {
6752    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6753    NewND = NewTD;
6754  }
6755
6756  if (!Redeclaration)
6757    PushOnScopeChains(NewND, S);
6758
6759  ActOnDocumentableDecl(NewND);
6760  return NewND;
6761}
6762
6763Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
6764                                             SourceLocation NamespaceLoc,
6765                                             SourceLocation AliasLoc,
6766                                             IdentifierInfo *Alias,
6767                                             CXXScopeSpec &SS,
6768                                             SourceLocation IdentLoc,
6769                                             IdentifierInfo *Ident) {
6770
6771  // Lookup the namespace name.
6772  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6773  LookupParsedName(R, S, &SS);
6774
6775  // Check if we have a previous declaration with the same name.
6776  NamedDecl *PrevDecl
6777    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6778                       ForRedeclaration);
6779  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6780    PrevDecl = 0;
6781
6782  if (PrevDecl) {
6783    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
6784      // We already have an alias with the same name that points to the same
6785      // namespace, so don't create a new one.
6786      // FIXME: At some point, we'll want to create the (redundant)
6787      // declaration to maintain better source information.
6788      if (!R.isAmbiguous() && !R.empty() &&
6789          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
6790        return 0;
6791    }
6792
6793    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6794      diag::err_redefinition_different_kind;
6795    Diag(AliasLoc, DiagID) << Alias;
6796    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6797    return 0;
6798  }
6799
6800  if (R.isAmbiguous())
6801    return 0;
6802
6803  if (R.empty()) {
6804    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
6805      Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6806      return 0;
6807    }
6808  }
6809
6810  NamespaceAliasDecl *AliasDecl =
6811    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
6812                               Alias, SS.getWithLocInContext(Context),
6813                               IdentLoc, R.getFoundDecl());
6814
6815  PushOnScopeChains(AliasDecl, S);
6816  return AliasDecl;
6817}
6818
6819namespace {
6820  /// \brief Scoped object used to handle the state changes required in Sema
6821  /// to implicitly define the body of a C++ member function;
6822  class ImplicitlyDefinedFunctionScope {
6823    Sema &S;
6824    Sema::ContextRAII SavedContext;
6825
6826  public:
6827    ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
6828      : S(S), SavedContext(S, Method)
6829    {
6830      S.PushFunctionScope();
6831      S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6832    }
6833
6834    ~ImplicitlyDefinedFunctionScope() {
6835      S.PopExpressionEvaluationContext();
6836      S.PopFunctionScopeInfo();
6837    }
6838  };
6839}
6840
6841Sema::ImplicitExceptionSpecification
6842Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
6843                                               CXXMethodDecl *MD) {
6844  CXXRecordDecl *ClassDecl = MD->getParent();
6845
6846  // C++ [except.spec]p14:
6847  //   An implicitly declared special member function (Clause 12) shall have an
6848  //   exception-specification. [...]
6849  ImplicitExceptionSpecification ExceptSpec(*this);
6850  if (ClassDecl->isInvalidDecl())
6851    return ExceptSpec;
6852
6853  // Direct base-class constructors.
6854  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6855                                       BEnd = ClassDecl->bases_end();
6856       B != BEnd; ++B) {
6857    if (B->isVirtual()) // Handled below.
6858      continue;
6859
6860    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6861      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6862      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6863      // If this is a deleted function, add it anyway. This might be conformant
6864      // with the standard. This might not. I'm not sure. It might not matter.
6865      if (Constructor)
6866        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
6867    }
6868  }
6869
6870  // Virtual base-class constructors.
6871  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6872                                       BEnd = ClassDecl->vbases_end();
6873       B != BEnd; ++B) {
6874    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6875      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6876      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6877      // If this is a deleted function, add it anyway. This might be conformant
6878      // with the standard. This might not. I'm not sure. It might not matter.
6879      if (Constructor)
6880        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
6881    }
6882  }
6883
6884  // Field constructors.
6885  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6886                               FEnd = ClassDecl->field_end();
6887       F != FEnd; ++F) {
6888    if (F->hasInClassInitializer()) {
6889      if (Expr *E = F->getInClassInitializer())
6890        ExceptSpec.CalledExpr(E);
6891      else if (!F->isInvalidDecl())
6892        // DR1351:
6893        //   If the brace-or-equal-initializer of a non-static data member
6894        //   invokes a defaulted default constructor of its class or of an
6895        //   enclosing class in a potentially evaluated subexpression, the
6896        //   program is ill-formed.
6897        //
6898        // This resolution is unworkable: the exception specification of the
6899        // default constructor can be needed in an unevaluated context, in
6900        // particular, in the operand of a noexcept-expression, and we can be
6901        // unable to compute an exception specification for an enclosed class.
6902        //
6903        // We do not allow an in-class initializer to require the evaluation
6904        // of the exception specification for any in-class initializer whose
6905        // definition is not lexically complete.
6906        Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
6907    } else if (const RecordType *RecordTy
6908              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
6909      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6910      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6911      // If this is a deleted function, add it anyway. This might be conformant
6912      // with the standard. This might not. I'm not sure. It might not matter.
6913      // In particular, the problem is that this function never gets called. It
6914      // might just be ill-formed because this function attempts to refer to
6915      // a deleted function here.
6916      if (Constructor)
6917        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
6918    }
6919  }
6920
6921  return ExceptSpec;
6922}
6923
6924CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6925                                                     CXXRecordDecl *ClassDecl) {
6926  // C++ [class.ctor]p5:
6927  //   A default constructor for a class X is a constructor of class X
6928  //   that can be called without an argument. If there is no
6929  //   user-declared constructor for class X, a default constructor is
6930  //   implicitly declared. An implicitly-declared default constructor
6931  //   is an inline public member of its class.
6932  assert(!ClassDecl->hasUserDeclaredConstructor() &&
6933         "Should not build implicit default constructor!");
6934
6935  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
6936                                                     CXXDefaultConstructor,
6937                                                     false);
6938
6939  // Create the actual constructor declaration.
6940  CanQualType ClassType
6941    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6942  SourceLocation ClassLoc = ClassDecl->getLocation();
6943  DeclarationName Name
6944    = Context.DeclarationNames.getCXXConstructorName(ClassType);
6945  DeclarationNameInfo NameInfo(Name, ClassLoc);
6946  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6947      Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
6948      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
6949      Constexpr);
6950  DefaultCon->setAccess(AS_public);
6951  DefaultCon->setDefaulted();
6952  DefaultCon->setImplicit();
6953  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
6954
6955  // Build an exception specification pointing back at this constructor.
6956  FunctionProtoType::ExtProtoInfo EPI;
6957  EPI.ExceptionSpecType = EST_Unevaluated;
6958  EPI.ExceptionSpecDecl = DefaultCon;
6959  DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6960
6961  // Note that we have declared this constructor.
6962  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6963
6964  if (Scope *S = getScopeForContext(ClassDecl))
6965    PushOnScopeChains(DefaultCon, S, false);
6966  ClassDecl->addDecl(DefaultCon);
6967
6968  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
6969    DefaultCon->setDeletedAsWritten();
6970
6971  return DefaultCon;
6972}
6973
6974void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6975                                            CXXConstructorDecl *Constructor) {
6976  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6977          !Constructor->doesThisDeclarationHaveABody() &&
6978          !Constructor->isDeleted()) &&
6979    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
6980
6981  CXXRecordDecl *ClassDecl = Constructor->getParent();
6982  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
6983
6984  ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
6985  DiagnosticErrorTrap Trap(Diags);
6986  if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
6987      Trap.hasErrorOccurred()) {
6988    Diag(CurrentLocation, diag::note_member_synthesized_at)
6989      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
6990    Constructor->setInvalidDecl();
6991    return;
6992  }
6993
6994  SourceLocation Loc = Constructor->getLocation();
6995  Constructor->setBody(new (Context) CompoundStmt(Loc));
6996
6997  Constructor->setUsed();
6998  MarkVTableUsed(CurrentLocation, ClassDecl);
6999
7000  if (ASTMutationListener *L = getASTMutationListener()) {
7001    L->CompletedImplicitDefinition(Constructor);
7002  }
7003}
7004
7005void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7006  if (!D) return;
7007  AdjustDeclIfTemplate(D);
7008
7009  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7010
7011  if (!ClassDecl->isDependentType())
7012    CheckExplicitlyDefaultedMethods(ClassDecl);
7013}
7014
7015void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7016  // We start with an initial pass over the base classes to collect those that
7017  // inherit constructors from. If there are none, we can forgo all further
7018  // processing.
7019  typedef SmallVector<const RecordType *, 4> BasesVector;
7020  BasesVector BasesToInheritFrom;
7021  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7022                                          BaseE = ClassDecl->bases_end();
7023         BaseIt != BaseE; ++BaseIt) {
7024    if (BaseIt->getInheritConstructors()) {
7025      QualType Base = BaseIt->getType();
7026      if (Base->isDependentType()) {
7027        // If we inherit constructors from anything that is dependent, just
7028        // abort processing altogether. We'll get another chance for the
7029        // instantiations.
7030        return;
7031      }
7032      BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7033    }
7034  }
7035  if (BasesToInheritFrom.empty())
7036    return;
7037
7038  // Now collect the constructors that we already have in the current class.
7039  // Those take precedence over inherited constructors.
7040  // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7041  //   unless there is a user-declared constructor with the same signature in
7042  //   the class where the using-declaration appears.
7043  llvm::SmallSet<const Type *, 8> ExistingConstructors;
7044  for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7045                                    CtorE = ClassDecl->ctor_end();
7046       CtorIt != CtorE; ++CtorIt) {
7047    ExistingConstructors.insert(
7048        Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7049  }
7050
7051  DeclarationName CreatedCtorName =
7052      Context.DeclarationNames.getCXXConstructorName(
7053          ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7054
7055  // Now comes the true work.
7056  // First, we keep a map from constructor types to the base that introduced
7057  // them. Needed for finding conflicting constructors. We also keep the
7058  // actually inserted declarations in there, for pretty diagnostics.
7059  typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7060  typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7061  ConstructorToSourceMap InheritedConstructors;
7062  for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7063                             BaseE = BasesToInheritFrom.end();
7064       BaseIt != BaseE; ++BaseIt) {
7065    const RecordType *Base = *BaseIt;
7066    CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7067    CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7068    for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7069                                      CtorE = BaseDecl->ctor_end();
7070         CtorIt != CtorE; ++CtorIt) {
7071      // Find the using declaration for inheriting this base's constructors.
7072      // FIXME: Don't perform name lookup just to obtain a source location!
7073      DeclarationName Name =
7074          Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7075      LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7076      LookupQualifiedName(Result, CurContext);
7077      UsingDecl *UD = Result.getAsSingle<UsingDecl>();
7078      SourceLocation UsingLoc = UD ? UD->getLocation() :
7079                                     ClassDecl->getLocation();
7080
7081      // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7082      //   from the class X named in the using-declaration consists of actual
7083      //   constructors and notional constructors that result from the
7084      //   transformation of defaulted parameters as follows:
7085      //   - all non-template default constructors of X, and
7086      //   - for each non-template constructor of X that has at least one
7087      //     parameter with a default argument, the set of constructors that
7088      //     results from omitting any ellipsis parameter specification and
7089      //     successively omitting parameters with a default argument from the
7090      //     end of the parameter-type-list.
7091      CXXConstructorDecl *BaseCtor = *CtorIt;
7092      bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7093      const FunctionProtoType *BaseCtorType =
7094          BaseCtor->getType()->getAs<FunctionProtoType>();
7095
7096      for (unsigned params = BaseCtor->getMinRequiredArguments(),
7097                    maxParams = BaseCtor->getNumParams();
7098           params <= maxParams; ++params) {
7099        // Skip default constructors. They're never inherited.
7100        if (params == 0)
7101          continue;
7102        // Skip copy and move constructors for the same reason.
7103        if (CanBeCopyOrMove && params == 1)
7104          continue;
7105
7106        // Build up a function type for this particular constructor.
7107        // FIXME: The working paper does not consider that the exception spec
7108        // for the inheriting constructor might be larger than that of the
7109        // source. This code doesn't yet, either. When it does, this code will
7110        // need to be delayed until after exception specifications and in-class
7111        // member initializers are attached.
7112        const Type *NewCtorType;
7113        if (params == maxParams)
7114          NewCtorType = BaseCtorType;
7115        else {
7116          SmallVector<QualType, 16> Args;
7117          for (unsigned i = 0; i < params; ++i) {
7118            Args.push_back(BaseCtorType->getArgType(i));
7119          }
7120          FunctionProtoType::ExtProtoInfo ExtInfo =
7121              BaseCtorType->getExtProtoInfo();
7122          ExtInfo.Variadic = false;
7123          NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7124                                                Args.data(), params, ExtInfo)
7125                       .getTypePtr();
7126        }
7127        const Type *CanonicalNewCtorType =
7128            Context.getCanonicalType(NewCtorType);
7129
7130        // Now that we have the type, first check if the class already has a
7131        // constructor with this signature.
7132        if (ExistingConstructors.count(CanonicalNewCtorType))
7133          continue;
7134
7135        // Then we check if we have already declared an inherited constructor
7136        // with this signature.
7137        std::pair<ConstructorToSourceMap::iterator, bool> result =
7138            InheritedConstructors.insert(std::make_pair(
7139                CanonicalNewCtorType,
7140                std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7141        if (!result.second) {
7142          // Already in the map. If it came from a different class, that's an
7143          // error. Not if it's from the same.
7144          CanQualType PreviousBase = result.first->second.first;
7145          if (CanonicalBase != PreviousBase) {
7146            const CXXConstructorDecl *PrevCtor = result.first->second.second;
7147            const CXXConstructorDecl *PrevBaseCtor =
7148                PrevCtor->getInheritedConstructor();
7149            assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7150
7151            Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7152            Diag(BaseCtor->getLocation(),
7153                 diag::note_using_decl_constructor_conflict_current_ctor);
7154            Diag(PrevBaseCtor->getLocation(),
7155                 diag::note_using_decl_constructor_conflict_previous_ctor);
7156            Diag(PrevCtor->getLocation(),
7157                 diag::note_using_decl_constructor_conflict_previous_using);
7158          }
7159          continue;
7160        }
7161
7162        // OK, we're there, now add the constructor.
7163        // C++0x [class.inhctor]p8: [...] that would be performed by a
7164        //   user-written inline constructor [...]
7165        DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7166        CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
7167            Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7168            /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
7169            /*ImplicitlyDeclared=*/true,
7170            // FIXME: Due to a defect in the standard, we treat inherited
7171            // constructors as constexpr even if that makes them ill-formed.
7172            /*Constexpr=*/BaseCtor->isConstexpr());
7173        NewCtor->setAccess(BaseCtor->getAccess());
7174
7175        // Build up the parameter decls and add them.
7176        SmallVector<ParmVarDecl *, 16> ParamDecls;
7177        for (unsigned i = 0; i < params; ++i) {
7178          ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7179                                                   UsingLoc, UsingLoc,
7180                                                   /*IdentifierInfo=*/0,
7181                                                   BaseCtorType->getArgType(i),
7182                                                   /*TInfo=*/0, SC_None,
7183                                                   SC_None, /*DefaultArg=*/0));
7184        }
7185        NewCtor->setParams(ParamDecls);
7186        NewCtor->setInheritedConstructor(BaseCtor);
7187
7188        ClassDecl->addDecl(NewCtor);
7189        result.first->second.second = NewCtor;
7190      }
7191    }
7192  }
7193}
7194
7195Sema::ImplicitExceptionSpecification
7196Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7197  CXXRecordDecl *ClassDecl = MD->getParent();
7198
7199  // C++ [except.spec]p14:
7200  //   An implicitly declared special member function (Clause 12) shall have
7201  //   an exception-specification.
7202  ImplicitExceptionSpecification ExceptSpec(*this);
7203  if (ClassDecl->isInvalidDecl())
7204    return ExceptSpec;
7205
7206  // Direct base-class destructors.
7207  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7208                                       BEnd = ClassDecl->bases_end();
7209       B != BEnd; ++B) {
7210    if (B->isVirtual()) // Handled below.
7211      continue;
7212
7213    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7214      ExceptSpec.CalledDecl(B->getLocStart(),
7215                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7216  }
7217
7218  // Virtual base-class destructors.
7219  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7220                                       BEnd = ClassDecl->vbases_end();
7221       B != BEnd; ++B) {
7222    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7223      ExceptSpec.CalledDecl(B->getLocStart(),
7224                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7225  }
7226
7227  // Field destructors.
7228  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7229                               FEnd = ClassDecl->field_end();
7230       F != FEnd; ++F) {
7231    if (const RecordType *RecordTy
7232        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7233      ExceptSpec.CalledDecl(F->getLocation(),
7234                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
7235  }
7236
7237  return ExceptSpec;
7238}
7239
7240CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7241  // C++ [class.dtor]p2:
7242  //   If a class has no user-declared destructor, a destructor is
7243  //   declared implicitly. An implicitly-declared destructor is an
7244  //   inline public member of its class.
7245
7246  // Create the actual destructor declaration.
7247  CanQualType ClassType
7248    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7249  SourceLocation ClassLoc = ClassDecl->getLocation();
7250  DeclarationName Name
7251    = Context.DeclarationNames.getCXXDestructorName(ClassType);
7252  DeclarationNameInfo NameInfo(Name, ClassLoc);
7253  CXXDestructorDecl *Destructor
7254      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7255                                  QualType(), 0, /*isInline=*/true,
7256                                  /*isImplicitlyDeclared=*/true);
7257  Destructor->setAccess(AS_public);
7258  Destructor->setDefaulted();
7259  Destructor->setImplicit();
7260  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7261
7262  // Build an exception specification pointing back at this destructor.
7263  FunctionProtoType::ExtProtoInfo EPI;
7264  EPI.ExceptionSpecType = EST_Unevaluated;
7265  EPI.ExceptionSpecDecl = Destructor;
7266  Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7267
7268  // Note that we have declared this destructor.
7269  ++ASTContext::NumImplicitDestructorsDeclared;
7270
7271  // Introduce this destructor into its scope.
7272  if (Scope *S = getScopeForContext(ClassDecl))
7273    PushOnScopeChains(Destructor, S, false);
7274  ClassDecl->addDecl(Destructor);
7275
7276  AddOverriddenMethods(ClassDecl, Destructor);
7277
7278  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7279    Destructor->setDeletedAsWritten();
7280
7281  return Destructor;
7282}
7283
7284void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
7285                                    CXXDestructorDecl *Destructor) {
7286  assert((Destructor->isDefaulted() &&
7287          !Destructor->doesThisDeclarationHaveABody() &&
7288          !Destructor->isDeleted()) &&
7289         "DefineImplicitDestructor - call it for implicit default dtor");
7290  CXXRecordDecl *ClassDecl = Destructor->getParent();
7291  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
7292
7293  if (Destructor->isInvalidDecl())
7294    return;
7295
7296  ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
7297
7298  DiagnosticErrorTrap Trap(Diags);
7299  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7300                                         Destructor->getParent());
7301
7302  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
7303    Diag(CurrentLocation, diag::note_member_synthesized_at)
7304      << CXXDestructor << Context.getTagDeclType(ClassDecl);
7305
7306    Destructor->setInvalidDecl();
7307    return;
7308  }
7309
7310  SourceLocation Loc = Destructor->getLocation();
7311  Destructor->setBody(new (Context) CompoundStmt(Loc));
7312  Destructor->setImplicitlyDefined(true);
7313  Destructor->setUsed();
7314  MarkVTableUsed(CurrentLocation, ClassDecl);
7315
7316  if (ASTMutationListener *L = getASTMutationListener()) {
7317    L->CompletedImplicitDefinition(Destructor);
7318  }
7319}
7320
7321/// \brief Perform any semantic analysis which needs to be delayed until all
7322/// pending class member declarations have been parsed.
7323void Sema::ActOnFinishCXXMemberDecls() {
7324  // Perform any deferred checking of exception specifications for virtual
7325  // destructors.
7326  for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7327       i != e; ++i) {
7328    const CXXDestructorDecl *Dtor =
7329        DelayedDestructorExceptionSpecChecks[i].first;
7330    assert(!Dtor->getParent()->isDependentType() &&
7331           "Should not ever add destructors of templates into the list.");
7332    CheckOverridingFunctionExceptionSpec(Dtor,
7333        DelayedDestructorExceptionSpecChecks[i].second);
7334  }
7335  DelayedDestructorExceptionSpecChecks.clear();
7336}
7337
7338void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7339                                         CXXDestructorDecl *Destructor) {
7340  assert(getLangOpts().CPlusPlus0x &&
7341         "adjusting dtor exception specs was introduced in c++11");
7342
7343  // C++11 [class.dtor]p3:
7344  //   A declaration of a destructor that does not have an exception-
7345  //   specification is implicitly considered to have the same exception-
7346  //   specification as an implicit declaration.
7347  const FunctionProtoType *DtorType = Destructor->getType()->
7348                                        getAs<FunctionProtoType>();
7349  if (DtorType->hasExceptionSpec())
7350    return;
7351
7352  // Replace the destructor's type, building off the existing one. Fortunately,
7353  // the only thing of interest in the destructor type is its extended info.
7354  // The return and arguments are fixed.
7355  FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7356  EPI.ExceptionSpecType = EST_Unevaluated;
7357  EPI.ExceptionSpecDecl = Destructor;
7358  Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7359
7360  // FIXME: If the destructor has a body that could throw, and the newly created
7361  // spec doesn't allow exceptions, we should emit a warning, because this
7362  // change in behavior can break conforming C++03 programs at runtime.
7363  // However, we don't have a body or an exception specification yet, so it
7364  // needs to be done somewhere else.
7365}
7366
7367/// \brief Builds a statement that copies/moves the given entity from \p From to
7368/// \c To.
7369///
7370/// This routine is used to copy/move the members of a class with an
7371/// implicitly-declared copy/move assignment operator. When the entities being
7372/// copied are arrays, this routine builds for loops to copy them.
7373///
7374/// \param S The Sema object used for type-checking.
7375///
7376/// \param Loc The location where the implicit copy/move is being generated.
7377///
7378/// \param T The type of the expressions being copied/moved. Both expressions
7379/// must have this type.
7380///
7381/// \param To The expression we are copying/moving to.
7382///
7383/// \param From The expression we are copying/moving from.
7384///
7385/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
7386/// Otherwise, it's a non-static member subobject.
7387///
7388/// \param Copying Whether we're copying or moving.
7389///
7390/// \param Depth Internal parameter recording the depth of the recursion.
7391///
7392/// \returns A statement or a loop that copies the expressions.
7393static StmtResult
7394BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
7395                      Expr *To, Expr *From,
7396                      bool CopyingBaseSubobject, bool Copying,
7397                      unsigned Depth = 0) {
7398  // C++0x [class.copy]p28:
7399  //   Each subobject is assigned in the manner appropriate to its type:
7400  //
7401  //     - if the subobject is of class type, as if by a call to operator= with
7402  //       the subobject as the object expression and the corresponding
7403  //       subobject of x as a single function argument (as if by explicit
7404  //       qualification; that is, ignoring any possible virtual overriding
7405  //       functions in more derived classes);
7406  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7407    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7408
7409    // Look for operator=.
7410    DeclarationName Name
7411      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7412    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7413    S.LookupQualifiedName(OpLookup, ClassDecl, false);
7414
7415    // Filter out any result that isn't a copy/move-assignment operator.
7416    LookupResult::Filter F = OpLookup.makeFilter();
7417    while (F.hasNext()) {
7418      NamedDecl *D = F.next();
7419      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
7420        if (Method->isCopyAssignmentOperator() ||
7421            (!Copying && Method->isMoveAssignmentOperator()))
7422          continue;
7423
7424      F.erase();
7425    }
7426    F.done();
7427
7428    // Suppress the protected check (C++ [class.protected]) for each of the
7429    // assignment operators we found. This strange dance is required when
7430    // we're assigning via a base classes's copy-assignment operator. To
7431    // ensure that we're getting the right base class subobject (without
7432    // ambiguities), we need to cast "this" to that subobject type; to
7433    // ensure that we don't go through the virtual call mechanism, we need
7434    // to qualify the operator= name with the base class (see below). However,
7435    // this means that if the base class has a protected copy assignment
7436    // operator, the protected member access check will fail. So, we
7437    // rewrite "protected" access to "public" access in this case, since we
7438    // know by construction that we're calling from a derived class.
7439    if (CopyingBaseSubobject) {
7440      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7441           L != LEnd; ++L) {
7442        if (L.getAccess() == AS_protected)
7443          L.setAccess(AS_public);
7444      }
7445    }
7446
7447    // Create the nested-name-specifier that will be used to qualify the
7448    // reference to operator=; this is required to suppress the virtual
7449    // call mechanism.
7450    CXXScopeSpec SS;
7451    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
7452    SS.MakeTrivial(S.Context,
7453                   NestedNameSpecifier::Create(S.Context, 0, false,
7454                                               CanonicalT),
7455                   Loc);
7456
7457    // Create the reference to operator=.
7458    ExprResult OpEqualRef
7459      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
7460                                   /*TemplateKWLoc=*/SourceLocation(),
7461                                   /*FirstQualifierInScope=*/0,
7462                                   OpLookup,
7463                                   /*TemplateArgs=*/0,
7464                                   /*SuppressQualifierCheck=*/true);
7465    if (OpEqualRef.isInvalid())
7466      return StmtError();
7467
7468    // Build the call to the assignment operator.
7469
7470    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
7471                                                  OpEqualRef.takeAs<Expr>(),
7472                                                  Loc, &From, 1, Loc);
7473    if (Call.isInvalid())
7474      return StmtError();
7475
7476    return S.Owned(Call.takeAs<Stmt>());
7477  }
7478
7479  //     - if the subobject is of scalar type, the built-in assignment
7480  //       operator is used.
7481  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7482  if (!ArrayTy) {
7483    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
7484    if (Assignment.isInvalid())
7485      return StmtError();
7486
7487    return S.Owned(Assignment.takeAs<Stmt>());
7488  }
7489
7490  //     - if the subobject is an array, each element is assigned, in the
7491  //       manner appropriate to the element type;
7492
7493  // Construct a loop over the array bounds, e.g.,
7494  //
7495  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7496  //
7497  // that will copy each of the array elements.
7498  QualType SizeType = S.Context.getSizeType();
7499
7500  // Create the iteration variable.
7501  IdentifierInfo *IterationVarName = 0;
7502  {
7503    SmallString<8> Str;
7504    llvm::raw_svector_ostream OS(Str);
7505    OS << "__i" << Depth;
7506    IterationVarName = &S.Context.Idents.get(OS.str());
7507  }
7508  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
7509                                          IterationVarName, SizeType,
7510                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
7511                                          SC_None, SC_None);
7512
7513  // Initialize the iteration variable to zero.
7514  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
7515  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
7516
7517  // Create a reference to the iteration variable; we'll use this several
7518  // times throughout.
7519  Expr *IterationVarRef
7520    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
7521  assert(IterationVarRef && "Reference to invented variable cannot fail!");
7522  Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7523  assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7524
7525  // Create the DeclStmt that holds the iteration variable.
7526  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7527
7528  // Create the comparison against the array bound.
7529  llvm::APInt Upper
7530    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
7531  Expr *Comparison
7532    = new (S.Context) BinaryOperator(IterationVarRefRVal,
7533                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7534                                     BO_NE, S.Context.BoolTy,
7535                                     VK_RValue, OK_Ordinary, Loc, false);
7536
7537  // Create the pre-increment of the iteration variable.
7538  Expr *Increment
7539    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7540                                    VK_LValue, OK_Ordinary, Loc);
7541
7542  // Subscript the "from" and "to" expressions with the iteration variable.
7543  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7544                                                         IterationVarRefRVal,
7545                                                         Loc));
7546  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7547                                                       IterationVarRefRVal,
7548                                                       Loc));
7549  if (!Copying) // Cast to rvalue
7550    From = CastForMoving(S, From);
7551
7552  // Build the copy/move for an individual element of the array.
7553  StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7554                                          To, From, CopyingBaseSubobject,
7555                                          Copying, Depth + 1);
7556  if (Copy.isInvalid())
7557    return StmtError();
7558
7559  // Construct the loop that copies all elements of this array.
7560  return S.ActOnForStmt(Loc, Loc, InitStmt,
7561                        S.MakeFullExpr(Comparison),
7562                        0, S.MakeFullExpr(Increment),
7563                        Loc, Copy.take());
7564}
7565
7566/// Determine whether an implicit copy assignment operator for ClassDecl has a
7567/// const argument.
7568/// FIXME: It ought to be possible to store this on the record.
7569static bool isImplicitCopyAssignmentArgConst(Sema &S,
7570                                             CXXRecordDecl *ClassDecl) {
7571  if (ClassDecl->isInvalidDecl())
7572    return true;
7573
7574  // C++ [class.copy]p10:
7575  //   If the class definition does not explicitly declare a copy
7576  //   assignment operator, one is declared implicitly.
7577  //   The implicitly-defined copy assignment operator for a class X
7578  //   will have the form
7579  //
7580  //       X& X::operator=(const X&)
7581  //
7582  //   if
7583  //       -- each direct base class B of X has a copy assignment operator
7584  //          whose parameter is of type const B&, const volatile B& or B,
7585  //          and
7586  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7587                                       BaseEnd = ClassDecl->bases_end();
7588       Base != BaseEnd; ++Base) {
7589    // We'll handle this below
7590    if (S.getLangOpts().CPlusPlus0x && Base->isVirtual())
7591      continue;
7592
7593    assert(!Base->getType()->isDependentType() &&
7594           "Cannot generate implicit members for class with dependent bases.");
7595    CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7596    if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0))
7597      return false;
7598  }
7599
7600  // In C++11, the above citation has "or virtual" added
7601  if (S.getLangOpts().CPlusPlus0x) {
7602    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7603                                         BaseEnd = ClassDecl->vbases_end();
7604         Base != BaseEnd; ++Base) {
7605      assert(!Base->getType()->isDependentType() &&
7606             "Cannot generate implicit members for class with dependent bases.");
7607      CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7608      if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7609                                     false, 0))
7610        return false;
7611    }
7612  }
7613
7614  //       -- for all the nonstatic data members of X that are of a class
7615  //          type M (or array thereof), each such class type has a copy
7616  //          assignment operator whose parameter is of type const M&,
7617  //          const volatile M& or M.
7618  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7619                                  FieldEnd = ClassDecl->field_end();
7620       Field != FieldEnd; ++Field) {
7621    QualType FieldType = S.Context.getBaseElementType(Field->getType());
7622    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl())
7623      if (!S.LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const,
7624                                     false, 0))
7625        return false;
7626  }
7627
7628  //   Otherwise, the implicitly declared copy assignment operator will
7629  //   have the form
7630  //
7631  //       X& X::operator=(X&)
7632
7633  return true;
7634}
7635
7636Sema::ImplicitExceptionSpecification
7637Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
7638  CXXRecordDecl *ClassDecl = MD->getParent();
7639
7640  ImplicitExceptionSpecification ExceptSpec(*this);
7641  if (ClassDecl->isInvalidDecl())
7642    return ExceptSpec;
7643
7644  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
7645  assert(T->getNumArgs() == 1 && "not a copy assignment op");
7646  unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
7647
7648  // C++ [except.spec]p14:
7649  //   An implicitly declared special member function (Clause 12) shall have an
7650  //   exception-specification. [...]
7651
7652  // It is unspecified whether or not an implicit copy assignment operator
7653  // attempts to deduplicate calls to assignment operators of virtual bases are
7654  // made. As such, this exception specification is effectively unspecified.
7655  // Based on a similar decision made for constness in C++0x, we're erring on
7656  // the side of assuming such calls to be made regardless of whether they
7657  // actually happen.
7658  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7659                                       BaseEnd = ClassDecl->bases_end();
7660       Base != BaseEnd; ++Base) {
7661    if (Base->isVirtual())
7662      continue;
7663
7664    CXXRecordDecl *BaseClassDecl
7665      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7666    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7667                                                            ArgQuals, false, 0))
7668      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
7669  }
7670
7671  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7672                                       BaseEnd = ClassDecl->vbases_end();
7673       Base != BaseEnd; ++Base) {
7674    CXXRecordDecl *BaseClassDecl
7675      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7676    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7677                                                            ArgQuals, false, 0))
7678      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
7679  }
7680
7681  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7682                                  FieldEnd = ClassDecl->field_end();
7683       Field != FieldEnd;
7684       ++Field) {
7685    QualType FieldType = Context.getBaseElementType(Field->getType());
7686    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7687      if (CXXMethodDecl *CopyAssign =
7688          LookupCopyingAssignment(FieldClassDecl,
7689                                  ArgQuals | FieldType.getCVRQualifiers(),
7690                                  false, 0))
7691        ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
7692    }
7693  }
7694
7695  return ExceptSpec;
7696}
7697
7698CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7699  // Note: The following rules are largely analoguous to the copy
7700  // constructor rules. Note that virtual bases are not taken into account
7701  // for determining the argument type of the operator. Note also that
7702  // operators taking an object instead of a reference are allowed.
7703
7704  QualType ArgType = Context.getTypeDeclType(ClassDecl);
7705  QualType RetType = Context.getLValueReferenceType(ArgType);
7706  if (isImplicitCopyAssignmentArgConst(*this, ClassDecl))
7707    ArgType = ArgType.withConst();
7708  ArgType = Context.getLValueReferenceType(ArgType);
7709
7710  //   An implicitly-declared copy assignment operator is an inline public
7711  //   member of its class.
7712  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7713  SourceLocation ClassLoc = ClassDecl->getLocation();
7714  DeclarationNameInfo NameInfo(Name, ClassLoc);
7715  CXXMethodDecl *CopyAssignment
7716    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
7717                            /*TInfo=*/0, /*isStatic=*/false,
7718                            /*StorageClassAsWritten=*/SC_None,
7719                            /*isInline=*/true, /*isConstexpr=*/false,
7720                            SourceLocation());
7721  CopyAssignment->setAccess(AS_public);
7722  CopyAssignment->setDefaulted();
7723  CopyAssignment->setImplicit();
7724  CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
7725
7726  // Build an exception specification pointing back at this member.
7727  FunctionProtoType::ExtProtoInfo EPI;
7728  EPI.ExceptionSpecType = EST_Unevaluated;
7729  EPI.ExceptionSpecDecl = CopyAssignment;
7730  CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
7731
7732  // Add the parameter to the operator.
7733  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
7734                                               ClassLoc, ClassLoc, /*Id=*/0,
7735                                               ArgType, /*TInfo=*/0,
7736                                               SC_None,
7737                                               SC_None, 0);
7738  CopyAssignment->setParams(FromParam);
7739
7740  // Note that we have added this copy-assignment operator.
7741  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
7742
7743  if (Scope *S = getScopeForContext(ClassDecl))
7744    PushOnScopeChains(CopyAssignment, S, false);
7745  ClassDecl->addDecl(CopyAssignment);
7746
7747  // C++0x [class.copy]p19:
7748  //   ....  If the class definition does not explicitly declare a copy
7749  //   assignment operator, there is no user-declared move constructor, and
7750  //   there is no user-declared move assignment operator, a copy assignment
7751  //   operator is implicitly declared as defaulted.
7752  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
7753    CopyAssignment->setDeletedAsWritten();
7754
7755  AddOverriddenMethods(ClassDecl, CopyAssignment);
7756  return CopyAssignment;
7757}
7758
7759void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7760                                        CXXMethodDecl *CopyAssignOperator) {
7761  assert((CopyAssignOperator->isDefaulted() &&
7762          CopyAssignOperator->isOverloadedOperator() &&
7763          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
7764          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7765          !CopyAssignOperator->isDeleted()) &&
7766         "DefineImplicitCopyAssignment called for wrong function");
7767
7768  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7769
7770  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7771    CopyAssignOperator->setInvalidDecl();
7772    return;
7773  }
7774
7775  CopyAssignOperator->setUsed();
7776
7777  ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
7778  DiagnosticErrorTrap Trap(Diags);
7779
7780  // C++0x [class.copy]p30:
7781  //   The implicitly-defined or explicitly-defaulted copy assignment operator
7782  //   for a non-union class X performs memberwise copy assignment of its
7783  //   subobjects. The direct base classes of X are assigned first, in the
7784  //   order of their declaration in the base-specifier-list, and then the
7785  //   immediate non-static data members of X are assigned, in the order in
7786  //   which they were declared in the class definition.
7787
7788  // The statements that form the synthesized function body.
7789  SmallVector<Stmt*, 8> Statements;
7790
7791  // The parameter for the "other" object, which we are copying from.
7792  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7793  Qualifiers OtherQuals = Other->getType().getQualifiers();
7794  QualType OtherRefType = Other->getType();
7795  if (const LValueReferenceType *OtherRef
7796                                = OtherRefType->getAs<LValueReferenceType>()) {
7797    OtherRefType = OtherRef->getPointeeType();
7798    OtherQuals = OtherRefType.getQualifiers();
7799  }
7800
7801  // Our location for everything implicitly-generated.
7802  SourceLocation Loc = CopyAssignOperator->getLocation();
7803
7804  // Construct a reference to the "other" object. We'll be using this
7805  // throughout the generated ASTs.
7806  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7807  assert(OtherRef && "Reference to parameter cannot fail!");
7808
7809  // Construct the "this" pointer. We'll be using this throughout the generated
7810  // ASTs.
7811  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7812  assert(This && "Reference to this cannot fail!");
7813
7814  // Assign base classes.
7815  bool Invalid = false;
7816  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7817       E = ClassDecl->bases_end(); Base != E; ++Base) {
7818    // Form the assignment:
7819    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7820    QualType BaseType = Base->getType().getUnqualifiedType();
7821    if (!BaseType->isRecordType()) {
7822      Invalid = true;
7823      continue;
7824    }
7825
7826    CXXCastPath BasePath;
7827    BasePath.push_back(Base);
7828
7829    // Construct the "from" expression, which is an implicit cast to the
7830    // appropriately-qualified base type.
7831    Expr *From = OtherRef;
7832    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7833                             CK_UncheckedDerivedToBase,
7834                             VK_LValue, &BasePath).take();
7835
7836    // Dereference "this".
7837    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7838
7839    // Implicitly cast "this" to the appropriately-qualified base type.
7840    To = ImpCastExprToType(To.take(),
7841                           Context.getCVRQualifiedType(BaseType,
7842                                     CopyAssignOperator->getTypeQualifiers()),
7843                           CK_UncheckedDerivedToBase,
7844                           VK_LValue, &BasePath);
7845
7846    // Build the copy.
7847    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
7848                                            To.get(), From,
7849                                            /*CopyingBaseSubobject=*/true,
7850                                            /*Copying=*/true);
7851    if (Copy.isInvalid()) {
7852      Diag(CurrentLocation, diag::note_member_synthesized_at)
7853        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7854      CopyAssignOperator->setInvalidDecl();
7855      return;
7856    }
7857
7858    // Success! Record the copy.
7859    Statements.push_back(Copy.takeAs<Expr>());
7860  }
7861
7862  // \brief Reference to the __builtin_memcpy function.
7863  Expr *BuiltinMemCpyRef = 0;
7864  // \brief Reference to the __builtin_objc_memmove_collectable function.
7865  Expr *CollectableMemCpyRef = 0;
7866
7867  // Assign non-static members.
7868  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7869                                  FieldEnd = ClassDecl->field_end();
7870       Field != FieldEnd; ++Field) {
7871    if (Field->isUnnamedBitfield())
7872      continue;
7873
7874    // Check for members of reference type; we can't copy those.
7875    if (Field->getType()->isReferenceType()) {
7876      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7877        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7878      Diag(Field->getLocation(), diag::note_declared_at);
7879      Diag(CurrentLocation, diag::note_member_synthesized_at)
7880        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7881      Invalid = true;
7882      continue;
7883    }
7884
7885    // Check for members of const-qualified, non-class type.
7886    QualType BaseType = Context.getBaseElementType(Field->getType());
7887    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7888      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7889        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7890      Diag(Field->getLocation(), diag::note_declared_at);
7891      Diag(CurrentLocation, diag::note_member_synthesized_at)
7892        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7893      Invalid = true;
7894      continue;
7895    }
7896
7897    // Suppress assigning zero-width bitfields.
7898    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7899      continue;
7900
7901    QualType FieldType = Field->getType().getNonReferenceType();
7902    if (FieldType->isIncompleteArrayType()) {
7903      assert(ClassDecl->hasFlexibleArrayMember() &&
7904             "Incomplete array type is not valid");
7905      continue;
7906    }
7907
7908    // Build references to the field in the object we're copying from and to.
7909    CXXScopeSpec SS; // Intentionally empty
7910    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7911                              LookupMemberName);
7912    MemberLookup.addDecl(*Field);
7913    MemberLookup.resolveKind();
7914    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7915                                               Loc, /*IsArrow=*/false,
7916                                               SS, SourceLocation(), 0,
7917                                               MemberLookup, 0);
7918    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7919                                             Loc, /*IsArrow=*/true,
7920                                             SS, SourceLocation(), 0,
7921                                             MemberLookup, 0);
7922    assert(!From.isInvalid() && "Implicit field reference cannot fail");
7923    assert(!To.isInvalid() && "Implicit field reference cannot fail");
7924
7925    // If the field should be copied with __builtin_memcpy rather than via
7926    // explicit assignments, do so. This optimization only applies for arrays
7927    // of scalars and arrays of class type with trivial copy-assignment
7928    // operators.
7929    if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7930        && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
7931      // Compute the size of the memory buffer to be copied.
7932      QualType SizeType = Context.getSizeType();
7933      llvm::APInt Size(Context.getTypeSize(SizeType),
7934                       Context.getTypeSizeInChars(BaseType).getQuantity());
7935      for (const ConstantArrayType *Array
7936              = Context.getAsConstantArrayType(FieldType);
7937           Array;
7938           Array = Context.getAsConstantArrayType(Array->getElementType())) {
7939        llvm::APInt ArraySize
7940          = Array->getSize().zextOrTrunc(Size.getBitWidth());
7941        Size *= ArraySize;
7942      }
7943
7944      // Take the address of the field references for "from" and "to".
7945      From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7946      To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
7947
7948      bool NeedsCollectableMemCpy =
7949          (BaseType->isRecordType() &&
7950           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7951
7952      if (NeedsCollectableMemCpy) {
7953        if (!CollectableMemCpyRef) {
7954          // Create a reference to the __builtin_objc_memmove_collectable function.
7955          LookupResult R(*this,
7956                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
7957                         Loc, LookupOrdinaryName);
7958          LookupName(R, TUScope, true);
7959
7960          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7961          if (!CollectableMemCpy) {
7962            // Something went horribly wrong earlier, and we will have
7963            // complained about it.
7964            Invalid = true;
7965            continue;
7966          }
7967
7968          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7969                                                  Context.BuiltinFnTy,
7970                                                  VK_RValue, Loc, 0).take();
7971          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7972        }
7973      }
7974      // Create a reference to the __builtin_memcpy builtin function.
7975      else if (!BuiltinMemCpyRef) {
7976        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7977                       LookupOrdinaryName);
7978        LookupName(R, TUScope, true);
7979
7980        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7981        if (!BuiltinMemCpy) {
7982          // Something went horribly wrong earlier, and we will have complained
7983          // about it.
7984          Invalid = true;
7985          continue;
7986        }
7987
7988        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7989                                            Context.BuiltinFnTy,
7990                                            VK_RValue, Loc, 0).take();
7991        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7992      }
7993
7994      SmallVector<Expr*, 8> CallArgs;
7995      CallArgs.push_back(To.takeAs<Expr>());
7996      CallArgs.push_back(From.takeAs<Expr>());
7997      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
7998      ExprResult Call = ExprError();
7999      if (NeedsCollectableMemCpy)
8000        Call = ActOnCallExpr(/*Scope=*/0,
8001                             CollectableMemCpyRef,
8002                             Loc, CallArgs,
8003                             Loc);
8004      else
8005        Call = ActOnCallExpr(/*Scope=*/0,
8006                             BuiltinMemCpyRef,
8007                             Loc, CallArgs,
8008                             Loc);
8009
8010      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8011      Statements.push_back(Call.takeAs<Expr>());
8012      continue;
8013    }
8014
8015    // Build the copy of this field.
8016    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
8017                                            To.get(), From.get(),
8018                                            /*CopyingBaseSubobject=*/false,
8019                                            /*Copying=*/true);
8020    if (Copy.isInvalid()) {
8021      Diag(CurrentLocation, diag::note_member_synthesized_at)
8022        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8023      CopyAssignOperator->setInvalidDecl();
8024      return;
8025    }
8026
8027    // Success! Record the copy.
8028    Statements.push_back(Copy.takeAs<Stmt>());
8029  }
8030
8031  if (!Invalid) {
8032    // Add a "return *this;"
8033    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8034
8035    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8036    if (Return.isInvalid())
8037      Invalid = true;
8038    else {
8039      Statements.push_back(Return.takeAs<Stmt>());
8040
8041      if (Trap.hasErrorOccurred()) {
8042        Diag(CurrentLocation, diag::note_member_synthesized_at)
8043          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8044        Invalid = true;
8045      }
8046    }
8047  }
8048
8049  if (Invalid) {
8050    CopyAssignOperator->setInvalidDecl();
8051    return;
8052  }
8053
8054  StmtResult Body;
8055  {
8056    CompoundScopeRAII CompoundScope(*this);
8057    Body = ActOnCompoundStmt(Loc, Loc, Statements,
8058                             /*isStmtExpr=*/false);
8059    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8060  }
8061  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
8062
8063  if (ASTMutationListener *L = getASTMutationListener()) {
8064    L->CompletedImplicitDefinition(CopyAssignOperator);
8065  }
8066}
8067
8068Sema::ImplicitExceptionSpecification
8069Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8070  CXXRecordDecl *ClassDecl = MD->getParent();
8071
8072  ImplicitExceptionSpecification ExceptSpec(*this);
8073  if (ClassDecl->isInvalidDecl())
8074    return ExceptSpec;
8075
8076  // C++0x [except.spec]p14:
8077  //   An implicitly declared special member function (Clause 12) shall have an
8078  //   exception-specification. [...]
8079
8080  // It is unspecified whether or not an implicit move assignment operator
8081  // attempts to deduplicate calls to assignment operators of virtual bases are
8082  // made. As such, this exception specification is effectively unspecified.
8083  // Based on a similar decision made for constness in C++0x, we're erring on
8084  // the side of assuming such calls to be made regardless of whether they
8085  // actually happen.
8086  // Note that a move constructor is not implicitly declared when there are
8087  // virtual bases, but it can still be user-declared and explicitly defaulted.
8088  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8089                                       BaseEnd = ClassDecl->bases_end();
8090       Base != BaseEnd; ++Base) {
8091    if (Base->isVirtual())
8092      continue;
8093
8094    CXXRecordDecl *BaseClassDecl
8095      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8096    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8097                                                           0, false, 0))
8098      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8099  }
8100
8101  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8102                                       BaseEnd = ClassDecl->vbases_end();
8103       Base != BaseEnd; ++Base) {
8104    CXXRecordDecl *BaseClassDecl
8105      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8106    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8107                                                           0, false, 0))
8108      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8109  }
8110
8111  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8112                                  FieldEnd = ClassDecl->field_end();
8113       Field != FieldEnd;
8114       ++Field) {
8115    QualType FieldType = Context.getBaseElementType(Field->getType());
8116    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8117      if (CXXMethodDecl *MoveAssign =
8118              LookupMovingAssignment(FieldClassDecl,
8119                                     FieldType.getCVRQualifiers(),
8120                                     false, 0))
8121        ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
8122    }
8123  }
8124
8125  return ExceptSpec;
8126}
8127
8128/// Determine whether the class type has any direct or indirect virtual base
8129/// classes which have a non-trivial move assignment operator.
8130static bool
8131hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8132  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8133                                          BaseEnd = ClassDecl->vbases_end();
8134       Base != BaseEnd; ++Base) {
8135    CXXRecordDecl *BaseClass =
8136        cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8137
8138    // Try to declare the move assignment. If it would be deleted, then the
8139    // class does not have a non-trivial move assignment.
8140    if (BaseClass->needsImplicitMoveAssignment())
8141      S.DeclareImplicitMoveAssignment(BaseClass);
8142
8143    // If the class has both a trivial move assignment and a non-trivial move
8144    // assignment, hasTrivialMoveAssignment() is false.
8145    if (BaseClass->hasDeclaredMoveAssignment() &&
8146        !BaseClass->hasTrivialMoveAssignment())
8147      return true;
8148  }
8149
8150  return false;
8151}
8152
8153/// Determine whether the given type either has a move constructor or is
8154/// trivially copyable.
8155static bool
8156hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8157  Type = S.Context.getBaseElementType(Type);
8158
8159  // FIXME: Technically, non-trivially-copyable non-class types, such as
8160  // reference types, are supposed to return false here, but that appears
8161  // to be a standard defect.
8162  CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
8163  if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
8164    return true;
8165
8166  if (Type.isTriviallyCopyableType(S.Context))
8167    return true;
8168
8169  if (IsConstructor) {
8170    if (ClassDecl->needsImplicitMoveConstructor())
8171      S.DeclareImplicitMoveConstructor(ClassDecl);
8172    return ClassDecl->hasDeclaredMoveConstructor();
8173  }
8174
8175  if (ClassDecl->needsImplicitMoveAssignment())
8176    S.DeclareImplicitMoveAssignment(ClassDecl);
8177  return ClassDecl->hasDeclaredMoveAssignment();
8178}
8179
8180/// Determine whether all non-static data members and direct or virtual bases
8181/// of class \p ClassDecl have either a move operation, or are trivially
8182/// copyable.
8183static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8184                                            bool IsConstructor) {
8185  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8186                                          BaseEnd = ClassDecl->bases_end();
8187       Base != BaseEnd; ++Base) {
8188    if (Base->isVirtual())
8189      continue;
8190
8191    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8192      return false;
8193  }
8194
8195  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8196                                          BaseEnd = ClassDecl->vbases_end();
8197       Base != BaseEnd; ++Base) {
8198    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8199      return false;
8200  }
8201
8202  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8203                                     FieldEnd = ClassDecl->field_end();
8204       Field != FieldEnd; ++Field) {
8205    if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
8206      return false;
8207  }
8208
8209  return true;
8210}
8211
8212CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8213  // C++11 [class.copy]p20:
8214  //   If the definition of a class X does not explicitly declare a move
8215  //   assignment operator, one will be implicitly declared as defaulted
8216  //   if and only if:
8217  //
8218  //   - [first 4 bullets]
8219  assert(ClassDecl->needsImplicitMoveAssignment());
8220
8221  // [Checked after we build the declaration]
8222  //   - the move assignment operator would not be implicitly defined as
8223  //     deleted,
8224
8225  // [DR1402]:
8226  //   - X has no direct or indirect virtual base class with a non-trivial
8227  //     move assignment operator, and
8228  //   - each of X's non-static data members and direct or virtual base classes
8229  //     has a type that either has a move assignment operator or is trivially
8230  //     copyable.
8231  if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8232      !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8233    ClassDecl->setFailedImplicitMoveAssignment();
8234    return 0;
8235  }
8236
8237  // Note: The following rules are largely analoguous to the move
8238  // constructor rules.
8239
8240  QualType ArgType = Context.getTypeDeclType(ClassDecl);
8241  QualType RetType = Context.getLValueReferenceType(ArgType);
8242  ArgType = Context.getRValueReferenceType(ArgType);
8243
8244  //   An implicitly-declared move assignment operator is an inline public
8245  //   member of its class.
8246  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8247  SourceLocation ClassLoc = ClassDecl->getLocation();
8248  DeclarationNameInfo NameInfo(Name, ClassLoc);
8249  CXXMethodDecl *MoveAssignment
8250    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8251                            /*TInfo=*/0, /*isStatic=*/false,
8252                            /*StorageClassAsWritten=*/SC_None,
8253                            /*isInline=*/true,
8254                            /*isConstexpr=*/false,
8255                            SourceLocation());
8256  MoveAssignment->setAccess(AS_public);
8257  MoveAssignment->setDefaulted();
8258  MoveAssignment->setImplicit();
8259  MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8260
8261  // Build an exception specification pointing back at this member.
8262  FunctionProtoType::ExtProtoInfo EPI;
8263  EPI.ExceptionSpecType = EST_Unevaluated;
8264  EPI.ExceptionSpecDecl = MoveAssignment;
8265  MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8266
8267  // Add the parameter to the operator.
8268  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8269                                               ClassLoc, ClassLoc, /*Id=*/0,
8270                                               ArgType, /*TInfo=*/0,
8271                                               SC_None,
8272                                               SC_None, 0);
8273  MoveAssignment->setParams(FromParam);
8274
8275  // Note that we have added this copy-assignment operator.
8276  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8277
8278  // C++0x [class.copy]p9:
8279  //   If the definition of a class X does not explicitly declare a move
8280  //   assignment operator, one will be implicitly declared as defaulted if and
8281  //   only if:
8282  //   [...]
8283  //   - the move assignment operator would not be implicitly defined as
8284  //     deleted.
8285  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
8286    // Cache this result so that we don't try to generate this over and over
8287    // on every lookup, leaking memory and wasting time.
8288    ClassDecl->setFailedImplicitMoveAssignment();
8289    return 0;
8290  }
8291
8292  if (Scope *S = getScopeForContext(ClassDecl))
8293    PushOnScopeChains(MoveAssignment, S, false);
8294  ClassDecl->addDecl(MoveAssignment);
8295
8296  AddOverriddenMethods(ClassDecl, MoveAssignment);
8297  return MoveAssignment;
8298}
8299
8300void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8301                                        CXXMethodDecl *MoveAssignOperator) {
8302  assert((MoveAssignOperator->isDefaulted() &&
8303          MoveAssignOperator->isOverloadedOperator() &&
8304          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8305          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8306          !MoveAssignOperator->isDeleted()) &&
8307         "DefineImplicitMoveAssignment called for wrong function");
8308
8309  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8310
8311  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8312    MoveAssignOperator->setInvalidDecl();
8313    return;
8314  }
8315
8316  MoveAssignOperator->setUsed();
8317
8318  ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8319  DiagnosticErrorTrap Trap(Diags);
8320
8321  // C++0x [class.copy]p28:
8322  //   The implicitly-defined or move assignment operator for a non-union class
8323  //   X performs memberwise move assignment of its subobjects. The direct base
8324  //   classes of X are assigned first, in the order of their declaration in the
8325  //   base-specifier-list, and then the immediate non-static data members of X
8326  //   are assigned, in the order in which they were declared in the class
8327  //   definition.
8328
8329  // The statements that form the synthesized function body.
8330  SmallVector<Stmt*, 8> Statements;
8331
8332  // The parameter for the "other" object, which we are move from.
8333  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8334  QualType OtherRefType = Other->getType()->
8335      getAs<RValueReferenceType>()->getPointeeType();
8336  assert(OtherRefType.getQualifiers() == 0 &&
8337         "Bad argument type of defaulted move assignment");
8338
8339  // Our location for everything implicitly-generated.
8340  SourceLocation Loc = MoveAssignOperator->getLocation();
8341
8342  // Construct a reference to the "other" object. We'll be using this
8343  // throughout the generated ASTs.
8344  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8345  assert(OtherRef && "Reference to parameter cannot fail!");
8346  // Cast to rvalue.
8347  OtherRef = CastForMoving(*this, OtherRef);
8348
8349  // Construct the "this" pointer. We'll be using this throughout the generated
8350  // ASTs.
8351  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8352  assert(This && "Reference to this cannot fail!");
8353
8354  // Assign base classes.
8355  bool Invalid = false;
8356  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8357       E = ClassDecl->bases_end(); Base != E; ++Base) {
8358    // Form the assignment:
8359    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8360    QualType BaseType = Base->getType().getUnqualifiedType();
8361    if (!BaseType->isRecordType()) {
8362      Invalid = true;
8363      continue;
8364    }
8365
8366    CXXCastPath BasePath;
8367    BasePath.push_back(Base);
8368
8369    // Construct the "from" expression, which is an implicit cast to the
8370    // appropriately-qualified base type.
8371    Expr *From = OtherRef;
8372    From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
8373                             VK_XValue, &BasePath).take();
8374
8375    // Dereference "this".
8376    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8377
8378    // Implicitly cast "this" to the appropriately-qualified base type.
8379    To = ImpCastExprToType(To.take(),
8380                           Context.getCVRQualifiedType(BaseType,
8381                                     MoveAssignOperator->getTypeQualifiers()),
8382                           CK_UncheckedDerivedToBase,
8383                           VK_LValue, &BasePath);
8384
8385    // Build the move.
8386    StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8387                                            To.get(), From,
8388                                            /*CopyingBaseSubobject=*/true,
8389                                            /*Copying=*/false);
8390    if (Move.isInvalid()) {
8391      Diag(CurrentLocation, diag::note_member_synthesized_at)
8392        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8393      MoveAssignOperator->setInvalidDecl();
8394      return;
8395    }
8396
8397    // Success! Record the move.
8398    Statements.push_back(Move.takeAs<Expr>());
8399  }
8400
8401  // \brief Reference to the __builtin_memcpy function.
8402  Expr *BuiltinMemCpyRef = 0;
8403  // \brief Reference to the __builtin_objc_memmove_collectable function.
8404  Expr *CollectableMemCpyRef = 0;
8405
8406  // Assign non-static members.
8407  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8408                                  FieldEnd = ClassDecl->field_end();
8409       Field != FieldEnd; ++Field) {
8410    if (Field->isUnnamedBitfield())
8411      continue;
8412
8413    // Check for members of reference type; we can't move those.
8414    if (Field->getType()->isReferenceType()) {
8415      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8416        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8417      Diag(Field->getLocation(), diag::note_declared_at);
8418      Diag(CurrentLocation, diag::note_member_synthesized_at)
8419        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8420      Invalid = true;
8421      continue;
8422    }
8423
8424    // Check for members of const-qualified, non-class type.
8425    QualType BaseType = Context.getBaseElementType(Field->getType());
8426    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8427      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8428        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8429      Diag(Field->getLocation(), diag::note_declared_at);
8430      Diag(CurrentLocation, diag::note_member_synthesized_at)
8431        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8432      Invalid = true;
8433      continue;
8434    }
8435
8436    // Suppress assigning zero-width bitfields.
8437    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8438      continue;
8439
8440    QualType FieldType = Field->getType().getNonReferenceType();
8441    if (FieldType->isIncompleteArrayType()) {
8442      assert(ClassDecl->hasFlexibleArrayMember() &&
8443             "Incomplete array type is not valid");
8444      continue;
8445    }
8446
8447    // Build references to the field in the object we're copying from and to.
8448    CXXScopeSpec SS; // Intentionally empty
8449    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8450                              LookupMemberName);
8451    MemberLookup.addDecl(*Field);
8452    MemberLookup.resolveKind();
8453    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8454                                               Loc, /*IsArrow=*/false,
8455                                               SS, SourceLocation(), 0,
8456                                               MemberLookup, 0);
8457    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8458                                             Loc, /*IsArrow=*/true,
8459                                             SS, SourceLocation(), 0,
8460                                             MemberLookup, 0);
8461    assert(!From.isInvalid() && "Implicit field reference cannot fail");
8462    assert(!To.isInvalid() && "Implicit field reference cannot fail");
8463
8464    assert(!From.get()->isLValue() && // could be xvalue or prvalue
8465        "Member reference with rvalue base must be rvalue except for reference "
8466        "members, which aren't allowed for move assignment.");
8467
8468    // If the field should be copied with __builtin_memcpy rather than via
8469    // explicit assignments, do so. This optimization only applies for arrays
8470    // of scalars and arrays of class type with trivial move-assignment
8471    // operators.
8472    if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8473        && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8474      // Compute the size of the memory buffer to be copied.
8475      QualType SizeType = Context.getSizeType();
8476      llvm::APInt Size(Context.getTypeSize(SizeType),
8477                       Context.getTypeSizeInChars(BaseType).getQuantity());
8478      for (const ConstantArrayType *Array
8479              = Context.getAsConstantArrayType(FieldType);
8480           Array;
8481           Array = Context.getAsConstantArrayType(Array->getElementType())) {
8482        llvm::APInt ArraySize
8483          = Array->getSize().zextOrTrunc(Size.getBitWidth());
8484        Size *= ArraySize;
8485      }
8486
8487      // Take the address of the field references for "from" and "to". We
8488      // directly construct UnaryOperators here because semantic analysis
8489      // does not permit us to take the address of an xvalue.
8490      From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8491                             Context.getPointerType(From.get()->getType()),
8492                             VK_RValue, OK_Ordinary, Loc);
8493      To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8494                           Context.getPointerType(To.get()->getType()),
8495                           VK_RValue, OK_Ordinary, Loc);
8496
8497      bool NeedsCollectableMemCpy =
8498          (BaseType->isRecordType() &&
8499           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8500
8501      if (NeedsCollectableMemCpy) {
8502        if (!CollectableMemCpyRef) {
8503          // Create a reference to the __builtin_objc_memmove_collectable function.
8504          LookupResult R(*this,
8505                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
8506                         Loc, LookupOrdinaryName);
8507          LookupName(R, TUScope, true);
8508
8509          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8510          if (!CollectableMemCpy) {
8511            // Something went horribly wrong earlier, and we will have
8512            // complained about it.
8513            Invalid = true;
8514            continue;
8515          }
8516
8517          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8518                                                  Context.BuiltinFnTy,
8519                                                  VK_RValue, Loc, 0).take();
8520          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8521        }
8522      }
8523      // Create a reference to the __builtin_memcpy builtin function.
8524      else if (!BuiltinMemCpyRef) {
8525        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8526                       LookupOrdinaryName);
8527        LookupName(R, TUScope, true);
8528
8529        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8530        if (!BuiltinMemCpy) {
8531          // Something went horribly wrong earlier, and we will have complained
8532          // about it.
8533          Invalid = true;
8534          continue;
8535        }
8536
8537        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8538                                            Context.BuiltinFnTy,
8539                                            VK_RValue, Loc, 0).take();
8540        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8541      }
8542
8543      SmallVector<Expr*, 8> CallArgs;
8544      CallArgs.push_back(To.takeAs<Expr>());
8545      CallArgs.push_back(From.takeAs<Expr>());
8546      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8547      ExprResult Call = ExprError();
8548      if (NeedsCollectableMemCpy)
8549        Call = ActOnCallExpr(/*Scope=*/0,
8550                             CollectableMemCpyRef,
8551                             Loc, CallArgs,
8552                             Loc);
8553      else
8554        Call = ActOnCallExpr(/*Scope=*/0,
8555                             BuiltinMemCpyRef,
8556                             Loc, CallArgs,
8557                             Loc);
8558
8559      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8560      Statements.push_back(Call.takeAs<Expr>());
8561      continue;
8562    }
8563
8564    // Build the move of this field.
8565    StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8566                                            To.get(), From.get(),
8567                                            /*CopyingBaseSubobject=*/false,
8568                                            /*Copying=*/false);
8569    if (Move.isInvalid()) {
8570      Diag(CurrentLocation, diag::note_member_synthesized_at)
8571        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8572      MoveAssignOperator->setInvalidDecl();
8573      return;
8574    }
8575
8576    // Success! Record the copy.
8577    Statements.push_back(Move.takeAs<Stmt>());
8578  }
8579
8580  if (!Invalid) {
8581    // Add a "return *this;"
8582    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8583
8584    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8585    if (Return.isInvalid())
8586      Invalid = true;
8587    else {
8588      Statements.push_back(Return.takeAs<Stmt>());
8589
8590      if (Trap.hasErrorOccurred()) {
8591        Diag(CurrentLocation, diag::note_member_synthesized_at)
8592          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8593        Invalid = true;
8594      }
8595    }
8596  }
8597
8598  if (Invalid) {
8599    MoveAssignOperator->setInvalidDecl();
8600    return;
8601  }
8602
8603  StmtResult Body;
8604  {
8605    CompoundScopeRAII CompoundScope(*this);
8606    Body = ActOnCompoundStmt(Loc, Loc, Statements,
8607                             /*isStmtExpr=*/false);
8608    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8609  }
8610  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8611
8612  if (ASTMutationListener *L = getASTMutationListener()) {
8613    L->CompletedImplicitDefinition(MoveAssignOperator);
8614  }
8615}
8616
8617/// Determine whether an implicit copy constructor for ClassDecl has a const
8618/// argument.
8619/// FIXME: It ought to be possible to store this on the record.
8620static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl) {
8621  if (ClassDecl->isInvalidDecl())
8622    return true;
8623
8624  // C++ [class.copy]p5:
8625  //   The implicitly-declared copy constructor for a class X will
8626  //   have the form
8627  //
8628  //       X::X(const X&)
8629  //
8630  //   if
8631  //     -- each direct or virtual base class B of X has a copy
8632  //        constructor whose first parameter is of type const B& or
8633  //        const volatile B&, and
8634  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8635                                       BaseEnd = ClassDecl->bases_end();
8636       Base != BaseEnd; ++Base) {
8637    // Virtual bases are handled below.
8638    if (Base->isVirtual())
8639      continue;
8640
8641    CXXRecordDecl *BaseClassDecl
8642      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8643    // FIXME: This lookup is wrong. If the copy ctor for a member or base is
8644    // ambiguous, we should still produce a constructor with a const-qualified
8645    // parameter.
8646    if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8647      return false;
8648  }
8649
8650  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8651                                       BaseEnd = ClassDecl->vbases_end();
8652       Base != BaseEnd; ++Base) {
8653    CXXRecordDecl *BaseClassDecl
8654      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8655    if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8656      return false;
8657  }
8658
8659  //     -- for all the nonstatic data members of X that are of a
8660  //        class type M (or array thereof), each such class type
8661  //        has a copy constructor whose first parameter is of type
8662  //        const M& or const volatile M&.
8663  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8664                                  FieldEnd = ClassDecl->field_end();
8665       Field != FieldEnd; ++Field) {
8666    QualType FieldType = S.Context.getBaseElementType(Field->getType());
8667    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8668      if (!S.LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const))
8669        return false;
8670    }
8671  }
8672
8673  //   Otherwise, the implicitly declared copy constructor will have
8674  //   the form
8675  //
8676  //       X::X(X&)
8677
8678  return true;
8679}
8680
8681Sema::ImplicitExceptionSpecification
8682Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
8683  CXXRecordDecl *ClassDecl = MD->getParent();
8684
8685  ImplicitExceptionSpecification ExceptSpec(*this);
8686  if (ClassDecl->isInvalidDecl())
8687    return ExceptSpec;
8688
8689  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8690  assert(T->getNumArgs() >= 1 && "not a copy ctor");
8691  unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8692
8693  // C++ [except.spec]p14:
8694  //   An implicitly declared special member function (Clause 12) shall have an
8695  //   exception-specification. [...]
8696  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8697                                       BaseEnd = ClassDecl->bases_end();
8698       Base != BaseEnd;
8699       ++Base) {
8700    // Virtual bases are handled below.
8701    if (Base->isVirtual())
8702      continue;
8703
8704    CXXRecordDecl *BaseClassDecl
8705      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8706    if (CXXConstructorDecl *CopyConstructor =
8707          LookupCopyingConstructor(BaseClassDecl, Quals))
8708      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
8709  }
8710  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8711                                       BaseEnd = ClassDecl->vbases_end();
8712       Base != BaseEnd;
8713       ++Base) {
8714    CXXRecordDecl *BaseClassDecl
8715      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8716    if (CXXConstructorDecl *CopyConstructor =
8717          LookupCopyingConstructor(BaseClassDecl, Quals))
8718      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
8719  }
8720  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8721                                  FieldEnd = ClassDecl->field_end();
8722       Field != FieldEnd;
8723       ++Field) {
8724    QualType FieldType = Context.getBaseElementType(Field->getType());
8725    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8726      if (CXXConstructorDecl *CopyConstructor =
8727              LookupCopyingConstructor(FieldClassDecl,
8728                                       Quals | FieldType.getCVRQualifiers()))
8729      ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
8730    }
8731  }
8732
8733  return ExceptSpec;
8734}
8735
8736CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8737                                                    CXXRecordDecl *ClassDecl) {
8738  // C++ [class.copy]p4:
8739  //   If the class definition does not explicitly declare a copy
8740  //   constructor, one is declared implicitly.
8741
8742  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8743  QualType ArgType = ClassType;
8744  bool Const = isImplicitCopyCtorArgConst(*this, ClassDecl);
8745  if (Const)
8746    ArgType = ArgType.withConst();
8747  ArgType = Context.getLValueReferenceType(ArgType);
8748
8749  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8750                                                     CXXCopyConstructor,
8751                                                     Const);
8752
8753  DeclarationName Name
8754    = Context.DeclarationNames.getCXXConstructorName(
8755                                           Context.getCanonicalType(ClassType));
8756  SourceLocation ClassLoc = ClassDecl->getLocation();
8757  DeclarationNameInfo NameInfo(Name, ClassLoc);
8758
8759  //   An implicitly-declared copy constructor is an inline public
8760  //   member of its class.
8761  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8762      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
8763      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8764      Constexpr);
8765  CopyConstructor->setAccess(AS_public);
8766  CopyConstructor->setDefaulted();
8767  CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8768
8769  // Build an exception specification pointing back at this member.
8770  FunctionProtoType::ExtProtoInfo EPI;
8771  EPI.ExceptionSpecType = EST_Unevaluated;
8772  EPI.ExceptionSpecDecl = CopyConstructor;
8773  CopyConstructor->setType(
8774      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8775
8776  // Note that we have declared this constructor.
8777  ++ASTContext::NumImplicitCopyConstructorsDeclared;
8778
8779  // Add the parameter to the constructor.
8780  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
8781                                               ClassLoc, ClassLoc,
8782                                               /*IdentifierInfo=*/0,
8783                                               ArgType, /*TInfo=*/0,
8784                                               SC_None,
8785                                               SC_None, 0);
8786  CopyConstructor->setParams(FromParam);
8787
8788  if (Scope *S = getScopeForContext(ClassDecl))
8789    PushOnScopeChains(CopyConstructor, S, false);
8790  ClassDecl->addDecl(CopyConstructor);
8791
8792  // C++11 [class.copy]p8:
8793  //   ... If the class definition does not explicitly declare a copy
8794  //   constructor, there is no user-declared move constructor, and there is no
8795  //   user-declared move assignment operator, a copy constructor is implicitly
8796  //   declared as defaulted.
8797  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
8798    CopyConstructor->setDeletedAsWritten();
8799
8800  return CopyConstructor;
8801}
8802
8803void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
8804                                   CXXConstructorDecl *CopyConstructor) {
8805  assert((CopyConstructor->isDefaulted() &&
8806          CopyConstructor->isCopyConstructor() &&
8807          !CopyConstructor->doesThisDeclarationHaveABody() &&
8808          !CopyConstructor->isDeleted()) &&
8809         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
8810
8811  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
8812  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
8813
8814  ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
8815  DiagnosticErrorTrap Trap(Diags);
8816
8817  if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
8818      Trap.hasErrorOccurred()) {
8819    Diag(CurrentLocation, diag::note_member_synthesized_at)
8820      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
8821    CopyConstructor->setInvalidDecl();
8822  }  else {
8823    Sema::CompoundScopeRAII CompoundScope(*this);
8824    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8825                                               CopyConstructor->getLocation(),
8826                                               MultiStmtArg(),
8827                                               /*isStmtExpr=*/false)
8828                                                              .takeAs<Stmt>());
8829    CopyConstructor->setImplicitlyDefined(true);
8830  }
8831
8832  CopyConstructor->setUsed();
8833  if (ASTMutationListener *L = getASTMutationListener()) {
8834    L->CompletedImplicitDefinition(CopyConstructor);
8835  }
8836}
8837
8838Sema::ImplicitExceptionSpecification
8839Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
8840  CXXRecordDecl *ClassDecl = MD->getParent();
8841
8842  // C++ [except.spec]p14:
8843  //   An implicitly declared special member function (Clause 12) shall have an
8844  //   exception-specification. [...]
8845  ImplicitExceptionSpecification ExceptSpec(*this);
8846  if (ClassDecl->isInvalidDecl())
8847    return ExceptSpec;
8848
8849  // Direct base-class constructors.
8850  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8851                                       BEnd = ClassDecl->bases_end();
8852       B != BEnd; ++B) {
8853    if (B->isVirtual()) // Handled below.
8854      continue;
8855
8856    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8857      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8858      CXXConstructorDecl *Constructor =
8859          LookupMovingConstructor(BaseClassDecl, 0);
8860      // If this is a deleted function, add it anyway. This might be conformant
8861      // with the standard. This might not. I'm not sure. It might not matter.
8862      if (Constructor)
8863        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8864    }
8865  }
8866
8867  // Virtual base-class constructors.
8868  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8869                                       BEnd = ClassDecl->vbases_end();
8870       B != BEnd; ++B) {
8871    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8872      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8873      CXXConstructorDecl *Constructor =
8874          LookupMovingConstructor(BaseClassDecl, 0);
8875      // If this is a deleted function, add it anyway. This might be conformant
8876      // with the standard. This might not. I'm not sure. It might not matter.
8877      if (Constructor)
8878        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8879    }
8880  }
8881
8882  // Field constructors.
8883  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8884                               FEnd = ClassDecl->field_end();
8885       F != FEnd; ++F) {
8886    QualType FieldType = Context.getBaseElementType(F->getType());
8887    if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
8888      CXXConstructorDecl *Constructor =
8889          LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
8890      // If this is a deleted function, add it anyway. This might be conformant
8891      // with the standard. This might not. I'm not sure. It might not matter.
8892      // In particular, the problem is that this function never gets called. It
8893      // might just be ill-formed because this function attempts to refer to
8894      // a deleted function here.
8895      if (Constructor)
8896        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8897    }
8898  }
8899
8900  return ExceptSpec;
8901}
8902
8903CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8904                                                    CXXRecordDecl *ClassDecl) {
8905  // C++11 [class.copy]p9:
8906  //   If the definition of a class X does not explicitly declare a move
8907  //   constructor, one will be implicitly declared as defaulted if and only if:
8908  //
8909  //   - [first 4 bullets]
8910  assert(ClassDecl->needsImplicitMoveConstructor());
8911
8912  // [Checked after we build the declaration]
8913  //   - the move assignment operator would not be implicitly defined as
8914  //     deleted,
8915
8916  // [DR1402]:
8917  //   - each of X's non-static data members and direct or virtual base classes
8918  //     has a type that either has a move constructor or is trivially copyable.
8919  if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8920    ClassDecl->setFailedImplicitMoveConstructor();
8921    return 0;
8922  }
8923
8924  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8925  QualType ArgType = Context.getRValueReferenceType(ClassType);
8926
8927  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8928                                                     CXXMoveConstructor,
8929                                                     false);
8930
8931  DeclarationName Name
8932    = Context.DeclarationNames.getCXXConstructorName(
8933                                           Context.getCanonicalType(ClassType));
8934  SourceLocation ClassLoc = ClassDecl->getLocation();
8935  DeclarationNameInfo NameInfo(Name, ClassLoc);
8936
8937  // C++0x [class.copy]p11:
8938  //   An implicitly-declared copy/move constructor is an inline public
8939  //   member of its class.
8940  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8941      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
8942      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8943      Constexpr);
8944  MoveConstructor->setAccess(AS_public);
8945  MoveConstructor->setDefaulted();
8946  MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8947
8948  // Build an exception specification pointing back at this member.
8949  FunctionProtoType::ExtProtoInfo EPI;
8950  EPI.ExceptionSpecType = EST_Unevaluated;
8951  EPI.ExceptionSpecDecl = MoveConstructor;
8952  MoveConstructor->setType(
8953      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8954
8955  // Add the parameter to the constructor.
8956  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8957                                               ClassLoc, ClassLoc,
8958                                               /*IdentifierInfo=*/0,
8959                                               ArgType, /*TInfo=*/0,
8960                                               SC_None,
8961                                               SC_None, 0);
8962  MoveConstructor->setParams(FromParam);
8963
8964  // C++0x [class.copy]p9:
8965  //   If the definition of a class X does not explicitly declare a move
8966  //   constructor, one will be implicitly declared as defaulted if and only if:
8967  //   [...]
8968  //   - the move constructor would not be implicitly defined as deleted.
8969  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
8970    // Cache this result so that we don't try to generate this over and over
8971    // on every lookup, leaking memory and wasting time.
8972    ClassDecl->setFailedImplicitMoveConstructor();
8973    return 0;
8974  }
8975
8976  // Note that we have declared this constructor.
8977  ++ASTContext::NumImplicitMoveConstructorsDeclared;
8978
8979  if (Scope *S = getScopeForContext(ClassDecl))
8980    PushOnScopeChains(MoveConstructor, S, false);
8981  ClassDecl->addDecl(MoveConstructor);
8982
8983  return MoveConstructor;
8984}
8985
8986void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8987                                   CXXConstructorDecl *MoveConstructor) {
8988  assert((MoveConstructor->isDefaulted() &&
8989          MoveConstructor->isMoveConstructor() &&
8990          !MoveConstructor->doesThisDeclarationHaveABody() &&
8991          !MoveConstructor->isDeleted()) &&
8992         "DefineImplicitMoveConstructor - call it for implicit move ctor");
8993
8994  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8995  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8996
8997  ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8998  DiagnosticErrorTrap Trap(Diags);
8999
9000  if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
9001      Trap.hasErrorOccurred()) {
9002    Diag(CurrentLocation, diag::note_member_synthesized_at)
9003      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9004    MoveConstructor->setInvalidDecl();
9005  }  else {
9006    Sema::CompoundScopeRAII CompoundScope(*this);
9007    MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9008                                               MoveConstructor->getLocation(),
9009                                               MultiStmtArg(),
9010                                               /*isStmtExpr=*/false)
9011                                                              .takeAs<Stmt>());
9012    MoveConstructor->setImplicitlyDefined(true);
9013  }
9014
9015  MoveConstructor->setUsed();
9016
9017  if (ASTMutationListener *L = getASTMutationListener()) {
9018    L->CompletedImplicitDefinition(MoveConstructor);
9019  }
9020}
9021
9022bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9023  return FD->isDeleted() &&
9024         (FD->isDefaulted() || FD->isImplicit()) &&
9025         isa<CXXMethodDecl>(FD);
9026}
9027
9028/// \brief Mark the call operator of the given lambda closure type as "used".
9029static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9030  CXXMethodDecl *CallOperator
9031    = cast<CXXMethodDecl>(
9032        *Lambda->lookup(
9033          S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
9034  CallOperator->setReferenced();
9035  CallOperator->setUsed();
9036}
9037
9038void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9039       SourceLocation CurrentLocation,
9040       CXXConversionDecl *Conv)
9041{
9042  CXXRecordDecl *Lambda = Conv->getParent();
9043
9044  // Make sure that the lambda call operator is marked used.
9045  markLambdaCallOperatorUsed(*this, Lambda);
9046
9047  Conv->setUsed();
9048
9049  ImplicitlyDefinedFunctionScope Scope(*this, Conv);
9050  DiagnosticErrorTrap Trap(Diags);
9051
9052  // Return the address of the __invoke function.
9053  DeclarationName InvokeName = &Context.Idents.get("__invoke");
9054  CXXMethodDecl *Invoke
9055    = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
9056  Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9057                                       VK_LValue, Conv->getLocation()).take();
9058  assert(FunctionRef && "Can't refer to __invoke function?");
9059  Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
9060  Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
9061                                           Conv->getLocation(),
9062                                           Conv->getLocation()));
9063
9064  // Fill in the __invoke function with a dummy implementation. IR generation
9065  // will fill in the actual details.
9066  Invoke->setUsed();
9067  Invoke->setReferenced();
9068  Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
9069
9070  if (ASTMutationListener *L = getASTMutationListener()) {
9071    L->CompletedImplicitDefinition(Conv);
9072    L->CompletedImplicitDefinition(Invoke);
9073  }
9074}
9075
9076void Sema::DefineImplicitLambdaToBlockPointerConversion(
9077       SourceLocation CurrentLocation,
9078       CXXConversionDecl *Conv)
9079{
9080  Conv->setUsed();
9081
9082  ImplicitlyDefinedFunctionScope Scope(*this, Conv);
9083  DiagnosticErrorTrap Trap(Diags);
9084
9085  // Copy-initialize the lambda object as needed to capture it.
9086  Expr *This = ActOnCXXThis(CurrentLocation).take();
9087  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
9088
9089  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9090                                                        Conv->getLocation(),
9091                                                        Conv, DerefThis);
9092
9093  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9094  // behavior.  Note that only the general conversion function does this
9095  // (since it's unusable otherwise); in the case where we inline the
9096  // block literal, it has block literal lifetime semantics.
9097  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
9098    BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9099                                          CK_CopyAndAutoreleaseBlockObject,
9100                                          BuildBlock.get(), 0, VK_RValue);
9101
9102  if (BuildBlock.isInvalid()) {
9103    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9104    Conv->setInvalidDecl();
9105    return;
9106  }
9107
9108  // Create the return statement that returns the block from the conversion
9109  // function.
9110  StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
9111  if (Return.isInvalid()) {
9112    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9113    Conv->setInvalidDecl();
9114    return;
9115  }
9116
9117  // Set the body of the conversion function.
9118  Stmt *ReturnS = Return.take();
9119  Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9120                                           Conv->getLocation(),
9121                                           Conv->getLocation()));
9122
9123  // We're done; notify the mutation listener, if any.
9124  if (ASTMutationListener *L = getASTMutationListener()) {
9125    L->CompletedImplicitDefinition(Conv);
9126  }
9127}
9128
9129/// \brief Determine whether the given list arguments contains exactly one
9130/// "real" (non-default) argument.
9131static bool hasOneRealArgument(MultiExprArg Args) {
9132  switch (Args.size()) {
9133  case 0:
9134    return false;
9135
9136  default:
9137    if (!Args[1]->isDefaultArgument())
9138      return false;
9139
9140    // fall through
9141  case 1:
9142    return !Args[0]->isDefaultArgument();
9143  }
9144
9145  return false;
9146}
9147
9148ExprResult
9149Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9150                            CXXConstructorDecl *Constructor,
9151                            MultiExprArg ExprArgs,
9152                            bool HadMultipleCandidates,
9153                            bool RequiresZeroInit,
9154                            unsigned ConstructKind,
9155                            SourceRange ParenRange) {
9156  bool Elidable = false;
9157
9158  // C++0x [class.copy]p34:
9159  //   When certain criteria are met, an implementation is allowed to
9160  //   omit the copy/move construction of a class object, even if the
9161  //   copy/move constructor and/or destructor for the object have
9162  //   side effects. [...]
9163  //     - when a temporary class object that has not been bound to a
9164  //       reference (12.2) would be copied/moved to a class object
9165  //       with the same cv-unqualified type, the copy/move operation
9166  //       can be omitted by constructing the temporary object
9167  //       directly into the target of the omitted copy/move
9168  if (ConstructKind == CXXConstructExpr::CK_Complete &&
9169      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
9170    Expr *SubExpr = ExprArgs[0];
9171    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
9172  }
9173
9174  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
9175                               Elidable, ExprArgs, HadMultipleCandidates,
9176                               RequiresZeroInit, ConstructKind, ParenRange);
9177}
9178
9179/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9180/// including handling of its default argument expressions.
9181ExprResult
9182Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9183                            CXXConstructorDecl *Constructor, bool Elidable,
9184                            MultiExprArg ExprArgs,
9185                            bool HadMultipleCandidates,
9186                            bool RequiresZeroInit,
9187                            unsigned ConstructKind,
9188                            SourceRange ParenRange) {
9189  MarkFunctionReferenced(ConstructLoc, Constructor);
9190  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
9191                                        Constructor, Elidable, ExprArgs,
9192                                        HadMultipleCandidates, /*FIXME*/false,
9193                                        RequiresZeroInit,
9194              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9195                                        ParenRange));
9196}
9197
9198bool Sema::InitializeVarWithConstructor(VarDecl *VD,
9199                                        CXXConstructorDecl *Constructor,
9200                                        MultiExprArg Exprs,
9201                                        bool HadMultipleCandidates) {
9202  // FIXME: Provide the correct paren SourceRange when available.
9203  ExprResult TempResult =
9204    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
9205                          Exprs, HadMultipleCandidates, false,
9206                          CXXConstructExpr::CK_Complete, SourceRange());
9207  if (TempResult.isInvalid())
9208    return true;
9209
9210  Expr *Temp = TempResult.takeAs<Expr>();
9211  CheckImplicitConversions(Temp, VD->getLocation());
9212  MarkFunctionReferenced(VD->getLocation(), Constructor);
9213  Temp = MaybeCreateExprWithCleanups(Temp);
9214  VD->setInit(Temp);
9215
9216  return false;
9217}
9218
9219void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
9220  if (VD->isInvalidDecl()) return;
9221
9222  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
9223  if (ClassDecl->isInvalidDecl()) return;
9224  if (ClassDecl->hasIrrelevantDestructor()) return;
9225  if (ClassDecl->isDependentContext()) return;
9226
9227  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9228  MarkFunctionReferenced(VD->getLocation(), Destructor);
9229  CheckDestructorAccess(VD->getLocation(), Destructor,
9230                        PDiag(diag::err_access_dtor_var)
9231                        << VD->getDeclName()
9232                        << VD->getType());
9233  DiagnoseUseOfDecl(Destructor, VD->getLocation());
9234
9235  if (!VD->hasGlobalStorage()) return;
9236
9237  // Emit warning for non-trivial dtor in global scope (a real global,
9238  // class-static, function-static).
9239  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9240
9241  // TODO: this should be re-enabled for static locals by !CXAAtExit
9242  if (!VD->isStaticLocal())
9243    Diag(VD->getLocation(), diag::warn_global_destructor);
9244}
9245
9246/// \brief Given a constructor and the set of arguments provided for the
9247/// constructor, convert the arguments and add any required default arguments
9248/// to form a proper call to this constructor.
9249///
9250/// \returns true if an error occurred, false otherwise.
9251bool
9252Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9253                              MultiExprArg ArgsPtr,
9254                              SourceLocation Loc,
9255                              SmallVectorImpl<Expr*> &ConvertedArgs,
9256                              bool AllowExplicit) {
9257  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9258  unsigned NumArgs = ArgsPtr.size();
9259  Expr **Args = ArgsPtr.data();
9260
9261  const FunctionProtoType *Proto
9262    = Constructor->getType()->getAs<FunctionProtoType>();
9263  assert(Proto && "Constructor without a prototype?");
9264  unsigned NumArgsInProto = Proto->getNumArgs();
9265
9266  // If too few arguments are available, we'll fill in the rest with defaults.
9267  if (NumArgs < NumArgsInProto)
9268    ConvertedArgs.reserve(NumArgsInProto);
9269  else
9270    ConvertedArgs.reserve(NumArgs);
9271
9272  VariadicCallType CallType =
9273    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
9274  SmallVector<Expr *, 8> AllArgs;
9275  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9276                                        Proto, 0, Args, NumArgs, AllArgs,
9277                                        CallType, AllowExplicit);
9278  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
9279
9280  DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9281
9282  CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9283                       Proto, Loc);
9284
9285  return Invalid;
9286}
9287
9288static inline bool
9289CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9290                                       const FunctionDecl *FnDecl) {
9291  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
9292  if (isa<NamespaceDecl>(DC)) {
9293    return SemaRef.Diag(FnDecl->getLocation(),
9294                        diag::err_operator_new_delete_declared_in_namespace)
9295      << FnDecl->getDeclName();
9296  }
9297
9298  if (isa<TranslationUnitDecl>(DC) &&
9299      FnDecl->getStorageClass() == SC_Static) {
9300    return SemaRef.Diag(FnDecl->getLocation(),
9301                        diag::err_operator_new_delete_declared_static)
9302      << FnDecl->getDeclName();
9303  }
9304
9305  return false;
9306}
9307
9308static inline bool
9309CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9310                            CanQualType ExpectedResultType,
9311                            CanQualType ExpectedFirstParamType,
9312                            unsigned DependentParamTypeDiag,
9313                            unsigned InvalidParamTypeDiag) {
9314  QualType ResultType =
9315    FnDecl->getType()->getAs<FunctionType>()->getResultType();
9316
9317  // Check that the result type is not dependent.
9318  if (ResultType->isDependentType())
9319    return SemaRef.Diag(FnDecl->getLocation(),
9320                        diag::err_operator_new_delete_dependent_result_type)
9321    << FnDecl->getDeclName() << ExpectedResultType;
9322
9323  // Check that the result type is what we expect.
9324  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9325    return SemaRef.Diag(FnDecl->getLocation(),
9326                        diag::err_operator_new_delete_invalid_result_type)
9327    << FnDecl->getDeclName() << ExpectedResultType;
9328
9329  // A function template must have at least 2 parameters.
9330  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9331    return SemaRef.Diag(FnDecl->getLocation(),
9332                      diag::err_operator_new_delete_template_too_few_parameters)
9333        << FnDecl->getDeclName();
9334
9335  // The function decl must have at least 1 parameter.
9336  if (FnDecl->getNumParams() == 0)
9337    return SemaRef.Diag(FnDecl->getLocation(),
9338                        diag::err_operator_new_delete_too_few_parameters)
9339      << FnDecl->getDeclName();
9340
9341  // Check the first parameter type is not dependent.
9342  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9343  if (FirstParamType->isDependentType())
9344    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9345      << FnDecl->getDeclName() << ExpectedFirstParamType;
9346
9347  // Check that the first parameter type is what we expect.
9348  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
9349      ExpectedFirstParamType)
9350    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9351    << FnDecl->getDeclName() << ExpectedFirstParamType;
9352
9353  return false;
9354}
9355
9356static bool
9357CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9358  // C++ [basic.stc.dynamic.allocation]p1:
9359  //   A program is ill-formed if an allocation function is declared in a
9360  //   namespace scope other than global scope or declared static in global
9361  //   scope.
9362  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9363    return true;
9364
9365  CanQualType SizeTy =
9366    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9367
9368  // C++ [basic.stc.dynamic.allocation]p1:
9369  //  The return type shall be void*. The first parameter shall have type
9370  //  std::size_t.
9371  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9372                                  SizeTy,
9373                                  diag::err_operator_new_dependent_param_type,
9374                                  diag::err_operator_new_param_type))
9375    return true;
9376
9377  // C++ [basic.stc.dynamic.allocation]p1:
9378  //  The first parameter shall not have an associated default argument.
9379  if (FnDecl->getParamDecl(0)->hasDefaultArg())
9380    return SemaRef.Diag(FnDecl->getLocation(),
9381                        diag::err_operator_new_default_arg)
9382      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9383
9384  return false;
9385}
9386
9387static bool
9388CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9389  // C++ [basic.stc.dynamic.deallocation]p1:
9390  //   A program is ill-formed if deallocation functions are declared in a
9391  //   namespace scope other than global scope or declared static in global
9392  //   scope.
9393  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9394    return true;
9395
9396  // C++ [basic.stc.dynamic.deallocation]p2:
9397  //   Each deallocation function shall return void and its first parameter
9398  //   shall be void*.
9399  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9400                                  SemaRef.Context.VoidPtrTy,
9401                                 diag::err_operator_delete_dependent_param_type,
9402                                 diag::err_operator_delete_param_type))
9403    return true;
9404
9405  return false;
9406}
9407
9408/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9409/// of this overloaded operator is well-formed. If so, returns false;
9410/// otherwise, emits appropriate diagnostics and returns true.
9411bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
9412  assert(FnDecl && FnDecl->isOverloadedOperator() &&
9413         "Expected an overloaded operator declaration");
9414
9415  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9416
9417  // C++ [over.oper]p5:
9418  //   The allocation and deallocation functions, operator new,
9419  //   operator new[], operator delete and operator delete[], are
9420  //   described completely in 3.7.3. The attributes and restrictions
9421  //   found in the rest of this subclause do not apply to them unless
9422  //   explicitly stated in 3.7.3.
9423  if (Op == OO_Delete || Op == OO_Array_Delete)
9424    return CheckOperatorDeleteDeclaration(*this, FnDecl);
9425
9426  if (Op == OO_New || Op == OO_Array_New)
9427    return CheckOperatorNewDeclaration(*this, FnDecl);
9428
9429  // C++ [over.oper]p6:
9430  //   An operator function shall either be a non-static member
9431  //   function or be a non-member function and have at least one
9432  //   parameter whose type is a class, a reference to a class, an
9433  //   enumeration, or a reference to an enumeration.
9434  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9435    if (MethodDecl->isStatic())
9436      return Diag(FnDecl->getLocation(),
9437                  diag::err_operator_overload_static) << FnDecl->getDeclName();
9438  } else {
9439    bool ClassOrEnumParam = false;
9440    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9441                                   ParamEnd = FnDecl->param_end();
9442         Param != ParamEnd; ++Param) {
9443      QualType ParamType = (*Param)->getType().getNonReferenceType();
9444      if (ParamType->isDependentType() || ParamType->isRecordType() ||
9445          ParamType->isEnumeralType()) {
9446        ClassOrEnumParam = true;
9447        break;
9448      }
9449    }
9450
9451    if (!ClassOrEnumParam)
9452      return Diag(FnDecl->getLocation(),
9453                  diag::err_operator_overload_needs_class_or_enum)
9454        << FnDecl->getDeclName();
9455  }
9456
9457  // C++ [over.oper]p8:
9458  //   An operator function cannot have default arguments (8.3.6),
9459  //   except where explicitly stated below.
9460  //
9461  // Only the function-call operator allows default arguments
9462  // (C++ [over.call]p1).
9463  if (Op != OO_Call) {
9464    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9465         Param != FnDecl->param_end(); ++Param) {
9466      if ((*Param)->hasDefaultArg())
9467        return Diag((*Param)->getLocation(),
9468                    diag::err_operator_overload_default_arg)
9469          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
9470    }
9471  }
9472
9473  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9474    { false, false, false }
9475#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9476    , { Unary, Binary, MemberOnly }
9477#include "clang/Basic/OperatorKinds.def"
9478  };
9479
9480  bool CanBeUnaryOperator = OperatorUses[Op][0];
9481  bool CanBeBinaryOperator = OperatorUses[Op][1];
9482  bool MustBeMemberOperator = OperatorUses[Op][2];
9483
9484  // C++ [over.oper]p8:
9485  //   [...] Operator functions cannot have more or fewer parameters
9486  //   than the number required for the corresponding operator, as
9487  //   described in the rest of this subclause.
9488  unsigned NumParams = FnDecl->getNumParams()
9489                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
9490  if (Op != OO_Call &&
9491      ((NumParams == 1 && !CanBeUnaryOperator) ||
9492       (NumParams == 2 && !CanBeBinaryOperator) ||
9493       (NumParams < 1) || (NumParams > 2))) {
9494    // We have the wrong number of parameters.
9495    unsigned ErrorKind;
9496    if (CanBeUnaryOperator && CanBeBinaryOperator) {
9497      ErrorKind = 2;  // 2 -> unary or binary.
9498    } else if (CanBeUnaryOperator) {
9499      ErrorKind = 0;  // 0 -> unary
9500    } else {
9501      assert(CanBeBinaryOperator &&
9502             "All non-call overloaded operators are unary or binary!");
9503      ErrorKind = 1;  // 1 -> binary
9504    }
9505
9506    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
9507      << FnDecl->getDeclName() << NumParams << ErrorKind;
9508  }
9509
9510  // Overloaded operators other than operator() cannot be variadic.
9511  if (Op != OO_Call &&
9512      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
9513    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
9514      << FnDecl->getDeclName();
9515  }
9516
9517  // Some operators must be non-static member functions.
9518  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9519    return Diag(FnDecl->getLocation(),
9520                diag::err_operator_overload_must_be_member)
9521      << FnDecl->getDeclName();
9522  }
9523
9524  // C++ [over.inc]p1:
9525  //   The user-defined function called operator++ implements the
9526  //   prefix and postfix ++ operator. If this function is a member
9527  //   function with no parameters, or a non-member function with one
9528  //   parameter of class or enumeration type, it defines the prefix
9529  //   increment operator ++ for objects of that type. If the function
9530  //   is a member function with one parameter (which shall be of type
9531  //   int) or a non-member function with two parameters (the second
9532  //   of which shall be of type int), it defines the postfix
9533  //   increment operator ++ for objects of that type.
9534  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9535    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9536    bool ParamIsInt = false;
9537    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
9538      ParamIsInt = BT->getKind() == BuiltinType::Int;
9539
9540    if (!ParamIsInt)
9541      return Diag(LastParam->getLocation(),
9542                  diag::err_operator_overload_post_incdec_must_be_int)
9543        << LastParam->getType() << (Op == OO_MinusMinus);
9544  }
9545
9546  return false;
9547}
9548
9549/// CheckLiteralOperatorDeclaration - Check whether the declaration
9550/// of this literal operator function is well-formed. If so, returns
9551/// false; otherwise, emits appropriate diagnostics and returns true.
9552bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9553  if (isa<CXXMethodDecl>(FnDecl)) {
9554    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9555      << FnDecl->getDeclName();
9556    return true;
9557  }
9558
9559  if (FnDecl->isExternC()) {
9560    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9561    return true;
9562  }
9563
9564  bool Valid = false;
9565
9566  // This might be the definition of a literal operator template.
9567  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9568  // This might be a specialization of a literal operator template.
9569  if (!TpDecl)
9570    TpDecl = FnDecl->getPrimaryTemplate();
9571
9572  // template <char...> type operator "" name() is the only valid template
9573  // signature, and the only valid signature with no parameters.
9574  if (TpDecl) {
9575    if (FnDecl->param_size() == 0) {
9576      // Must have only one template parameter
9577      TemplateParameterList *Params = TpDecl->getTemplateParameters();
9578      if (Params->size() == 1) {
9579        NonTypeTemplateParmDecl *PmDecl =
9580          dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
9581
9582        // The template parameter must be a char parameter pack.
9583        if (PmDecl && PmDecl->isTemplateParameterPack() &&
9584            Context.hasSameType(PmDecl->getType(), Context.CharTy))
9585          Valid = true;
9586      }
9587    }
9588  } else if (FnDecl->param_size()) {
9589    // Check the first parameter
9590    FunctionDecl::param_iterator Param = FnDecl->param_begin();
9591
9592    QualType T = (*Param)->getType().getUnqualifiedType();
9593
9594    // unsigned long long int, long double, and any character type are allowed
9595    // as the only parameters.
9596    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9597        Context.hasSameType(T, Context.LongDoubleTy) ||
9598        Context.hasSameType(T, Context.CharTy) ||
9599        Context.hasSameType(T, Context.WCharTy) ||
9600        Context.hasSameType(T, Context.Char16Ty) ||
9601        Context.hasSameType(T, Context.Char32Ty)) {
9602      if (++Param == FnDecl->param_end())
9603        Valid = true;
9604      goto FinishedParams;
9605    }
9606
9607    // Otherwise it must be a pointer to const; let's strip those qualifiers.
9608    const PointerType *PT = T->getAs<PointerType>();
9609    if (!PT)
9610      goto FinishedParams;
9611    T = PT->getPointeeType();
9612    if (!T.isConstQualified() || T.isVolatileQualified())
9613      goto FinishedParams;
9614    T = T.getUnqualifiedType();
9615
9616    // Move on to the second parameter;
9617    ++Param;
9618
9619    // If there is no second parameter, the first must be a const char *
9620    if (Param == FnDecl->param_end()) {
9621      if (Context.hasSameType(T, Context.CharTy))
9622        Valid = true;
9623      goto FinishedParams;
9624    }
9625
9626    // const char *, const wchar_t*, const char16_t*, and const char32_t*
9627    // are allowed as the first parameter to a two-parameter function
9628    if (!(Context.hasSameType(T, Context.CharTy) ||
9629          Context.hasSameType(T, Context.WCharTy) ||
9630          Context.hasSameType(T, Context.Char16Ty) ||
9631          Context.hasSameType(T, Context.Char32Ty)))
9632      goto FinishedParams;
9633
9634    // The second and final parameter must be an std::size_t
9635    T = (*Param)->getType().getUnqualifiedType();
9636    if (Context.hasSameType(T, Context.getSizeType()) &&
9637        ++Param == FnDecl->param_end())
9638      Valid = true;
9639  }
9640
9641  // FIXME: This diagnostic is absolutely terrible.
9642FinishedParams:
9643  if (!Valid) {
9644    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9645      << FnDecl->getDeclName();
9646    return true;
9647  }
9648
9649  // A parameter-declaration-clause containing a default argument is not
9650  // equivalent to any of the permitted forms.
9651  for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9652                                    ParamEnd = FnDecl->param_end();
9653       Param != ParamEnd; ++Param) {
9654    if ((*Param)->hasDefaultArg()) {
9655      Diag((*Param)->getDefaultArgRange().getBegin(),
9656           diag::err_literal_operator_default_argument)
9657        << (*Param)->getDefaultArgRange();
9658      break;
9659    }
9660  }
9661
9662  StringRef LiteralName
9663    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9664  if (LiteralName[0] != '_') {
9665    // C++11 [usrlit.suffix]p1:
9666    //   Literal suffix identifiers that do not start with an underscore
9667    //   are reserved for future standardization.
9668    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9669  }
9670
9671  return false;
9672}
9673
9674/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9675/// linkage specification, including the language and (if present)
9676/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9677/// the location of the language string literal, which is provided
9678/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9679/// the '{' brace. Otherwise, this linkage specification does not
9680/// have any braces.
9681Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9682                                           SourceLocation LangLoc,
9683                                           StringRef Lang,
9684                                           SourceLocation LBraceLoc) {
9685  LinkageSpecDecl::LanguageIDs Language;
9686  if (Lang == "\"C\"")
9687    Language = LinkageSpecDecl::lang_c;
9688  else if (Lang == "\"C++\"")
9689    Language = LinkageSpecDecl::lang_cxx;
9690  else {
9691    Diag(LangLoc, diag::err_bad_language);
9692    return 0;
9693  }
9694
9695  // FIXME: Add all the various semantics of linkage specifications
9696
9697  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
9698                                               ExternLoc, LangLoc, Language);
9699  CurContext->addDecl(D);
9700  PushDeclContext(S, D);
9701  return D;
9702}
9703
9704/// ActOnFinishLinkageSpecification - Complete the definition of
9705/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9706/// valid, it's the position of the closing '}' brace in a linkage
9707/// specification that uses braces.
9708Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
9709                                            Decl *LinkageSpec,
9710                                            SourceLocation RBraceLoc) {
9711  if (LinkageSpec) {
9712    if (RBraceLoc.isValid()) {
9713      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9714      LSDecl->setRBraceLoc(RBraceLoc);
9715    }
9716    PopDeclContext();
9717  }
9718  return LinkageSpec;
9719}
9720
9721/// \brief Perform semantic analysis for the variable declaration that
9722/// occurs within a C++ catch clause, returning the newly-created
9723/// variable.
9724VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
9725                                         TypeSourceInfo *TInfo,
9726                                         SourceLocation StartLoc,
9727                                         SourceLocation Loc,
9728                                         IdentifierInfo *Name) {
9729  bool Invalid = false;
9730  QualType ExDeclType = TInfo->getType();
9731
9732  // Arrays and functions decay.
9733  if (ExDeclType->isArrayType())
9734    ExDeclType = Context.getArrayDecayedType(ExDeclType);
9735  else if (ExDeclType->isFunctionType())
9736    ExDeclType = Context.getPointerType(ExDeclType);
9737
9738  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9739  // The exception-declaration shall not denote a pointer or reference to an
9740  // incomplete type, other than [cv] void*.
9741  // N2844 forbids rvalue references.
9742  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
9743    Diag(Loc, diag::err_catch_rvalue_ref);
9744    Invalid = true;
9745  }
9746
9747  QualType BaseType = ExDeclType;
9748  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
9749  unsigned DK = diag::err_catch_incomplete;
9750  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
9751    BaseType = Ptr->getPointeeType();
9752    Mode = 1;
9753    DK = diag::err_catch_incomplete_ptr;
9754  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
9755    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
9756    BaseType = Ref->getPointeeType();
9757    Mode = 2;
9758    DK = diag::err_catch_incomplete_ref;
9759  }
9760  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
9761      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
9762    Invalid = true;
9763
9764  if (!Invalid && !ExDeclType->isDependentType() &&
9765      RequireNonAbstractType(Loc, ExDeclType,
9766                             diag::err_abstract_type_in_decl,
9767                             AbstractVariableType))
9768    Invalid = true;
9769
9770  // Only the non-fragile NeXT runtime currently supports C++ catches
9771  // of ObjC types, and no runtime supports catching ObjC types by value.
9772  if (!Invalid && getLangOpts().ObjC1) {
9773    QualType T = ExDeclType;
9774    if (const ReferenceType *RT = T->getAs<ReferenceType>())
9775      T = RT->getPointeeType();
9776
9777    if (T->isObjCObjectType()) {
9778      Diag(Loc, diag::err_objc_object_catch);
9779      Invalid = true;
9780    } else if (T->isObjCObjectPointerType()) {
9781      // FIXME: should this be a test for macosx-fragile specifically?
9782      if (getLangOpts().ObjCRuntime.isFragile())
9783        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
9784    }
9785  }
9786
9787  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9788                                    ExDeclType, TInfo, SC_None, SC_None);
9789  ExDecl->setExceptionVariable(true);
9790
9791  // In ARC, infer 'retaining' for variables of retainable type.
9792  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9793    Invalid = true;
9794
9795  if (!Invalid && !ExDeclType->isDependentType()) {
9796    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
9797      // C++ [except.handle]p16:
9798      //   The object declared in an exception-declaration or, if the
9799      //   exception-declaration does not specify a name, a temporary (12.2) is
9800      //   copy-initialized (8.5) from the exception object. [...]
9801      //   The object is destroyed when the handler exits, after the destruction
9802      //   of any automatic objects initialized within the handler.
9803      //
9804      // We just pretend to initialize the object with itself, then make sure
9805      // it can be destroyed later.
9806      QualType initType = ExDeclType;
9807
9808      InitializedEntity entity =
9809        InitializedEntity::InitializeVariable(ExDecl);
9810      InitializationKind initKind =
9811        InitializationKind::CreateCopy(Loc, SourceLocation());
9812
9813      Expr *opaqueValue =
9814        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9815      InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9816      ExprResult result = sequence.Perform(*this, entity, initKind,
9817                                           MultiExprArg(&opaqueValue, 1));
9818      if (result.isInvalid())
9819        Invalid = true;
9820      else {
9821        // If the constructor used was non-trivial, set this as the
9822        // "initializer".
9823        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9824        if (!construct->getConstructor()->isTrivial()) {
9825          Expr *init = MaybeCreateExprWithCleanups(construct);
9826          ExDecl->setInit(init);
9827        }
9828
9829        // And make sure it's destructable.
9830        FinalizeVarWithDestructor(ExDecl, recordType);
9831      }
9832    }
9833  }
9834
9835  if (Invalid)
9836    ExDecl->setInvalidDecl();
9837
9838  return ExDecl;
9839}
9840
9841/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9842/// handler.
9843Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
9844  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9845  bool Invalid = D.isInvalidType();
9846
9847  // Check for unexpanded parameter packs.
9848  if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9849                                               UPPC_ExceptionType)) {
9850    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9851                                             D.getIdentifierLoc());
9852    Invalid = true;
9853  }
9854
9855  IdentifierInfo *II = D.getIdentifier();
9856  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
9857                                             LookupOrdinaryName,
9858                                             ForRedeclaration)) {
9859    // The scope should be freshly made just for us. There is just no way
9860    // it contains any previous declaration.
9861    assert(!S->isDeclScope(PrevDecl));
9862    if (PrevDecl->isTemplateParameter()) {
9863      // Maybe we will complain about the shadowed template parameter.
9864      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9865      PrevDecl = 0;
9866    }
9867  }
9868
9869  if (D.getCXXScopeSpec().isSet() && !Invalid) {
9870    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9871      << D.getCXXScopeSpec().getRange();
9872    Invalid = true;
9873  }
9874
9875  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
9876                                              D.getLocStart(),
9877                                              D.getIdentifierLoc(),
9878                                              D.getIdentifier());
9879  if (Invalid)
9880    ExDecl->setInvalidDecl();
9881
9882  // Add the exception declaration into this scope.
9883  if (II)
9884    PushOnScopeChains(ExDecl, S);
9885  else
9886    CurContext->addDecl(ExDecl);
9887
9888  ProcessDeclAttributes(S, ExDecl, D);
9889  return ExDecl;
9890}
9891
9892Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9893                                         Expr *AssertExpr,
9894                                         Expr *AssertMessageExpr,
9895                                         SourceLocation RParenLoc) {
9896  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
9897
9898  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9899    return 0;
9900
9901  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
9902                                      AssertMessage, RParenLoc, false);
9903}
9904
9905Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9906                                         Expr *AssertExpr,
9907                                         StringLiteral *AssertMessage,
9908                                         SourceLocation RParenLoc,
9909                                         bool Failed) {
9910  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
9911      !Failed) {
9912    // In a static_assert-declaration, the constant-expression shall be a
9913    // constant expression that can be contextually converted to bool.
9914    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9915    if (Converted.isInvalid())
9916      Failed = true;
9917
9918    llvm::APSInt Cond;
9919    if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
9920          diag::err_static_assert_expression_is_not_constant,
9921          /*AllowFold=*/false).isInvalid())
9922      Failed = true;
9923
9924    if (!Failed && !Cond) {
9925      llvm::SmallString<256> MsgBuffer;
9926      llvm::raw_svector_ostream Msg(MsgBuffer);
9927      AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
9928      Diag(StaticAssertLoc, diag::err_static_assert_failed)
9929        << Msg.str() << AssertExpr->getSourceRange();
9930      Failed = true;
9931    }
9932  }
9933
9934  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9935                                        AssertExpr, AssertMessage, RParenLoc,
9936                                        Failed);
9937
9938  CurContext->addDecl(Decl);
9939  return Decl;
9940}
9941
9942/// \brief Perform semantic analysis of the given friend type declaration.
9943///
9944/// \returns A friend declaration that.
9945FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
9946                                      SourceLocation FriendLoc,
9947                                      TypeSourceInfo *TSInfo) {
9948  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9949
9950  QualType T = TSInfo->getType();
9951  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
9952
9953  // C++03 [class.friend]p2:
9954  //   An elaborated-type-specifier shall be used in a friend declaration
9955  //   for a class.*
9956  //
9957  //   * The class-key of the elaborated-type-specifier is required.
9958  if (!ActiveTemplateInstantiations.empty()) {
9959    // Do not complain about the form of friend template types during
9960    // template instantiation; we will already have complained when the
9961    // template was declared.
9962  } else if (!T->isElaboratedTypeSpecifier()) {
9963    // If we evaluated the type to a record type, suggest putting
9964    // a tag in front.
9965    if (const RecordType *RT = T->getAs<RecordType>()) {
9966      RecordDecl *RD = RT->getDecl();
9967
9968      std::string InsertionText = std::string(" ") + RD->getKindName();
9969
9970      Diag(TypeRange.getBegin(),
9971           getLangOpts().CPlusPlus0x ?
9972             diag::warn_cxx98_compat_unelaborated_friend_type :
9973             diag::ext_unelaborated_friend_type)
9974        << (unsigned) RD->getTagKind()
9975        << T
9976        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9977                                      InsertionText);
9978    } else {
9979      Diag(FriendLoc,
9980           getLangOpts().CPlusPlus0x ?
9981             diag::warn_cxx98_compat_nonclass_type_friend :
9982             diag::ext_nonclass_type_friend)
9983        << T
9984        << TypeRange;
9985    }
9986  } else if (T->getAs<EnumType>()) {
9987    Diag(FriendLoc,
9988         getLangOpts().CPlusPlus0x ?
9989           diag::warn_cxx98_compat_enum_friend :
9990           diag::ext_enum_friend)
9991      << T
9992      << TypeRange;
9993  }
9994
9995  // C++11 [class.friend]p3:
9996  //   A friend declaration that does not declare a function shall have one
9997  //   of the following forms:
9998  //     friend elaborated-type-specifier ;
9999  //     friend simple-type-specifier ;
10000  //     friend typename-specifier ;
10001  if (getLangOpts().CPlusPlus0x && LocStart != FriendLoc)
10002    Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10003
10004  //   If the type specifier in a friend declaration designates a (possibly
10005  //   cv-qualified) class type, that class is declared as a friend; otherwise,
10006  //   the friend declaration is ignored.
10007  return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
10008}
10009
10010/// Handle a friend tag declaration where the scope specifier was
10011/// templated.
10012Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10013                                    unsigned TagSpec, SourceLocation TagLoc,
10014                                    CXXScopeSpec &SS,
10015                                    IdentifierInfo *Name, SourceLocation NameLoc,
10016                                    AttributeList *Attr,
10017                                    MultiTemplateParamsArg TempParamLists) {
10018  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10019
10020  bool isExplicitSpecialization = false;
10021  bool Invalid = false;
10022
10023  if (TemplateParameterList *TemplateParams
10024        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
10025                                                  TempParamLists.data(),
10026                                                  TempParamLists.size(),
10027                                                  /*friend*/ true,
10028                                                  isExplicitSpecialization,
10029                                                  Invalid)) {
10030    if (TemplateParams->size() > 0) {
10031      // This is a declaration of a class template.
10032      if (Invalid)
10033        return 0;
10034
10035      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10036                                SS, Name, NameLoc, Attr,
10037                                TemplateParams, AS_public,
10038                                /*ModulePrivateLoc=*/SourceLocation(),
10039                                TempParamLists.size() - 1,
10040                                TempParamLists.data()).take();
10041    } else {
10042      // The "template<>" header is extraneous.
10043      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10044        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10045      isExplicitSpecialization = true;
10046    }
10047  }
10048
10049  if (Invalid) return 0;
10050
10051  bool isAllExplicitSpecializations = true;
10052  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
10053    if (TempParamLists[I]->size()) {
10054      isAllExplicitSpecializations = false;
10055      break;
10056    }
10057  }
10058
10059  // FIXME: don't ignore attributes.
10060
10061  // If it's explicit specializations all the way down, just forget
10062  // about the template header and build an appropriate non-templated
10063  // friend.  TODO: for source fidelity, remember the headers.
10064  if (isAllExplicitSpecializations) {
10065    if (SS.isEmpty()) {
10066      bool Owned = false;
10067      bool IsDependent = false;
10068      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10069                      Attr, AS_public,
10070                      /*ModulePrivateLoc=*/SourceLocation(),
10071                      MultiTemplateParamsArg(), Owned, IsDependent,
10072                      /*ScopedEnumKWLoc=*/SourceLocation(),
10073                      /*ScopedEnumUsesClassTag=*/false,
10074                      /*UnderlyingType=*/TypeResult());
10075    }
10076
10077    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10078    ElaboratedTypeKeyword Keyword
10079      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10080    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
10081                                   *Name, NameLoc);
10082    if (T.isNull())
10083      return 0;
10084
10085    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10086    if (isa<DependentNameType>(T)) {
10087      DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10088      TL.setElaboratedKeywordLoc(TagLoc);
10089      TL.setQualifierLoc(QualifierLoc);
10090      TL.setNameLoc(NameLoc);
10091    } else {
10092      ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
10093      TL.setElaboratedKeywordLoc(TagLoc);
10094      TL.setQualifierLoc(QualifierLoc);
10095      cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10096    }
10097
10098    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10099                                            TSI, FriendLoc);
10100    Friend->setAccess(AS_public);
10101    CurContext->addDecl(Friend);
10102    return Friend;
10103  }
10104
10105  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10106
10107
10108
10109  // Handle the case of a templated-scope friend class.  e.g.
10110  //   template <class T> class A<T>::B;
10111  // FIXME: we don't support these right now.
10112  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10113  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10114  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10115  DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10116  TL.setElaboratedKeywordLoc(TagLoc);
10117  TL.setQualifierLoc(SS.getWithLocInContext(Context));
10118  TL.setNameLoc(NameLoc);
10119
10120  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10121                                          TSI, FriendLoc);
10122  Friend->setAccess(AS_public);
10123  Friend->setUnsupportedFriend(true);
10124  CurContext->addDecl(Friend);
10125  return Friend;
10126}
10127
10128
10129/// Handle a friend type declaration.  This works in tandem with
10130/// ActOnTag.
10131///
10132/// Notes on friend class templates:
10133///
10134/// We generally treat friend class declarations as if they were
10135/// declaring a class.  So, for example, the elaborated type specifier
10136/// in a friend declaration is required to obey the restrictions of a
10137/// class-head (i.e. no typedefs in the scope chain), template
10138/// parameters are required to match up with simple template-ids, &c.
10139/// However, unlike when declaring a template specialization, it's
10140/// okay to refer to a template specialization without an empty
10141/// template parameter declaration, e.g.
10142///   friend class A<T>::B<unsigned>;
10143/// We permit this as a special case; if there are any template
10144/// parameters present at all, require proper matching, i.e.
10145///   template <> template \<class T> friend class A<int>::B;
10146Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
10147                                MultiTemplateParamsArg TempParams) {
10148  SourceLocation Loc = DS.getLocStart();
10149
10150  assert(DS.isFriendSpecified());
10151  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10152
10153  // Try to convert the decl specifier to a type.  This works for
10154  // friend templates because ActOnTag never produces a ClassTemplateDecl
10155  // for a TUK_Friend.
10156  Declarator TheDeclarator(DS, Declarator::MemberContext);
10157  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10158  QualType T = TSI->getType();
10159  if (TheDeclarator.isInvalidType())
10160    return 0;
10161
10162  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10163    return 0;
10164
10165  // This is definitely an error in C++98.  It's probably meant to
10166  // be forbidden in C++0x, too, but the specification is just
10167  // poorly written.
10168  //
10169  // The problem is with declarations like the following:
10170  //   template <T> friend A<T>::foo;
10171  // where deciding whether a class C is a friend or not now hinges
10172  // on whether there exists an instantiation of A that causes
10173  // 'foo' to equal C.  There are restrictions on class-heads
10174  // (which we declare (by fiat) elaborated friend declarations to
10175  // be) that makes this tractable.
10176  //
10177  // FIXME: handle "template <> friend class A<T>;", which
10178  // is possibly well-formed?  Who even knows?
10179  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
10180    Diag(Loc, diag::err_tagless_friend_type_template)
10181      << DS.getSourceRange();
10182    return 0;
10183  }
10184
10185  // C++98 [class.friend]p1: A friend of a class is a function
10186  //   or class that is not a member of the class . . .
10187  // This is fixed in DR77, which just barely didn't make the C++03
10188  // deadline.  It's also a very silly restriction that seriously
10189  // affects inner classes and which nobody else seems to implement;
10190  // thus we never diagnose it, not even in -pedantic.
10191  //
10192  // But note that we could warn about it: it's always useless to
10193  // friend one of your own members (it's not, however, worthless to
10194  // friend a member of an arbitrary specialization of your template).
10195
10196  Decl *D;
10197  if (unsigned NumTempParamLists = TempParams.size())
10198    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
10199                                   NumTempParamLists,
10200                                   TempParams.data(),
10201                                   TSI,
10202                                   DS.getFriendSpecLoc());
10203  else
10204    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
10205
10206  if (!D)
10207    return 0;
10208
10209  D->setAccess(AS_public);
10210  CurContext->addDecl(D);
10211
10212  return D;
10213}
10214
10215Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10216                                    MultiTemplateParamsArg TemplateParams) {
10217  const DeclSpec &DS = D.getDeclSpec();
10218
10219  assert(DS.isFriendSpecified());
10220  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10221
10222  SourceLocation Loc = D.getIdentifierLoc();
10223  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10224
10225  // C++ [class.friend]p1
10226  //   A friend of a class is a function or class....
10227  // Note that this sees through typedefs, which is intended.
10228  // It *doesn't* see through dependent types, which is correct
10229  // according to [temp.arg.type]p3:
10230  //   If a declaration acquires a function type through a
10231  //   type dependent on a template-parameter and this causes
10232  //   a declaration that does not use the syntactic form of a
10233  //   function declarator to have a function type, the program
10234  //   is ill-formed.
10235  if (!TInfo->getType()->isFunctionType()) {
10236    Diag(Loc, diag::err_unexpected_friend);
10237
10238    // It might be worthwhile to try to recover by creating an
10239    // appropriate declaration.
10240    return 0;
10241  }
10242
10243  // C++ [namespace.memdef]p3
10244  //  - If a friend declaration in a non-local class first declares a
10245  //    class or function, the friend class or function is a member
10246  //    of the innermost enclosing namespace.
10247  //  - The name of the friend is not found by simple name lookup
10248  //    until a matching declaration is provided in that namespace
10249  //    scope (either before or after the class declaration granting
10250  //    friendship).
10251  //  - If a friend function is called, its name may be found by the
10252  //    name lookup that considers functions from namespaces and
10253  //    classes associated with the types of the function arguments.
10254  //  - When looking for a prior declaration of a class or a function
10255  //    declared as a friend, scopes outside the innermost enclosing
10256  //    namespace scope are not considered.
10257
10258  CXXScopeSpec &SS = D.getCXXScopeSpec();
10259  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10260  DeclarationName Name = NameInfo.getName();
10261  assert(Name);
10262
10263  // Check for unexpanded parameter packs.
10264  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10265      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10266      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10267    return 0;
10268
10269  // The context we found the declaration in, or in which we should
10270  // create the declaration.
10271  DeclContext *DC;
10272  Scope *DCScope = S;
10273  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10274                        ForRedeclaration);
10275
10276  // FIXME: there are different rules in local classes
10277
10278  // There are four cases here.
10279  //   - There's no scope specifier, in which case we just go to the
10280  //     appropriate scope and look for a function or function template
10281  //     there as appropriate.
10282  // Recover from invalid scope qualifiers as if they just weren't there.
10283  if (SS.isInvalid() || !SS.isSet()) {
10284    // C++0x [namespace.memdef]p3:
10285    //   If the name in a friend declaration is neither qualified nor
10286    //   a template-id and the declaration is a function or an
10287    //   elaborated-type-specifier, the lookup to determine whether
10288    //   the entity has been previously declared shall not consider
10289    //   any scopes outside the innermost enclosing namespace.
10290    // C++0x [class.friend]p11:
10291    //   If a friend declaration appears in a local class and the name
10292    //   specified is an unqualified name, a prior declaration is
10293    //   looked up without considering scopes that are outside the
10294    //   innermost enclosing non-class scope. For a friend function
10295    //   declaration, if there is no prior declaration, the program is
10296    //   ill-formed.
10297    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
10298    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
10299
10300    // Find the appropriate context according to the above.
10301    DC = CurContext;
10302    while (true) {
10303      // Skip class contexts.  If someone can cite chapter and verse
10304      // for this behavior, that would be nice --- it's what GCC and
10305      // EDG do, and it seems like a reasonable intent, but the spec
10306      // really only says that checks for unqualified existing
10307      // declarations should stop at the nearest enclosing namespace,
10308      // not that they should only consider the nearest enclosing
10309      // namespace.
10310      while (DC->isRecord() || DC->isTransparentContext())
10311        DC = DC->getParent();
10312
10313      LookupQualifiedName(Previous, DC);
10314
10315      // TODO: decide what we think about using declarations.
10316      if (isLocal || !Previous.empty())
10317        break;
10318
10319      if (isTemplateId) {
10320        if (isa<TranslationUnitDecl>(DC)) break;
10321      } else {
10322        if (DC->isFileContext()) break;
10323      }
10324      DC = DC->getParent();
10325    }
10326
10327    // C++ [class.friend]p1: A friend of a class is a function or
10328    //   class that is not a member of the class . . .
10329    // C++11 changes this for both friend types and functions.
10330    // Most C++ 98 compilers do seem to give an error here, so
10331    // we do, too.
10332    if (!Previous.empty() && DC->Equals(CurContext))
10333      Diag(DS.getFriendSpecLoc(),
10334           getLangOpts().CPlusPlus0x ?
10335             diag::warn_cxx98_compat_friend_is_member :
10336             diag::err_friend_is_member);
10337
10338    DCScope = getScopeForDeclContext(S, DC);
10339
10340    // C++ [class.friend]p6:
10341    //   A function can be defined in a friend declaration of a class if and
10342    //   only if the class is a non-local class (9.8), the function name is
10343    //   unqualified, and the function has namespace scope.
10344    if (isLocal && D.isFunctionDefinition()) {
10345      Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10346    }
10347
10348  //   - There's a non-dependent scope specifier, in which case we
10349  //     compute it and do a previous lookup there for a function
10350  //     or function template.
10351  } else if (!SS.getScopeRep()->isDependent()) {
10352    DC = computeDeclContext(SS);
10353    if (!DC) return 0;
10354
10355    if (RequireCompleteDeclContext(SS, DC)) return 0;
10356
10357    LookupQualifiedName(Previous, DC);
10358
10359    // Ignore things found implicitly in the wrong scope.
10360    // TODO: better diagnostics for this case.  Suggesting the right
10361    // qualified scope would be nice...
10362    LookupResult::Filter F = Previous.makeFilter();
10363    while (F.hasNext()) {
10364      NamedDecl *D = F.next();
10365      if (!DC->InEnclosingNamespaceSetOf(
10366              D->getDeclContext()->getRedeclContext()))
10367        F.erase();
10368    }
10369    F.done();
10370
10371    if (Previous.empty()) {
10372      D.setInvalidType();
10373      Diag(Loc, diag::err_qualified_friend_not_found)
10374          << Name << TInfo->getType();
10375      return 0;
10376    }
10377
10378    // C++ [class.friend]p1: A friend of a class is a function or
10379    //   class that is not a member of the class . . .
10380    if (DC->Equals(CurContext))
10381      Diag(DS.getFriendSpecLoc(),
10382           getLangOpts().CPlusPlus0x ?
10383             diag::warn_cxx98_compat_friend_is_member :
10384             diag::err_friend_is_member);
10385
10386    if (D.isFunctionDefinition()) {
10387      // C++ [class.friend]p6:
10388      //   A function can be defined in a friend declaration of a class if and
10389      //   only if the class is a non-local class (9.8), the function name is
10390      //   unqualified, and the function has namespace scope.
10391      SemaDiagnosticBuilder DB
10392        = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10393
10394      DB << SS.getScopeRep();
10395      if (DC->isFileContext())
10396        DB << FixItHint::CreateRemoval(SS.getRange());
10397      SS.clear();
10398    }
10399
10400  //   - There's a scope specifier that does not match any template
10401  //     parameter lists, in which case we use some arbitrary context,
10402  //     create a method or method template, and wait for instantiation.
10403  //   - There's a scope specifier that does match some template
10404  //     parameter lists, which we don't handle right now.
10405  } else {
10406    if (D.isFunctionDefinition()) {
10407      // C++ [class.friend]p6:
10408      //   A function can be defined in a friend declaration of a class if and
10409      //   only if the class is a non-local class (9.8), the function name is
10410      //   unqualified, and the function has namespace scope.
10411      Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10412        << SS.getScopeRep();
10413    }
10414
10415    DC = CurContext;
10416    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
10417  }
10418
10419  if (!DC->isRecord()) {
10420    // This implies that it has to be an operator or function.
10421    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10422        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10423        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
10424      Diag(Loc, diag::err_introducing_special_friend) <<
10425        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10426         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
10427      return 0;
10428    }
10429  }
10430
10431  // FIXME: This is an egregious hack to cope with cases where the scope stack
10432  // does not contain the declaration context, i.e., in an out-of-line
10433  // definition of a class.
10434  Scope FakeDCScope(S, Scope::DeclScope, Diags);
10435  if (!DCScope) {
10436    FakeDCScope.setEntity(DC);
10437    DCScope = &FakeDCScope;
10438  }
10439
10440  bool AddToScope = true;
10441  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10442                                          TemplateParams, AddToScope);
10443  if (!ND) return 0;
10444
10445  assert(ND->getDeclContext() == DC);
10446  assert(ND->getLexicalDeclContext() == CurContext);
10447
10448  // Add the function declaration to the appropriate lookup tables,
10449  // adjusting the redeclarations list as necessary.  We don't
10450  // want to do this yet if the friending class is dependent.
10451  //
10452  // Also update the scope-based lookup if the target context's
10453  // lookup context is in lexical scope.
10454  if (!CurContext->isDependentContext()) {
10455    DC = DC->getRedeclContext();
10456    DC->makeDeclVisibleInContext(ND);
10457    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10458      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
10459  }
10460
10461  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
10462                                       D.getIdentifierLoc(), ND,
10463                                       DS.getFriendSpecLoc());
10464  FrD->setAccess(AS_public);
10465  CurContext->addDecl(FrD);
10466
10467  if (ND->isInvalidDecl()) {
10468    FrD->setInvalidDecl();
10469  } else {
10470    if (DC->isRecord()) CheckFriendAccess(ND);
10471
10472    FunctionDecl *FD;
10473    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10474      FD = FTD->getTemplatedDecl();
10475    else
10476      FD = cast<FunctionDecl>(ND);
10477
10478    // Mark templated-scope function declarations as unsupported.
10479    if (FD->getNumTemplateParameterLists())
10480      FrD->setUnsupportedFriend(true);
10481  }
10482
10483  return ND;
10484}
10485
10486void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10487  AdjustDeclIfTemplate(Dcl);
10488
10489  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10490  if (!Fn) {
10491    Diag(DelLoc, diag::err_deleted_non_function);
10492    return;
10493  }
10494  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
10495    // Don't consider the implicit declaration we generate for explicit
10496    // specializations. FIXME: Do not generate these implicit declarations.
10497    if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10498        || Prev->getPreviousDecl()) && !Prev->isDefined()) {
10499      Diag(DelLoc, diag::err_deleted_decl_not_first);
10500      Diag(Prev->getLocation(), diag::note_previous_declaration);
10501    }
10502    // If the declaration wasn't the first, we delete the function anyway for
10503    // recovery.
10504  }
10505  Fn->setDeletedAsWritten();
10506
10507  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10508  if (!MD)
10509    return;
10510
10511  // A deleted special member function is trivial if the corresponding
10512  // implicitly-declared function would have been.
10513  switch (getSpecialMember(MD)) {
10514  case CXXInvalid:
10515    break;
10516  case CXXDefaultConstructor:
10517    MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10518    break;
10519  case CXXCopyConstructor:
10520    MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10521    break;
10522  case CXXMoveConstructor:
10523    MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10524    break;
10525  case CXXCopyAssignment:
10526    MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10527    break;
10528  case CXXMoveAssignment:
10529    MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10530    break;
10531  case CXXDestructor:
10532    MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10533    break;
10534  }
10535}
10536
10537void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10538  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10539
10540  if (MD) {
10541    if (MD->getParent()->isDependentType()) {
10542      MD->setDefaulted();
10543      MD->setExplicitlyDefaulted();
10544      return;
10545    }
10546
10547    CXXSpecialMember Member = getSpecialMember(MD);
10548    if (Member == CXXInvalid) {
10549      Diag(DefaultLoc, diag::err_default_special_members);
10550      return;
10551    }
10552
10553    MD->setDefaulted();
10554    MD->setExplicitlyDefaulted();
10555
10556    // If this definition appears within the record, do the checking when
10557    // the record is complete.
10558    const FunctionDecl *Primary = MD;
10559    if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
10560      // Find the uninstantiated declaration that actually had the '= default'
10561      // on it.
10562      Pattern->isDefined(Primary);
10563
10564    if (Primary == Primary->getCanonicalDecl())
10565      return;
10566
10567    CheckExplicitlyDefaultedSpecialMember(MD);
10568
10569    switch (Member) {
10570    case CXXDefaultConstructor: {
10571      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10572      if (!CD->isInvalidDecl())
10573        DefineImplicitDefaultConstructor(DefaultLoc, CD);
10574      break;
10575    }
10576
10577    case CXXCopyConstructor: {
10578      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10579      if (!CD->isInvalidDecl())
10580        DefineImplicitCopyConstructor(DefaultLoc, CD);
10581      break;
10582    }
10583
10584    case CXXCopyAssignment: {
10585      if (!MD->isInvalidDecl())
10586        DefineImplicitCopyAssignment(DefaultLoc, MD);
10587      break;
10588    }
10589
10590    case CXXDestructor: {
10591      CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10592      if (!DD->isInvalidDecl())
10593        DefineImplicitDestructor(DefaultLoc, DD);
10594      break;
10595    }
10596
10597    case CXXMoveConstructor: {
10598      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10599      if (!CD->isInvalidDecl())
10600        DefineImplicitMoveConstructor(DefaultLoc, CD);
10601      break;
10602    }
10603
10604    case CXXMoveAssignment: {
10605      if (!MD->isInvalidDecl())
10606        DefineImplicitMoveAssignment(DefaultLoc, MD);
10607      break;
10608    }
10609
10610    case CXXInvalid:
10611      llvm_unreachable("Invalid special member.");
10612    }
10613  } else {
10614    Diag(DefaultLoc, diag::err_default_special_members);
10615  }
10616}
10617
10618static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
10619  for (Stmt::child_range CI = S->children(); CI; ++CI) {
10620    Stmt *SubStmt = *CI;
10621    if (!SubStmt)
10622      continue;
10623    if (isa<ReturnStmt>(SubStmt))
10624      Self.Diag(SubStmt->getLocStart(),
10625           diag::err_return_in_constructor_handler);
10626    if (!isa<Expr>(SubStmt))
10627      SearchForReturnInStmt(Self, SubStmt);
10628  }
10629}
10630
10631void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10632  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10633    CXXCatchStmt *Handler = TryBlock->getHandler(I);
10634    SearchForReturnInStmt(*this, Handler);
10635  }
10636}
10637
10638bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
10639                                             const CXXMethodDecl *Old) {
10640  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10641  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
10642
10643  if (Context.hasSameType(NewTy, OldTy) ||
10644      NewTy->isDependentType() || OldTy->isDependentType())
10645    return false;
10646
10647  // Check if the return types are covariant
10648  QualType NewClassTy, OldClassTy;
10649
10650  /// Both types must be pointers or references to classes.
10651  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10652    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
10653      NewClassTy = NewPT->getPointeeType();
10654      OldClassTy = OldPT->getPointeeType();
10655    }
10656  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10657    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10658      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10659        NewClassTy = NewRT->getPointeeType();
10660        OldClassTy = OldRT->getPointeeType();
10661      }
10662    }
10663  }
10664
10665  // The return types aren't either both pointers or references to a class type.
10666  if (NewClassTy.isNull()) {
10667    Diag(New->getLocation(),
10668         diag::err_different_return_type_for_overriding_virtual_function)
10669      << New->getDeclName() << NewTy << OldTy;
10670    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10671
10672    return true;
10673  }
10674
10675  // C++ [class.virtual]p6:
10676  //   If the return type of D::f differs from the return type of B::f, the
10677  //   class type in the return type of D::f shall be complete at the point of
10678  //   declaration of D::f or shall be the class type D.
10679  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10680    if (!RT->isBeingDefined() &&
10681        RequireCompleteType(New->getLocation(), NewClassTy,
10682                            diag::err_covariant_return_incomplete,
10683                            New->getDeclName()))
10684    return true;
10685  }
10686
10687  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
10688    // Check if the new class derives from the old class.
10689    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10690      Diag(New->getLocation(),
10691           diag::err_covariant_return_not_derived)
10692      << New->getDeclName() << NewTy << OldTy;
10693      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10694      return true;
10695    }
10696
10697    // Check if we the conversion from derived to base is valid.
10698    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
10699                    diag::err_covariant_return_inaccessible_base,
10700                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
10701                    // FIXME: Should this point to the return type?
10702                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
10703      // FIXME: this note won't trigger for delayed access control
10704      // diagnostics, and it's impossible to get an undelayed error
10705      // here from access control during the original parse because
10706      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
10707      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10708      return true;
10709    }
10710  }
10711
10712  // The qualifiers of the return types must be the same.
10713  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
10714    Diag(New->getLocation(),
10715         diag::err_covariant_return_type_different_qualifications)
10716    << New->getDeclName() << NewTy << OldTy;
10717    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10718    return true;
10719  };
10720
10721
10722  // The new class type must have the same or less qualifiers as the old type.
10723  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10724    Diag(New->getLocation(),
10725         diag::err_covariant_return_type_class_type_more_qualified)
10726    << New->getDeclName() << NewTy << OldTy;
10727    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10728    return true;
10729  };
10730
10731  return false;
10732}
10733
10734/// \brief Mark the given method pure.
10735///
10736/// \param Method the method to be marked pure.
10737///
10738/// \param InitRange the source range that covers the "0" initializer.
10739bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
10740  SourceLocation EndLoc = InitRange.getEnd();
10741  if (EndLoc.isValid())
10742    Method->setRangeEnd(EndLoc);
10743
10744  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10745    Method->setPure();
10746    return false;
10747  }
10748
10749  if (!Method->isInvalidDecl())
10750    Diag(Method->getLocation(), diag::err_non_virtual_pure)
10751      << Method->getDeclName() << InitRange;
10752  return true;
10753}
10754
10755/// \brief Determine whether the given declaration is a static data member.
10756static bool isStaticDataMember(Decl *D) {
10757  VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10758  if (!Var)
10759    return false;
10760
10761  return Var->isStaticDataMember();
10762}
10763/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10764/// an initializer for the out-of-line declaration 'Dcl'.  The scope
10765/// is a fresh scope pushed for just this purpose.
10766///
10767/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10768/// static data member of class X, names should be looked up in the scope of
10769/// class X.
10770void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
10771  // If there is no declaration, there was an error parsing it.
10772  if (D == 0 || D->isInvalidDecl()) return;
10773
10774  // We should only get called for declarations with scope specifiers, like:
10775  //   int foo::bar;
10776  assert(D->isOutOfLine());
10777  EnterDeclaratorContext(S, D->getDeclContext());
10778
10779  // If we are parsing the initializer for a static data member, push a
10780  // new expression evaluation context that is associated with this static
10781  // data member.
10782  if (isStaticDataMember(D))
10783    PushExpressionEvaluationContext(PotentiallyEvaluated, D);
10784}
10785
10786/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
10787/// initializer for the out-of-line declaration 'D'.
10788void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
10789  // If there is no declaration, there was an error parsing it.
10790  if (D == 0 || D->isInvalidDecl()) return;
10791
10792  if (isStaticDataMember(D))
10793    PopExpressionEvaluationContext();
10794
10795  assert(D->isOutOfLine());
10796  ExitDeclaratorContext(S);
10797}
10798
10799/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10800/// C++ if/switch/while/for statement.
10801/// e.g: "if (int x = f()) {...}"
10802DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
10803  // C++ 6.4p2:
10804  // The declarator shall not specify a function or an array.
10805  // The type-specifier-seq shall not contain typedef and shall not declare a
10806  // new class or enumeration.
10807  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10808         "Parser allowed 'typedef' as storage class of condition decl.");
10809
10810  Decl *Dcl = ActOnDeclarator(S, D);
10811  if (!Dcl)
10812    return true;
10813
10814  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10815    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
10816      << D.getSourceRange();
10817    return true;
10818  }
10819
10820  return Dcl;
10821}
10822
10823void Sema::LoadExternalVTableUses() {
10824  if (!ExternalSource)
10825    return;
10826
10827  SmallVector<ExternalVTableUse, 4> VTables;
10828  ExternalSource->ReadUsedVTables(VTables);
10829  SmallVector<VTableUse, 4> NewUses;
10830  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10831    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10832      = VTablesUsed.find(VTables[I].Record);
10833    // Even if a definition wasn't required before, it may be required now.
10834    if (Pos != VTablesUsed.end()) {
10835      if (!Pos->second && VTables[I].DefinitionRequired)
10836        Pos->second = true;
10837      continue;
10838    }
10839
10840    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10841    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10842  }
10843
10844  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10845}
10846
10847void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10848                          bool DefinitionRequired) {
10849  // Ignore any vtable uses in unevaluated operands or for classes that do
10850  // not have a vtable.
10851  if (!Class->isDynamicClass() || Class->isDependentContext() ||
10852      CurContext->isDependentContext() ||
10853      ExprEvalContexts.back().Context == Unevaluated)
10854    return;
10855
10856  // Try to insert this class into the map.
10857  LoadExternalVTableUses();
10858  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10859  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10860    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10861  if (!Pos.second) {
10862    // If we already had an entry, check to see if we are promoting this vtable
10863    // to required a definition. If so, we need to reappend to the VTableUses
10864    // list, since we may have already processed the first entry.
10865    if (DefinitionRequired && !Pos.first->second) {
10866      Pos.first->second = true;
10867    } else {
10868      // Otherwise, we can early exit.
10869      return;
10870    }
10871  }
10872
10873  // Local classes need to have their virtual members marked
10874  // immediately. For all other classes, we mark their virtual members
10875  // at the end of the translation unit.
10876  if (Class->isLocalClass())
10877    MarkVirtualMembersReferenced(Loc, Class);
10878  else
10879    VTableUses.push_back(std::make_pair(Class, Loc));
10880}
10881
10882bool Sema::DefineUsedVTables() {
10883  LoadExternalVTableUses();
10884  if (VTableUses.empty())
10885    return false;
10886
10887  // Note: The VTableUses vector could grow as a result of marking
10888  // the members of a class as "used", so we check the size each
10889  // time through the loop and prefer indices (which are stable) to
10890  // iterators (which are not).
10891  bool DefinedAnything = false;
10892  for (unsigned I = 0; I != VTableUses.size(); ++I) {
10893    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
10894    if (!Class)
10895      continue;
10896
10897    SourceLocation Loc = VTableUses[I].second;
10898
10899    bool DefineVTable = true;
10900
10901    // If this class has a key function, but that key function is
10902    // defined in another translation unit, we don't need to emit the
10903    // vtable even though we're using it.
10904    const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
10905    if (KeyFunction && !KeyFunction->hasBody()) {
10906      switch (KeyFunction->getTemplateSpecializationKind()) {
10907      case TSK_Undeclared:
10908      case TSK_ExplicitSpecialization:
10909      case TSK_ExplicitInstantiationDeclaration:
10910        // The key function is in another translation unit.
10911        DefineVTable = false;
10912        break;
10913
10914      case TSK_ExplicitInstantiationDefinition:
10915      case TSK_ImplicitInstantiation:
10916        // We will be instantiating the key function.
10917        break;
10918      }
10919    } else if (!KeyFunction) {
10920      // If we have a class with no key function that is the subject
10921      // of an explicit instantiation declaration, suppress the
10922      // vtable; it will live with the explicit instantiation
10923      // definition.
10924      bool IsExplicitInstantiationDeclaration
10925        = Class->getTemplateSpecializationKind()
10926                                      == TSK_ExplicitInstantiationDeclaration;
10927      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10928                                 REnd = Class->redecls_end();
10929           R != REnd; ++R) {
10930        TemplateSpecializationKind TSK
10931          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10932        if (TSK == TSK_ExplicitInstantiationDeclaration)
10933          IsExplicitInstantiationDeclaration = true;
10934        else if (TSK == TSK_ExplicitInstantiationDefinition) {
10935          IsExplicitInstantiationDeclaration = false;
10936          break;
10937        }
10938      }
10939
10940      if (IsExplicitInstantiationDeclaration)
10941        DefineVTable = false;
10942    }
10943
10944    // The exception specifications for all virtual members may be needed even
10945    // if we are not providing an authoritative form of the vtable in this TU.
10946    // We may choose to emit it available_externally anyway.
10947    if (!DefineVTable) {
10948      MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
10949      continue;
10950    }
10951
10952    // Mark all of the virtual members of this class as referenced, so
10953    // that we can build a vtable. Then, tell the AST consumer that a
10954    // vtable for this class is required.
10955    DefinedAnything = true;
10956    MarkVirtualMembersReferenced(Loc, Class);
10957    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10958    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10959
10960    // Optionally warn if we're emitting a weak vtable.
10961    if (Class->getLinkage() == ExternalLinkage &&
10962        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
10963      const FunctionDecl *KeyFunctionDef = 0;
10964      if (!KeyFunction ||
10965          (KeyFunction->hasBody(KeyFunctionDef) &&
10966           KeyFunctionDef->isInlined()))
10967        Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10968             TSK_ExplicitInstantiationDefinition
10969             ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10970          << Class;
10971    }
10972  }
10973  VTableUses.clear();
10974
10975  return DefinedAnything;
10976}
10977
10978void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
10979                                                 const CXXRecordDecl *RD) {
10980  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
10981                                      E = RD->method_end(); I != E; ++I)
10982    if ((*I)->isVirtual() && !(*I)->isPure())
10983      ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
10984}
10985
10986void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10987                                        const CXXRecordDecl *RD) {
10988  // Mark all functions which will appear in RD's vtable as used.
10989  CXXFinalOverriderMap FinalOverriders;
10990  RD->getFinalOverriders(FinalOverriders);
10991  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
10992                                            E = FinalOverriders.end();
10993       I != E; ++I) {
10994    for (OverridingMethods::const_iterator OI = I->second.begin(),
10995                                           OE = I->second.end();
10996         OI != OE; ++OI) {
10997      assert(OI->second.size() > 0 && "no final overrider");
10998      CXXMethodDecl *Overrider = OI->second.front().Method;
10999
11000      // C++ [basic.def.odr]p2:
11001      //   [...] A virtual member function is used if it is not pure. [...]
11002      if (!Overrider->isPure())
11003        MarkFunctionReferenced(Loc, Overrider);
11004    }
11005  }
11006
11007  // Only classes that have virtual bases need a VTT.
11008  if (RD->getNumVBases() == 0)
11009    return;
11010
11011  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11012           e = RD->bases_end(); i != e; ++i) {
11013    const CXXRecordDecl *Base =
11014        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
11015    if (Base->getNumVBases() == 0)
11016      continue;
11017    MarkVirtualMembersReferenced(Loc, Base);
11018  }
11019}
11020
11021/// SetIvarInitializers - This routine builds initialization ASTs for the
11022/// Objective-C implementation whose ivars need be initialized.
11023void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
11024  if (!getLangOpts().CPlusPlus)
11025    return;
11026  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
11027    SmallVector<ObjCIvarDecl*, 8> ivars;
11028    CollectIvarsToConstructOrDestruct(OID, ivars);
11029    if (ivars.empty())
11030      return;
11031    SmallVector<CXXCtorInitializer*, 32> AllToInit;
11032    for (unsigned i = 0; i < ivars.size(); i++) {
11033      FieldDecl *Field = ivars[i];
11034      if (Field->isInvalidDecl())
11035        continue;
11036
11037      CXXCtorInitializer *Member;
11038      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11039      InitializationKind InitKind =
11040        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11041
11042      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
11043      ExprResult MemberInit =
11044        InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
11045      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
11046      // Note, MemberInit could actually come back empty if no initialization
11047      // is required (e.g., because it would call a trivial default constructor)
11048      if (!MemberInit.get() || MemberInit.isInvalid())
11049        continue;
11050
11051      Member =
11052        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11053                                         SourceLocation(),
11054                                         MemberInit.takeAs<Expr>(),
11055                                         SourceLocation());
11056      AllToInit.push_back(Member);
11057
11058      // Be sure that the destructor is accessible and is marked as referenced.
11059      if (const RecordType *RecordTy
11060                  = Context.getBaseElementType(Field->getType())
11061                                                        ->getAs<RecordType>()) {
11062                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
11063        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
11064          MarkFunctionReferenced(Field->getLocation(), Destructor);
11065          CheckDestructorAccess(Field->getLocation(), Destructor,
11066                            PDiag(diag::err_access_dtor_ivar)
11067                              << Context.getBaseElementType(Field->getType()));
11068        }
11069      }
11070    }
11071    ObjCImplementation->setIvarInitializers(Context,
11072                                            AllToInit.data(), AllToInit.size());
11073  }
11074}
11075
11076static
11077void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11078                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11079                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11080                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11081                           Sema &S) {
11082  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11083                                                   CE = Current.end();
11084  if (Ctor->isInvalidDecl())
11085    return;
11086
11087  CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11088
11089  // Target may not be determinable yet, for instance if this is a dependent
11090  // call in an uninstantiated template.
11091  if (Target) {
11092    const FunctionDecl *FNTarget = 0;
11093    (void)Target->hasBody(FNTarget);
11094    Target = const_cast<CXXConstructorDecl*>(
11095      cast_or_null<CXXConstructorDecl>(FNTarget));
11096  }
11097
11098  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11099                     // Avoid dereferencing a null pointer here.
11100                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11101
11102  if (!Current.insert(Canonical))
11103    return;
11104
11105  // We know that beyond here, we aren't chaining into a cycle.
11106  if (!Target || !Target->isDelegatingConstructor() ||
11107      Target->isInvalidDecl() || Valid.count(TCanonical)) {
11108    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11109      Valid.insert(*CI);
11110    Current.clear();
11111  // We've hit a cycle.
11112  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11113             Current.count(TCanonical)) {
11114    // If we haven't diagnosed this cycle yet, do so now.
11115    if (!Invalid.count(TCanonical)) {
11116      S.Diag((*Ctor->init_begin())->getSourceLocation(),
11117             diag::warn_delegating_ctor_cycle)
11118        << Ctor;
11119
11120      // Don't add a note for a function delegating directly to itself.
11121      if (TCanonical != Canonical)
11122        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11123
11124      CXXConstructorDecl *C = Target;
11125      while (C->getCanonicalDecl() != Canonical) {
11126        const FunctionDecl *FNTarget = 0;
11127        (void)C->getTargetConstructor()->hasBody(FNTarget);
11128        assert(FNTarget && "Ctor cycle through bodiless function");
11129
11130        C = const_cast<CXXConstructorDecl*>(
11131          cast<CXXConstructorDecl>(FNTarget));
11132        S.Diag(C->getLocation(), diag::note_which_delegates_to);
11133      }
11134    }
11135
11136    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11137      Invalid.insert(*CI);
11138    Current.clear();
11139  } else {
11140    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11141  }
11142}
11143
11144
11145void Sema::CheckDelegatingCtorCycles() {
11146  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11147
11148  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11149                                                   CE = Current.end();
11150
11151  for (DelegatingCtorDeclsType::iterator
11152         I = DelegatingCtorDecls.begin(ExternalSource),
11153         E = DelegatingCtorDecls.end();
11154       I != E; ++I)
11155    DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
11156
11157  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11158    (*CI)->setInvalidDecl();
11159}
11160
11161namespace {
11162  /// \brief AST visitor that finds references to the 'this' expression.
11163  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11164    Sema &S;
11165
11166  public:
11167    explicit FindCXXThisExpr(Sema &S) : S(S) { }
11168
11169    bool VisitCXXThisExpr(CXXThisExpr *E) {
11170      S.Diag(E->getLocation(), diag::err_this_static_member_func)
11171        << E->isImplicit();
11172      return false;
11173    }
11174  };
11175}
11176
11177bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11178  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11179  if (!TSInfo)
11180    return false;
11181
11182  TypeLoc TL = TSInfo->getTypeLoc();
11183  FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11184  if (!ProtoTL)
11185    return false;
11186
11187  // C++11 [expr.prim.general]p3:
11188  //   [The expression this] shall not appear before the optional
11189  //   cv-qualifier-seq and it shall not appear within the declaration of a
11190  //   static member function (although its type and value category are defined
11191  //   within a static member function as they are within a non-static member
11192  //   function). [ Note: this is because declaration matching does not occur
11193  //  until the complete declarator is known. - end note ]
11194  const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11195  FindCXXThisExpr Finder(*this);
11196
11197  // If the return type came after the cv-qualifier-seq, check it now.
11198  if (Proto->hasTrailingReturn() &&
11199      !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11200    return true;
11201
11202  // Check the exception specification.
11203  if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11204    return true;
11205
11206  return checkThisInStaticMemberFunctionAttributes(Method);
11207}
11208
11209bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11210  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11211  if (!TSInfo)
11212    return false;
11213
11214  TypeLoc TL = TSInfo->getTypeLoc();
11215  FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11216  if (!ProtoTL)
11217    return false;
11218
11219  const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11220  FindCXXThisExpr Finder(*this);
11221
11222  switch (Proto->getExceptionSpecType()) {
11223  case EST_Uninstantiated:
11224  case EST_Unevaluated:
11225  case EST_BasicNoexcept:
11226  case EST_DynamicNone:
11227  case EST_MSAny:
11228  case EST_None:
11229    break;
11230
11231  case EST_ComputedNoexcept:
11232    if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11233      return true;
11234
11235  case EST_Dynamic:
11236    for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
11237         EEnd = Proto->exception_end();
11238         E != EEnd; ++E) {
11239      if (!Finder.TraverseType(*E))
11240        return true;
11241    }
11242    break;
11243  }
11244
11245  return false;
11246}
11247
11248bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11249  FindCXXThisExpr Finder(*this);
11250
11251  // Check attributes.
11252  for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11253       A != AEnd; ++A) {
11254    // FIXME: This should be emitted by tblgen.
11255    Expr *Arg = 0;
11256    ArrayRef<Expr *> Args;
11257    if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11258      Arg = G->getArg();
11259    else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11260      Arg = G->getArg();
11261    else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11262      Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11263    else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11264      Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11265    else if (ExclusiveLockFunctionAttr *ELF
11266               = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11267      Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11268    else if (SharedLockFunctionAttr *SLF
11269               = dyn_cast<SharedLockFunctionAttr>(*A))
11270      Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11271    else if (ExclusiveTrylockFunctionAttr *ETLF
11272               = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11273      Arg = ETLF->getSuccessValue();
11274      Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11275    } else if (SharedTrylockFunctionAttr *STLF
11276                 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11277      Arg = STLF->getSuccessValue();
11278      Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11279    } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11280      Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11281    else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11282      Arg = LR->getArg();
11283    else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11284      Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11285    else if (ExclusiveLocksRequiredAttr *ELR
11286               = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11287      Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11288    else if (SharedLocksRequiredAttr *SLR
11289               = dyn_cast<SharedLocksRequiredAttr>(*A))
11290      Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11291
11292    if (Arg && !Finder.TraverseStmt(Arg))
11293      return true;
11294
11295    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11296      if (!Finder.TraverseStmt(Args[I]))
11297        return true;
11298    }
11299  }
11300
11301  return false;
11302}
11303
11304void
11305Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11306                                  ArrayRef<ParsedType> DynamicExceptions,
11307                                  ArrayRef<SourceRange> DynamicExceptionRanges,
11308                                  Expr *NoexceptExpr,
11309                                  llvm::SmallVectorImpl<QualType> &Exceptions,
11310                                  FunctionProtoType::ExtProtoInfo &EPI) {
11311  Exceptions.clear();
11312  EPI.ExceptionSpecType = EST;
11313  if (EST == EST_Dynamic) {
11314    Exceptions.reserve(DynamicExceptions.size());
11315    for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11316      // FIXME: Preserve type source info.
11317      QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11318
11319      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11320      collectUnexpandedParameterPacks(ET, Unexpanded);
11321      if (!Unexpanded.empty()) {
11322        DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11323                                         UPPC_ExceptionType,
11324                                         Unexpanded);
11325        continue;
11326      }
11327
11328      // Check that the type is valid for an exception spec, and
11329      // drop it if not.
11330      if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11331        Exceptions.push_back(ET);
11332    }
11333    EPI.NumExceptions = Exceptions.size();
11334    EPI.Exceptions = Exceptions.data();
11335    return;
11336  }
11337
11338  if (EST == EST_ComputedNoexcept) {
11339    // If an error occurred, there's no expression here.
11340    if (NoexceptExpr) {
11341      assert((NoexceptExpr->isTypeDependent() ||
11342              NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11343              Context.BoolTy) &&
11344             "Parser should have made sure that the expression is boolean");
11345      if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11346        EPI.ExceptionSpecType = EST_BasicNoexcept;
11347        return;
11348      }
11349
11350      if (!NoexceptExpr->isValueDependent())
11351        NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
11352                         diag::err_noexcept_needs_constant_expression,
11353                         /*AllowFold*/ false).take();
11354      EPI.NoexceptExpr = NoexceptExpr;
11355    }
11356    return;
11357  }
11358}
11359
11360/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11361Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11362  // Implicitly declared functions (e.g. copy constructors) are
11363  // __host__ __device__
11364  if (D->isImplicit())
11365    return CFT_HostDevice;
11366
11367  if (D->hasAttr<CUDAGlobalAttr>())
11368    return CFT_Global;
11369
11370  if (D->hasAttr<CUDADeviceAttr>()) {
11371    if (D->hasAttr<CUDAHostAttr>())
11372      return CFT_HostDevice;
11373    else
11374      return CFT_Device;
11375  }
11376
11377  return CFT_Host;
11378}
11379
11380bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11381                           CUDAFunctionTarget CalleeTarget) {
11382  // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11383  // Callable from the device only."
11384  if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11385    return true;
11386
11387  // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11388  // Callable from the host only."
11389  // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11390  // Callable from the host only."
11391  if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11392      (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11393    return true;
11394
11395  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11396    return true;
11397
11398  return false;
11399}
11400