SemaDeclCXX.cpp revision b8abff66a8d30356c82314c4734c692cdd479e5e
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      }
521    }
522  }
523
524  // DR1344: If a default argument is added outside a class definition and that
525  // default argument makes the function a special member function, the program
526  // is ill-formed. This can only happen for constructors.
527  if (isa<CXXConstructorDecl>(New) &&
528      New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
529    CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
530                     OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
531    if (NewSM != OldSM) {
532      ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
533      assert(NewParam->hasDefaultArg());
534      Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
535        << NewParam->getDefaultArgRange() << NewSM;
536      Diag(Old->getLocation(), diag::note_previous_declaration);
537    }
538  }
539
540  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
541  // template has a constexpr specifier then all its declarations shall
542  // contain the constexpr specifier.
543  if (New->isConstexpr() != Old->isConstexpr()) {
544    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
545      << New << New->isConstexpr();
546    Diag(Old->getLocation(), diag::note_previous_declaration);
547    Invalid = true;
548  }
549
550  if (CheckEquivalentExceptionSpec(Old, New))
551    Invalid = true;
552
553  return Invalid;
554}
555
556/// \brief Merge the exception specifications of two variable declarations.
557///
558/// This is called when there's a redeclaration of a VarDecl. The function
559/// checks if the redeclaration might have an exception specification and
560/// validates compatibility and merges the specs if necessary.
561void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
562  // Shortcut if exceptions are disabled.
563  if (!getLangOpts().CXXExceptions)
564    return;
565
566  assert(Context.hasSameType(New->getType(), Old->getType()) &&
567         "Should only be called if types are otherwise the same.");
568
569  QualType NewType = New->getType();
570  QualType OldType = Old->getType();
571
572  // We're only interested in pointers and references to functions, as well
573  // as pointers to member functions.
574  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
575    NewType = R->getPointeeType();
576    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
577  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
578    NewType = P->getPointeeType();
579    OldType = OldType->getAs<PointerType>()->getPointeeType();
580  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
581    NewType = M->getPointeeType();
582    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
583  }
584
585  if (!NewType->isFunctionProtoType())
586    return;
587
588  // There's lots of special cases for functions. For function pointers, system
589  // libraries are hopefully not as broken so that we don't need these
590  // workarounds.
591  if (CheckEquivalentExceptionSpec(
592        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
593        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
594    New->setInvalidDecl();
595  }
596}
597
598/// CheckCXXDefaultArguments - Verify that the default arguments for a
599/// function declaration are well-formed according to C++
600/// [dcl.fct.default].
601void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
602  unsigned NumParams = FD->getNumParams();
603  unsigned p;
604
605  bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
606                  isa<CXXMethodDecl>(FD) &&
607                  cast<CXXMethodDecl>(FD)->getParent()->isLambda();
608
609  // Find first parameter with a default argument
610  for (p = 0; p < NumParams; ++p) {
611    ParmVarDecl *Param = FD->getParamDecl(p);
612    if (Param->hasDefaultArg()) {
613      // C++11 [expr.prim.lambda]p5:
614      //   [...] Default arguments (8.3.6) shall not be specified in the
615      //   parameter-declaration-clause of a lambda-declarator.
616      //
617      // FIXME: Core issue 974 strikes this sentence, we only provide an
618      // extension warning.
619      if (IsLambda)
620        Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
621          << Param->getDefaultArgRange();
622      break;
623    }
624  }
625
626  // C++ [dcl.fct.default]p4:
627  //   In a given function declaration, all parameters
628  //   subsequent to a parameter with a default argument shall
629  //   have default arguments supplied in this or previous
630  //   declarations. A default argument shall not be redefined
631  //   by a later declaration (not even to the same value).
632  unsigned LastMissingDefaultArg = 0;
633  for (; p < NumParams; ++p) {
634    ParmVarDecl *Param = FD->getParamDecl(p);
635    if (!Param->hasDefaultArg()) {
636      if (Param->isInvalidDecl())
637        /* We already complained about this parameter. */;
638      else if (Param->getIdentifier())
639        Diag(Param->getLocation(),
640             diag::err_param_default_argument_missing_name)
641          << Param->getIdentifier();
642      else
643        Diag(Param->getLocation(),
644             diag::err_param_default_argument_missing);
645
646      LastMissingDefaultArg = p;
647    }
648  }
649
650  if (LastMissingDefaultArg > 0) {
651    // Some default arguments were missing. Clear out all of the
652    // default arguments up to (and including) the last missing
653    // default argument, so that we leave the function parameters
654    // in a semantically valid state.
655    for (p = 0; p <= LastMissingDefaultArg; ++p) {
656      ParmVarDecl *Param = FD->getParamDecl(p);
657      if (Param->hasDefaultArg()) {
658        Param->setDefaultArg(0);
659      }
660    }
661  }
662}
663
664// CheckConstexprParameterTypes - Check whether a function's parameter types
665// are all literal types. If so, return true. If not, produce a suitable
666// diagnostic and return false.
667static bool CheckConstexprParameterTypes(Sema &SemaRef,
668                                         const FunctionDecl *FD) {
669  unsigned ArgIndex = 0;
670  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
671  for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
672       e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
673    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
674    SourceLocation ParamLoc = PD->getLocation();
675    if (!(*i)->isDependentType() &&
676        SemaRef.RequireLiteralType(ParamLoc, *i,
677                                   diag::err_constexpr_non_literal_param,
678                                   ArgIndex+1, PD->getSourceRange(),
679                                   isa<CXXConstructorDecl>(FD)))
680      return false;
681  }
682  return true;
683}
684
685/// \brief Get diagnostic %select index for tag kind for
686/// record diagnostic message.
687/// WARNING: Indexes apply to particular diagnostics only!
688///
689/// \returns diagnostic %select index.
690static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
691  switch (Tag) {
692  case TTK_Struct: return 0;
693  case TTK_Interface: return 1;
694  case TTK_Class:  return 2;
695  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
696  }
697}
698
699// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
700// the requirements of a constexpr function definition or a constexpr
701// constructor definition. If so, return true. If not, produce appropriate
702// diagnostics and return false.
703//
704// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
705bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
706  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
707  if (MD && MD->isInstance()) {
708    // C++11 [dcl.constexpr]p4:
709    //  The definition of a constexpr constructor shall satisfy the following
710    //  constraints:
711    //  - the class shall not have any virtual base classes;
712    const CXXRecordDecl *RD = MD->getParent();
713    if (RD->getNumVBases()) {
714      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
715        << isa<CXXConstructorDecl>(NewFD)
716        << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
717      for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
718             E = RD->vbases_end(); I != E; ++I)
719        Diag(I->getLocStart(),
720             diag::note_constexpr_virtual_base_here) << I->getSourceRange();
721      return false;
722    }
723  }
724
725  if (!isa<CXXConstructorDecl>(NewFD)) {
726    // C++11 [dcl.constexpr]p3:
727    //  The definition of a constexpr function shall satisfy the following
728    //  constraints:
729    // - it shall not be virtual;
730    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
731    if (Method && Method->isVirtual()) {
732      Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
733
734      // If it's not obvious why this function is virtual, find an overridden
735      // function which uses the 'virtual' keyword.
736      const CXXMethodDecl *WrittenVirtual = Method;
737      while (!WrittenVirtual->isVirtualAsWritten())
738        WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
739      if (WrittenVirtual != Method)
740        Diag(WrittenVirtual->getLocation(),
741             diag::note_overridden_virtual_function);
742      return false;
743    }
744
745    // - its return type shall be a literal type;
746    QualType RT = NewFD->getResultType();
747    if (!RT->isDependentType() &&
748        RequireLiteralType(NewFD->getLocation(), RT,
749                           diag::err_constexpr_non_literal_return))
750      return false;
751  }
752
753  // - each of its parameter types shall be a literal type;
754  if (!CheckConstexprParameterTypes(*this, NewFD))
755    return false;
756
757  return true;
758}
759
760/// Check the given declaration statement is legal within a constexpr function
761/// body. C++0x [dcl.constexpr]p3,p4.
762///
763/// \return true if the body is OK, false if we have diagnosed a problem.
764static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
765                                   DeclStmt *DS) {
766  // C++0x [dcl.constexpr]p3 and p4:
767  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
768  //  contain only
769  for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
770         DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
771    switch ((*DclIt)->getKind()) {
772    case Decl::StaticAssert:
773    case Decl::Using:
774    case Decl::UsingShadow:
775    case Decl::UsingDirective:
776    case Decl::UnresolvedUsingTypename:
777      //   - static_assert-declarations
778      //   - using-declarations,
779      //   - using-directives,
780      continue;
781
782    case Decl::Typedef:
783    case Decl::TypeAlias: {
784      //   - typedef declarations and alias-declarations that do not define
785      //     classes or enumerations,
786      TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
787      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
788        // Don't allow variably-modified types in constexpr functions.
789        TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
790        SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
791          << TL.getSourceRange() << TL.getType()
792          << isa<CXXConstructorDecl>(Dcl);
793        return false;
794      }
795      continue;
796    }
797
798    case Decl::Enum:
799    case Decl::CXXRecord:
800      // As an extension, we allow the declaration (but not the definition) of
801      // classes and enumerations in all declarations, not just in typedef and
802      // alias declarations.
803      if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
804        SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
805          << isa<CXXConstructorDecl>(Dcl);
806        return false;
807      }
808      continue;
809
810    case Decl::Var:
811      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
812        << isa<CXXConstructorDecl>(Dcl);
813      return false;
814
815    default:
816      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
817        << isa<CXXConstructorDecl>(Dcl);
818      return false;
819    }
820  }
821
822  return true;
823}
824
825/// Check that the given field is initialized within a constexpr constructor.
826///
827/// \param Dcl The constexpr constructor being checked.
828/// \param Field The field being checked. This may be a member of an anonymous
829///        struct or union nested within the class being checked.
830/// \param Inits All declarations, including anonymous struct/union members and
831///        indirect members, for which any initialization was provided.
832/// \param Diagnosed Set to true if an error is produced.
833static void CheckConstexprCtorInitializer(Sema &SemaRef,
834                                          const FunctionDecl *Dcl,
835                                          FieldDecl *Field,
836                                          llvm::SmallSet<Decl*, 16> &Inits,
837                                          bool &Diagnosed) {
838  if (Field->isUnnamedBitfield())
839    return;
840
841  if (Field->isAnonymousStructOrUnion() &&
842      Field->getType()->getAsCXXRecordDecl()->isEmpty())
843    return;
844
845  if (!Inits.count(Field)) {
846    if (!Diagnosed) {
847      SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
848      Diagnosed = true;
849    }
850    SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
851  } else if (Field->isAnonymousStructOrUnion()) {
852    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
853    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
854         I != E; ++I)
855      // If an anonymous union contains an anonymous struct of which any member
856      // is initialized, all members must be initialized.
857      if (!RD->isUnion() || Inits.count(*I))
858        CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
859  }
860}
861
862/// Check the body for the given constexpr function declaration only contains
863/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
864///
865/// \return true if the body is OK, false if we have diagnosed a problem.
866bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
867  if (isa<CXXTryStmt>(Body)) {
868    // C++11 [dcl.constexpr]p3:
869    //  The definition of a constexpr function shall satisfy the following
870    //  constraints: [...]
871    // - its function-body shall be = delete, = default, or a
872    //   compound-statement
873    //
874    // C++11 [dcl.constexpr]p4:
875    //  In the definition of a constexpr constructor, [...]
876    // - its function-body shall not be a function-try-block;
877    Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
878      << isa<CXXConstructorDecl>(Dcl);
879    return false;
880  }
881
882  // - its function-body shall be [...] a compound-statement that contains only
883  CompoundStmt *CompBody = cast<CompoundStmt>(Body);
884
885  llvm::SmallVector<SourceLocation, 4> ReturnStmts;
886  for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
887         BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
888    switch ((*BodyIt)->getStmtClass()) {
889    case Stmt::NullStmtClass:
890      //   - null statements,
891      continue;
892
893    case Stmt::DeclStmtClass:
894      //   - static_assert-declarations
895      //   - using-declarations,
896      //   - using-directives,
897      //   - typedef declarations and alias-declarations that do not define
898      //     classes or enumerations,
899      if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
900        return false;
901      continue;
902
903    case Stmt::ReturnStmtClass:
904      //   - and exactly one return statement;
905      if (isa<CXXConstructorDecl>(Dcl))
906        break;
907
908      ReturnStmts.push_back((*BodyIt)->getLocStart());
909      continue;
910
911    default:
912      break;
913    }
914
915    Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
916      << isa<CXXConstructorDecl>(Dcl);
917    return false;
918  }
919
920  if (const CXXConstructorDecl *Constructor
921        = dyn_cast<CXXConstructorDecl>(Dcl)) {
922    const CXXRecordDecl *RD = Constructor->getParent();
923    // DR1359:
924    // - every non-variant non-static data member and base class sub-object
925    //   shall be initialized;
926    // - if the class is a non-empty union, or for each non-empty anonymous
927    //   union member of a non-union class, exactly one non-static data member
928    //   shall be initialized;
929    if (RD->isUnion()) {
930      if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
931        Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
932        return false;
933      }
934    } else if (!Constructor->isDependentContext() &&
935               !Constructor->isDelegatingConstructor()) {
936      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
937
938      // Skip detailed checking if we have enough initializers, and we would
939      // allow at most one initializer per member.
940      bool AnyAnonStructUnionMembers = false;
941      unsigned Fields = 0;
942      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
943           E = RD->field_end(); I != E; ++I, ++Fields) {
944        if (I->isAnonymousStructOrUnion()) {
945          AnyAnonStructUnionMembers = true;
946          break;
947        }
948      }
949      if (AnyAnonStructUnionMembers ||
950          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
951        // Check initialization of non-static data members. Base classes are
952        // always initialized so do not need to be checked. Dependent bases
953        // might not have initializers in the member initializer list.
954        llvm::SmallSet<Decl*, 16> Inits;
955        for (CXXConstructorDecl::init_const_iterator
956               I = Constructor->init_begin(), E = Constructor->init_end();
957             I != E; ++I) {
958          if (FieldDecl *FD = (*I)->getMember())
959            Inits.insert(FD);
960          else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
961            Inits.insert(ID->chain_begin(), ID->chain_end());
962        }
963
964        bool Diagnosed = false;
965        for (CXXRecordDecl::field_iterator I = RD->field_begin(),
966             E = RD->field_end(); I != E; ++I)
967          CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
968        if (Diagnosed)
969          return false;
970      }
971    }
972  } else {
973    if (ReturnStmts.empty()) {
974      Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
975      return false;
976    }
977    if (ReturnStmts.size() > 1) {
978      Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
979      for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
980        Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
981      return false;
982    }
983  }
984
985  // C++11 [dcl.constexpr]p5:
986  //   if no function argument values exist such that the function invocation
987  //   substitution would produce a constant expression, the program is
988  //   ill-formed; no diagnostic required.
989  // C++11 [dcl.constexpr]p3:
990  //   - every constructor call and implicit conversion used in initializing the
991  //     return value shall be one of those allowed in a constant expression.
992  // C++11 [dcl.constexpr]p4:
993  //   - every constructor involved in initializing non-static data members and
994  //     base class sub-objects shall be a constexpr constructor.
995  llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
996  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
997    Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
998      << isa<CXXConstructorDecl>(Dcl);
999    for (size_t I = 0, N = Diags.size(); I != N; ++I)
1000      Diag(Diags[I].first, Diags[I].second);
1001    return false;
1002  }
1003
1004  return true;
1005}
1006
1007/// isCurrentClassName - Determine whether the identifier II is the
1008/// name of the class type currently being defined. In the case of
1009/// nested classes, this will only return true if II is the name of
1010/// the innermost class.
1011bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1012                              const CXXScopeSpec *SS) {
1013  assert(getLangOpts().CPlusPlus && "No class names in C!");
1014
1015  CXXRecordDecl *CurDecl;
1016  if (SS && SS->isSet() && !SS->isInvalid()) {
1017    DeclContext *DC = computeDeclContext(*SS, true);
1018    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1019  } else
1020    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1021
1022  if (CurDecl && CurDecl->getIdentifier())
1023    return &II == CurDecl->getIdentifier();
1024  else
1025    return false;
1026}
1027
1028/// \brief Determine whether the given class is a base class of the given
1029/// class, including looking at dependent bases.
1030static bool findCircularInheritance(const CXXRecordDecl *Class,
1031                                    const CXXRecordDecl *Current) {
1032  SmallVector<const CXXRecordDecl*, 8> Queue;
1033
1034  Class = Class->getCanonicalDecl();
1035  while (true) {
1036    for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1037                                                  E = Current->bases_end();
1038         I != E; ++I) {
1039      CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1040      if (!Base)
1041        continue;
1042
1043      Base = Base->getDefinition();
1044      if (!Base)
1045        continue;
1046
1047      if (Base->getCanonicalDecl() == Class)
1048        return true;
1049
1050      Queue.push_back(Base);
1051    }
1052
1053    if (Queue.empty())
1054      return false;
1055
1056    Current = Queue.back();
1057    Queue.pop_back();
1058  }
1059
1060  return false;
1061}
1062
1063/// \brief Check the validity of a C++ base class specifier.
1064///
1065/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1066/// and returns NULL otherwise.
1067CXXBaseSpecifier *
1068Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1069                         SourceRange SpecifierRange,
1070                         bool Virtual, AccessSpecifier Access,
1071                         TypeSourceInfo *TInfo,
1072                         SourceLocation EllipsisLoc) {
1073  QualType BaseType = TInfo->getType();
1074
1075  // C++ [class.union]p1:
1076  //   A union shall not have base classes.
1077  if (Class->isUnion()) {
1078    Diag(Class->getLocation(), diag::err_base_clause_on_union)
1079      << SpecifierRange;
1080    return 0;
1081  }
1082
1083  if (EllipsisLoc.isValid() &&
1084      !TInfo->getType()->containsUnexpandedParameterPack()) {
1085    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1086      << TInfo->getTypeLoc().getSourceRange();
1087    EllipsisLoc = SourceLocation();
1088  }
1089
1090  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1091
1092  if (BaseType->isDependentType()) {
1093    // Make sure that we don't have circular inheritance among our dependent
1094    // bases. For non-dependent bases, the check for completeness below handles
1095    // this.
1096    if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1097      if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1098          ((BaseDecl = BaseDecl->getDefinition()) &&
1099           findCircularInheritance(Class, BaseDecl))) {
1100        Diag(BaseLoc, diag::err_circular_inheritance)
1101          << BaseType << Context.getTypeDeclType(Class);
1102
1103        if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1104          Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1105            << BaseType;
1106
1107        return 0;
1108      }
1109    }
1110
1111    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1112                                          Class->getTagKind() == TTK_Class,
1113                                          Access, TInfo, EllipsisLoc);
1114  }
1115
1116  // Base specifiers must be record types.
1117  if (!BaseType->isRecordType()) {
1118    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1119    return 0;
1120  }
1121
1122  // C++ [class.union]p1:
1123  //   A union shall not be used as a base class.
1124  if (BaseType->isUnionType()) {
1125    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1126    return 0;
1127  }
1128
1129  // C++ [class.derived]p2:
1130  //   The class-name in a base-specifier shall not be an incompletely
1131  //   defined class.
1132  if (RequireCompleteType(BaseLoc, BaseType,
1133                          diag::err_incomplete_base_class, SpecifierRange)) {
1134    Class->setInvalidDecl();
1135    return 0;
1136  }
1137
1138  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1139  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1140  assert(BaseDecl && "Record type has no declaration");
1141  BaseDecl = BaseDecl->getDefinition();
1142  assert(BaseDecl && "Base type is not incomplete, but has no definition");
1143  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1144  assert(CXXBaseDecl && "Base type is not a C++ type");
1145
1146  // C++ [class]p3:
1147  //   If a class is marked final and it appears as a base-type-specifier in
1148  //   base-clause, the program is ill-formed.
1149  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1150    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1151      << CXXBaseDecl->getDeclName();
1152    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1153      << CXXBaseDecl->getDeclName();
1154    return 0;
1155  }
1156
1157  if (BaseDecl->isInvalidDecl())
1158    Class->setInvalidDecl();
1159
1160  // Create the base specifier.
1161  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1162                                        Class->getTagKind() == TTK_Class,
1163                                        Access, TInfo, EllipsisLoc);
1164}
1165
1166/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1167/// one entry in the base class list of a class specifier, for
1168/// example:
1169///    class foo : public bar, virtual private baz {
1170/// 'public bar' and 'virtual private baz' are each base-specifiers.
1171BaseResult
1172Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1173                         bool Virtual, AccessSpecifier Access,
1174                         ParsedType basetype, SourceLocation BaseLoc,
1175                         SourceLocation EllipsisLoc) {
1176  if (!classdecl)
1177    return true;
1178
1179  AdjustDeclIfTemplate(classdecl);
1180  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1181  if (!Class)
1182    return true;
1183
1184  TypeSourceInfo *TInfo = 0;
1185  GetTypeFromParser(basetype, &TInfo);
1186
1187  if (EllipsisLoc.isInvalid() &&
1188      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1189                                      UPPC_BaseType))
1190    return true;
1191
1192  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1193                                                      Virtual, Access, TInfo,
1194                                                      EllipsisLoc))
1195    return BaseSpec;
1196  else
1197    Class->setInvalidDecl();
1198
1199  return true;
1200}
1201
1202/// \brief Performs the actual work of attaching the given base class
1203/// specifiers to a C++ class.
1204bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1205                                unsigned NumBases) {
1206 if (NumBases == 0)
1207    return false;
1208
1209  // Used to keep track of which base types we have already seen, so
1210  // that we can properly diagnose redundant direct base types. Note
1211  // that the key is always the unqualified canonical type of the base
1212  // class.
1213  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1214
1215  // Copy non-redundant base specifiers into permanent storage.
1216  unsigned NumGoodBases = 0;
1217  bool Invalid = false;
1218  for (unsigned idx = 0; idx < NumBases; ++idx) {
1219    QualType NewBaseType
1220      = Context.getCanonicalType(Bases[idx]->getType());
1221    NewBaseType = NewBaseType.getLocalUnqualifiedType();
1222
1223    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1224    if (KnownBase) {
1225      // C++ [class.mi]p3:
1226      //   A class shall not be specified as a direct base class of a
1227      //   derived class more than once.
1228      Diag(Bases[idx]->getLocStart(),
1229           diag::err_duplicate_base_class)
1230        << KnownBase->getType()
1231        << Bases[idx]->getSourceRange();
1232
1233      // Delete the duplicate base class specifier; we're going to
1234      // overwrite its pointer later.
1235      Context.Deallocate(Bases[idx]);
1236
1237      Invalid = true;
1238    } else {
1239      // Okay, add this new base class.
1240      KnownBase = Bases[idx];
1241      Bases[NumGoodBases++] = Bases[idx];
1242      if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1243        const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1244        if (Class->isInterface() &&
1245              (!RD->isInterface() ||
1246               KnownBase->getAccessSpecifier() != AS_public)) {
1247          // The Microsoft extension __interface does not permit bases that
1248          // are not themselves public interfaces.
1249          Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1250            << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1251            << RD->getSourceRange();
1252          Invalid = true;
1253        }
1254        if (RD->hasAttr<WeakAttr>())
1255          Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1256      }
1257    }
1258  }
1259
1260  // Attach the remaining base class specifiers to the derived class.
1261  Class->setBases(Bases, NumGoodBases);
1262
1263  // Delete the remaining (good) base class specifiers, since their
1264  // data has been copied into the CXXRecordDecl.
1265  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1266    Context.Deallocate(Bases[idx]);
1267
1268  return Invalid;
1269}
1270
1271/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1272/// class, after checking whether there are any duplicate base
1273/// classes.
1274void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1275                               unsigned NumBases) {
1276  if (!ClassDecl || !Bases || !NumBases)
1277    return;
1278
1279  AdjustDeclIfTemplate(ClassDecl);
1280  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1281                       (CXXBaseSpecifier**)(Bases), NumBases);
1282}
1283
1284static CXXRecordDecl *GetClassForType(QualType T) {
1285  if (const RecordType *RT = T->getAs<RecordType>())
1286    return cast<CXXRecordDecl>(RT->getDecl());
1287  else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1288    return ICT->getDecl();
1289  else
1290    return 0;
1291}
1292
1293/// \brief Determine whether the type \p Derived is a C++ class that is
1294/// derived from the type \p Base.
1295bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1296  if (!getLangOpts().CPlusPlus)
1297    return false;
1298
1299  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1300  if (!DerivedRD)
1301    return false;
1302
1303  CXXRecordDecl *BaseRD = GetClassForType(Base);
1304  if (!BaseRD)
1305    return false;
1306
1307  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1308  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1309}
1310
1311/// \brief Determine whether the type \p Derived is a C++ class that is
1312/// derived from the type \p Base.
1313bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1314  if (!getLangOpts().CPlusPlus)
1315    return false;
1316
1317  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1318  if (!DerivedRD)
1319    return false;
1320
1321  CXXRecordDecl *BaseRD = GetClassForType(Base);
1322  if (!BaseRD)
1323    return false;
1324
1325  return DerivedRD->isDerivedFrom(BaseRD, Paths);
1326}
1327
1328void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1329                              CXXCastPath &BasePathArray) {
1330  assert(BasePathArray.empty() && "Base path array must be empty!");
1331  assert(Paths.isRecordingPaths() && "Must record paths!");
1332
1333  const CXXBasePath &Path = Paths.front();
1334
1335  // We first go backward and check if we have a virtual base.
1336  // FIXME: It would be better if CXXBasePath had the base specifier for
1337  // the nearest virtual base.
1338  unsigned Start = 0;
1339  for (unsigned I = Path.size(); I != 0; --I) {
1340    if (Path[I - 1].Base->isVirtual()) {
1341      Start = I - 1;
1342      break;
1343    }
1344  }
1345
1346  // Now add all bases.
1347  for (unsigned I = Start, E = Path.size(); I != E; ++I)
1348    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1349}
1350
1351/// \brief Determine whether the given base path includes a virtual
1352/// base class.
1353bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1354  for (CXXCastPath::const_iterator B = BasePath.begin(),
1355                                BEnd = BasePath.end();
1356       B != BEnd; ++B)
1357    if ((*B)->isVirtual())
1358      return true;
1359
1360  return false;
1361}
1362
1363/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1364/// conversion (where Derived and Base are class types) is
1365/// well-formed, meaning that the conversion is unambiguous (and
1366/// that all of the base classes are accessible). Returns true
1367/// and emits a diagnostic if the code is ill-formed, returns false
1368/// otherwise. Loc is the location where this routine should point to
1369/// if there is an error, and Range is the source range to highlight
1370/// if there is an error.
1371bool
1372Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1373                                   unsigned InaccessibleBaseID,
1374                                   unsigned AmbigiousBaseConvID,
1375                                   SourceLocation Loc, SourceRange Range,
1376                                   DeclarationName Name,
1377                                   CXXCastPath *BasePath) {
1378  // First, determine whether the path from Derived to Base is
1379  // ambiguous. This is slightly more expensive than checking whether
1380  // the Derived to Base conversion exists, because here we need to
1381  // explore multiple paths to determine if there is an ambiguity.
1382  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1383                     /*DetectVirtual=*/false);
1384  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1385  assert(DerivationOkay &&
1386         "Can only be used with a derived-to-base conversion");
1387  (void)DerivationOkay;
1388
1389  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1390    if (InaccessibleBaseID) {
1391      // Check that the base class can be accessed.
1392      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1393                                   InaccessibleBaseID)) {
1394        case AR_inaccessible:
1395          return true;
1396        case AR_accessible:
1397        case AR_dependent:
1398        case AR_delayed:
1399          break;
1400      }
1401    }
1402
1403    // Build a base path if necessary.
1404    if (BasePath)
1405      BuildBasePathArray(Paths, *BasePath);
1406    return false;
1407  }
1408
1409  // We know that the derived-to-base conversion is ambiguous, and
1410  // we're going to produce a diagnostic. Perform the derived-to-base
1411  // search just one more time to compute all of the possible paths so
1412  // that we can print them out. This is more expensive than any of
1413  // the previous derived-to-base checks we've done, but at this point
1414  // performance isn't as much of an issue.
1415  Paths.clear();
1416  Paths.setRecordingPaths(true);
1417  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1418  assert(StillOkay && "Can only be used with a derived-to-base conversion");
1419  (void)StillOkay;
1420
1421  // Build up a textual representation of the ambiguous paths, e.g.,
1422  // D -> B -> A, that will be used to illustrate the ambiguous
1423  // conversions in the diagnostic. We only print one of the paths
1424  // to each base class subobject.
1425  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1426
1427  Diag(Loc, AmbigiousBaseConvID)
1428  << Derived << Base << PathDisplayStr << Range << Name;
1429  return true;
1430}
1431
1432bool
1433Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1434                                   SourceLocation Loc, SourceRange Range,
1435                                   CXXCastPath *BasePath,
1436                                   bool IgnoreAccess) {
1437  return CheckDerivedToBaseConversion(Derived, Base,
1438                                      IgnoreAccess ? 0
1439                                       : diag::err_upcast_to_inaccessible_base,
1440                                      diag::err_ambiguous_derived_to_base_conv,
1441                                      Loc, Range, DeclarationName(),
1442                                      BasePath);
1443}
1444
1445
1446/// @brief Builds a string representing ambiguous paths from a
1447/// specific derived class to different subobjects of the same base
1448/// class.
1449///
1450/// This function builds a string that can be used in error messages
1451/// to show the different paths that one can take through the
1452/// inheritance hierarchy to go from the derived class to different
1453/// subobjects of a base class. The result looks something like this:
1454/// @code
1455/// struct D -> struct B -> struct A
1456/// struct D -> struct C -> struct A
1457/// @endcode
1458std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1459  std::string PathDisplayStr;
1460  std::set<unsigned> DisplayedPaths;
1461  for (CXXBasePaths::paths_iterator Path = Paths.begin();
1462       Path != Paths.end(); ++Path) {
1463    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1464      // We haven't displayed a path to this particular base
1465      // class subobject yet.
1466      PathDisplayStr += "\n    ";
1467      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1468      for (CXXBasePath::const_iterator Element = Path->begin();
1469           Element != Path->end(); ++Element)
1470        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1471    }
1472  }
1473
1474  return PathDisplayStr;
1475}
1476
1477//===----------------------------------------------------------------------===//
1478// C++ class member Handling
1479//===----------------------------------------------------------------------===//
1480
1481/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1482bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1483                                SourceLocation ASLoc,
1484                                SourceLocation ColonLoc,
1485                                AttributeList *Attrs) {
1486  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1487  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1488                                                  ASLoc, ColonLoc);
1489  CurContext->addHiddenDecl(ASDecl);
1490  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1491}
1492
1493/// CheckOverrideControl - Check C++11 override control semantics.
1494void Sema::CheckOverrideControl(Decl *D) {
1495  if (D->isInvalidDecl())
1496    return;
1497
1498  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1499
1500  // Do we know which functions this declaration might be overriding?
1501  bool OverridesAreKnown = !MD ||
1502      (!MD->getParent()->hasAnyDependentBases() &&
1503       !MD->getType()->isDependentType());
1504
1505  if (!MD || !MD->isVirtual()) {
1506    if (OverridesAreKnown) {
1507      if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1508        Diag(OA->getLocation(),
1509             diag::override_keyword_only_allowed_on_virtual_member_functions)
1510          << "override" << FixItHint::CreateRemoval(OA->getLocation());
1511        D->dropAttr<OverrideAttr>();
1512      }
1513      if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1514        Diag(FA->getLocation(),
1515             diag::override_keyword_only_allowed_on_virtual_member_functions)
1516          << "final" << FixItHint::CreateRemoval(FA->getLocation());
1517        D->dropAttr<FinalAttr>();
1518      }
1519    }
1520    return;
1521  }
1522
1523  if (!OverridesAreKnown)
1524    return;
1525
1526  // C++11 [class.virtual]p5:
1527  //   If a virtual function is marked with the virt-specifier override and
1528  //   does not override a member function of a base class, the program is
1529  //   ill-formed.
1530  bool HasOverriddenMethods =
1531    MD->begin_overridden_methods() != MD->end_overridden_methods();
1532  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1533    Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1534      << MD->getDeclName();
1535}
1536
1537/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1538/// function overrides a virtual member function marked 'final', according to
1539/// C++11 [class.virtual]p4.
1540bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1541                                                  const CXXMethodDecl *Old) {
1542  if (!Old->hasAttr<FinalAttr>())
1543    return false;
1544
1545  Diag(New->getLocation(), diag::err_final_function_overridden)
1546    << New->getDeclName();
1547  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1548  return true;
1549}
1550
1551static bool InitializationHasSideEffects(const FieldDecl &FD) {
1552  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1553  // FIXME: Destruction of ObjC lifetime types has side-effects.
1554  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1555    return !RD->isCompleteDefinition() ||
1556           !RD->hasTrivialDefaultConstructor() ||
1557           !RD->hasTrivialDestructor();
1558  return false;
1559}
1560
1561/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1562/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1563/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1564/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1565/// present (but parsing it has been deferred).
1566Decl *
1567Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1568                               MultiTemplateParamsArg TemplateParameterLists,
1569                               Expr *BW, const VirtSpecifiers &VS,
1570                               InClassInitStyle InitStyle) {
1571  const DeclSpec &DS = D.getDeclSpec();
1572  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1573  DeclarationName Name = NameInfo.getName();
1574  SourceLocation Loc = NameInfo.getLoc();
1575
1576  // For anonymous bitfields, the location should point to the type.
1577  if (Loc.isInvalid())
1578    Loc = D.getLocStart();
1579
1580  Expr *BitWidth = static_cast<Expr*>(BW);
1581
1582  assert(isa<CXXRecordDecl>(CurContext));
1583  assert(!DS.isFriendSpecified());
1584
1585  bool isFunc = D.isDeclarationOfFunction();
1586
1587  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1588    // The Microsoft extension __interface only permits public member functions
1589    // and prohibits constructors, destructors, operators, non-public member
1590    // functions, static methods and data members.
1591    unsigned InvalidDecl;
1592    bool ShowDeclName = true;
1593    if (!isFunc)
1594      InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1595    else if (AS != AS_public)
1596      InvalidDecl = 2;
1597    else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1598      InvalidDecl = 3;
1599    else switch (Name.getNameKind()) {
1600      case DeclarationName::CXXConstructorName:
1601        InvalidDecl = 4;
1602        ShowDeclName = false;
1603        break;
1604
1605      case DeclarationName::CXXDestructorName:
1606        InvalidDecl = 5;
1607        ShowDeclName = false;
1608        break;
1609
1610      case DeclarationName::CXXOperatorName:
1611      case DeclarationName::CXXConversionFunctionName:
1612        InvalidDecl = 6;
1613        break;
1614
1615      default:
1616        InvalidDecl = 0;
1617        break;
1618    }
1619
1620    if (InvalidDecl) {
1621      if (ShowDeclName)
1622        Diag(Loc, diag::err_invalid_member_in_interface)
1623          << (InvalidDecl-1) << Name;
1624      else
1625        Diag(Loc, diag::err_invalid_member_in_interface)
1626          << (InvalidDecl-1) << "";
1627      return 0;
1628    }
1629  }
1630
1631  // C++ 9.2p6: A member shall not be declared to have automatic storage
1632  // duration (auto, register) or with the extern storage-class-specifier.
1633  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1634  // data members and cannot be applied to names declared const or static,
1635  // and cannot be applied to reference members.
1636  switch (DS.getStorageClassSpec()) {
1637    case DeclSpec::SCS_unspecified:
1638    case DeclSpec::SCS_typedef:
1639    case DeclSpec::SCS_static:
1640      // FALL THROUGH.
1641      break;
1642    case DeclSpec::SCS_mutable:
1643      if (isFunc) {
1644        if (DS.getStorageClassSpecLoc().isValid())
1645          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1646        else
1647          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1648
1649        // FIXME: It would be nicer if the keyword was ignored only for this
1650        // declarator. Otherwise we could get follow-up errors.
1651        D.getMutableDeclSpec().ClearStorageClassSpecs();
1652      }
1653      break;
1654    default:
1655      if (DS.getStorageClassSpecLoc().isValid())
1656        Diag(DS.getStorageClassSpecLoc(),
1657             diag::err_storageclass_invalid_for_member);
1658      else
1659        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1660      D.getMutableDeclSpec().ClearStorageClassSpecs();
1661  }
1662
1663  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1664                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1665                      !isFunc);
1666
1667  Decl *Member;
1668  if (isInstField) {
1669    CXXScopeSpec &SS = D.getCXXScopeSpec();
1670
1671    // Data members must have identifiers for names.
1672    if (!Name.isIdentifier()) {
1673      Diag(Loc, diag::err_bad_variable_name)
1674        << Name;
1675      return 0;
1676    }
1677
1678    IdentifierInfo *II = Name.getAsIdentifierInfo();
1679
1680    // Member field could not be with "template" keyword.
1681    // So TemplateParameterLists should be empty in this case.
1682    if (TemplateParameterLists.size()) {
1683      TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1684      if (TemplateParams->size()) {
1685        // There is no such thing as a member field template.
1686        Diag(D.getIdentifierLoc(), diag::err_template_member)
1687            << II
1688            << SourceRange(TemplateParams->getTemplateLoc(),
1689                TemplateParams->getRAngleLoc());
1690      } else {
1691        // There is an extraneous 'template<>' for this member.
1692        Diag(TemplateParams->getTemplateLoc(),
1693            diag::err_template_member_noparams)
1694            << II
1695            << SourceRange(TemplateParams->getTemplateLoc(),
1696                TemplateParams->getRAngleLoc());
1697      }
1698      return 0;
1699    }
1700
1701    if (SS.isSet() && !SS.isInvalid()) {
1702      // The user provided a superfluous scope specifier inside a class
1703      // definition:
1704      //
1705      // class X {
1706      //   int X::member;
1707      // };
1708      if (DeclContext *DC = computeDeclContext(SS, false))
1709        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1710      else
1711        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1712          << Name << SS.getRange();
1713
1714      SS.clear();
1715    }
1716
1717    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1718                         InitStyle, AS);
1719    assert(Member && "HandleField never returns null");
1720  } else {
1721    assert(InitStyle == ICIS_NoInit);
1722
1723    Member = HandleDeclarator(S, D, TemplateParameterLists);
1724    if (!Member) {
1725      return 0;
1726    }
1727
1728    // Non-instance-fields can't have a bitfield.
1729    if (BitWidth) {
1730      if (Member->isInvalidDecl()) {
1731        // don't emit another diagnostic.
1732      } else if (isa<VarDecl>(Member)) {
1733        // C++ 9.6p3: A bit-field shall not be a static member.
1734        // "static member 'A' cannot be a bit-field"
1735        Diag(Loc, diag::err_static_not_bitfield)
1736          << Name << BitWidth->getSourceRange();
1737      } else if (isa<TypedefDecl>(Member)) {
1738        // "typedef member 'x' cannot be a bit-field"
1739        Diag(Loc, diag::err_typedef_not_bitfield)
1740          << Name << BitWidth->getSourceRange();
1741      } else {
1742        // A function typedef ("typedef int f(); f a;").
1743        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1744        Diag(Loc, diag::err_not_integral_type_bitfield)
1745          << Name << cast<ValueDecl>(Member)->getType()
1746          << BitWidth->getSourceRange();
1747      }
1748
1749      BitWidth = 0;
1750      Member->setInvalidDecl();
1751    }
1752
1753    Member->setAccess(AS);
1754
1755    // If we have declared a member function template, set the access of the
1756    // templated declaration as well.
1757    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1758      FunTmpl->getTemplatedDecl()->setAccess(AS);
1759  }
1760
1761  if (VS.isOverrideSpecified())
1762    Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1763  if (VS.isFinalSpecified())
1764    Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1765
1766  if (VS.getLastLocation().isValid()) {
1767    // Update the end location of a method that has a virt-specifiers.
1768    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1769      MD->setRangeEnd(VS.getLastLocation());
1770  }
1771
1772  CheckOverrideControl(Member);
1773
1774  assert((Name || isInstField) && "No identifier for non-field ?");
1775
1776  if (isInstField) {
1777    FieldDecl *FD = cast<FieldDecl>(Member);
1778    FieldCollector->Add(FD);
1779
1780    if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1781                                 FD->getLocation())
1782          != DiagnosticsEngine::Ignored) {
1783      // Remember all explicit private FieldDecls that have a name, no side
1784      // effects and are not part of a dependent type declaration.
1785      if (!FD->isImplicit() && FD->getDeclName() &&
1786          FD->getAccess() == AS_private &&
1787          !FD->hasAttr<UnusedAttr>() &&
1788          !FD->getParent()->isDependentContext() &&
1789          !InitializationHasSideEffects(*FD))
1790        UnusedPrivateFields.insert(FD);
1791    }
1792  }
1793
1794  return Member;
1795}
1796
1797namespace {
1798  class UninitializedFieldVisitor
1799      : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1800    Sema &S;
1801    ValueDecl *VD;
1802  public:
1803    typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1804    UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
1805                                                        S(S) {
1806      if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1807        this->VD = IFD->getAnonField();
1808      else
1809        this->VD = VD;
1810    }
1811
1812    void HandleExpr(Expr *E) {
1813      if (!E) return;
1814
1815      // Expressions like x(x) sometimes lack the surrounding expressions
1816      // but need to be checked anyways.
1817      HandleValue(E);
1818      Visit(E);
1819    }
1820
1821    void HandleValue(Expr *E) {
1822      E = E->IgnoreParens();
1823
1824      if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1825        if (isa<EnumConstantDecl>(ME->getMemberDecl()))
1826          return;
1827
1828        // FieldME is the inner-most MemberExpr that is not an anonymous struct
1829        // or union.
1830        MemberExpr *FieldME = ME;
1831
1832        Expr *Base = E;
1833        while (isa<MemberExpr>(Base)) {
1834          ME = cast<MemberExpr>(Base);
1835
1836          if (isa<VarDecl>(ME->getMemberDecl()))
1837            return;
1838
1839          if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1840            if (!FD->isAnonymousStructOrUnion())
1841              FieldME = ME;
1842
1843          Base = ME->getBase();
1844        }
1845
1846        if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
1847          unsigned diag = VD->getType()->isReferenceType()
1848              ? diag::warn_reference_field_is_uninit
1849              : diag::warn_field_is_uninit;
1850          S.Diag(FieldME->getExprLoc(), diag) << VD;
1851        }
1852        return;
1853      }
1854
1855      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1856        HandleValue(CO->getTrueExpr());
1857        HandleValue(CO->getFalseExpr());
1858        return;
1859      }
1860
1861      if (BinaryConditionalOperator *BCO =
1862              dyn_cast<BinaryConditionalOperator>(E)) {
1863        HandleValue(BCO->getCommon());
1864        HandleValue(BCO->getFalseExpr());
1865        return;
1866      }
1867
1868      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1869        switch (BO->getOpcode()) {
1870        default:
1871          return;
1872        case(BO_PtrMemD):
1873        case(BO_PtrMemI):
1874          HandleValue(BO->getLHS());
1875          return;
1876        case(BO_Comma):
1877          HandleValue(BO->getRHS());
1878          return;
1879        }
1880      }
1881    }
1882
1883    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1884      if (E->getCastKind() == CK_LValueToRValue)
1885        HandleValue(E->getSubExpr());
1886
1887      Inherited::VisitImplicitCastExpr(E);
1888    }
1889
1890    void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1891      Expr *Callee = E->getCallee();
1892      if (isa<MemberExpr>(Callee))
1893        HandleValue(Callee);
1894
1895      Inherited::VisitCXXMemberCallExpr(E);
1896    }
1897  };
1898  static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1899                                                       ValueDecl *VD) {
1900    UninitializedFieldVisitor(S, VD).HandleExpr(E);
1901  }
1902} // namespace
1903
1904/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1905/// in-class initializer for a non-static C++ class member, and after
1906/// instantiating an in-class initializer in a class template. Such actions
1907/// are deferred until the class is complete.
1908void
1909Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
1910                                       Expr *InitExpr) {
1911  FieldDecl *FD = cast<FieldDecl>(D);
1912  assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1913         "must set init style when field is created");
1914
1915  if (!InitExpr) {
1916    FD->setInvalidDecl();
1917    FD->removeInClassInitializer();
1918    return;
1919  }
1920
1921  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1922    FD->setInvalidDecl();
1923    FD->removeInClassInitializer();
1924    return;
1925  }
1926
1927  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1928      != DiagnosticsEngine::Ignored) {
1929    CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1930  }
1931
1932  ExprResult Init = InitExpr;
1933  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent() &&
1934      !FD->getDeclContext()->isDependentContext()) {
1935    // Note: We don't type-check when we're in a dependent context, because
1936    // the initialization-substitution code does not properly handle direct
1937    // list initialization. We have the same hackaround for ctor-initializers.
1938    if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
1939      Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
1940        << /*at end of ctor*/1 << InitExpr->getSourceRange();
1941    }
1942    Expr **Inits = &InitExpr;
1943    unsigned NumInits = 1;
1944    InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1945    InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
1946        ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1947        : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
1948    InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1949    Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
1950    if (Init.isInvalid()) {
1951      FD->setInvalidDecl();
1952      return;
1953    }
1954
1955    CheckImplicitConversions(Init.get(), InitLoc);
1956  }
1957
1958  // C++0x [class.base.init]p7:
1959  //   The initialization of each base and member constitutes a
1960  //   full-expression.
1961  Init = MaybeCreateExprWithCleanups(Init);
1962  if (Init.isInvalid()) {
1963    FD->setInvalidDecl();
1964    return;
1965  }
1966
1967  InitExpr = Init.release();
1968
1969  FD->setInClassInitializer(InitExpr);
1970}
1971
1972/// \brief Find the direct and/or virtual base specifiers that
1973/// correspond to the given base type, for use in base initialization
1974/// within a constructor.
1975static bool FindBaseInitializer(Sema &SemaRef,
1976                                CXXRecordDecl *ClassDecl,
1977                                QualType BaseType,
1978                                const CXXBaseSpecifier *&DirectBaseSpec,
1979                                const CXXBaseSpecifier *&VirtualBaseSpec) {
1980  // First, check for a direct base class.
1981  DirectBaseSpec = 0;
1982  for (CXXRecordDecl::base_class_const_iterator Base
1983         = ClassDecl->bases_begin();
1984       Base != ClassDecl->bases_end(); ++Base) {
1985    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1986      // We found a direct base of this type. That's what we're
1987      // initializing.
1988      DirectBaseSpec = &*Base;
1989      break;
1990    }
1991  }
1992
1993  // Check for a virtual base class.
1994  // FIXME: We might be able to short-circuit this if we know in advance that
1995  // there are no virtual bases.
1996  VirtualBaseSpec = 0;
1997  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1998    // We haven't found a base yet; search the class hierarchy for a
1999    // virtual base class.
2000    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2001                       /*DetectVirtual=*/false);
2002    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2003                              BaseType, Paths)) {
2004      for (CXXBasePaths::paths_iterator Path = Paths.begin();
2005           Path != Paths.end(); ++Path) {
2006        if (Path->back().Base->isVirtual()) {
2007          VirtualBaseSpec = Path->back().Base;
2008          break;
2009        }
2010      }
2011    }
2012  }
2013
2014  return DirectBaseSpec || VirtualBaseSpec;
2015}
2016
2017/// \brief Handle a C++ member initializer using braced-init-list syntax.
2018MemInitResult
2019Sema::ActOnMemInitializer(Decl *ConstructorD,
2020                          Scope *S,
2021                          CXXScopeSpec &SS,
2022                          IdentifierInfo *MemberOrBase,
2023                          ParsedType TemplateTypeTy,
2024                          const DeclSpec &DS,
2025                          SourceLocation IdLoc,
2026                          Expr *InitList,
2027                          SourceLocation EllipsisLoc) {
2028  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2029                             DS, IdLoc, InitList,
2030                             EllipsisLoc);
2031}
2032
2033/// \brief Handle a C++ member initializer using parentheses syntax.
2034MemInitResult
2035Sema::ActOnMemInitializer(Decl *ConstructorD,
2036                          Scope *S,
2037                          CXXScopeSpec &SS,
2038                          IdentifierInfo *MemberOrBase,
2039                          ParsedType TemplateTypeTy,
2040                          const DeclSpec &DS,
2041                          SourceLocation IdLoc,
2042                          SourceLocation LParenLoc,
2043                          Expr **Args, unsigned NumArgs,
2044                          SourceLocation RParenLoc,
2045                          SourceLocation EllipsisLoc) {
2046  Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2047                                           llvm::makeArrayRef(Args, NumArgs),
2048                                           RParenLoc);
2049  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2050                             DS, IdLoc, List, EllipsisLoc);
2051}
2052
2053namespace {
2054
2055// Callback to only accept typo corrections that can be a valid C++ member
2056// intializer: either a non-static field member or a base class.
2057class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2058 public:
2059  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2060      : ClassDecl(ClassDecl) {}
2061
2062  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2063    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2064      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2065        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2066      else
2067        return isa<TypeDecl>(ND);
2068    }
2069    return false;
2070  }
2071
2072 private:
2073  CXXRecordDecl *ClassDecl;
2074};
2075
2076}
2077
2078/// \brief Handle a C++ member initializer.
2079MemInitResult
2080Sema::BuildMemInitializer(Decl *ConstructorD,
2081                          Scope *S,
2082                          CXXScopeSpec &SS,
2083                          IdentifierInfo *MemberOrBase,
2084                          ParsedType TemplateTypeTy,
2085                          const DeclSpec &DS,
2086                          SourceLocation IdLoc,
2087                          Expr *Init,
2088                          SourceLocation EllipsisLoc) {
2089  if (!ConstructorD)
2090    return true;
2091
2092  AdjustDeclIfTemplate(ConstructorD);
2093
2094  CXXConstructorDecl *Constructor
2095    = dyn_cast<CXXConstructorDecl>(ConstructorD);
2096  if (!Constructor) {
2097    // The user wrote a constructor initializer on a function that is
2098    // not a C++ constructor. Ignore the error for now, because we may
2099    // have more member initializers coming; we'll diagnose it just
2100    // once in ActOnMemInitializers.
2101    return true;
2102  }
2103
2104  CXXRecordDecl *ClassDecl = Constructor->getParent();
2105
2106  // C++ [class.base.init]p2:
2107  //   Names in a mem-initializer-id are looked up in the scope of the
2108  //   constructor's class and, if not found in that scope, are looked
2109  //   up in the scope containing the constructor's definition.
2110  //   [Note: if the constructor's class contains a member with the
2111  //   same name as a direct or virtual base class of the class, a
2112  //   mem-initializer-id naming the member or base class and composed
2113  //   of a single identifier refers to the class member. A
2114  //   mem-initializer-id for the hidden base class may be specified
2115  //   using a qualified name. ]
2116  if (!SS.getScopeRep() && !TemplateTypeTy) {
2117    // Look for a member, first.
2118    DeclContext::lookup_result Result
2119      = ClassDecl->lookup(MemberOrBase);
2120    if (Result.first != Result.second) {
2121      ValueDecl *Member;
2122      if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
2123          (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
2124        if (EllipsisLoc.isValid())
2125          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2126            << MemberOrBase
2127            << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2128
2129        return BuildMemberInitializer(Member, Init, IdLoc);
2130      }
2131    }
2132  }
2133  // It didn't name a member, so see if it names a class.
2134  QualType BaseType;
2135  TypeSourceInfo *TInfo = 0;
2136
2137  if (TemplateTypeTy) {
2138    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2139  } else if (DS.getTypeSpecType() == TST_decltype) {
2140    BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2141  } else {
2142    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2143    LookupParsedName(R, S, &SS);
2144
2145    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2146    if (!TyD) {
2147      if (R.isAmbiguous()) return true;
2148
2149      // We don't want access-control diagnostics here.
2150      R.suppressDiagnostics();
2151
2152      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2153        bool NotUnknownSpecialization = false;
2154        DeclContext *DC = computeDeclContext(SS, false);
2155        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2156          NotUnknownSpecialization = !Record->hasAnyDependentBases();
2157
2158        if (!NotUnknownSpecialization) {
2159          // When the scope specifier can refer to a member of an unknown
2160          // specialization, we take it as a type name.
2161          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2162                                       SS.getWithLocInContext(Context),
2163                                       *MemberOrBase, IdLoc);
2164          if (BaseType.isNull())
2165            return true;
2166
2167          R.clear();
2168          R.setLookupName(MemberOrBase);
2169        }
2170      }
2171
2172      // If no results were found, try to correct typos.
2173      TypoCorrection Corr;
2174      MemInitializerValidatorCCC Validator(ClassDecl);
2175      if (R.empty() && BaseType.isNull() &&
2176          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2177                              Validator, ClassDecl))) {
2178        std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2179        std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
2180        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2181          // We have found a non-static data member with a similar
2182          // name to what was typed; complain and initialize that
2183          // member.
2184          Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2185            << MemberOrBase << true << CorrectedQuotedStr
2186            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2187          Diag(Member->getLocation(), diag::note_previous_decl)
2188            << CorrectedQuotedStr;
2189
2190          return BuildMemberInitializer(Member, Init, IdLoc);
2191        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2192          const CXXBaseSpecifier *DirectBaseSpec;
2193          const CXXBaseSpecifier *VirtualBaseSpec;
2194          if (FindBaseInitializer(*this, ClassDecl,
2195                                  Context.getTypeDeclType(Type),
2196                                  DirectBaseSpec, VirtualBaseSpec)) {
2197            // We have found a direct or virtual base class with a
2198            // similar name to what was typed; complain and initialize
2199            // that base class.
2200            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2201              << MemberOrBase << false << CorrectedQuotedStr
2202              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2203
2204            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2205                                                             : VirtualBaseSpec;
2206            Diag(BaseSpec->getLocStart(),
2207                 diag::note_base_class_specified_here)
2208              << BaseSpec->getType()
2209              << BaseSpec->getSourceRange();
2210
2211            TyD = Type;
2212          }
2213        }
2214      }
2215
2216      if (!TyD && BaseType.isNull()) {
2217        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2218          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2219        return true;
2220      }
2221    }
2222
2223    if (BaseType.isNull()) {
2224      BaseType = Context.getTypeDeclType(TyD);
2225      if (SS.isSet()) {
2226        NestedNameSpecifier *Qualifier =
2227          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2228
2229        // FIXME: preserve source range information
2230        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
2231      }
2232    }
2233  }
2234
2235  if (!TInfo)
2236    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2237
2238  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2239}
2240
2241/// Checks a member initializer expression for cases where reference (or
2242/// pointer) members are bound to by-value parameters (or their addresses).
2243static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2244                                               Expr *Init,
2245                                               SourceLocation IdLoc) {
2246  QualType MemberTy = Member->getType();
2247
2248  // We only handle pointers and references currently.
2249  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2250  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2251    return;
2252
2253  const bool IsPointer = MemberTy->isPointerType();
2254  if (IsPointer) {
2255    if (const UnaryOperator *Op
2256          = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2257      // The only case we're worried about with pointers requires taking the
2258      // address.
2259      if (Op->getOpcode() != UO_AddrOf)
2260        return;
2261
2262      Init = Op->getSubExpr();
2263    } else {
2264      // We only handle address-of expression initializers for pointers.
2265      return;
2266    }
2267  }
2268
2269  if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2270    // Taking the address of a temporary will be diagnosed as a hard error.
2271    if (IsPointer)
2272      return;
2273
2274    S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2275      << Member << Init->getSourceRange();
2276  } else if (const DeclRefExpr *DRE
2277               = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2278    // We only warn when referring to a non-reference parameter declaration.
2279    const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2280    if (!Parameter || Parameter->getType()->isReferenceType())
2281      return;
2282
2283    S.Diag(Init->getExprLoc(),
2284           IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2285                     : diag::warn_bind_ref_member_to_parameter)
2286      << Member << Parameter << Init->getSourceRange();
2287  } else {
2288    // Other initializers are fine.
2289    return;
2290  }
2291
2292  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2293    << (unsigned)IsPointer;
2294}
2295
2296MemInitResult
2297Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2298                             SourceLocation IdLoc) {
2299  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2300  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2301  assert((DirectMember || IndirectMember) &&
2302         "Member must be a FieldDecl or IndirectFieldDecl");
2303
2304  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2305    return true;
2306
2307  if (Member->isInvalidDecl())
2308    return true;
2309
2310  // Diagnose value-uses of fields to initialize themselves, e.g.
2311  //   foo(foo)
2312  // where foo is not also a parameter to the constructor.
2313  // TODO: implement -Wuninitialized and fold this into that framework.
2314  Expr **Args;
2315  unsigned NumArgs;
2316  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2317    Args = ParenList->getExprs();
2318    NumArgs = ParenList->getNumExprs();
2319  } else {
2320    InitListExpr *InitList = cast<InitListExpr>(Init);
2321    Args = InitList->getInits();
2322    NumArgs = InitList->getNumInits();
2323  }
2324
2325  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2326        != DiagnosticsEngine::Ignored)
2327    for (unsigned i = 0; i < NumArgs; ++i)
2328      // FIXME: Warn about the case when other fields are used before being
2329      // initialized. For example, let this field be the i'th field. When
2330      // initializing the i'th field, throw a warning if any of the >= i'th
2331      // fields are used, as they are not yet initialized.
2332      // Right now we are only handling the case where the i'th field uses
2333      // itself in its initializer.
2334      // Also need to take into account that some fields may be initialized by
2335      // in-class initializers, see C++11 [class.base.init]p9.
2336      CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
2337
2338  SourceRange InitRange = Init->getSourceRange();
2339
2340  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2341    // Can't check initialization for a member of dependent type or when
2342    // any of the arguments are type-dependent expressions.
2343    DiscardCleanupsInEvaluationContext();
2344  } else {
2345    bool InitList = false;
2346    if (isa<InitListExpr>(Init)) {
2347      InitList = true;
2348      Args = &Init;
2349      NumArgs = 1;
2350
2351      if (isStdInitializerList(Member->getType(), 0)) {
2352        Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2353            << /*at end of ctor*/1 << InitRange;
2354      }
2355    }
2356
2357    // Initialize the member.
2358    InitializedEntity MemberEntity =
2359      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2360                   : InitializedEntity::InitializeMember(IndirectMember, 0);
2361    InitializationKind Kind =
2362      InitList ? InitializationKind::CreateDirectList(IdLoc)
2363               : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2364                                                  InitRange.getEnd());
2365
2366    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2367    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2368                                            MultiExprArg(Args, NumArgs),
2369                                            0);
2370    if (MemberInit.isInvalid())
2371      return true;
2372
2373    CheckImplicitConversions(MemberInit.get(),
2374                             InitRange.getBegin());
2375
2376    // C++0x [class.base.init]p7:
2377    //   The initialization of each base and member constitutes a
2378    //   full-expression.
2379    MemberInit = MaybeCreateExprWithCleanups(MemberInit);
2380    if (MemberInit.isInvalid())
2381      return true;
2382
2383    // If we are in a dependent context, template instantiation will
2384    // perform this type-checking again. Just save the arguments that we
2385    // received.
2386    // FIXME: This isn't quite ideal, since our ASTs don't capture all
2387    // of the information that we have about the member
2388    // initializer. However, deconstructing the ASTs is a dicey process,
2389    // and this approach is far more likely to get the corner cases right.
2390    if (CurContext->isDependentContext()) {
2391      // The existing Init will do fine.
2392    } else {
2393      Init = MemberInit.get();
2394      CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2395    }
2396  }
2397
2398  if (DirectMember) {
2399    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2400                                            InitRange.getBegin(), Init,
2401                                            InitRange.getEnd());
2402  } else {
2403    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2404                                            InitRange.getBegin(), Init,
2405                                            InitRange.getEnd());
2406  }
2407}
2408
2409MemInitResult
2410Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2411                                 CXXRecordDecl *ClassDecl) {
2412  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2413  if (!LangOpts.CPlusPlus0x)
2414    return Diag(NameLoc, diag::err_delegating_ctor)
2415      << TInfo->getTypeLoc().getLocalSourceRange();
2416  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2417
2418  bool InitList = true;
2419  Expr **Args = &Init;
2420  unsigned NumArgs = 1;
2421  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2422    InitList = false;
2423    Args = ParenList->getExprs();
2424    NumArgs = ParenList->getNumExprs();
2425  }
2426
2427  SourceRange InitRange = Init->getSourceRange();
2428  // Initialize the object.
2429  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2430                                     QualType(ClassDecl->getTypeForDecl(), 0));
2431  InitializationKind Kind =
2432    InitList ? InitializationKind::CreateDirectList(NameLoc)
2433             : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2434                                                InitRange.getEnd());
2435  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2436  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2437                                              MultiExprArg(Args, NumArgs),
2438                                              0);
2439  if (DelegationInit.isInvalid())
2440    return true;
2441
2442  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2443         "Delegating constructor with no target?");
2444
2445  CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
2446
2447  // C++0x [class.base.init]p7:
2448  //   The initialization of each base and member constitutes a
2449  //   full-expression.
2450  DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2451  if (DelegationInit.isInvalid())
2452    return true;
2453
2454  // If we are in a dependent context, template instantiation will
2455  // perform this type-checking again. Just save the arguments that we
2456  // received in a ParenListExpr.
2457  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2458  // of the information that we have about the base
2459  // initializer. However, deconstructing the ASTs is a dicey process,
2460  // and this approach is far more likely to get the corner cases right.
2461  if (CurContext->isDependentContext())
2462    DelegationInit = Owned(Init);
2463
2464  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2465                                          DelegationInit.takeAs<Expr>(),
2466                                          InitRange.getEnd());
2467}
2468
2469MemInitResult
2470Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2471                           Expr *Init, CXXRecordDecl *ClassDecl,
2472                           SourceLocation EllipsisLoc) {
2473  SourceLocation BaseLoc
2474    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2475
2476  if (!BaseType->isDependentType() && !BaseType->isRecordType())
2477    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2478             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2479
2480  // C++ [class.base.init]p2:
2481  //   [...] Unless the mem-initializer-id names a nonstatic data
2482  //   member of the constructor's class or a direct or virtual base
2483  //   of that class, the mem-initializer is ill-formed. A
2484  //   mem-initializer-list can initialize a base class using any
2485  //   name that denotes that base class type.
2486  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2487
2488  SourceRange InitRange = Init->getSourceRange();
2489  if (EllipsisLoc.isValid()) {
2490    // This is a pack expansion.
2491    if (!BaseType->containsUnexpandedParameterPack())  {
2492      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2493        << SourceRange(BaseLoc, InitRange.getEnd());
2494
2495      EllipsisLoc = SourceLocation();
2496    }
2497  } else {
2498    // Check for any unexpanded parameter packs.
2499    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2500      return true;
2501
2502    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2503      return true;
2504  }
2505
2506  // Check for direct and virtual base classes.
2507  const CXXBaseSpecifier *DirectBaseSpec = 0;
2508  const CXXBaseSpecifier *VirtualBaseSpec = 0;
2509  if (!Dependent) {
2510    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2511                                       BaseType))
2512      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2513
2514    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2515                        VirtualBaseSpec);
2516
2517    // C++ [base.class.init]p2:
2518    // Unless the mem-initializer-id names a nonstatic data member of the
2519    // constructor's class or a direct or virtual base of that class, the
2520    // mem-initializer is ill-formed.
2521    if (!DirectBaseSpec && !VirtualBaseSpec) {
2522      // If the class has any dependent bases, then it's possible that
2523      // one of those types will resolve to the same type as
2524      // BaseType. Therefore, just treat this as a dependent base
2525      // class initialization.  FIXME: Should we try to check the
2526      // initialization anyway? It seems odd.
2527      if (ClassDecl->hasAnyDependentBases())
2528        Dependent = true;
2529      else
2530        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2531          << BaseType << Context.getTypeDeclType(ClassDecl)
2532          << BaseTInfo->getTypeLoc().getLocalSourceRange();
2533    }
2534  }
2535
2536  if (Dependent) {
2537    DiscardCleanupsInEvaluationContext();
2538
2539    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2540                                            /*IsVirtual=*/false,
2541                                            InitRange.getBegin(), Init,
2542                                            InitRange.getEnd(), EllipsisLoc);
2543  }
2544
2545  // C++ [base.class.init]p2:
2546  //   If a mem-initializer-id is ambiguous because it designates both
2547  //   a direct non-virtual base class and an inherited virtual base
2548  //   class, the mem-initializer is ill-formed.
2549  if (DirectBaseSpec && VirtualBaseSpec)
2550    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2551      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2552
2553  CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2554  if (!BaseSpec)
2555    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2556
2557  // Initialize the base.
2558  bool InitList = true;
2559  Expr **Args = &Init;
2560  unsigned NumArgs = 1;
2561  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2562    InitList = false;
2563    Args = ParenList->getExprs();
2564    NumArgs = ParenList->getNumExprs();
2565  }
2566
2567  InitializedEntity BaseEntity =
2568    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2569  InitializationKind Kind =
2570    InitList ? InitializationKind::CreateDirectList(BaseLoc)
2571             : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2572                                                InitRange.getEnd());
2573  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2574  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2575                                        MultiExprArg(Args, NumArgs), 0);
2576  if (BaseInit.isInvalid())
2577    return true;
2578
2579  CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
2580
2581  // C++0x [class.base.init]p7:
2582  //   The initialization of each base and member constitutes a
2583  //   full-expression.
2584  BaseInit = MaybeCreateExprWithCleanups(BaseInit);
2585  if (BaseInit.isInvalid())
2586    return true;
2587
2588  // If we are in a dependent context, template instantiation will
2589  // perform this type-checking again. Just save the arguments that we
2590  // received in a ParenListExpr.
2591  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2592  // of the information that we have about the base
2593  // initializer. However, deconstructing the ASTs is a dicey process,
2594  // and this approach is far more likely to get the corner cases right.
2595  if (CurContext->isDependentContext())
2596    BaseInit = Owned(Init);
2597
2598  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2599                                          BaseSpec->isVirtual(),
2600                                          InitRange.getBegin(),
2601                                          BaseInit.takeAs<Expr>(),
2602                                          InitRange.getEnd(), EllipsisLoc);
2603}
2604
2605// Create a static_cast\<T&&>(expr).
2606static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2607  QualType ExprType = E->getType();
2608  QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2609  SourceLocation ExprLoc = E->getLocStart();
2610  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2611      TargetType, ExprLoc);
2612
2613  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2614                                   SourceRange(ExprLoc, ExprLoc),
2615                                   E->getSourceRange()).take();
2616}
2617
2618/// ImplicitInitializerKind - How an implicit base or member initializer should
2619/// initialize its base or member.
2620enum ImplicitInitializerKind {
2621  IIK_Default,
2622  IIK_Copy,
2623  IIK_Move
2624};
2625
2626static bool
2627BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2628                             ImplicitInitializerKind ImplicitInitKind,
2629                             CXXBaseSpecifier *BaseSpec,
2630                             bool IsInheritedVirtualBase,
2631                             CXXCtorInitializer *&CXXBaseInit) {
2632  InitializedEntity InitEntity
2633    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2634                                        IsInheritedVirtualBase);
2635
2636  ExprResult BaseInit;
2637
2638  switch (ImplicitInitKind) {
2639  case IIK_Default: {
2640    InitializationKind InitKind
2641      = InitializationKind::CreateDefault(Constructor->getLocation());
2642    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2643    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2644    break;
2645  }
2646
2647  case IIK_Move:
2648  case IIK_Copy: {
2649    bool Moving = ImplicitInitKind == IIK_Move;
2650    ParmVarDecl *Param = Constructor->getParamDecl(0);
2651    QualType ParamType = Param->getType().getNonReferenceType();
2652
2653    Expr *CopyCtorArg =
2654      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2655                          SourceLocation(), Param, false,
2656                          Constructor->getLocation(), ParamType,
2657                          VK_LValue, 0);
2658
2659    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2660
2661    // Cast to the base class to avoid ambiguities.
2662    QualType ArgTy =
2663      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2664                                       ParamType.getQualifiers());
2665
2666    if (Moving) {
2667      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2668    }
2669
2670    CXXCastPath BasePath;
2671    BasePath.push_back(BaseSpec);
2672    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2673                                            CK_UncheckedDerivedToBase,
2674                                            Moving ? VK_XValue : VK_LValue,
2675                                            &BasePath).take();
2676
2677    InitializationKind InitKind
2678      = InitializationKind::CreateDirect(Constructor->getLocation(),
2679                                         SourceLocation(), SourceLocation());
2680    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2681                                   &CopyCtorArg, 1);
2682    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2683                               MultiExprArg(&CopyCtorArg, 1));
2684    break;
2685  }
2686  }
2687
2688  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2689  if (BaseInit.isInvalid())
2690    return true;
2691
2692  CXXBaseInit =
2693    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2694               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2695                                                        SourceLocation()),
2696                                             BaseSpec->isVirtual(),
2697                                             SourceLocation(),
2698                                             BaseInit.takeAs<Expr>(),
2699                                             SourceLocation(),
2700                                             SourceLocation());
2701
2702  return false;
2703}
2704
2705static bool RefersToRValueRef(Expr *MemRef) {
2706  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2707  return Referenced->getType()->isRValueReferenceType();
2708}
2709
2710static bool
2711BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2712                               ImplicitInitializerKind ImplicitInitKind,
2713                               FieldDecl *Field, IndirectFieldDecl *Indirect,
2714                               CXXCtorInitializer *&CXXMemberInit) {
2715  if (Field->isInvalidDecl())
2716    return true;
2717
2718  SourceLocation Loc = Constructor->getLocation();
2719
2720  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2721    bool Moving = ImplicitInitKind == IIK_Move;
2722    ParmVarDecl *Param = Constructor->getParamDecl(0);
2723    QualType ParamType = Param->getType().getNonReferenceType();
2724
2725    // Suppress copying zero-width bitfields.
2726    if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2727      return false;
2728
2729    Expr *MemberExprBase =
2730      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2731                          SourceLocation(), Param, false,
2732                          Loc, ParamType, VK_LValue, 0);
2733
2734    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2735
2736    if (Moving) {
2737      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2738    }
2739
2740    // Build a reference to this field within the parameter.
2741    CXXScopeSpec SS;
2742    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2743                              Sema::LookupMemberName);
2744    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2745                                  : cast<ValueDecl>(Field), AS_public);
2746    MemberLookup.resolveKind();
2747    ExprResult CtorArg
2748      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2749                                         ParamType, Loc,
2750                                         /*IsArrow=*/false,
2751                                         SS,
2752                                         /*TemplateKWLoc=*/SourceLocation(),
2753                                         /*FirstQualifierInScope=*/0,
2754                                         MemberLookup,
2755                                         /*TemplateArgs=*/0);
2756    if (CtorArg.isInvalid())
2757      return true;
2758
2759    // C++11 [class.copy]p15:
2760    //   - if a member m has rvalue reference type T&&, it is direct-initialized
2761    //     with static_cast<T&&>(x.m);
2762    if (RefersToRValueRef(CtorArg.get())) {
2763      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2764    }
2765
2766    // When the field we are copying is an array, create index variables for
2767    // each dimension of the array. We use these index variables to subscript
2768    // the source array, and other clients (e.g., CodeGen) will perform the
2769    // necessary iteration with these index variables.
2770    SmallVector<VarDecl *, 4> IndexVariables;
2771    QualType BaseType = Field->getType();
2772    QualType SizeType = SemaRef.Context.getSizeType();
2773    bool InitializingArray = false;
2774    while (const ConstantArrayType *Array
2775                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2776      InitializingArray = true;
2777      // Create the iteration variable for this array index.
2778      IdentifierInfo *IterationVarName = 0;
2779      {
2780        SmallString<8> Str;
2781        llvm::raw_svector_ostream OS(Str);
2782        OS << "__i" << IndexVariables.size();
2783        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2784      }
2785      VarDecl *IterationVar
2786        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2787                          IterationVarName, SizeType,
2788                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2789                          SC_None, SC_None);
2790      IndexVariables.push_back(IterationVar);
2791
2792      // Create a reference to the iteration variable.
2793      ExprResult IterationVarRef
2794        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
2795      assert(!IterationVarRef.isInvalid() &&
2796             "Reference to invented variable cannot fail!");
2797      IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2798      assert(!IterationVarRef.isInvalid() &&
2799             "Conversion of invented variable cannot fail!");
2800
2801      // Subscript the array with this iteration variable.
2802      CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
2803                                                        IterationVarRef.take(),
2804                                                        Loc);
2805      if (CtorArg.isInvalid())
2806        return true;
2807
2808      BaseType = Array->getElementType();
2809    }
2810
2811    // The array subscript expression is an lvalue, which is wrong for moving.
2812    if (Moving && InitializingArray)
2813      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2814
2815    // Construct the entity that we will be initializing. For an array, this
2816    // will be first element in the array, which may require several levels
2817    // of array-subscript entities.
2818    SmallVector<InitializedEntity, 4> Entities;
2819    Entities.reserve(1 + IndexVariables.size());
2820    if (Indirect)
2821      Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2822    else
2823      Entities.push_back(InitializedEntity::InitializeMember(Field));
2824    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2825      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2826                                                              0,
2827                                                              Entities.back()));
2828
2829    // Direct-initialize to use the copy constructor.
2830    InitializationKind InitKind =
2831      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2832
2833    Expr *CtorArgE = CtorArg.takeAs<Expr>();
2834    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2835                                   &CtorArgE, 1);
2836
2837    ExprResult MemberInit
2838      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2839                        MultiExprArg(&CtorArgE, 1));
2840    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2841    if (MemberInit.isInvalid())
2842      return true;
2843
2844    if (Indirect) {
2845      assert(IndexVariables.size() == 0 &&
2846             "Indirect field improperly initialized");
2847      CXXMemberInit
2848        = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2849                                                   Loc, Loc,
2850                                                   MemberInit.takeAs<Expr>(),
2851                                                   Loc);
2852    } else
2853      CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2854                                                 Loc, MemberInit.takeAs<Expr>(),
2855                                                 Loc,
2856                                                 IndexVariables.data(),
2857                                                 IndexVariables.size());
2858    return false;
2859  }
2860
2861  assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2862
2863  QualType FieldBaseElementType =
2864    SemaRef.Context.getBaseElementType(Field->getType());
2865
2866  if (FieldBaseElementType->isRecordType()) {
2867    InitializedEntity InitEntity
2868      = Indirect? InitializedEntity::InitializeMember(Indirect)
2869                : InitializedEntity::InitializeMember(Field);
2870    InitializationKind InitKind =
2871      InitializationKind::CreateDefault(Loc);
2872
2873    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2874    ExprResult MemberInit =
2875      InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2876
2877    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2878    if (MemberInit.isInvalid())
2879      return true;
2880
2881    if (Indirect)
2882      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2883                                                               Indirect, Loc,
2884                                                               Loc,
2885                                                               MemberInit.get(),
2886                                                               Loc);
2887    else
2888      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2889                                                               Field, Loc, Loc,
2890                                                               MemberInit.get(),
2891                                                               Loc);
2892    return false;
2893  }
2894
2895  if (!Field->getParent()->isUnion()) {
2896    if (FieldBaseElementType->isReferenceType()) {
2897      SemaRef.Diag(Constructor->getLocation(),
2898                   diag::err_uninitialized_member_in_ctor)
2899      << (int)Constructor->isImplicit()
2900      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2901      << 0 << Field->getDeclName();
2902      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2903      return true;
2904    }
2905
2906    if (FieldBaseElementType.isConstQualified()) {
2907      SemaRef.Diag(Constructor->getLocation(),
2908                   diag::err_uninitialized_member_in_ctor)
2909      << (int)Constructor->isImplicit()
2910      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2911      << 1 << Field->getDeclName();
2912      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2913      return true;
2914    }
2915  }
2916
2917  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2918      FieldBaseElementType->isObjCRetainableType() &&
2919      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2920      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2921    // ARC:
2922    //   Default-initialize Objective-C pointers to NULL.
2923    CXXMemberInit
2924      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2925                                                 Loc, Loc,
2926                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2927                                                 Loc);
2928    return false;
2929  }
2930
2931  // Nothing to initialize.
2932  CXXMemberInit = 0;
2933  return false;
2934}
2935
2936namespace {
2937struct BaseAndFieldInfo {
2938  Sema &S;
2939  CXXConstructorDecl *Ctor;
2940  bool AnyErrorsInInits;
2941  ImplicitInitializerKind IIK;
2942  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2943  SmallVector<CXXCtorInitializer*, 8> AllToInit;
2944
2945  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2946    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2947    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2948    if (Generated && Ctor->isCopyConstructor())
2949      IIK = IIK_Copy;
2950    else if (Generated && Ctor->isMoveConstructor())
2951      IIK = IIK_Move;
2952    else
2953      IIK = IIK_Default;
2954  }
2955
2956  bool isImplicitCopyOrMove() const {
2957    switch (IIK) {
2958    case IIK_Copy:
2959    case IIK_Move:
2960      return true;
2961
2962    case IIK_Default:
2963      return false;
2964    }
2965
2966    llvm_unreachable("Invalid ImplicitInitializerKind!");
2967  }
2968
2969  bool addFieldInitializer(CXXCtorInitializer *Init) {
2970    AllToInit.push_back(Init);
2971
2972    // Check whether this initializer makes the field "used".
2973    if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2974      S.UnusedPrivateFields.remove(Init->getAnyMember());
2975
2976    return false;
2977  }
2978};
2979}
2980
2981/// \brief Determine whether the given indirect field declaration is somewhere
2982/// within an anonymous union.
2983static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2984  for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2985                                      CEnd = F->chain_end();
2986       C != CEnd; ++C)
2987    if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2988      if (Record->isUnion())
2989        return true;
2990
2991  return false;
2992}
2993
2994/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2995/// array type.
2996static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2997  if (T->isIncompleteArrayType())
2998    return true;
2999
3000  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3001    if (!ArrayT->getSize())
3002      return true;
3003
3004    T = ArrayT->getElementType();
3005  }
3006
3007  return false;
3008}
3009
3010static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3011                                    FieldDecl *Field,
3012                                    IndirectFieldDecl *Indirect = 0) {
3013
3014  // Overwhelmingly common case: we have a direct initializer for this field.
3015  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3016    return Info.addFieldInitializer(Init);
3017
3018  // C++11 [class.base.init]p8: if the entity is a non-static data member that
3019  // has a brace-or-equal-initializer, the entity is initialized as specified
3020  // in [dcl.init].
3021  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3022    CXXCtorInitializer *Init;
3023    if (Indirect)
3024      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3025                                                      SourceLocation(),
3026                                                      SourceLocation(), 0,
3027                                                      SourceLocation());
3028    else
3029      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3030                                                      SourceLocation(),
3031                                                      SourceLocation(), 0,
3032                                                      SourceLocation());
3033    return Info.addFieldInitializer(Init);
3034  }
3035
3036  // Don't build an implicit initializer for union members if none was
3037  // explicitly specified.
3038  if (Field->getParent()->isUnion() ||
3039      (Indirect && isWithinAnonymousUnion(Indirect)))
3040    return false;
3041
3042  // Don't initialize incomplete or zero-length arrays.
3043  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3044    return false;
3045
3046  // Don't try to build an implicit initializer if there were semantic
3047  // errors in any of the initializers (and therefore we might be
3048  // missing some that the user actually wrote).
3049  if (Info.AnyErrorsInInits || Field->isInvalidDecl())
3050    return false;
3051
3052  CXXCtorInitializer *Init = 0;
3053  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3054                                     Indirect, Init))
3055    return true;
3056
3057  if (!Init)
3058    return false;
3059
3060  return Info.addFieldInitializer(Init);
3061}
3062
3063bool
3064Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3065                               CXXCtorInitializer *Initializer) {
3066  assert(Initializer->isDelegatingInitializer());
3067  Constructor->setNumCtorInitializers(1);
3068  CXXCtorInitializer **initializer =
3069    new (Context) CXXCtorInitializer*[1];
3070  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3071  Constructor->setCtorInitializers(initializer);
3072
3073  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3074    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3075    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3076  }
3077
3078  DelegatingCtorDecls.push_back(Constructor);
3079
3080  return false;
3081}
3082
3083bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
3084                               CXXCtorInitializer **Initializers,
3085                               unsigned NumInitializers,
3086                               bool AnyErrors) {
3087  if (Constructor->isDependentContext()) {
3088    // Just store the initializers as written, they will be checked during
3089    // instantiation.
3090    if (NumInitializers > 0) {
3091      Constructor->setNumCtorInitializers(NumInitializers);
3092      CXXCtorInitializer **baseOrMemberInitializers =
3093        new (Context) CXXCtorInitializer*[NumInitializers];
3094      memcpy(baseOrMemberInitializers, Initializers,
3095             NumInitializers * sizeof(CXXCtorInitializer*));
3096      Constructor->setCtorInitializers(baseOrMemberInitializers);
3097    }
3098
3099    // Let template instantiation know whether we had errors.
3100    if (AnyErrors)
3101      Constructor->setInvalidDecl();
3102
3103    return false;
3104  }
3105
3106  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3107
3108  // We need to build the initializer AST according to order of construction
3109  // and not what user specified in the Initializers list.
3110  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3111  if (!ClassDecl)
3112    return true;
3113
3114  bool HadError = false;
3115
3116  for (unsigned i = 0; i < NumInitializers; i++) {
3117    CXXCtorInitializer *Member = Initializers[i];
3118
3119    if (Member->isBaseInitializer())
3120      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3121    else
3122      Info.AllBaseFields[Member->getAnyMember()] = Member;
3123  }
3124
3125  // Keep track of the direct virtual bases.
3126  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3127  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3128       E = ClassDecl->bases_end(); I != E; ++I) {
3129    if (I->isVirtual())
3130      DirectVBases.insert(I);
3131  }
3132
3133  // Push virtual bases before others.
3134  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3135       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3136
3137    if (CXXCtorInitializer *Value
3138        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3139      Info.AllToInit.push_back(Value);
3140    } else if (!AnyErrors) {
3141      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3142      CXXCtorInitializer *CXXBaseInit;
3143      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3144                                       VBase, IsInheritedVirtualBase,
3145                                       CXXBaseInit)) {
3146        HadError = true;
3147        continue;
3148      }
3149
3150      Info.AllToInit.push_back(CXXBaseInit);
3151    }
3152  }
3153
3154  // Non-virtual bases.
3155  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3156       E = ClassDecl->bases_end(); Base != E; ++Base) {
3157    // Virtuals are in the virtual base list and already constructed.
3158    if (Base->isVirtual())
3159      continue;
3160
3161    if (CXXCtorInitializer *Value
3162          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3163      Info.AllToInit.push_back(Value);
3164    } else if (!AnyErrors) {
3165      CXXCtorInitializer *CXXBaseInit;
3166      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3167                                       Base, /*IsInheritedVirtualBase=*/false,
3168                                       CXXBaseInit)) {
3169        HadError = true;
3170        continue;
3171      }
3172
3173      Info.AllToInit.push_back(CXXBaseInit);
3174    }
3175  }
3176
3177  // Fields.
3178  for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3179                               MemEnd = ClassDecl->decls_end();
3180       Mem != MemEnd; ++Mem) {
3181    if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3182      // C++ [class.bit]p2:
3183      //   A declaration for a bit-field that omits the identifier declares an
3184      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3185      //   initialized.
3186      if (F->isUnnamedBitfield())
3187        continue;
3188
3189      // If we're not generating the implicit copy/move constructor, then we'll
3190      // handle anonymous struct/union fields based on their individual
3191      // indirect fields.
3192      if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3193        continue;
3194
3195      if (CollectFieldInitializer(*this, Info, F))
3196        HadError = true;
3197      continue;
3198    }
3199
3200    // Beyond this point, we only consider default initialization.
3201    if (Info.IIK != IIK_Default)
3202      continue;
3203
3204    if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3205      if (F->getType()->isIncompleteArrayType()) {
3206        assert(ClassDecl->hasFlexibleArrayMember() &&
3207               "Incomplete array type is not valid");
3208        continue;
3209      }
3210
3211      // Initialize each field of an anonymous struct individually.
3212      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3213        HadError = true;
3214
3215      continue;
3216    }
3217  }
3218
3219  NumInitializers = Info.AllToInit.size();
3220  if (NumInitializers > 0) {
3221    Constructor->setNumCtorInitializers(NumInitializers);
3222    CXXCtorInitializer **baseOrMemberInitializers =
3223      new (Context) CXXCtorInitializer*[NumInitializers];
3224    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3225           NumInitializers * sizeof(CXXCtorInitializer*));
3226    Constructor->setCtorInitializers(baseOrMemberInitializers);
3227
3228    // Constructors implicitly reference the base and member
3229    // destructors.
3230    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3231                                           Constructor->getParent());
3232  }
3233
3234  return HadError;
3235}
3236
3237static void *GetKeyForTopLevelField(FieldDecl *Field) {
3238  // For anonymous unions, use the class declaration as the key.
3239  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3240    if (RT->getDecl()->isAnonymousStructOrUnion())
3241      return static_cast<void *>(RT->getDecl());
3242  }
3243  return static_cast<void *>(Field);
3244}
3245
3246static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3247  return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3248}
3249
3250static void *GetKeyForMember(ASTContext &Context,
3251                             CXXCtorInitializer *Member) {
3252  if (!Member->isAnyMemberInitializer())
3253    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3254
3255  // For fields injected into the class via declaration of an anonymous union,
3256  // use its anonymous union class declaration as the unique key.
3257  FieldDecl *Field = Member->getAnyMember();
3258
3259  // If the field is a member of an anonymous struct or union, our key
3260  // is the anonymous record decl that's a direct child of the class.
3261  RecordDecl *RD = Field->getParent();
3262  if (RD->isAnonymousStructOrUnion()) {
3263    while (true) {
3264      RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3265      if (Parent->isAnonymousStructOrUnion())
3266        RD = Parent;
3267      else
3268        break;
3269    }
3270
3271    return static_cast<void *>(RD);
3272  }
3273
3274  return static_cast<void *>(Field);
3275}
3276
3277static void
3278DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
3279                                  const CXXConstructorDecl *Constructor,
3280                                  CXXCtorInitializer **Inits,
3281                                  unsigned NumInits) {
3282  if (Constructor->getDeclContext()->isDependentContext())
3283    return;
3284
3285  // Don't check initializers order unless the warning is enabled at the
3286  // location of at least one initializer.
3287  bool ShouldCheckOrder = false;
3288  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3289    CXXCtorInitializer *Init = Inits[InitIndex];
3290    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3291                                         Init->getSourceLocation())
3292          != DiagnosticsEngine::Ignored) {
3293      ShouldCheckOrder = true;
3294      break;
3295    }
3296  }
3297  if (!ShouldCheckOrder)
3298    return;
3299
3300  // Build the list of bases and members in the order that they'll
3301  // actually be initialized.  The explicit initializers should be in
3302  // this same order but may be missing things.
3303  SmallVector<const void*, 32> IdealInitKeys;
3304
3305  const CXXRecordDecl *ClassDecl = Constructor->getParent();
3306
3307  // 1. Virtual bases.
3308  for (CXXRecordDecl::base_class_const_iterator VBase =
3309       ClassDecl->vbases_begin(),
3310       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3311    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3312
3313  // 2. Non-virtual bases.
3314  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3315       E = ClassDecl->bases_end(); Base != E; ++Base) {
3316    if (Base->isVirtual())
3317      continue;
3318    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3319  }
3320
3321  // 3. Direct fields.
3322  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3323       E = ClassDecl->field_end(); Field != E; ++Field) {
3324    if (Field->isUnnamedBitfield())
3325      continue;
3326
3327    IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
3328  }
3329
3330  unsigned NumIdealInits = IdealInitKeys.size();
3331  unsigned IdealIndex = 0;
3332
3333  CXXCtorInitializer *PrevInit = 0;
3334  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3335    CXXCtorInitializer *Init = Inits[InitIndex];
3336    void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3337
3338    // Scan forward to try to find this initializer in the idealized
3339    // initializers list.
3340    for (; IdealIndex != NumIdealInits; ++IdealIndex)
3341      if (InitKey == IdealInitKeys[IdealIndex])
3342        break;
3343
3344    // If we didn't find this initializer, it must be because we
3345    // scanned past it on a previous iteration.  That can only
3346    // happen if we're out of order;  emit a warning.
3347    if (IdealIndex == NumIdealInits && PrevInit) {
3348      Sema::SemaDiagnosticBuilder D =
3349        SemaRef.Diag(PrevInit->getSourceLocation(),
3350                     diag::warn_initializer_out_of_order);
3351
3352      if (PrevInit->isAnyMemberInitializer())
3353        D << 0 << PrevInit->getAnyMember()->getDeclName();
3354      else
3355        D << 1 << PrevInit->getTypeSourceInfo()->getType();
3356
3357      if (Init->isAnyMemberInitializer())
3358        D << 0 << Init->getAnyMember()->getDeclName();
3359      else
3360        D << 1 << Init->getTypeSourceInfo()->getType();
3361
3362      // Move back to the initializer's location in the ideal list.
3363      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3364        if (InitKey == IdealInitKeys[IdealIndex])
3365          break;
3366
3367      assert(IdealIndex != NumIdealInits &&
3368             "initializer not found in initializer list");
3369    }
3370
3371    PrevInit = Init;
3372  }
3373}
3374
3375namespace {
3376bool CheckRedundantInit(Sema &S,
3377                        CXXCtorInitializer *Init,
3378                        CXXCtorInitializer *&PrevInit) {
3379  if (!PrevInit) {
3380    PrevInit = Init;
3381    return false;
3382  }
3383
3384  if (FieldDecl *Field = Init->getMember())
3385    S.Diag(Init->getSourceLocation(),
3386           diag::err_multiple_mem_initialization)
3387      << Field->getDeclName()
3388      << Init->getSourceRange();
3389  else {
3390    const Type *BaseClass = Init->getBaseClass();
3391    assert(BaseClass && "neither field nor base");
3392    S.Diag(Init->getSourceLocation(),
3393           diag::err_multiple_base_initialization)
3394      << QualType(BaseClass, 0)
3395      << Init->getSourceRange();
3396  }
3397  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3398    << 0 << PrevInit->getSourceRange();
3399
3400  return true;
3401}
3402
3403typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3404typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3405
3406bool CheckRedundantUnionInit(Sema &S,
3407                             CXXCtorInitializer *Init,
3408                             RedundantUnionMap &Unions) {
3409  FieldDecl *Field = Init->getAnyMember();
3410  RecordDecl *Parent = Field->getParent();
3411  NamedDecl *Child = Field;
3412
3413  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3414    if (Parent->isUnion()) {
3415      UnionEntry &En = Unions[Parent];
3416      if (En.first && En.first != Child) {
3417        S.Diag(Init->getSourceLocation(),
3418               diag::err_multiple_mem_union_initialization)
3419          << Field->getDeclName()
3420          << Init->getSourceRange();
3421        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3422          << 0 << En.second->getSourceRange();
3423        return true;
3424      }
3425      if (!En.first) {
3426        En.first = Child;
3427        En.second = Init;
3428      }
3429      if (!Parent->isAnonymousStructOrUnion())
3430        return false;
3431    }
3432
3433    Child = Parent;
3434    Parent = cast<RecordDecl>(Parent->getDeclContext());
3435  }
3436
3437  return false;
3438}
3439}
3440
3441/// ActOnMemInitializers - Handle the member initializers for a constructor.
3442void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3443                                SourceLocation ColonLoc,
3444                                CXXCtorInitializer **meminits,
3445                                unsigned NumMemInits,
3446                                bool AnyErrors) {
3447  if (!ConstructorDecl)
3448    return;
3449
3450  AdjustDeclIfTemplate(ConstructorDecl);
3451
3452  CXXConstructorDecl *Constructor
3453    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3454
3455  if (!Constructor) {
3456    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3457    return;
3458  }
3459
3460  CXXCtorInitializer **MemInits =
3461    reinterpret_cast<CXXCtorInitializer **>(meminits);
3462
3463  // Mapping for the duplicate initializers check.
3464  // For member initializers, this is keyed with a FieldDecl*.
3465  // For base initializers, this is keyed with a Type*.
3466  llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3467
3468  // Mapping for the inconsistent anonymous-union initializers check.
3469  RedundantUnionMap MemberUnions;
3470
3471  bool HadError = false;
3472  for (unsigned i = 0; i < NumMemInits; i++) {
3473    CXXCtorInitializer *Init = MemInits[i];
3474
3475    // Set the source order index.
3476    Init->setSourceOrder(i);
3477
3478    if (Init->isAnyMemberInitializer()) {
3479      FieldDecl *Field = Init->getAnyMember();
3480      if (CheckRedundantInit(*this, Init, Members[Field]) ||
3481          CheckRedundantUnionInit(*this, Init, MemberUnions))
3482        HadError = true;
3483    } else if (Init->isBaseInitializer()) {
3484      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3485      if (CheckRedundantInit(*this, Init, Members[Key]))
3486        HadError = true;
3487    } else {
3488      assert(Init->isDelegatingInitializer());
3489      // This must be the only initializer
3490      if (NumMemInits != 1) {
3491        Diag(Init->getSourceLocation(),
3492             diag::err_delegating_initializer_alone)
3493          << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3494        // We will treat this as being the only initializer.
3495      }
3496      SetDelegatingInitializer(Constructor, MemInits[i]);
3497      // Return immediately as the initializer is set.
3498      return;
3499    }
3500  }
3501
3502  if (HadError)
3503    return;
3504
3505  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
3506
3507  SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
3508}
3509
3510void
3511Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3512                                             CXXRecordDecl *ClassDecl) {
3513  // Ignore dependent contexts. Also ignore unions, since their members never
3514  // have destructors implicitly called.
3515  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3516    return;
3517
3518  // FIXME: all the access-control diagnostics are positioned on the
3519  // field/base declaration.  That's probably good; that said, the
3520  // user might reasonably want to know why the destructor is being
3521  // emitted, and we currently don't say.
3522
3523  // Non-static data members.
3524  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3525       E = ClassDecl->field_end(); I != E; ++I) {
3526    FieldDecl *Field = *I;
3527    if (Field->isInvalidDecl())
3528      continue;
3529
3530    // Don't destroy incomplete or zero-length arrays.
3531    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3532      continue;
3533
3534    QualType FieldType = Context.getBaseElementType(Field->getType());
3535
3536    const RecordType* RT = FieldType->getAs<RecordType>();
3537    if (!RT)
3538      continue;
3539
3540    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3541    if (FieldClassDecl->isInvalidDecl())
3542      continue;
3543    if (FieldClassDecl->hasIrrelevantDestructor())
3544      continue;
3545    // The destructor for an implicit anonymous union member is never invoked.
3546    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3547      continue;
3548
3549    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3550    assert(Dtor && "No dtor found for FieldClassDecl!");
3551    CheckDestructorAccess(Field->getLocation(), Dtor,
3552                          PDiag(diag::err_access_dtor_field)
3553                            << Field->getDeclName()
3554                            << FieldType);
3555
3556    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3557    DiagnoseUseOfDecl(Dtor, Location);
3558  }
3559
3560  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3561
3562  // Bases.
3563  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3564       E = ClassDecl->bases_end(); Base != E; ++Base) {
3565    // Bases are always records in a well-formed non-dependent class.
3566    const RecordType *RT = Base->getType()->getAs<RecordType>();
3567
3568    // Remember direct virtual bases.
3569    if (Base->isVirtual())
3570      DirectVirtualBases.insert(RT);
3571
3572    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3573    // If our base class is invalid, we probably can't get its dtor anyway.
3574    if (BaseClassDecl->isInvalidDecl())
3575      continue;
3576    if (BaseClassDecl->hasIrrelevantDestructor())
3577      continue;
3578
3579    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3580    assert(Dtor && "No dtor found for BaseClassDecl!");
3581
3582    // FIXME: caret should be on the start of the class name
3583    CheckDestructorAccess(Base->getLocStart(), Dtor,
3584                          PDiag(diag::err_access_dtor_base)
3585                            << Base->getType()
3586                            << Base->getSourceRange(),
3587                          Context.getTypeDeclType(ClassDecl));
3588
3589    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3590    DiagnoseUseOfDecl(Dtor, Location);
3591  }
3592
3593  // Virtual bases.
3594  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3595       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3596
3597    // Bases are always records in a well-formed non-dependent class.
3598    const RecordType *RT = VBase->getType()->castAs<RecordType>();
3599
3600    // Ignore direct virtual bases.
3601    if (DirectVirtualBases.count(RT))
3602      continue;
3603
3604    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3605    // If our base class is invalid, we probably can't get its dtor anyway.
3606    if (BaseClassDecl->isInvalidDecl())
3607      continue;
3608    if (BaseClassDecl->hasIrrelevantDestructor())
3609      continue;
3610
3611    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3612    assert(Dtor && "No dtor found for BaseClassDecl!");
3613    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3614                          PDiag(diag::err_access_dtor_vbase)
3615                            << VBase->getType(),
3616                          Context.getTypeDeclType(ClassDecl));
3617
3618    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3619    DiagnoseUseOfDecl(Dtor, Location);
3620  }
3621}
3622
3623void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3624  if (!CDtorDecl)
3625    return;
3626
3627  if (CXXConstructorDecl *Constructor
3628      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3629    SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
3630}
3631
3632bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3633                                  unsigned DiagID, AbstractDiagSelID SelID) {
3634  class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3635    unsigned DiagID;
3636    AbstractDiagSelID SelID;
3637
3638  public:
3639    NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3640      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3641
3642    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3643      if (Suppressed) return;
3644      if (SelID == -1)
3645        S.Diag(Loc, DiagID) << T;
3646      else
3647        S.Diag(Loc, DiagID) << SelID << T;
3648    }
3649  } Diagnoser(DiagID, SelID);
3650
3651  return RequireNonAbstractType(Loc, T, Diagnoser);
3652}
3653
3654bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3655                                  TypeDiagnoser &Diagnoser) {
3656  if (!getLangOpts().CPlusPlus)
3657    return false;
3658
3659  if (const ArrayType *AT = Context.getAsArrayType(T))
3660    return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3661
3662  if (const PointerType *PT = T->getAs<PointerType>()) {
3663    // Find the innermost pointer type.
3664    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3665      PT = T;
3666
3667    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3668      return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3669  }
3670
3671  const RecordType *RT = T->getAs<RecordType>();
3672  if (!RT)
3673    return false;
3674
3675  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3676
3677  // We can't answer whether something is abstract until it has a
3678  // definition.  If it's currently being defined, we'll walk back
3679  // over all the declarations when we have a full definition.
3680  const CXXRecordDecl *Def = RD->getDefinition();
3681  if (!Def || Def->isBeingDefined())
3682    return false;
3683
3684  if (!RD->isAbstract())
3685    return false;
3686
3687  Diagnoser.diagnose(*this, Loc, T);
3688  DiagnoseAbstractType(RD);
3689
3690  return true;
3691}
3692
3693void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3694  // Check if we've already emitted the list of pure virtual functions
3695  // for this class.
3696  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3697    return;
3698
3699  CXXFinalOverriderMap FinalOverriders;
3700  RD->getFinalOverriders(FinalOverriders);
3701
3702  // Keep a set of seen pure methods so we won't diagnose the same method
3703  // more than once.
3704  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3705
3706  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3707                                   MEnd = FinalOverriders.end();
3708       M != MEnd;
3709       ++M) {
3710    for (OverridingMethods::iterator SO = M->second.begin(),
3711                                  SOEnd = M->second.end();
3712         SO != SOEnd; ++SO) {
3713      // C++ [class.abstract]p4:
3714      //   A class is abstract if it contains or inherits at least one
3715      //   pure virtual function for which the final overrider is pure
3716      //   virtual.
3717
3718      //
3719      if (SO->second.size() != 1)
3720        continue;
3721
3722      if (!SO->second.front().Method->isPure())
3723        continue;
3724
3725      if (!SeenPureMethods.insert(SO->second.front().Method))
3726        continue;
3727
3728      Diag(SO->second.front().Method->getLocation(),
3729           diag::note_pure_virtual_function)
3730        << SO->second.front().Method->getDeclName() << RD->getDeclName();
3731    }
3732  }
3733
3734  if (!PureVirtualClassDiagSet)
3735    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3736  PureVirtualClassDiagSet->insert(RD);
3737}
3738
3739namespace {
3740struct AbstractUsageInfo {
3741  Sema &S;
3742  CXXRecordDecl *Record;
3743  CanQualType AbstractType;
3744  bool Invalid;
3745
3746  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3747    : S(S), Record(Record),
3748      AbstractType(S.Context.getCanonicalType(
3749                   S.Context.getTypeDeclType(Record))),
3750      Invalid(false) {}
3751
3752  void DiagnoseAbstractType() {
3753    if (Invalid) return;
3754    S.DiagnoseAbstractType(Record);
3755    Invalid = true;
3756  }
3757
3758  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3759};
3760
3761struct CheckAbstractUsage {
3762  AbstractUsageInfo &Info;
3763  const NamedDecl *Ctx;
3764
3765  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3766    : Info(Info), Ctx(Ctx) {}
3767
3768  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3769    switch (TL.getTypeLocClass()) {
3770#define ABSTRACT_TYPELOC(CLASS, PARENT)
3771#define TYPELOC(CLASS, PARENT) \
3772    case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3773#include "clang/AST/TypeLocNodes.def"
3774    }
3775  }
3776
3777  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3778    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3779    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3780      if (!TL.getArg(I))
3781        continue;
3782
3783      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3784      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3785    }
3786  }
3787
3788  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3789    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3790  }
3791
3792  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3793    // Visit the type parameters from a permissive context.
3794    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3795      TemplateArgumentLoc TAL = TL.getArgLoc(I);
3796      if (TAL.getArgument().getKind() == TemplateArgument::Type)
3797        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3798          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3799      // TODO: other template argument types?
3800    }
3801  }
3802
3803  // Visit pointee types from a permissive context.
3804#define CheckPolymorphic(Type) \
3805  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3806    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3807  }
3808  CheckPolymorphic(PointerTypeLoc)
3809  CheckPolymorphic(ReferenceTypeLoc)
3810  CheckPolymorphic(MemberPointerTypeLoc)
3811  CheckPolymorphic(BlockPointerTypeLoc)
3812  CheckPolymorphic(AtomicTypeLoc)
3813
3814  /// Handle all the types we haven't given a more specific
3815  /// implementation for above.
3816  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3817    // Every other kind of type that we haven't called out already
3818    // that has an inner type is either (1) sugar or (2) contains that
3819    // inner type in some way as a subobject.
3820    if (TypeLoc Next = TL.getNextTypeLoc())
3821      return Visit(Next, Sel);
3822
3823    // If there's no inner type and we're in a permissive context,
3824    // don't diagnose.
3825    if (Sel == Sema::AbstractNone) return;
3826
3827    // Check whether the type matches the abstract type.
3828    QualType T = TL.getType();
3829    if (T->isArrayType()) {
3830      Sel = Sema::AbstractArrayType;
3831      T = Info.S.Context.getBaseElementType(T);
3832    }
3833    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3834    if (CT != Info.AbstractType) return;
3835
3836    // It matched; do some magic.
3837    if (Sel == Sema::AbstractArrayType) {
3838      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3839        << T << TL.getSourceRange();
3840    } else {
3841      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3842        << Sel << T << TL.getSourceRange();
3843    }
3844    Info.DiagnoseAbstractType();
3845  }
3846};
3847
3848void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3849                                  Sema::AbstractDiagSelID Sel) {
3850  CheckAbstractUsage(*this, D).Visit(TL, Sel);
3851}
3852
3853}
3854
3855/// Check for invalid uses of an abstract type in a method declaration.
3856static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3857                                    CXXMethodDecl *MD) {
3858  // No need to do the check on definitions, which require that
3859  // the return/param types be complete.
3860  if (MD->doesThisDeclarationHaveABody())
3861    return;
3862
3863  // For safety's sake, just ignore it if we don't have type source
3864  // information.  This should never happen for non-implicit methods,
3865  // but...
3866  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3867    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3868}
3869
3870/// Check for invalid uses of an abstract type within a class definition.
3871static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3872                                    CXXRecordDecl *RD) {
3873  for (CXXRecordDecl::decl_iterator
3874         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3875    Decl *D = *I;
3876    if (D->isImplicit()) continue;
3877
3878    // Methods and method templates.
3879    if (isa<CXXMethodDecl>(D)) {
3880      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3881    } else if (isa<FunctionTemplateDecl>(D)) {
3882      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3883      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3884
3885    // Fields and static variables.
3886    } else if (isa<FieldDecl>(D)) {
3887      FieldDecl *FD = cast<FieldDecl>(D);
3888      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3889        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3890    } else if (isa<VarDecl>(D)) {
3891      VarDecl *VD = cast<VarDecl>(D);
3892      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3893        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3894
3895    // Nested classes and class templates.
3896    } else if (isa<CXXRecordDecl>(D)) {
3897      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3898    } else if (isa<ClassTemplateDecl>(D)) {
3899      CheckAbstractClassUsage(Info,
3900                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3901    }
3902  }
3903}
3904
3905/// \brief Perform semantic checks on a class definition that has been
3906/// completing, introducing implicitly-declared members, checking for
3907/// abstract types, etc.
3908void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3909  if (!Record)
3910    return;
3911
3912  if (Record->isAbstract() && !Record->isInvalidDecl()) {
3913    AbstractUsageInfo Info(*this, Record);
3914    CheckAbstractClassUsage(Info, Record);
3915  }
3916
3917  // If this is not an aggregate type and has no user-declared constructor,
3918  // complain about any non-static data members of reference or const scalar
3919  // type, since they will never get initializers.
3920  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3921      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3922      !Record->isLambda()) {
3923    bool Complained = false;
3924    for (RecordDecl::field_iterator F = Record->field_begin(),
3925                                 FEnd = Record->field_end();
3926         F != FEnd; ++F) {
3927      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
3928        continue;
3929
3930      if (F->getType()->isReferenceType() ||
3931          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3932        if (!Complained) {
3933          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3934            << Record->getTagKind() << Record;
3935          Complained = true;
3936        }
3937
3938        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3939          << F->getType()->isReferenceType()
3940          << F->getDeclName();
3941      }
3942    }
3943  }
3944
3945  if (Record->isDynamicClass() && !Record->isDependentType())
3946    DynamicClasses.push_back(Record);
3947
3948  if (Record->getIdentifier()) {
3949    // C++ [class.mem]p13:
3950    //   If T is the name of a class, then each of the following shall have a
3951    //   name different from T:
3952    //     - every member of every anonymous union that is a member of class T.
3953    //
3954    // C++ [class.mem]p14:
3955    //   In addition, if class T has a user-declared constructor (12.1), every
3956    //   non-static data member of class T shall have a name different from T.
3957    for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3958         R.first != R.second; ++R.first) {
3959      NamedDecl *D = *R.first;
3960      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3961          isa<IndirectFieldDecl>(D)) {
3962        Diag(D->getLocation(), diag::err_member_name_of_class)
3963          << D->getDeclName();
3964        break;
3965      }
3966    }
3967  }
3968
3969  // Warn if the class has virtual methods but non-virtual public destructor.
3970  if (Record->isPolymorphic() && !Record->isDependentType()) {
3971    CXXDestructorDecl *dtor = Record->getDestructor();
3972    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3973      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3974           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3975  }
3976
3977  if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
3978    Diag(Record->getLocation(), diag::warn_abstract_final_class);
3979    DiagnoseAbstractType(Record);
3980  }
3981
3982  // See if a method overloads virtual methods in a base
3983  /// class without overriding any.
3984  if (!Record->isDependentType()) {
3985    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3986                                     MEnd = Record->method_end();
3987         M != MEnd; ++M) {
3988      if (!M->isStatic())
3989        DiagnoseHiddenVirtualMethods(Record, *M);
3990    }
3991  }
3992
3993  // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3994  // function that is not a constructor declares that member function to be
3995  // const. [...] The class of which that function is a member shall be
3996  // a literal type.
3997  //
3998  // If the class has virtual bases, any constexpr members will already have
3999  // been diagnosed by the checks performed on the member declaration, so
4000  // suppress this (less useful) diagnostic.
4001  if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
4002      !Record->isLiteral() && !Record->getNumVBases()) {
4003    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4004                                     MEnd = Record->method_end();
4005         M != MEnd; ++M) {
4006      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4007        switch (Record->getTemplateSpecializationKind()) {
4008        case TSK_ImplicitInstantiation:
4009        case TSK_ExplicitInstantiationDeclaration:
4010        case TSK_ExplicitInstantiationDefinition:
4011          // If a template instantiates to a non-literal type, but its members
4012          // instantiate to constexpr functions, the template is technically
4013          // ill-formed, but we allow it for sanity.
4014          continue;
4015
4016        case TSK_Undeclared:
4017        case TSK_ExplicitSpecialization:
4018          RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4019                             diag::err_constexpr_method_non_literal);
4020          break;
4021        }
4022
4023        // Only produce one error per class.
4024        break;
4025      }
4026    }
4027  }
4028
4029  // Declare inherited constructors. We do this eagerly here because:
4030  // - The standard requires an eager diagnostic for conflicting inherited
4031  //   constructors from different classes.
4032  // - The lazy declaration of the other implicit constructors is so as to not
4033  //   waste space and performance on classes that are not meant to be
4034  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4035  //   have inherited constructors.
4036  DeclareInheritedConstructors(Record);
4037}
4038
4039void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
4040  for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
4041                                      ME = Record->method_end();
4042       MI != ME; ++MI)
4043    if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
4044      CheckExplicitlyDefaultedSpecialMember(*MI);
4045}
4046
4047/// Is the special member function which would be selected to perform the
4048/// specified operation on the specified class type a constexpr constructor?
4049static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4050                                     Sema::CXXSpecialMember CSM,
4051                                     bool ConstArg) {
4052  Sema::SpecialMemberOverloadResult *SMOR =
4053      S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4054                            false, false, false, false);
4055  if (!SMOR || !SMOR->getMethod())
4056    // A constructor we wouldn't select can't be "involved in initializing"
4057    // anything.
4058    return true;
4059  return SMOR->getMethod()->isConstexpr();
4060}
4061
4062/// Determine whether the specified special member function would be constexpr
4063/// if it were implicitly defined.
4064static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4065                                              Sema::CXXSpecialMember CSM,
4066                                              bool ConstArg) {
4067  if (!S.getLangOpts().CPlusPlus0x)
4068    return false;
4069
4070  // C++11 [dcl.constexpr]p4:
4071  // In the definition of a constexpr constructor [...]
4072  switch (CSM) {
4073  case Sema::CXXDefaultConstructor:
4074    // Since default constructor lookup is essentially trivial (and cannot
4075    // involve, for instance, template instantiation), we compute whether a
4076    // defaulted default constructor is constexpr directly within CXXRecordDecl.
4077    //
4078    // This is important for performance; we need to know whether the default
4079    // constructor is constexpr to determine whether the type is a literal type.
4080    return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4081
4082  case Sema::CXXCopyConstructor:
4083  case Sema::CXXMoveConstructor:
4084    // For copy or move constructors, we need to perform overload resolution.
4085    break;
4086
4087  case Sema::CXXCopyAssignment:
4088  case Sema::CXXMoveAssignment:
4089  case Sema::CXXDestructor:
4090  case Sema::CXXInvalid:
4091    return false;
4092  }
4093
4094  //   -- if the class is a non-empty union, or for each non-empty anonymous
4095  //      union member of a non-union class, exactly one non-static data member
4096  //      shall be initialized; [DR1359]
4097  //
4098  // If we squint, this is guaranteed, since exactly one non-static data member
4099  // will be initialized (if the constructor isn't deleted), we just don't know
4100  // which one.
4101  if (ClassDecl->isUnion())
4102    return true;
4103
4104  //   -- the class shall not have any virtual base classes;
4105  if (ClassDecl->getNumVBases())
4106    return false;
4107
4108  //   -- every constructor involved in initializing [...] base class
4109  //      sub-objects shall be a constexpr constructor;
4110  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4111                                       BEnd = ClassDecl->bases_end();
4112       B != BEnd; ++B) {
4113    const RecordType *BaseType = B->getType()->getAs<RecordType>();
4114    if (!BaseType) continue;
4115
4116    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4117    if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4118      return false;
4119  }
4120
4121  //   -- every constructor involved in initializing non-static data members
4122  //      [...] shall be a constexpr constructor;
4123  //   -- every non-static data member and base class sub-object shall be
4124  //      initialized
4125  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4126                               FEnd = ClassDecl->field_end();
4127       F != FEnd; ++F) {
4128    if (F->isInvalidDecl())
4129      continue;
4130    if (const RecordType *RecordTy =
4131            S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4132      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4133      if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4134        return false;
4135    }
4136  }
4137
4138  // All OK, it's constexpr!
4139  return true;
4140}
4141
4142static Sema::ImplicitExceptionSpecification
4143computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4144  switch (S.getSpecialMember(MD)) {
4145  case Sema::CXXDefaultConstructor:
4146    return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4147  case Sema::CXXCopyConstructor:
4148    return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4149  case Sema::CXXCopyAssignment:
4150    return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4151  case Sema::CXXMoveConstructor:
4152    return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4153  case Sema::CXXMoveAssignment:
4154    return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4155  case Sema::CXXDestructor:
4156    return S.ComputeDefaultedDtorExceptionSpec(MD);
4157  case Sema::CXXInvalid:
4158    break;
4159  }
4160  llvm_unreachable("only special members have implicit exception specs");
4161}
4162
4163static void
4164updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4165                    const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4166  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4167  ExceptSpec.getEPI(EPI);
4168  const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4169    S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4170                              FPT->getNumArgs(), EPI));
4171  FD->setType(QualType(NewFPT, 0));
4172}
4173
4174void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4175  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4176  if (FPT->getExceptionSpecType() != EST_Unevaluated)
4177    return;
4178
4179  // Evaluate the exception specification.
4180  ImplicitExceptionSpecification ExceptSpec =
4181      computeImplicitExceptionSpec(*this, Loc, MD);
4182
4183  // Update the type of the special member to use it.
4184  updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4185
4186  // A user-provided destructor can be defined outside the class. When that
4187  // happens, be sure to update the exception specification on both
4188  // declarations.
4189  const FunctionProtoType *CanonicalFPT =
4190    MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4191  if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4192    updateExceptionSpec(*this, MD->getCanonicalDecl(),
4193                        CanonicalFPT, ExceptSpec);
4194}
4195
4196static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4197static bool isImplicitCopyAssignmentArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4198
4199void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4200  CXXRecordDecl *RD = MD->getParent();
4201  CXXSpecialMember CSM = getSpecialMember(MD);
4202
4203  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4204         "not an explicitly-defaulted special member");
4205
4206  // Whether this was the first-declared instance of the constructor.
4207  // This affects whether we implicitly add an exception spec and constexpr.
4208  bool First = MD == MD->getCanonicalDecl();
4209
4210  bool HadError = false;
4211
4212  // C++11 [dcl.fct.def.default]p1:
4213  //   A function that is explicitly defaulted shall
4214  //     -- be a special member function (checked elsewhere),
4215  //     -- have the same type (except for ref-qualifiers, and except that a
4216  //        copy operation can take a non-const reference) as an implicit
4217  //        declaration, and
4218  //     -- not have default arguments.
4219  unsigned ExpectedParams = 1;
4220  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4221    ExpectedParams = 0;
4222  if (MD->getNumParams() != ExpectedParams) {
4223    // This also checks for default arguments: a copy or move constructor with a
4224    // default argument is classified as a default constructor, and assignment
4225    // operations and destructors can't have default arguments.
4226    Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4227      << CSM << MD->getSourceRange();
4228    HadError = true;
4229  }
4230
4231  const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4232
4233  // Compute argument constness, constexpr, and triviality.
4234  bool CanHaveConstParam = false;
4235  bool Trivial = false;
4236  switch (CSM) {
4237  case CXXDefaultConstructor:
4238    Trivial = RD->hasTrivialDefaultConstructor();
4239    break;
4240  case CXXCopyConstructor:
4241    CanHaveConstParam = isImplicitCopyCtorArgConst(*this, RD);
4242    Trivial = RD->hasTrivialCopyConstructor();
4243    break;
4244  case CXXCopyAssignment:
4245    CanHaveConstParam = isImplicitCopyAssignmentArgConst(*this, RD);
4246    Trivial = RD->hasTrivialCopyAssignment();
4247    break;
4248  case CXXMoveConstructor:
4249    Trivial = RD->hasTrivialMoveConstructor();
4250    break;
4251  case CXXMoveAssignment:
4252    Trivial = RD->hasTrivialMoveAssignment();
4253    break;
4254  case CXXDestructor:
4255    Trivial = RD->hasTrivialDestructor();
4256    break;
4257  case CXXInvalid:
4258    llvm_unreachable("non-special member explicitly defaulted!");
4259  }
4260
4261  QualType ReturnType = Context.VoidTy;
4262  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4263    // Check for return type matching.
4264    ReturnType = Type->getResultType();
4265    QualType ExpectedReturnType =
4266        Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4267    if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4268      Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4269        << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4270      HadError = true;
4271    }
4272
4273    // A defaulted special member cannot have cv-qualifiers.
4274    if (Type->getTypeQuals()) {
4275      Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4276        << (CSM == CXXMoveAssignment);
4277      HadError = true;
4278    }
4279  }
4280
4281  // Check for parameter type matching.
4282  QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4283  bool HasConstParam = false;
4284  if (ExpectedParams && ArgType->isReferenceType()) {
4285    // Argument must be reference to possibly-const T.
4286    QualType ReferentType = ArgType->getPointeeType();
4287    HasConstParam = ReferentType.isConstQualified();
4288
4289    if (ReferentType.isVolatileQualified()) {
4290      Diag(MD->getLocation(),
4291           diag::err_defaulted_special_member_volatile_param) << CSM;
4292      HadError = true;
4293    }
4294
4295    if (HasConstParam && !CanHaveConstParam) {
4296      if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4297        Diag(MD->getLocation(),
4298             diag::err_defaulted_special_member_copy_const_param)
4299          << (CSM == CXXCopyAssignment);
4300        // FIXME: Explain why this special member can't be const.
4301      } else {
4302        Diag(MD->getLocation(),
4303             diag::err_defaulted_special_member_move_const_param)
4304          << (CSM == CXXMoveAssignment);
4305      }
4306      HadError = true;
4307    }
4308
4309    // If a function is explicitly defaulted on its first declaration, it shall
4310    // have the same parameter type as if it had been implicitly declared.
4311    // (Presumably this is to prevent it from being trivial?)
4312    if (!HasConstParam && CanHaveConstParam && First)
4313      Diag(MD->getLocation(),
4314           diag::err_defaulted_special_member_copy_non_const_param)
4315        << (CSM == CXXCopyAssignment);
4316  } else if (ExpectedParams) {
4317    // A copy assignment operator can take its argument by value, but a
4318    // defaulted one cannot.
4319    assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4320    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4321    HadError = true;
4322  }
4323
4324  // Rebuild the type with the implicit exception specification added, if we
4325  // are going to need it.
4326  const FunctionProtoType *ImplicitType = 0;
4327  if (First || Type->hasExceptionSpec()) {
4328    FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4329    computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4330    ImplicitType = cast<FunctionProtoType>(
4331      Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
4332  }
4333
4334  // C++11 [dcl.fct.def.default]p2:
4335  //   An explicitly-defaulted function may be declared constexpr only if it
4336  //   would have been implicitly declared as constexpr,
4337  // Do not apply this rule to members of class templates, since core issue 1358
4338  // makes such functions always instantiate to constexpr functions. For
4339  // non-constructors, this is checked elsewhere.
4340  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4341                                                     HasConstParam);
4342  if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4343      MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4344    Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4345    // FIXME: Explain why the constructor can't be constexpr.
4346    HadError = true;
4347  }
4348  //   and may have an explicit exception-specification only if it is compatible
4349  //   with the exception-specification on the implicit declaration.
4350  if (Type->hasExceptionSpec() &&
4351      CheckEquivalentExceptionSpec(
4352        PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
4353        PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
4354    HadError = true;
4355
4356  //   If a function is explicitly defaulted on its first declaration,
4357  if (First) {
4358    //  -- it is implicitly considered to be constexpr if the implicit
4359    //     definition would be,
4360    MD->setConstexpr(Constexpr);
4361
4362    //  -- it is implicitly considered to have the same exception-specification
4363    //     as if it had been implicitly declared,
4364    MD->setType(QualType(ImplicitType, 0));
4365
4366    // Such a function is also trivial if the implicitly-declared function
4367    // would have been.
4368    MD->setTrivial(Trivial);
4369  }
4370
4371  if (ShouldDeleteSpecialMember(MD, CSM)) {
4372    if (First) {
4373      MD->setDeletedAsWritten();
4374    } else {
4375      // C++11 [dcl.fct.def.default]p4:
4376      //   [For a] user-provided explicitly-defaulted function [...] if such a
4377      //   function is implicitly defined as deleted, the program is ill-formed.
4378      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4379      HadError = true;
4380    }
4381  }
4382
4383  if (HadError)
4384    MD->setInvalidDecl();
4385}
4386
4387namespace {
4388struct SpecialMemberDeletionInfo {
4389  Sema &S;
4390  CXXMethodDecl *MD;
4391  Sema::CXXSpecialMember CSM;
4392  bool Diagnose;
4393
4394  // Properties of the special member, computed for convenience.
4395  bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4396  SourceLocation Loc;
4397
4398  bool AllFieldsAreConst;
4399
4400  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4401                            Sema::CXXSpecialMember CSM, bool Diagnose)
4402    : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4403      IsConstructor(false), IsAssignment(false), IsMove(false),
4404      ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4405      AllFieldsAreConst(true) {
4406    switch (CSM) {
4407      case Sema::CXXDefaultConstructor:
4408      case Sema::CXXCopyConstructor:
4409        IsConstructor = true;
4410        break;
4411      case Sema::CXXMoveConstructor:
4412        IsConstructor = true;
4413        IsMove = true;
4414        break;
4415      case Sema::CXXCopyAssignment:
4416        IsAssignment = true;
4417        break;
4418      case Sema::CXXMoveAssignment:
4419        IsAssignment = true;
4420        IsMove = true;
4421        break;
4422      case Sema::CXXDestructor:
4423        break;
4424      case Sema::CXXInvalid:
4425        llvm_unreachable("invalid special member kind");
4426    }
4427
4428    if (MD->getNumParams()) {
4429      ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4430      VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4431    }
4432  }
4433
4434  bool inUnion() const { return MD->getParent()->isUnion(); }
4435
4436  /// Look up the corresponding special member in the given class.
4437  Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4438                                              unsigned Quals) {
4439    unsigned TQ = MD->getTypeQualifiers();
4440    // cv-qualifiers on class members don't affect default ctor / dtor calls.
4441    if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4442      Quals = 0;
4443    return S.LookupSpecialMember(Class, CSM,
4444                                 ConstArg || (Quals & Qualifiers::Const),
4445                                 VolatileArg || (Quals & Qualifiers::Volatile),
4446                                 MD->getRefQualifier() == RQ_RValue,
4447                                 TQ & Qualifiers::Const,
4448                                 TQ & Qualifiers::Volatile);
4449  }
4450
4451  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4452
4453  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4454  bool shouldDeleteForField(FieldDecl *FD);
4455  bool shouldDeleteForAllConstMembers();
4456
4457  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4458                                     unsigned Quals);
4459  bool shouldDeleteForSubobjectCall(Subobject Subobj,
4460                                    Sema::SpecialMemberOverloadResult *SMOR,
4461                                    bool IsDtorCallInCtor);
4462
4463  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4464};
4465}
4466
4467/// Is the given special member inaccessible when used on the given
4468/// sub-object.
4469bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4470                                             CXXMethodDecl *target) {
4471  /// If we're operating on a base class, the object type is the
4472  /// type of this special member.
4473  QualType objectTy;
4474  AccessSpecifier access = target->getAccess();
4475  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4476    objectTy = S.Context.getTypeDeclType(MD->getParent());
4477    access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4478
4479  // If we're operating on a field, the object type is the type of the field.
4480  } else {
4481    objectTy = S.Context.getTypeDeclType(target->getParent());
4482  }
4483
4484  return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4485}
4486
4487/// Check whether we should delete a special member due to the implicit
4488/// definition containing a call to a special member of a subobject.
4489bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4490    Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4491    bool IsDtorCallInCtor) {
4492  CXXMethodDecl *Decl = SMOR->getMethod();
4493  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4494
4495  int DiagKind = -1;
4496
4497  if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4498    DiagKind = !Decl ? 0 : 1;
4499  else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4500    DiagKind = 2;
4501  else if (!isAccessible(Subobj, Decl))
4502    DiagKind = 3;
4503  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4504           !Decl->isTrivial()) {
4505    // A member of a union must have a trivial corresponding special member.
4506    // As a weird special case, a destructor call from a union's constructor
4507    // must be accessible and non-deleted, but need not be trivial. Such a
4508    // destructor is never actually called, but is semantically checked as
4509    // if it were.
4510    DiagKind = 4;
4511  }
4512
4513  if (DiagKind == -1)
4514    return false;
4515
4516  if (Diagnose) {
4517    if (Field) {
4518      S.Diag(Field->getLocation(),
4519             diag::note_deleted_special_member_class_subobject)
4520        << CSM << MD->getParent() << /*IsField*/true
4521        << Field << DiagKind << IsDtorCallInCtor;
4522    } else {
4523      CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4524      S.Diag(Base->getLocStart(),
4525             diag::note_deleted_special_member_class_subobject)
4526        << CSM << MD->getParent() << /*IsField*/false
4527        << Base->getType() << DiagKind << IsDtorCallInCtor;
4528    }
4529
4530    if (DiagKind == 1)
4531      S.NoteDeletedFunction(Decl);
4532    // FIXME: Explain inaccessibility if DiagKind == 3.
4533  }
4534
4535  return true;
4536}
4537
4538/// Check whether we should delete a special member function due to having a
4539/// direct or virtual base class or non-static data member of class type M.
4540bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4541    CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
4542  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4543
4544  // C++11 [class.ctor]p5:
4545  // -- any direct or virtual base class, or non-static data member with no
4546  //    brace-or-equal-initializer, has class type M (or array thereof) and
4547  //    either M has no default constructor or overload resolution as applied
4548  //    to M's default constructor results in an ambiguity or in a function
4549  //    that is deleted or inaccessible
4550  // C++11 [class.copy]p11, C++11 [class.copy]p23:
4551  // -- a direct or virtual base class B that cannot be copied/moved because
4552  //    overload resolution, as applied to B's corresponding special member,
4553  //    results in an ambiguity or a function that is deleted or inaccessible
4554  //    from the defaulted special member
4555  // C++11 [class.dtor]p5:
4556  // -- any direct or virtual base class [...] has a type with a destructor
4557  //    that is deleted or inaccessible
4558  if (!(CSM == Sema::CXXDefaultConstructor &&
4559        Field && Field->hasInClassInitializer()) &&
4560      shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
4561    return true;
4562
4563  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4564  // -- any direct or virtual base class or non-static data member has a
4565  //    type with a destructor that is deleted or inaccessible
4566  if (IsConstructor) {
4567    Sema::SpecialMemberOverloadResult *SMOR =
4568        S.LookupSpecialMember(Class, Sema::CXXDestructor,
4569                              false, false, false, false, false);
4570    if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4571      return true;
4572  }
4573
4574  return false;
4575}
4576
4577/// Check whether we should delete a special member function due to the class
4578/// having a particular direct or virtual base class.
4579bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4580  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4581  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
4582}
4583
4584/// Check whether we should delete a special member function due to the class
4585/// having a particular non-static data member.
4586bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4587  QualType FieldType = S.Context.getBaseElementType(FD->getType());
4588  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4589
4590  if (CSM == Sema::CXXDefaultConstructor) {
4591    // For a default constructor, all references must be initialized in-class
4592    // and, if a union, it must have a non-const member.
4593    if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4594      if (Diagnose)
4595        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4596          << MD->getParent() << FD << FieldType << /*Reference*/0;
4597      return true;
4598    }
4599    // C++11 [class.ctor]p5: any non-variant non-static data member of
4600    // const-qualified type (or array thereof) with no
4601    // brace-or-equal-initializer does not have a user-provided default
4602    // constructor.
4603    if (!inUnion() && FieldType.isConstQualified() &&
4604        !FD->hasInClassInitializer() &&
4605        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4606      if (Diagnose)
4607        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4608          << MD->getParent() << FD << FD->getType() << /*Const*/1;
4609      return true;
4610    }
4611
4612    if (inUnion() && !FieldType.isConstQualified())
4613      AllFieldsAreConst = false;
4614  } else if (CSM == Sema::CXXCopyConstructor) {
4615    // For a copy constructor, data members must not be of rvalue reference
4616    // type.
4617    if (FieldType->isRValueReferenceType()) {
4618      if (Diagnose)
4619        S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4620          << MD->getParent() << FD << FieldType;
4621      return true;
4622    }
4623  } else if (IsAssignment) {
4624    // For an assignment operator, data members must not be of reference type.
4625    if (FieldType->isReferenceType()) {
4626      if (Diagnose)
4627        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4628          << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4629      return true;
4630    }
4631    if (!FieldRecord && FieldType.isConstQualified()) {
4632      // C++11 [class.copy]p23:
4633      // -- a non-static data member of const non-class type (or array thereof)
4634      if (Diagnose)
4635        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4636          << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
4637      return true;
4638    }
4639  }
4640
4641  if (FieldRecord) {
4642    // Some additional restrictions exist on the variant members.
4643    if (!inUnion() && FieldRecord->isUnion() &&
4644        FieldRecord->isAnonymousStructOrUnion()) {
4645      bool AllVariantFieldsAreConst = true;
4646
4647      // FIXME: Handle anonymous unions declared within anonymous unions.
4648      for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4649                                         UE = FieldRecord->field_end();
4650           UI != UE; ++UI) {
4651        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4652
4653        if (!UnionFieldType.isConstQualified())
4654          AllVariantFieldsAreConst = false;
4655
4656        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4657        if (UnionFieldRecord &&
4658            shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4659                                          UnionFieldType.getCVRQualifiers()))
4660          return true;
4661      }
4662
4663      // At least one member in each anonymous union must be non-const
4664      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4665          FieldRecord->field_begin() != FieldRecord->field_end()) {
4666        if (Diagnose)
4667          S.Diag(FieldRecord->getLocation(),
4668                 diag::note_deleted_default_ctor_all_const)
4669            << MD->getParent() << /*anonymous union*/1;
4670        return true;
4671      }
4672
4673      // Don't check the implicit member of the anonymous union type.
4674      // This is technically non-conformant, but sanity demands it.
4675      return false;
4676    }
4677
4678    if (shouldDeleteForClassSubobject(FieldRecord, FD,
4679                                      FieldType.getCVRQualifiers()))
4680      return true;
4681  }
4682
4683  return false;
4684}
4685
4686/// C++11 [class.ctor] p5:
4687///   A defaulted default constructor for a class X is defined as deleted if
4688/// X is a union and all of its variant members are of const-qualified type.
4689bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4690  // This is a silly definition, because it gives an empty union a deleted
4691  // default constructor. Don't do that.
4692  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4693      (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4694    if (Diagnose)
4695      S.Diag(MD->getParent()->getLocation(),
4696             diag::note_deleted_default_ctor_all_const)
4697        << MD->getParent() << /*not anonymous union*/0;
4698    return true;
4699  }
4700  return false;
4701}
4702
4703/// Determine whether a defaulted special member function should be defined as
4704/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4705/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
4706bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4707                                     bool Diagnose) {
4708  if (MD->isInvalidDecl())
4709    return false;
4710  CXXRecordDecl *RD = MD->getParent();
4711  assert(!RD->isDependentType() && "do deletion after instantiation");
4712  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4713    return false;
4714
4715  // C++11 [expr.lambda.prim]p19:
4716  //   The closure type associated with a lambda-expression has a
4717  //   deleted (8.4.3) default constructor and a deleted copy
4718  //   assignment operator.
4719  if (RD->isLambda() &&
4720      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4721    if (Diagnose)
4722      Diag(RD->getLocation(), diag::note_lambda_decl);
4723    return true;
4724  }
4725
4726  // For an anonymous struct or union, the copy and assignment special members
4727  // will never be used, so skip the check. For an anonymous union declared at
4728  // namespace scope, the constructor and destructor are used.
4729  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4730      RD->isAnonymousStructOrUnion())
4731    return false;
4732
4733  // C++11 [class.copy]p7, p18:
4734  //   If the class definition declares a move constructor or move assignment
4735  //   operator, an implicitly declared copy constructor or copy assignment
4736  //   operator is defined as deleted.
4737  if (MD->isImplicit() &&
4738      (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4739    CXXMethodDecl *UserDeclaredMove = 0;
4740
4741    // In Microsoft mode, a user-declared move only causes the deletion of the
4742    // corresponding copy operation, not both copy operations.
4743    if (RD->hasUserDeclaredMoveConstructor() &&
4744        (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4745      if (!Diagnose) return true;
4746      UserDeclaredMove = RD->getMoveConstructor();
4747      assert(UserDeclaredMove);
4748    } else if (RD->hasUserDeclaredMoveAssignment() &&
4749               (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4750      if (!Diagnose) return true;
4751      UserDeclaredMove = RD->getMoveAssignmentOperator();
4752      assert(UserDeclaredMove);
4753    }
4754
4755    if (UserDeclaredMove) {
4756      Diag(UserDeclaredMove->getLocation(),
4757           diag::note_deleted_copy_user_declared_move)
4758        << (CSM == CXXCopyAssignment) << RD
4759        << UserDeclaredMove->isMoveAssignmentOperator();
4760      return true;
4761    }
4762  }
4763
4764  // Do access control from the special member function
4765  ContextRAII MethodContext(*this, MD);
4766
4767  // C++11 [class.dtor]p5:
4768  // -- for a virtual destructor, lookup of the non-array deallocation function
4769  //    results in an ambiguity or in a function that is deleted or inaccessible
4770  if (CSM == CXXDestructor && MD->isVirtual()) {
4771    FunctionDecl *OperatorDelete = 0;
4772    DeclarationName Name =
4773      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4774    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
4775                                 OperatorDelete, false)) {
4776      if (Diagnose)
4777        Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
4778      return true;
4779    }
4780  }
4781
4782  SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
4783
4784  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4785                                          BE = RD->bases_end(); BI != BE; ++BI)
4786    if (!BI->isVirtual() &&
4787        SMI.shouldDeleteForBase(BI))
4788      return true;
4789
4790  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4791                                          BE = RD->vbases_end(); BI != BE; ++BI)
4792    if (SMI.shouldDeleteForBase(BI))
4793      return true;
4794
4795  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4796                                     FE = RD->field_end(); FI != FE; ++FI)
4797    if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4798        SMI.shouldDeleteForField(*FI))
4799      return true;
4800
4801  if (SMI.shouldDeleteForAllConstMembers())
4802    return true;
4803
4804  return false;
4805}
4806
4807/// \brief Data used with FindHiddenVirtualMethod
4808namespace {
4809  struct FindHiddenVirtualMethodData {
4810    Sema *S;
4811    CXXMethodDecl *Method;
4812    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4813    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4814  };
4815}
4816
4817/// \brief Check whether any most overriden method from MD in Methods
4818static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
4819                   const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
4820  if (MD->size_overridden_methods() == 0)
4821    return Methods.count(MD->getCanonicalDecl());
4822  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4823                                      E = MD->end_overridden_methods();
4824       I != E; ++I)
4825    if (CheckMostOverridenMethods(*I, Methods))
4826      return true;
4827  return false;
4828}
4829
4830/// \brief Member lookup function that determines whether a given C++
4831/// method overloads virtual methods in a base class without overriding any,
4832/// to be used with CXXRecordDecl::lookupInBases().
4833static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4834                                    CXXBasePath &Path,
4835                                    void *UserData) {
4836  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4837
4838  FindHiddenVirtualMethodData &Data
4839    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4840
4841  DeclarationName Name = Data.Method->getDeclName();
4842  assert(Name.getNameKind() == DeclarationName::Identifier);
4843
4844  bool foundSameNameMethod = false;
4845  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4846  for (Path.Decls = BaseRecord->lookup(Name);
4847       Path.Decls.first != Path.Decls.second;
4848       ++Path.Decls.first) {
4849    NamedDecl *D = *Path.Decls.first;
4850    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4851      MD = MD->getCanonicalDecl();
4852      foundSameNameMethod = true;
4853      // Interested only in hidden virtual methods.
4854      if (!MD->isVirtual())
4855        continue;
4856      // If the method we are checking overrides a method from its base
4857      // don't warn about the other overloaded methods.
4858      if (!Data.S->IsOverload(Data.Method, MD, false))
4859        return true;
4860      // Collect the overload only if its hidden.
4861      if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
4862        overloadedMethods.push_back(MD);
4863    }
4864  }
4865
4866  if (foundSameNameMethod)
4867    Data.OverloadedMethods.append(overloadedMethods.begin(),
4868                                   overloadedMethods.end());
4869  return foundSameNameMethod;
4870}
4871
4872/// \brief Add the most overriden methods from MD to Methods
4873static void AddMostOverridenMethods(const CXXMethodDecl *MD,
4874                         llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
4875  if (MD->size_overridden_methods() == 0)
4876    Methods.insert(MD->getCanonicalDecl());
4877  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4878                                      E = MD->end_overridden_methods();
4879       I != E; ++I)
4880    AddMostOverridenMethods(*I, Methods);
4881}
4882
4883/// \brief See if a method overloads virtual methods in a base class without
4884/// overriding any.
4885void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4886  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4887                               MD->getLocation()) == DiagnosticsEngine::Ignored)
4888    return;
4889  if (!MD->getDeclName().isIdentifier())
4890    return;
4891
4892  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4893                     /*bool RecordPaths=*/false,
4894                     /*bool DetectVirtual=*/false);
4895  FindHiddenVirtualMethodData Data;
4896  Data.Method = MD;
4897  Data.S = this;
4898
4899  // Keep the base methods that were overriden or introduced in the subclass
4900  // by 'using' in a set. A base method not in this set is hidden.
4901  for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4902       res.first != res.second; ++res.first) {
4903    NamedDecl *ND = *res.first;
4904    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4905      ND = shad->getTargetDecl();
4906    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4907      AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
4908  }
4909
4910  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4911      !Data.OverloadedMethods.empty()) {
4912    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4913      << MD << (Data.OverloadedMethods.size() > 1);
4914
4915    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4916      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4917      Diag(overloadedMD->getLocation(),
4918           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4919    }
4920  }
4921}
4922
4923void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4924                                             Decl *TagDecl,
4925                                             SourceLocation LBrac,
4926                                             SourceLocation RBrac,
4927                                             AttributeList *AttrList) {
4928  if (!TagDecl)
4929    return;
4930
4931  AdjustDeclIfTemplate(TagDecl);
4932
4933  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4934    if (l->getKind() != AttributeList::AT_Visibility)
4935      continue;
4936    l->setInvalid();
4937    Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
4938      l->getName();
4939  }
4940
4941  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
4942              // strict aliasing violation!
4943              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
4944              FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
4945
4946  CheckCompletedCXXClass(
4947                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
4948}
4949
4950/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4951/// special functions, such as the default constructor, copy
4952/// constructor, or destructor, to the given C++ class (C++
4953/// [special]p1).  This routine can only be executed just before the
4954/// definition of the class is complete.
4955void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
4956  if (!ClassDecl->hasUserDeclaredConstructor())
4957    ++ASTContext::NumImplicitDefaultConstructors;
4958
4959  if (!ClassDecl->hasUserDeclaredCopyConstructor())
4960    ++ASTContext::NumImplicitCopyConstructors;
4961
4962  if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
4963    ++ASTContext::NumImplicitMoveConstructors;
4964
4965  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4966    ++ASTContext::NumImplicitCopyAssignmentOperators;
4967
4968    // If we have a dynamic class, then the copy assignment operator may be
4969    // virtual, so we have to declare it immediately. This ensures that, e.g.,
4970    // it shows up in the right place in the vtable and that we diagnose
4971    // problems with the implicit exception specification.
4972    if (ClassDecl->isDynamicClass())
4973      DeclareImplicitCopyAssignment(ClassDecl);
4974  }
4975
4976  if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
4977    ++ASTContext::NumImplicitMoveAssignmentOperators;
4978
4979    // Likewise for the move assignment operator.
4980    if (ClassDecl->isDynamicClass())
4981      DeclareImplicitMoveAssignment(ClassDecl);
4982  }
4983
4984  if (!ClassDecl->hasUserDeclaredDestructor()) {
4985    ++ASTContext::NumImplicitDestructors;
4986
4987    // If we have a dynamic class, then the destructor may be virtual, so we
4988    // have to declare the destructor immediately. This ensures that, e.g., it
4989    // shows up in the right place in the vtable and that we diagnose problems
4990    // with the implicit exception specification.
4991    if (ClassDecl->isDynamicClass())
4992      DeclareImplicitDestructor(ClassDecl);
4993  }
4994}
4995
4996void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4997  if (!D)
4998    return;
4999
5000  int NumParamList = D->getNumTemplateParameterLists();
5001  for (int i = 0; i < NumParamList; i++) {
5002    TemplateParameterList* Params = D->getTemplateParameterList(i);
5003    for (TemplateParameterList::iterator Param = Params->begin(),
5004                                      ParamEnd = Params->end();
5005          Param != ParamEnd; ++Param) {
5006      NamedDecl *Named = cast<NamedDecl>(*Param);
5007      if (Named->getDeclName()) {
5008        S->AddDecl(Named);
5009        IdResolver.AddDecl(Named);
5010      }
5011    }
5012  }
5013}
5014
5015void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
5016  if (!D)
5017    return;
5018
5019  TemplateParameterList *Params = 0;
5020  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5021    Params = Template->getTemplateParameters();
5022  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5023           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5024    Params = PartialSpec->getTemplateParameters();
5025  else
5026    return;
5027
5028  for (TemplateParameterList::iterator Param = Params->begin(),
5029                                    ParamEnd = Params->end();
5030       Param != ParamEnd; ++Param) {
5031    NamedDecl *Named = cast<NamedDecl>(*Param);
5032    if (Named->getDeclName()) {
5033      S->AddDecl(Named);
5034      IdResolver.AddDecl(Named);
5035    }
5036  }
5037}
5038
5039void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5040  if (!RecordD) return;
5041  AdjustDeclIfTemplate(RecordD);
5042  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
5043  PushDeclContext(S, Record);
5044}
5045
5046void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5047  if (!RecordD) return;
5048  PopDeclContext();
5049}
5050
5051/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5052/// parsing a top-level (non-nested) C++ class, and we are now
5053/// parsing those parts of the given Method declaration that could
5054/// not be parsed earlier (C++ [class.mem]p2), such as default
5055/// arguments. This action should enter the scope of the given
5056/// Method declaration as if we had just parsed the qualified method
5057/// name. However, it should not bring the parameters into scope;
5058/// that will be performed by ActOnDelayedCXXMethodParameter.
5059void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5060}
5061
5062/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5063/// C++ method declaration. We're (re-)introducing the given
5064/// function parameter into scope for use in parsing later parts of
5065/// the method declaration. For example, we could see an
5066/// ActOnParamDefaultArgument event for this parameter.
5067void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
5068  if (!ParamD)
5069    return;
5070
5071  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
5072
5073  // If this parameter has an unparsed default argument, clear it out
5074  // to make way for the parsed default argument.
5075  if (Param->hasUnparsedDefaultArg())
5076    Param->setDefaultArg(0);
5077
5078  S->AddDecl(Param);
5079  if (Param->getDeclName())
5080    IdResolver.AddDecl(Param);
5081}
5082
5083/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5084/// processing the delayed method declaration for Method. The method
5085/// declaration is now considered finished. There may be a separate
5086/// ActOnStartOfFunctionDef action later (not necessarily
5087/// immediately!) for this method, if it was also defined inside the
5088/// class body.
5089void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5090  if (!MethodD)
5091    return;
5092
5093  AdjustDeclIfTemplate(MethodD);
5094
5095  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
5096
5097  // Now that we have our default arguments, check the constructor
5098  // again. It could produce additional diagnostics or affect whether
5099  // the class has implicitly-declared destructors, among other
5100  // things.
5101  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5102    CheckConstructor(Constructor);
5103
5104  // Check the default arguments, which we may have added.
5105  if (!Method->isInvalidDecl())
5106    CheckCXXDefaultArguments(Method);
5107}
5108
5109/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
5110/// the well-formedness of the constructor declarator @p D with type @p
5111/// R. If there are any errors in the declarator, this routine will
5112/// emit diagnostics and set the invalid bit to true.  In any case, the type
5113/// will be updated to reflect a well-formed type for the constructor and
5114/// returned.
5115QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
5116                                          StorageClass &SC) {
5117  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5118
5119  // C++ [class.ctor]p3:
5120  //   A constructor shall not be virtual (10.3) or static (9.4). A
5121  //   constructor can be invoked for a const, volatile or const
5122  //   volatile object. A constructor shall not be declared const,
5123  //   volatile, or const volatile (9.3.2).
5124  if (isVirtual) {
5125    if (!D.isInvalidType())
5126      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5127        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5128        << SourceRange(D.getIdentifierLoc());
5129    D.setInvalidType();
5130  }
5131  if (SC == SC_Static) {
5132    if (!D.isInvalidType())
5133      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5134        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5135        << SourceRange(D.getIdentifierLoc());
5136    D.setInvalidType();
5137    SC = SC_None;
5138  }
5139
5140  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5141  if (FTI.TypeQuals != 0) {
5142    if (FTI.TypeQuals & Qualifiers::Const)
5143      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5144        << "const" << SourceRange(D.getIdentifierLoc());
5145    if (FTI.TypeQuals & Qualifiers::Volatile)
5146      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5147        << "volatile" << SourceRange(D.getIdentifierLoc());
5148    if (FTI.TypeQuals & Qualifiers::Restrict)
5149      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5150        << "restrict" << SourceRange(D.getIdentifierLoc());
5151    D.setInvalidType();
5152  }
5153
5154  // C++0x [class.ctor]p4:
5155  //   A constructor shall not be declared with a ref-qualifier.
5156  if (FTI.hasRefQualifier()) {
5157    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5158      << FTI.RefQualifierIsLValueRef
5159      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5160    D.setInvalidType();
5161  }
5162
5163  // Rebuild the function type "R" without any type qualifiers (in
5164  // case any of the errors above fired) and with "void" as the
5165  // return type, since constructors don't have return types.
5166  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5167  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5168    return R;
5169
5170  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5171  EPI.TypeQuals = 0;
5172  EPI.RefQualifier = RQ_None;
5173
5174  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
5175                                 Proto->getNumArgs(), EPI);
5176}
5177
5178/// CheckConstructor - Checks a fully-formed constructor for
5179/// well-formedness, issuing any diagnostics required. Returns true if
5180/// the constructor declarator is invalid.
5181void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5182  CXXRecordDecl *ClassDecl
5183    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5184  if (!ClassDecl)
5185    return Constructor->setInvalidDecl();
5186
5187  // C++ [class.copy]p3:
5188  //   A declaration of a constructor for a class X is ill-formed if
5189  //   its first parameter is of type (optionally cv-qualified) X and
5190  //   either there are no other parameters or else all other
5191  //   parameters have default arguments.
5192  if (!Constructor->isInvalidDecl() &&
5193      ((Constructor->getNumParams() == 1) ||
5194       (Constructor->getNumParams() > 1 &&
5195        Constructor->getParamDecl(1)->hasDefaultArg())) &&
5196      Constructor->getTemplateSpecializationKind()
5197                                              != TSK_ImplicitInstantiation) {
5198    QualType ParamType = Constructor->getParamDecl(0)->getType();
5199    QualType ClassTy = Context.getTagDeclType(ClassDecl);
5200    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5201      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5202      const char *ConstRef
5203        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5204                                                        : " const &";
5205      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5206        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5207
5208      // FIXME: Rather that making the constructor invalid, we should endeavor
5209      // to fix the type.
5210      Constructor->setInvalidDecl();
5211    }
5212  }
5213}
5214
5215/// CheckDestructor - Checks a fully-formed destructor definition for
5216/// well-formedness, issuing any diagnostics required.  Returns true
5217/// on error.
5218bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5219  CXXRecordDecl *RD = Destructor->getParent();
5220
5221  if (Destructor->isVirtual()) {
5222    SourceLocation Loc;
5223
5224    if (!Destructor->isImplicit())
5225      Loc = Destructor->getLocation();
5226    else
5227      Loc = RD->getLocation();
5228
5229    // If we have a virtual destructor, look up the deallocation function
5230    FunctionDecl *OperatorDelete = 0;
5231    DeclarationName Name =
5232    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5233    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5234      return true;
5235
5236    MarkFunctionReferenced(Loc, OperatorDelete);
5237
5238    Destructor->setOperatorDelete(OperatorDelete);
5239  }
5240
5241  return false;
5242}
5243
5244static inline bool
5245FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5246  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5247          FTI.ArgInfo[0].Param &&
5248          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5249}
5250
5251/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5252/// the well-formednes of the destructor declarator @p D with type @p
5253/// R. If there are any errors in the declarator, this routine will
5254/// emit diagnostics and set the declarator to invalid.  Even if this happens,
5255/// will be updated to reflect a well-formed type for the destructor and
5256/// returned.
5257QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5258                                         StorageClass& SC) {
5259  // C++ [class.dtor]p1:
5260  //   [...] A typedef-name that names a class is a class-name
5261  //   (7.1.3); however, a typedef-name that names a class shall not
5262  //   be used as the identifier in the declarator for a destructor
5263  //   declaration.
5264  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5265  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5266    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5267      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5268  else if (const TemplateSpecializationType *TST =
5269             DeclaratorType->getAs<TemplateSpecializationType>())
5270    if (TST->isTypeAlias())
5271      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5272        << DeclaratorType << 1;
5273
5274  // C++ [class.dtor]p2:
5275  //   A destructor is used to destroy objects of its class type. A
5276  //   destructor takes no parameters, and no return type can be
5277  //   specified for it (not even void). The address of a destructor
5278  //   shall not be taken. A destructor shall not be static. A
5279  //   destructor can be invoked for a const, volatile or const
5280  //   volatile object. A destructor shall not be declared const,
5281  //   volatile or const volatile (9.3.2).
5282  if (SC == SC_Static) {
5283    if (!D.isInvalidType())
5284      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5285        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5286        << SourceRange(D.getIdentifierLoc())
5287        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5288
5289    SC = SC_None;
5290  }
5291  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5292    // Destructors don't have return types, but the parser will
5293    // happily parse something like:
5294    //
5295    //   class X {
5296    //     float ~X();
5297    //   };
5298    //
5299    // The return type will be eliminated later.
5300    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5301      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5302      << SourceRange(D.getIdentifierLoc());
5303  }
5304
5305  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5306  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5307    if (FTI.TypeQuals & Qualifiers::Const)
5308      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5309        << "const" << SourceRange(D.getIdentifierLoc());
5310    if (FTI.TypeQuals & Qualifiers::Volatile)
5311      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5312        << "volatile" << SourceRange(D.getIdentifierLoc());
5313    if (FTI.TypeQuals & Qualifiers::Restrict)
5314      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5315        << "restrict" << SourceRange(D.getIdentifierLoc());
5316    D.setInvalidType();
5317  }
5318
5319  // C++0x [class.dtor]p2:
5320  //   A destructor shall not be declared with a ref-qualifier.
5321  if (FTI.hasRefQualifier()) {
5322    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5323      << FTI.RefQualifierIsLValueRef
5324      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5325    D.setInvalidType();
5326  }
5327
5328  // Make sure we don't have any parameters.
5329  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5330    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5331
5332    // Delete the parameters.
5333    FTI.freeArgs();
5334    D.setInvalidType();
5335  }
5336
5337  // Make sure the destructor isn't variadic.
5338  if (FTI.isVariadic) {
5339    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5340    D.setInvalidType();
5341  }
5342
5343  // Rebuild the function type "R" without any type qualifiers or
5344  // parameters (in case any of the errors above fired) and with
5345  // "void" as the return type, since destructors don't have return
5346  // types.
5347  if (!D.isInvalidType())
5348    return R;
5349
5350  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5351  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5352  EPI.Variadic = false;
5353  EPI.TypeQuals = 0;
5354  EPI.RefQualifier = RQ_None;
5355  return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
5356}
5357
5358/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5359/// well-formednes of the conversion function declarator @p D with
5360/// type @p R. If there are any errors in the declarator, this routine
5361/// will emit diagnostics and return true. Otherwise, it will return
5362/// false. Either way, the type @p R will be updated to reflect a
5363/// well-formed type for the conversion operator.
5364void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
5365                                     StorageClass& SC) {
5366  // C++ [class.conv.fct]p1:
5367  //   Neither parameter types nor return type can be specified. The
5368  //   type of a conversion function (8.3.5) is "function taking no
5369  //   parameter returning conversion-type-id."
5370  if (SC == SC_Static) {
5371    if (!D.isInvalidType())
5372      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5373        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5374        << SourceRange(D.getIdentifierLoc());
5375    D.setInvalidType();
5376    SC = SC_None;
5377  }
5378
5379  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5380
5381  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5382    // Conversion functions don't have return types, but the parser will
5383    // happily parse something like:
5384    //
5385    //   class X {
5386    //     float operator bool();
5387    //   };
5388    //
5389    // The return type will be changed later anyway.
5390    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5391      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5392      << SourceRange(D.getIdentifierLoc());
5393    D.setInvalidType();
5394  }
5395
5396  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5397
5398  // Make sure we don't have any parameters.
5399  if (Proto->getNumArgs() > 0) {
5400    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5401
5402    // Delete the parameters.
5403    D.getFunctionTypeInfo().freeArgs();
5404    D.setInvalidType();
5405  } else if (Proto->isVariadic()) {
5406    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
5407    D.setInvalidType();
5408  }
5409
5410  // Diagnose "&operator bool()" and other such nonsense.  This
5411  // is actually a gcc extension which we don't support.
5412  if (Proto->getResultType() != ConvType) {
5413    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5414      << Proto->getResultType();
5415    D.setInvalidType();
5416    ConvType = Proto->getResultType();
5417  }
5418
5419  // C++ [class.conv.fct]p4:
5420  //   The conversion-type-id shall not represent a function type nor
5421  //   an array type.
5422  if (ConvType->isArrayType()) {
5423    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5424    ConvType = Context.getPointerType(ConvType);
5425    D.setInvalidType();
5426  } else if (ConvType->isFunctionType()) {
5427    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5428    ConvType = Context.getPointerType(ConvType);
5429    D.setInvalidType();
5430  }
5431
5432  // Rebuild the function type "R" without any parameters (in case any
5433  // of the errors above fired) and with the conversion type as the
5434  // return type.
5435  if (D.isInvalidType())
5436    R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
5437
5438  // C++0x explicit conversion operators.
5439  if (D.getDeclSpec().isExplicitSpecified())
5440    Diag(D.getDeclSpec().getExplicitSpecLoc(),
5441         getLangOpts().CPlusPlus0x ?
5442           diag::warn_cxx98_compat_explicit_conversion_functions :
5443           diag::ext_explicit_conversion_functions)
5444      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
5445}
5446
5447/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5448/// the declaration of the given C++ conversion function. This routine
5449/// is responsible for recording the conversion function in the C++
5450/// class, if possible.
5451Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
5452  assert(Conversion && "Expected to receive a conversion function declaration");
5453
5454  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
5455
5456  // Make sure we aren't redeclaring the conversion function.
5457  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
5458
5459  // C++ [class.conv.fct]p1:
5460  //   [...] A conversion function is never used to convert a
5461  //   (possibly cv-qualified) object to the (possibly cv-qualified)
5462  //   same object type (or a reference to it), to a (possibly
5463  //   cv-qualified) base class of that type (or a reference to it),
5464  //   or to (possibly cv-qualified) void.
5465  // FIXME: Suppress this warning if the conversion function ends up being a
5466  // virtual function that overrides a virtual function in a base class.
5467  QualType ClassType
5468    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5469  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
5470    ConvType = ConvTypeRef->getPointeeType();
5471  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5472      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5473    /* Suppress diagnostics for instantiations. */;
5474  else if (ConvType->isRecordType()) {
5475    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5476    if (ConvType == ClassType)
5477      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
5478        << ClassType;
5479    else if (IsDerivedFrom(ClassType, ConvType))
5480      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
5481        <<  ClassType << ConvType;
5482  } else if (ConvType->isVoidType()) {
5483    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
5484      << ClassType << ConvType;
5485  }
5486
5487  if (FunctionTemplateDecl *ConversionTemplate
5488                                = Conversion->getDescribedFunctionTemplate())
5489    return ConversionTemplate;
5490
5491  return Conversion;
5492}
5493
5494//===----------------------------------------------------------------------===//
5495// Namespace Handling
5496//===----------------------------------------------------------------------===//
5497
5498/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
5499/// reopened.
5500static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
5501                                            SourceLocation Loc,
5502                                            IdentifierInfo *II, bool *IsInline,
5503                                            NamespaceDecl *PrevNS) {
5504  assert(*IsInline != PrevNS->isInline());
5505
5506  // HACK: Work around a bug in libstdc++4.6's <atomic>, where
5507  // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
5508  // inline namespaces, with the intention of bringing names into namespace std.
5509  //
5510  // We support this just well enough to get that case working; this is not
5511  // sufficient to support reopening namespaces as inline in general.
5512  if (*IsInline && II && II->getName().startswith("__atomic") &&
5513      S.getSourceManager().isInSystemHeader(Loc)) {
5514    // Mark all prior declarations of the namespace as inline.
5515    for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
5516         NS = NS->getPreviousDecl())
5517      NS->setInline(*IsInline);
5518    // Patch up the lookup table for the containing namespace. This isn't really
5519    // correct, but it's good enough for this particular case.
5520    for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
5521                                    E = PrevNS->decls_end(); I != E; ++I)
5522      if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
5523        PrevNS->getParent()->makeDeclVisibleInContext(ND);
5524    return;
5525  }
5526
5527  if (PrevNS->isInline())
5528    // The user probably just forgot the 'inline', so suggest that it
5529    // be added back.
5530    S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5531      << FixItHint::CreateInsertion(KeywordLoc, "inline ");
5532  else
5533    S.Diag(Loc, diag::err_inline_namespace_mismatch)
5534      << IsInline;
5535
5536  S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
5537  *IsInline = PrevNS->isInline();
5538}
5539
5540/// ActOnStartNamespaceDef - This is called at the start of a namespace
5541/// definition.
5542Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
5543                                   SourceLocation InlineLoc,
5544                                   SourceLocation NamespaceLoc,
5545                                   SourceLocation IdentLoc,
5546                                   IdentifierInfo *II,
5547                                   SourceLocation LBrace,
5548                                   AttributeList *AttrList) {
5549  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5550  // For anonymous namespace, take the location of the left brace.
5551  SourceLocation Loc = II ? IdentLoc : LBrace;
5552  bool IsInline = InlineLoc.isValid();
5553  bool IsInvalid = false;
5554  bool IsStd = false;
5555  bool AddToKnown = false;
5556  Scope *DeclRegionScope = NamespcScope->getParent();
5557
5558  NamespaceDecl *PrevNS = 0;
5559  if (II) {
5560    // C++ [namespace.def]p2:
5561    //   The identifier in an original-namespace-definition shall not
5562    //   have been previously defined in the declarative region in
5563    //   which the original-namespace-definition appears. The
5564    //   identifier in an original-namespace-definition is the name of
5565    //   the namespace. Subsequently in that declarative region, it is
5566    //   treated as an original-namespace-name.
5567    //
5568    // Since namespace names are unique in their scope, and we don't
5569    // look through using directives, just look for any ordinary names.
5570
5571    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5572    Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5573    Decl::IDNS_Namespace;
5574    NamedDecl *PrevDecl = 0;
5575    for (DeclContext::lookup_result R
5576         = CurContext->getRedeclContext()->lookup(II);
5577         R.first != R.second; ++R.first) {
5578      if ((*R.first)->getIdentifierNamespace() & IDNS) {
5579        PrevDecl = *R.first;
5580        break;
5581      }
5582    }
5583
5584    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5585
5586    if (PrevNS) {
5587      // This is an extended namespace definition.
5588      if (IsInline != PrevNS->isInline())
5589        DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
5590                                        &IsInline, PrevNS);
5591    } else if (PrevDecl) {
5592      // This is an invalid name redefinition.
5593      Diag(Loc, diag::err_redefinition_different_kind)
5594        << II;
5595      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5596      IsInvalid = true;
5597      // Continue on to push Namespc as current DeclContext and return it.
5598    } else if (II->isStr("std") &&
5599               CurContext->getRedeclContext()->isTranslationUnit()) {
5600      // This is the first "real" definition of the namespace "std", so update
5601      // our cache of the "std" namespace to point at this definition.
5602      PrevNS = getStdNamespace();
5603      IsStd = true;
5604      AddToKnown = !IsInline;
5605    } else {
5606      // We've seen this namespace for the first time.
5607      AddToKnown = !IsInline;
5608    }
5609  } else {
5610    // Anonymous namespaces.
5611
5612    // Determine whether the parent already has an anonymous namespace.
5613    DeclContext *Parent = CurContext->getRedeclContext();
5614    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5615      PrevNS = TU->getAnonymousNamespace();
5616    } else {
5617      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5618      PrevNS = ND->getAnonymousNamespace();
5619    }
5620
5621    if (PrevNS && IsInline != PrevNS->isInline())
5622      DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
5623                                      &IsInline, PrevNS);
5624  }
5625
5626  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5627                                                 StartLoc, Loc, II, PrevNS);
5628  if (IsInvalid)
5629    Namespc->setInvalidDecl();
5630
5631  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5632
5633  // FIXME: Should we be merging attributes?
5634  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5635    PushNamespaceVisibilityAttr(Attr, Loc);
5636
5637  if (IsStd)
5638    StdNamespace = Namespc;
5639  if (AddToKnown)
5640    KnownNamespaces[Namespc] = false;
5641
5642  if (II) {
5643    PushOnScopeChains(Namespc, DeclRegionScope);
5644  } else {
5645    // Link the anonymous namespace into its parent.
5646    DeclContext *Parent = CurContext->getRedeclContext();
5647    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5648      TU->setAnonymousNamespace(Namespc);
5649    } else {
5650      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
5651    }
5652
5653    CurContext->addDecl(Namespc);
5654
5655    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
5656    //   behaves as if it were replaced by
5657    //     namespace unique { /* empty body */ }
5658    //     using namespace unique;
5659    //     namespace unique { namespace-body }
5660    //   where all occurrences of 'unique' in a translation unit are
5661    //   replaced by the same identifier and this identifier differs
5662    //   from all other identifiers in the entire program.
5663
5664    // We just create the namespace with an empty name and then add an
5665    // implicit using declaration, just like the standard suggests.
5666    //
5667    // CodeGen enforces the "universally unique" aspect by giving all
5668    // declarations semantically contained within an anonymous
5669    // namespace internal linkage.
5670
5671    if (!PrevNS) {
5672      UsingDirectiveDecl* UD
5673        = UsingDirectiveDecl::Create(Context, Parent,
5674                                     /* 'using' */ LBrace,
5675                                     /* 'namespace' */ SourceLocation(),
5676                                     /* qualifier */ NestedNameSpecifierLoc(),
5677                                     /* identifier */ SourceLocation(),
5678                                     Namespc,
5679                                     /* Ancestor */ Parent);
5680      UD->setImplicit();
5681      Parent->addDecl(UD);
5682    }
5683  }
5684
5685  ActOnDocumentableDecl(Namespc);
5686
5687  // Although we could have an invalid decl (i.e. the namespace name is a
5688  // redefinition), push it as current DeclContext and try to continue parsing.
5689  // FIXME: We should be able to push Namespc here, so that the each DeclContext
5690  // for the namespace has the declarations that showed up in that particular
5691  // namespace definition.
5692  PushDeclContext(NamespcScope, Namespc);
5693  return Namespc;
5694}
5695
5696/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5697/// is a namespace alias, returns the namespace it points to.
5698static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5699  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5700    return AD->getNamespace();
5701  return dyn_cast_or_null<NamespaceDecl>(D);
5702}
5703
5704/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5705/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5706void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
5707  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5708  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
5709  Namespc->setRBraceLoc(RBrace);
5710  PopDeclContext();
5711  if (Namespc->hasAttr<VisibilityAttr>())
5712    PopPragmaVisibility(true, RBrace);
5713}
5714
5715CXXRecordDecl *Sema::getStdBadAlloc() const {
5716  return cast_or_null<CXXRecordDecl>(
5717                                  StdBadAlloc.get(Context.getExternalSource()));
5718}
5719
5720NamespaceDecl *Sema::getStdNamespace() const {
5721  return cast_or_null<NamespaceDecl>(
5722                                 StdNamespace.get(Context.getExternalSource()));
5723}
5724
5725/// \brief Retrieve the special "std" namespace, which may require us to
5726/// implicitly define the namespace.
5727NamespaceDecl *Sema::getOrCreateStdNamespace() {
5728  if (!StdNamespace) {
5729    // The "std" namespace has not yet been defined, so build one implicitly.
5730    StdNamespace = NamespaceDecl::Create(Context,
5731                                         Context.getTranslationUnitDecl(),
5732                                         /*Inline=*/false,
5733                                         SourceLocation(), SourceLocation(),
5734                                         &PP.getIdentifierTable().get("std"),
5735                                         /*PrevDecl=*/0);
5736    getStdNamespace()->setImplicit(true);
5737  }
5738
5739  return getStdNamespace();
5740}
5741
5742bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5743  assert(getLangOpts().CPlusPlus &&
5744         "Looking for std::initializer_list outside of C++.");
5745
5746  // We're looking for implicit instantiations of
5747  // template <typename E> class std::initializer_list.
5748
5749  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5750    return false;
5751
5752  ClassTemplateDecl *Template = 0;
5753  const TemplateArgument *Arguments = 0;
5754
5755  if (const RecordType *RT = Ty->getAs<RecordType>()) {
5756
5757    ClassTemplateSpecializationDecl *Specialization =
5758        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5759    if (!Specialization)
5760      return false;
5761
5762    Template = Specialization->getSpecializedTemplate();
5763    Arguments = Specialization->getTemplateArgs().data();
5764  } else if (const TemplateSpecializationType *TST =
5765                 Ty->getAs<TemplateSpecializationType>()) {
5766    Template = dyn_cast_or_null<ClassTemplateDecl>(
5767        TST->getTemplateName().getAsTemplateDecl());
5768    Arguments = TST->getArgs();
5769  }
5770  if (!Template)
5771    return false;
5772
5773  if (!StdInitializerList) {
5774    // Haven't recognized std::initializer_list yet, maybe this is it.
5775    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5776    if (TemplateClass->getIdentifier() !=
5777            &PP.getIdentifierTable().get("initializer_list") ||
5778        !getStdNamespace()->InEnclosingNamespaceSetOf(
5779            TemplateClass->getDeclContext()))
5780      return false;
5781    // This is a template called std::initializer_list, but is it the right
5782    // template?
5783    TemplateParameterList *Params = Template->getTemplateParameters();
5784    if (Params->getMinRequiredArguments() != 1)
5785      return false;
5786    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5787      return false;
5788
5789    // It's the right template.
5790    StdInitializerList = Template;
5791  }
5792
5793  if (Template != StdInitializerList)
5794    return false;
5795
5796  // This is an instance of std::initializer_list. Find the argument type.
5797  if (Element)
5798    *Element = Arguments[0].getAsType();
5799  return true;
5800}
5801
5802static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5803  NamespaceDecl *Std = S.getStdNamespace();
5804  if (!Std) {
5805    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5806    return 0;
5807  }
5808
5809  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5810                      Loc, Sema::LookupOrdinaryName);
5811  if (!S.LookupQualifiedName(Result, Std)) {
5812    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5813    return 0;
5814  }
5815  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5816  if (!Template) {
5817    Result.suppressDiagnostics();
5818    // We found something weird. Complain about the first thing we found.
5819    NamedDecl *Found = *Result.begin();
5820    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5821    return 0;
5822  }
5823
5824  // We found some template called std::initializer_list. Now verify that it's
5825  // correct.
5826  TemplateParameterList *Params = Template->getTemplateParameters();
5827  if (Params->getMinRequiredArguments() != 1 ||
5828      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5829    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5830    return 0;
5831  }
5832
5833  return Template;
5834}
5835
5836QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5837  if (!StdInitializerList) {
5838    StdInitializerList = LookupStdInitializerList(*this, Loc);
5839    if (!StdInitializerList)
5840      return QualType();
5841  }
5842
5843  TemplateArgumentListInfo Args(Loc, Loc);
5844  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5845                                       Context.getTrivialTypeSourceInfo(Element,
5846                                                                        Loc)));
5847  return Context.getCanonicalType(
5848      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5849}
5850
5851bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5852  // C++ [dcl.init.list]p2:
5853  //   A constructor is an initializer-list constructor if its first parameter
5854  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
5855  //   std::initializer_list<E> for some type E, and either there are no other
5856  //   parameters or else all other parameters have default arguments.
5857  if (Ctor->getNumParams() < 1 ||
5858      (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5859    return false;
5860
5861  QualType ArgType = Ctor->getParamDecl(0)->getType();
5862  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5863    ArgType = RT->getPointeeType().getUnqualifiedType();
5864
5865  return isStdInitializerList(ArgType, 0);
5866}
5867
5868/// \brief Determine whether a using statement is in a context where it will be
5869/// apply in all contexts.
5870static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5871  switch (CurContext->getDeclKind()) {
5872    case Decl::TranslationUnit:
5873      return true;
5874    case Decl::LinkageSpec:
5875      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5876    default:
5877      return false;
5878  }
5879}
5880
5881namespace {
5882
5883// Callback to only accept typo corrections that are namespaces.
5884class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5885 public:
5886  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5887    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5888      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5889    }
5890    return false;
5891  }
5892};
5893
5894}
5895
5896static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5897                                       CXXScopeSpec &SS,
5898                                       SourceLocation IdentLoc,
5899                                       IdentifierInfo *Ident) {
5900  NamespaceValidatorCCC Validator;
5901  R.clear();
5902  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5903                                               R.getLookupKind(), Sc, &SS,
5904                                               Validator)) {
5905    std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5906    std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
5907    if (DeclContext *DC = S.computeDeclContext(SS, false))
5908      S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5909        << Ident << DC << CorrectedQuotedStr << SS.getRange()
5910        << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
5911                                        CorrectedStr);
5912    else
5913      S.Diag(IdentLoc, diag::err_using_directive_suggest)
5914        << Ident << CorrectedQuotedStr
5915        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5916
5917    S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5918         diag::note_namespace_defined_here) << CorrectedQuotedStr;
5919
5920    R.addDecl(Corrected.getCorrectionDecl());
5921    return true;
5922  }
5923  return false;
5924}
5925
5926Decl *Sema::ActOnUsingDirective(Scope *S,
5927                                          SourceLocation UsingLoc,
5928                                          SourceLocation NamespcLoc,
5929                                          CXXScopeSpec &SS,
5930                                          SourceLocation IdentLoc,
5931                                          IdentifierInfo *NamespcName,
5932                                          AttributeList *AttrList) {
5933  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5934  assert(NamespcName && "Invalid NamespcName.");
5935  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
5936
5937  // This can only happen along a recovery path.
5938  while (S->getFlags() & Scope::TemplateParamScope)
5939    S = S->getParent();
5940  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5941
5942  UsingDirectiveDecl *UDir = 0;
5943  NestedNameSpecifier *Qualifier = 0;
5944  if (SS.isSet())
5945    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5946
5947  // Lookup namespace name.
5948  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5949  LookupParsedName(R, S, &SS);
5950  if (R.isAmbiguous())
5951    return 0;
5952
5953  if (R.empty()) {
5954    R.clear();
5955    // Allow "using namespace std;" or "using namespace ::std;" even if
5956    // "std" hasn't been defined yet, for GCC compatibility.
5957    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5958        NamespcName->isStr("std")) {
5959      Diag(IdentLoc, diag::ext_using_undefined_std);
5960      R.addDecl(getOrCreateStdNamespace());
5961      R.resolveKind();
5962    }
5963    // Otherwise, attempt typo correction.
5964    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
5965  }
5966
5967  if (!R.empty()) {
5968    NamedDecl *Named = R.getFoundDecl();
5969    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5970        && "expected namespace decl");
5971    // C++ [namespace.udir]p1:
5972    //   A using-directive specifies that the names in the nominated
5973    //   namespace can be used in the scope in which the
5974    //   using-directive appears after the using-directive. During
5975    //   unqualified name lookup (3.4.1), the names appear as if they
5976    //   were declared in the nearest enclosing namespace which
5977    //   contains both the using-directive and the nominated
5978    //   namespace. [Note: in this context, "contains" means "contains
5979    //   directly or indirectly". ]
5980
5981    // Find enclosing context containing both using-directive and
5982    // nominated namespace.
5983    NamespaceDecl *NS = getNamespaceDecl(Named);
5984    DeclContext *CommonAncestor = cast<DeclContext>(NS);
5985    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5986      CommonAncestor = CommonAncestor->getParent();
5987
5988    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
5989                                      SS.getWithLocInContext(Context),
5990                                      IdentLoc, Named, CommonAncestor);
5991
5992    if (IsUsingDirectiveInToplevelContext(CurContext) &&
5993        !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
5994      Diag(IdentLoc, diag::warn_using_directive_in_header);
5995    }
5996
5997    PushUsingDirective(S, UDir);
5998  } else {
5999    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6000  }
6001
6002  // FIXME: We ignore attributes for now.
6003  return UDir;
6004}
6005
6006void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6007  // If the scope has an associated entity and the using directive is at
6008  // namespace or translation unit scope, add the UsingDirectiveDecl into
6009  // its lookup structure so qualified name lookup can find it.
6010  DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6011  if (Ctx && !Ctx->isFunctionOrMethod())
6012    Ctx->addDecl(UDir);
6013  else
6014    // Otherwise, it is at block sope. The using-directives will affect lookup
6015    // only to the end of the scope.
6016    S->PushUsingDirective(UDir);
6017}
6018
6019
6020Decl *Sema::ActOnUsingDeclaration(Scope *S,
6021                                  AccessSpecifier AS,
6022                                  bool HasUsingKeyword,
6023                                  SourceLocation UsingLoc,
6024                                  CXXScopeSpec &SS,
6025                                  UnqualifiedId &Name,
6026                                  AttributeList *AttrList,
6027                                  bool IsTypeName,
6028                                  SourceLocation TypenameLoc) {
6029  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6030
6031  switch (Name.getKind()) {
6032  case UnqualifiedId::IK_ImplicitSelfParam:
6033  case UnqualifiedId::IK_Identifier:
6034  case UnqualifiedId::IK_OperatorFunctionId:
6035  case UnqualifiedId::IK_LiteralOperatorId:
6036  case UnqualifiedId::IK_ConversionFunctionId:
6037    break;
6038
6039  case UnqualifiedId::IK_ConstructorName:
6040  case UnqualifiedId::IK_ConstructorTemplateId:
6041    // C++11 inheriting constructors.
6042    Diag(Name.getLocStart(),
6043         getLangOpts().CPlusPlus0x ?
6044           // FIXME: Produce warn_cxx98_compat_using_decl_constructor
6045           //        instead once inheriting constructors work.
6046           diag::err_using_decl_constructor_unsupported :
6047           diag::err_using_decl_constructor)
6048      << SS.getRange();
6049
6050    if (getLangOpts().CPlusPlus0x) break;
6051
6052    return 0;
6053
6054  case UnqualifiedId::IK_DestructorName:
6055    Diag(Name.getLocStart(), diag::err_using_decl_destructor)
6056      << SS.getRange();
6057    return 0;
6058
6059  case UnqualifiedId::IK_TemplateId:
6060    Diag(Name.getLocStart(), diag::err_using_decl_template_id)
6061      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
6062    return 0;
6063  }
6064
6065  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6066  DeclarationName TargetName = TargetNameInfo.getName();
6067  if (!TargetName)
6068    return 0;
6069
6070  // Warn about using declarations.
6071  // TODO: store that the declaration was written without 'using' and
6072  // talk about access decls instead of using decls in the
6073  // diagnostics.
6074  if (!HasUsingKeyword) {
6075    UsingLoc = Name.getLocStart();
6076
6077    Diag(UsingLoc, diag::warn_access_decl_deprecated)
6078      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
6079  }
6080
6081  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6082      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6083    return 0;
6084
6085  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
6086                                        TargetNameInfo, AttrList,
6087                                        /* IsInstantiation */ false,
6088                                        IsTypeName, TypenameLoc);
6089  if (UD)
6090    PushOnScopeChains(UD, S, /*AddToContext*/ false);
6091
6092  return UD;
6093}
6094
6095/// \brief Determine whether a using declaration considers the given
6096/// declarations as "equivalent", e.g., if they are redeclarations of
6097/// the same entity or are both typedefs of the same type.
6098static bool
6099IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6100                         bool &SuppressRedeclaration) {
6101  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6102    SuppressRedeclaration = false;
6103    return true;
6104  }
6105
6106  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6107    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
6108      SuppressRedeclaration = true;
6109      return Context.hasSameType(TD1->getUnderlyingType(),
6110                                 TD2->getUnderlyingType());
6111    }
6112
6113  return false;
6114}
6115
6116
6117/// Determines whether to create a using shadow decl for a particular
6118/// decl, given the set of decls existing prior to this using lookup.
6119bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6120                                const LookupResult &Previous) {
6121  // Diagnose finding a decl which is not from a base class of the
6122  // current class.  We do this now because there are cases where this
6123  // function will silently decide not to build a shadow decl, which
6124  // will pre-empt further diagnostics.
6125  //
6126  // We don't need to do this in C++0x because we do the check once on
6127  // the qualifier.
6128  //
6129  // FIXME: diagnose the following if we care enough:
6130  //   struct A { int foo; };
6131  //   struct B : A { using A::foo; };
6132  //   template <class T> struct C : A {};
6133  //   template <class T> struct D : C<T> { using B::foo; } // <---
6134  // This is invalid (during instantiation) in C++03 because B::foo
6135  // resolves to the using decl in B, which is not a base class of D<T>.
6136  // We can't diagnose it immediately because C<T> is an unknown
6137  // specialization.  The UsingShadowDecl in D<T> then points directly
6138  // to A::foo, which will look well-formed when we instantiate.
6139  // The right solution is to not collapse the shadow-decl chain.
6140  if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
6141    DeclContext *OrigDC = Orig->getDeclContext();
6142
6143    // Handle enums and anonymous structs.
6144    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6145    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6146    while (OrigRec->isAnonymousStructOrUnion())
6147      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6148
6149    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6150      if (OrigDC == CurContext) {
6151        Diag(Using->getLocation(),
6152             diag::err_using_decl_nested_name_specifier_is_current_class)
6153          << Using->getQualifierLoc().getSourceRange();
6154        Diag(Orig->getLocation(), diag::note_using_decl_target);
6155        return true;
6156      }
6157
6158      Diag(Using->getQualifierLoc().getBeginLoc(),
6159           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6160        << Using->getQualifier()
6161        << cast<CXXRecordDecl>(CurContext)
6162        << Using->getQualifierLoc().getSourceRange();
6163      Diag(Orig->getLocation(), diag::note_using_decl_target);
6164      return true;
6165    }
6166  }
6167
6168  if (Previous.empty()) return false;
6169
6170  NamedDecl *Target = Orig;
6171  if (isa<UsingShadowDecl>(Target))
6172    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6173
6174  // If the target happens to be one of the previous declarations, we
6175  // don't have a conflict.
6176  //
6177  // FIXME: but we might be increasing its access, in which case we
6178  // should redeclare it.
6179  NamedDecl *NonTag = 0, *Tag = 0;
6180  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6181         I != E; ++I) {
6182    NamedDecl *D = (*I)->getUnderlyingDecl();
6183    bool Result;
6184    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6185      return Result;
6186
6187    (isa<TagDecl>(D) ? Tag : NonTag) = D;
6188  }
6189
6190  if (Target->isFunctionOrFunctionTemplate()) {
6191    FunctionDecl *FD;
6192    if (isa<FunctionTemplateDecl>(Target))
6193      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6194    else
6195      FD = cast<FunctionDecl>(Target);
6196
6197    NamedDecl *OldDecl = 0;
6198    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6199    case Ovl_Overload:
6200      return false;
6201
6202    case Ovl_NonFunction:
6203      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6204      break;
6205
6206    // We found a decl with the exact signature.
6207    case Ovl_Match:
6208      // If we're in a record, we want to hide the target, so we
6209      // return true (without a diagnostic) to tell the caller not to
6210      // build a shadow decl.
6211      if (CurContext->isRecord())
6212        return true;
6213
6214      // If we're not in a record, this is an error.
6215      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6216      break;
6217    }
6218
6219    Diag(Target->getLocation(), diag::note_using_decl_target);
6220    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6221    return true;
6222  }
6223
6224  // Target is not a function.
6225
6226  if (isa<TagDecl>(Target)) {
6227    // No conflict between a tag and a non-tag.
6228    if (!Tag) return false;
6229
6230    Diag(Using->getLocation(), diag::err_using_decl_conflict);
6231    Diag(Target->getLocation(), diag::note_using_decl_target);
6232    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6233    return true;
6234  }
6235
6236  // No conflict between a tag and a non-tag.
6237  if (!NonTag) return false;
6238
6239  Diag(Using->getLocation(), diag::err_using_decl_conflict);
6240  Diag(Target->getLocation(), diag::note_using_decl_target);
6241  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6242  return true;
6243}
6244
6245/// Builds a shadow declaration corresponding to a 'using' declaration.
6246UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6247                                            UsingDecl *UD,
6248                                            NamedDecl *Orig) {
6249
6250  // If we resolved to another shadow declaration, just coalesce them.
6251  NamedDecl *Target = Orig;
6252  if (isa<UsingShadowDecl>(Target)) {
6253    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6254    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6255  }
6256
6257  UsingShadowDecl *Shadow
6258    = UsingShadowDecl::Create(Context, CurContext,
6259                              UD->getLocation(), UD, Target);
6260  UD->addShadowDecl(Shadow);
6261
6262  Shadow->setAccess(UD->getAccess());
6263  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6264    Shadow->setInvalidDecl();
6265
6266  if (S)
6267    PushOnScopeChains(Shadow, S);
6268  else
6269    CurContext->addDecl(Shadow);
6270
6271
6272  return Shadow;
6273}
6274
6275/// Hides a using shadow declaration.  This is required by the current
6276/// using-decl implementation when a resolvable using declaration in a
6277/// class is followed by a declaration which would hide or override
6278/// one or more of the using decl's targets; for example:
6279///
6280///   struct Base { void foo(int); };
6281///   struct Derived : Base {
6282///     using Base::foo;
6283///     void foo(int);
6284///   };
6285///
6286/// The governing language is C++03 [namespace.udecl]p12:
6287///
6288///   When a using-declaration brings names from a base class into a
6289///   derived class scope, member functions in the derived class
6290///   override and/or hide member functions with the same name and
6291///   parameter types in a base class (rather than conflicting).
6292///
6293/// There are two ways to implement this:
6294///   (1) optimistically create shadow decls when they're not hidden
6295///       by existing declarations, or
6296///   (2) don't create any shadow decls (or at least don't make them
6297///       visible) until we've fully parsed/instantiated the class.
6298/// The problem with (1) is that we might have to retroactively remove
6299/// a shadow decl, which requires several O(n) operations because the
6300/// decl structures are (very reasonably) not designed for removal.
6301/// (2) avoids this but is very fiddly and phase-dependent.
6302void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6303  if (Shadow->getDeclName().getNameKind() ==
6304        DeclarationName::CXXConversionFunctionName)
6305    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6306
6307  // Remove it from the DeclContext...
6308  Shadow->getDeclContext()->removeDecl(Shadow);
6309
6310  // ...and the scope, if applicable...
6311  if (S) {
6312    S->RemoveDecl(Shadow);
6313    IdResolver.RemoveDecl(Shadow);
6314  }
6315
6316  // ...and the using decl.
6317  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6318
6319  // TODO: complain somehow if Shadow was used.  It shouldn't
6320  // be possible for this to happen, because...?
6321}
6322
6323/// Builds a using declaration.
6324///
6325/// \param IsInstantiation - Whether this call arises from an
6326///   instantiation of an unresolved using declaration.  We treat
6327///   the lookup differently for these declarations.
6328NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6329                                       SourceLocation UsingLoc,
6330                                       CXXScopeSpec &SS,
6331                                       const DeclarationNameInfo &NameInfo,
6332                                       AttributeList *AttrList,
6333                                       bool IsInstantiation,
6334                                       bool IsTypeName,
6335                                       SourceLocation TypenameLoc) {
6336  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6337  SourceLocation IdentLoc = NameInfo.getLoc();
6338  assert(IdentLoc.isValid() && "Invalid TargetName location.");
6339
6340  // FIXME: We ignore attributes for now.
6341
6342  if (SS.isEmpty()) {
6343    Diag(IdentLoc, diag::err_using_requires_qualname);
6344    return 0;
6345  }
6346
6347  // Do the redeclaration lookup in the current scope.
6348  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
6349                        ForRedeclaration);
6350  Previous.setHideTags(false);
6351  if (S) {
6352    LookupName(Previous, S);
6353
6354    // It is really dumb that we have to do this.
6355    LookupResult::Filter F = Previous.makeFilter();
6356    while (F.hasNext()) {
6357      NamedDecl *D = F.next();
6358      if (!isDeclInScope(D, CurContext, S))
6359        F.erase();
6360    }
6361    F.done();
6362  } else {
6363    assert(IsInstantiation && "no scope in non-instantiation");
6364    assert(CurContext->isRecord() && "scope not record in instantiation");
6365    LookupQualifiedName(Previous, CurContext);
6366  }
6367
6368  // Check for invalid redeclarations.
6369  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6370    return 0;
6371
6372  // Check for bad qualifiers.
6373  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6374    return 0;
6375
6376  DeclContext *LookupContext = computeDeclContext(SS);
6377  NamedDecl *D;
6378  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6379  if (!LookupContext) {
6380    if (IsTypeName) {
6381      // FIXME: not all declaration name kinds are legal here
6382      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6383                                              UsingLoc, TypenameLoc,
6384                                              QualifierLoc,
6385                                              IdentLoc, NameInfo.getName());
6386    } else {
6387      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6388                                           QualifierLoc, NameInfo);
6389    }
6390  } else {
6391    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6392                          NameInfo, IsTypeName);
6393  }
6394  D->setAccess(AS);
6395  CurContext->addDecl(D);
6396
6397  if (!LookupContext) return D;
6398  UsingDecl *UD = cast<UsingDecl>(D);
6399
6400  if (RequireCompleteDeclContext(SS, LookupContext)) {
6401    UD->setInvalidDecl();
6402    return UD;
6403  }
6404
6405  // The normal rules do not apply to inheriting constructor declarations.
6406  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
6407    if (CheckInheritingConstructorUsingDecl(UD))
6408      UD->setInvalidDecl();
6409    return UD;
6410  }
6411
6412  // Otherwise, look up the target name.
6413
6414  LookupResult R(*this, NameInfo, LookupOrdinaryName);
6415
6416  // Unlike most lookups, we don't always want to hide tag
6417  // declarations: tag names are visible through the using declaration
6418  // even if hidden by ordinary names, *except* in a dependent context
6419  // where it's important for the sanity of two-phase lookup.
6420  if (!IsInstantiation)
6421    R.setHideTags(false);
6422
6423  // For the purposes of this lookup, we have a base object type
6424  // equal to that of the current context.
6425  if (CurContext->isRecord()) {
6426    R.setBaseObjectType(
6427                   Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6428  }
6429
6430  LookupQualifiedName(R, LookupContext);
6431
6432  if (R.empty()) {
6433    Diag(IdentLoc, diag::err_no_member)
6434      << NameInfo.getName() << LookupContext << SS.getRange();
6435    UD->setInvalidDecl();
6436    return UD;
6437  }
6438
6439  if (R.isAmbiguous()) {
6440    UD->setInvalidDecl();
6441    return UD;
6442  }
6443
6444  if (IsTypeName) {
6445    // If we asked for a typename and got a non-type decl, error out.
6446    if (!R.getAsSingle<TypeDecl>()) {
6447      Diag(IdentLoc, diag::err_using_typename_non_type);
6448      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6449        Diag((*I)->getUnderlyingDecl()->getLocation(),
6450             diag::note_using_decl_target);
6451      UD->setInvalidDecl();
6452      return UD;
6453    }
6454  } else {
6455    // If we asked for a non-typename and we got a type, error out,
6456    // but only if this is an instantiation of an unresolved using
6457    // decl.  Otherwise just silently find the type name.
6458    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
6459      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6460      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
6461      UD->setInvalidDecl();
6462      return UD;
6463    }
6464  }
6465
6466  // C++0x N2914 [namespace.udecl]p6:
6467  // A using-declaration shall not name a namespace.
6468  if (R.getAsSingle<NamespaceDecl>()) {
6469    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6470      << SS.getRange();
6471    UD->setInvalidDecl();
6472    return UD;
6473  }
6474
6475  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6476    if (!CheckUsingShadowDecl(UD, *I, Previous))
6477      BuildUsingShadowDecl(S, UD, *I);
6478  }
6479
6480  return UD;
6481}
6482
6483/// Additional checks for a using declaration referring to a constructor name.
6484bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6485  assert(!UD->isTypeName() && "expecting a constructor name");
6486
6487  const Type *SourceType = UD->getQualifier()->getAsType();
6488  assert(SourceType &&
6489         "Using decl naming constructor doesn't have type in scope spec.");
6490  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6491
6492  // Check whether the named type is a direct base class.
6493  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6494  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6495  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6496       BaseIt != BaseE; ++BaseIt) {
6497    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6498    if (CanonicalSourceType == BaseType)
6499      break;
6500    if (BaseIt->getType()->isDependentType())
6501      break;
6502  }
6503
6504  if (BaseIt == BaseE) {
6505    // Did not find SourceType in the bases.
6506    Diag(UD->getUsingLocation(),
6507         diag::err_using_decl_constructor_not_in_direct_base)
6508      << UD->getNameInfo().getSourceRange()
6509      << QualType(SourceType, 0) << TargetClass;
6510    return true;
6511  }
6512
6513  if (!CurContext->isDependentContext())
6514    BaseIt->setInheritConstructors();
6515
6516  return false;
6517}
6518
6519/// Checks that the given using declaration is not an invalid
6520/// redeclaration.  Note that this is checking only for the using decl
6521/// itself, not for any ill-formedness among the UsingShadowDecls.
6522bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6523                                       bool isTypeName,
6524                                       const CXXScopeSpec &SS,
6525                                       SourceLocation NameLoc,
6526                                       const LookupResult &Prev) {
6527  // C++03 [namespace.udecl]p8:
6528  // C++0x [namespace.udecl]p10:
6529  //   A using-declaration is a declaration and can therefore be used
6530  //   repeatedly where (and only where) multiple declarations are
6531  //   allowed.
6532  //
6533  // That's in non-member contexts.
6534  if (!CurContext->getRedeclContext()->isRecord())
6535    return false;
6536
6537  NestedNameSpecifier *Qual
6538    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6539
6540  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6541    NamedDecl *D = *I;
6542
6543    bool DTypename;
6544    NestedNameSpecifier *DQual;
6545    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6546      DTypename = UD->isTypeName();
6547      DQual = UD->getQualifier();
6548    } else if (UnresolvedUsingValueDecl *UD
6549                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6550      DTypename = false;
6551      DQual = UD->getQualifier();
6552    } else if (UnresolvedUsingTypenameDecl *UD
6553                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6554      DTypename = true;
6555      DQual = UD->getQualifier();
6556    } else continue;
6557
6558    // using decls differ if one says 'typename' and the other doesn't.
6559    // FIXME: non-dependent using decls?
6560    if (isTypeName != DTypename) continue;
6561
6562    // using decls differ if they name different scopes (but note that
6563    // template instantiation can cause this check to trigger when it
6564    // didn't before instantiation).
6565    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6566        Context.getCanonicalNestedNameSpecifier(DQual))
6567      continue;
6568
6569    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
6570    Diag(D->getLocation(), diag::note_using_decl) << 1;
6571    return true;
6572  }
6573
6574  return false;
6575}
6576
6577
6578/// Checks that the given nested-name qualifier used in a using decl
6579/// in the current context is appropriately related to the current
6580/// scope.  If an error is found, diagnoses it and returns true.
6581bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6582                                   const CXXScopeSpec &SS,
6583                                   SourceLocation NameLoc) {
6584  DeclContext *NamedContext = computeDeclContext(SS);
6585
6586  if (!CurContext->isRecord()) {
6587    // C++03 [namespace.udecl]p3:
6588    // C++0x [namespace.udecl]p8:
6589    //   A using-declaration for a class member shall be a member-declaration.
6590
6591    // If we weren't able to compute a valid scope, it must be a
6592    // dependent class scope.
6593    if (!NamedContext || NamedContext->isRecord()) {
6594      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6595        << SS.getRange();
6596      return true;
6597    }
6598
6599    // Otherwise, everything is known to be fine.
6600    return false;
6601  }
6602
6603  // The current scope is a record.
6604
6605  // If the named context is dependent, we can't decide much.
6606  if (!NamedContext) {
6607    // FIXME: in C++0x, we can diagnose if we can prove that the
6608    // nested-name-specifier does not refer to a base class, which is
6609    // still possible in some cases.
6610
6611    // Otherwise we have to conservatively report that things might be
6612    // okay.
6613    return false;
6614  }
6615
6616  if (!NamedContext->isRecord()) {
6617    // Ideally this would point at the last name in the specifier,
6618    // but we don't have that level of source info.
6619    Diag(SS.getRange().getBegin(),
6620         diag::err_using_decl_nested_name_specifier_is_not_class)
6621      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6622    return true;
6623  }
6624
6625  if (!NamedContext->isDependentContext() &&
6626      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6627    return true;
6628
6629  if (getLangOpts().CPlusPlus0x) {
6630    // C++0x [namespace.udecl]p3:
6631    //   In a using-declaration used as a member-declaration, the
6632    //   nested-name-specifier shall name a base class of the class
6633    //   being defined.
6634
6635    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6636                                 cast<CXXRecordDecl>(NamedContext))) {
6637      if (CurContext == NamedContext) {
6638        Diag(NameLoc,
6639             diag::err_using_decl_nested_name_specifier_is_current_class)
6640          << SS.getRange();
6641        return true;
6642      }
6643
6644      Diag(SS.getRange().getBegin(),
6645           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6646        << (NestedNameSpecifier*) SS.getScopeRep()
6647        << cast<CXXRecordDecl>(CurContext)
6648        << SS.getRange();
6649      return true;
6650    }
6651
6652    return false;
6653  }
6654
6655  // C++03 [namespace.udecl]p4:
6656  //   A using-declaration used as a member-declaration shall refer
6657  //   to a member of a base class of the class being defined [etc.].
6658
6659  // Salient point: SS doesn't have to name a base class as long as
6660  // lookup only finds members from base classes.  Therefore we can
6661  // diagnose here only if we can prove that that can't happen,
6662  // i.e. if the class hierarchies provably don't intersect.
6663
6664  // TODO: it would be nice if "definitely valid" results were cached
6665  // in the UsingDecl and UsingShadowDecl so that these checks didn't
6666  // need to be repeated.
6667
6668  struct UserData {
6669    llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
6670
6671    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6672      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6673      Data->Bases.insert(Base);
6674      return true;
6675    }
6676
6677    bool hasDependentBases(const CXXRecordDecl *Class) {
6678      return !Class->forallBases(collect, this);
6679    }
6680
6681    /// Returns true if the base is dependent or is one of the
6682    /// accumulated base classes.
6683    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6684      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6685      return !Data->Bases.count(Base);
6686    }
6687
6688    bool mightShareBases(const CXXRecordDecl *Class) {
6689      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6690    }
6691  };
6692
6693  UserData Data;
6694
6695  // Returns false if we find a dependent base.
6696  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6697    return false;
6698
6699  // Returns false if the class has a dependent base or if it or one
6700  // of its bases is present in the base set of the current context.
6701  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6702    return false;
6703
6704  Diag(SS.getRange().getBegin(),
6705       diag::err_using_decl_nested_name_specifier_is_not_base_class)
6706    << (NestedNameSpecifier*) SS.getScopeRep()
6707    << cast<CXXRecordDecl>(CurContext)
6708    << SS.getRange();
6709
6710  return true;
6711}
6712
6713Decl *Sema::ActOnAliasDeclaration(Scope *S,
6714                                  AccessSpecifier AS,
6715                                  MultiTemplateParamsArg TemplateParamLists,
6716                                  SourceLocation UsingLoc,
6717                                  UnqualifiedId &Name,
6718                                  TypeResult Type) {
6719  // Skip up to the relevant declaration scope.
6720  while (S->getFlags() & Scope::TemplateParamScope)
6721    S = S->getParent();
6722  assert((S->getFlags() & Scope::DeclScope) &&
6723         "got alias-declaration outside of declaration scope");
6724
6725  if (Type.isInvalid())
6726    return 0;
6727
6728  bool Invalid = false;
6729  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6730  TypeSourceInfo *TInfo = 0;
6731  GetTypeFromParser(Type.get(), &TInfo);
6732
6733  if (DiagnoseClassNameShadow(CurContext, NameInfo))
6734    return 0;
6735
6736  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
6737                                      UPPC_DeclarationType)) {
6738    Invalid = true;
6739    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6740                                             TInfo->getTypeLoc().getBeginLoc());
6741  }
6742
6743  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6744  LookupName(Previous, S);
6745
6746  // Warn about shadowing the name of a template parameter.
6747  if (Previous.isSingleResult() &&
6748      Previous.getFoundDecl()->isTemplateParameter()) {
6749    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
6750    Previous.clear();
6751  }
6752
6753  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6754         "name in alias declaration must be an identifier");
6755  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6756                                               Name.StartLocation,
6757                                               Name.Identifier, TInfo);
6758
6759  NewTD->setAccess(AS);
6760
6761  if (Invalid)
6762    NewTD->setInvalidDecl();
6763
6764  CheckTypedefForVariablyModifiedType(S, NewTD);
6765  Invalid |= NewTD->isInvalidDecl();
6766
6767  bool Redeclaration = false;
6768
6769  NamedDecl *NewND;
6770  if (TemplateParamLists.size()) {
6771    TypeAliasTemplateDecl *OldDecl = 0;
6772    TemplateParameterList *OldTemplateParams = 0;
6773
6774    if (TemplateParamLists.size() != 1) {
6775      Diag(UsingLoc, diag::err_alias_template_extra_headers)
6776        << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
6777         TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
6778    }
6779    TemplateParameterList *TemplateParams = TemplateParamLists[0];
6780
6781    // Only consider previous declarations in the same scope.
6782    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6783                         /*ExplicitInstantiationOrSpecialization*/false);
6784    if (!Previous.empty()) {
6785      Redeclaration = true;
6786
6787      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6788      if (!OldDecl && !Invalid) {
6789        Diag(UsingLoc, diag::err_redefinition_different_kind)
6790          << Name.Identifier;
6791
6792        NamedDecl *OldD = Previous.getRepresentativeDecl();
6793        if (OldD->getLocation().isValid())
6794          Diag(OldD->getLocation(), diag::note_previous_definition);
6795
6796        Invalid = true;
6797      }
6798
6799      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6800        if (TemplateParameterListsAreEqual(TemplateParams,
6801                                           OldDecl->getTemplateParameters(),
6802                                           /*Complain=*/true,
6803                                           TPL_TemplateMatch))
6804          OldTemplateParams = OldDecl->getTemplateParameters();
6805        else
6806          Invalid = true;
6807
6808        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6809        if (!Invalid &&
6810            !Context.hasSameType(OldTD->getUnderlyingType(),
6811                                 NewTD->getUnderlyingType())) {
6812          // FIXME: The C++0x standard does not clearly say this is ill-formed,
6813          // but we can't reasonably accept it.
6814          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6815            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6816          if (OldTD->getLocation().isValid())
6817            Diag(OldTD->getLocation(), diag::note_previous_definition);
6818          Invalid = true;
6819        }
6820      }
6821    }
6822
6823    // Merge any previous default template arguments into our parameters,
6824    // and check the parameter list.
6825    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6826                                   TPC_TypeAliasTemplate))
6827      return 0;
6828
6829    TypeAliasTemplateDecl *NewDecl =
6830      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6831                                    Name.Identifier, TemplateParams,
6832                                    NewTD);
6833
6834    NewDecl->setAccess(AS);
6835
6836    if (Invalid)
6837      NewDecl->setInvalidDecl();
6838    else if (OldDecl)
6839      NewDecl->setPreviousDeclaration(OldDecl);
6840
6841    NewND = NewDecl;
6842  } else {
6843    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6844    NewND = NewTD;
6845  }
6846
6847  if (!Redeclaration)
6848    PushOnScopeChains(NewND, S);
6849
6850  ActOnDocumentableDecl(NewND);
6851  return NewND;
6852}
6853
6854Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
6855                                             SourceLocation NamespaceLoc,
6856                                             SourceLocation AliasLoc,
6857                                             IdentifierInfo *Alias,
6858                                             CXXScopeSpec &SS,
6859                                             SourceLocation IdentLoc,
6860                                             IdentifierInfo *Ident) {
6861
6862  // Lookup the namespace name.
6863  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6864  LookupParsedName(R, S, &SS);
6865
6866  // Check if we have a previous declaration with the same name.
6867  NamedDecl *PrevDecl
6868    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6869                       ForRedeclaration);
6870  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6871    PrevDecl = 0;
6872
6873  if (PrevDecl) {
6874    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
6875      // We already have an alias with the same name that points to the same
6876      // namespace, so don't create a new one.
6877      // FIXME: At some point, we'll want to create the (redundant)
6878      // declaration to maintain better source information.
6879      if (!R.isAmbiguous() && !R.empty() &&
6880          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
6881        return 0;
6882    }
6883
6884    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6885      diag::err_redefinition_different_kind;
6886    Diag(AliasLoc, DiagID) << Alias;
6887    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6888    return 0;
6889  }
6890
6891  if (R.isAmbiguous())
6892    return 0;
6893
6894  if (R.empty()) {
6895    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
6896      Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6897      return 0;
6898    }
6899  }
6900
6901  NamespaceAliasDecl *AliasDecl =
6902    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
6903                               Alias, SS.getWithLocInContext(Context),
6904                               IdentLoc, R.getFoundDecl());
6905
6906  PushOnScopeChains(AliasDecl, S);
6907  return AliasDecl;
6908}
6909
6910Sema::ImplicitExceptionSpecification
6911Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
6912                                               CXXMethodDecl *MD) {
6913  CXXRecordDecl *ClassDecl = MD->getParent();
6914
6915  // C++ [except.spec]p14:
6916  //   An implicitly declared special member function (Clause 12) shall have an
6917  //   exception-specification. [...]
6918  ImplicitExceptionSpecification ExceptSpec(*this);
6919  if (ClassDecl->isInvalidDecl())
6920    return ExceptSpec;
6921
6922  // Direct base-class constructors.
6923  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6924                                       BEnd = ClassDecl->bases_end();
6925       B != BEnd; ++B) {
6926    if (B->isVirtual()) // Handled below.
6927      continue;
6928
6929    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6930      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6931      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6932      // If this is a deleted function, add it anyway. This might be conformant
6933      // with the standard. This might not. I'm not sure. It might not matter.
6934      if (Constructor)
6935        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
6936    }
6937  }
6938
6939  // Virtual base-class constructors.
6940  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6941                                       BEnd = ClassDecl->vbases_end();
6942       B != BEnd; ++B) {
6943    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6944      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6945      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6946      // If this is a deleted function, add it anyway. This might be conformant
6947      // with the standard. This might not. I'm not sure. It might not matter.
6948      if (Constructor)
6949        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
6950    }
6951  }
6952
6953  // Field constructors.
6954  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6955                               FEnd = ClassDecl->field_end();
6956       F != FEnd; ++F) {
6957    if (F->hasInClassInitializer()) {
6958      if (Expr *E = F->getInClassInitializer())
6959        ExceptSpec.CalledExpr(E);
6960      else if (!F->isInvalidDecl())
6961        // DR1351:
6962        //   If the brace-or-equal-initializer of a non-static data member
6963        //   invokes a defaulted default constructor of its class or of an
6964        //   enclosing class in a potentially evaluated subexpression, the
6965        //   program is ill-formed.
6966        //
6967        // This resolution is unworkable: the exception specification of the
6968        // default constructor can be needed in an unevaluated context, in
6969        // particular, in the operand of a noexcept-expression, and we can be
6970        // unable to compute an exception specification for an enclosed class.
6971        //
6972        // We do not allow an in-class initializer to require the evaluation
6973        // of the exception specification for any in-class initializer whose
6974        // definition is not lexically complete.
6975        Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
6976    } else if (const RecordType *RecordTy
6977              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
6978      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6979      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6980      // If this is a deleted function, add it anyway. This might be conformant
6981      // with the standard. This might not. I'm not sure. It might not matter.
6982      // In particular, the problem is that this function never gets called. It
6983      // might just be ill-formed because this function attempts to refer to
6984      // a deleted function here.
6985      if (Constructor)
6986        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
6987    }
6988  }
6989
6990  return ExceptSpec;
6991}
6992
6993CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6994                                                     CXXRecordDecl *ClassDecl) {
6995  // C++ [class.ctor]p5:
6996  //   A default constructor for a class X is a constructor of class X
6997  //   that can be called without an argument. If there is no
6998  //   user-declared constructor for class X, a default constructor is
6999  //   implicitly declared. An implicitly-declared default constructor
7000  //   is an inline public member of its class.
7001  assert(ClassDecl->needsImplicitDefaultConstructor() &&
7002         "Should not build implicit default constructor!");
7003
7004  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7005                                                     CXXDefaultConstructor,
7006                                                     false);
7007
7008  // Create the actual constructor declaration.
7009  CanQualType ClassType
7010    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7011  SourceLocation ClassLoc = ClassDecl->getLocation();
7012  DeclarationName Name
7013    = Context.DeclarationNames.getCXXConstructorName(ClassType);
7014  DeclarationNameInfo NameInfo(Name, ClassLoc);
7015  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7016      Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
7017      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7018      Constexpr);
7019  DefaultCon->setAccess(AS_public);
7020  DefaultCon->setDefaulted();
7021  DefaultCon->setImplicit();
7022  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7023
7024  // Build an exception specification pointing back at this constructor.
7025  FunctionProtoType::ExtProtoInfo EPI;
7026  EPI.ExceptionSpecType = EST_Unevaluated;
7027  EPI.ExceptionSpecDecl = DefaultCon;
7028  DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7029
7030  // Note that we have declared this constructor.
7031  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7032
7033  if (Scope *S = getScopeForContext(ClassDecl))
7034    PushOnScopeChains(DefaultCon, S, false);
7035  ClassDecl->addDecl(DefaultCon);
7036
7037  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7038    DefaultCon->setDeletedAsWritten();
7039
7040  return DefaultCon;
7041}
7042
7043void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7044                                            CXXConstructorDecl *Constructor) {
7045  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7046          !Constructor->doesThisDeclarationHaveABody() &&
7047          !Constructor->isDeleted()) &&
7048    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
7049
7050  CXXRecordDecl *ClassDecl = Constructor->getParent();
7051  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
7052
7053  SynthesizedFunctionScope Scope(*this, Constructor);
7054  DiagnosticErrorTrap Trap(Diags);
7055  if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
7056      Trap.hasErrorOccurred()) {
7057    Diag(CurrentLocation, diag::note_member_synthesized_at)
7058      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
7059    Constructor->setInvalidDecl();
7060    return;
7061  }
7062
7063  SourceLocation Loc = Constructor->getLocation();
7064  Constructor->setBody(new (Context) CompoundStmt(Loc));
7065
7066  Constructor->setUsed();
7067  MarkVTableUsed(CurrentLocation, ClassDecl);
7068
7069  if (ASTMutationListener *L = getASTMutationListener()) {
7070    L->CompletedImplicitDefinition(Constructor);
7071  }
7072}
7073
7074void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7075  if (!D) return;
7076  AdjustDeclIfTemplate(D);
7077
7078  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7079
7080  if (!ClassDecl->isDependentType())
7081    CheckExplicitlyDefaultedMethods(ClassDecl);
7082}
7083
7084void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7085  // We start with an initial pass over the base classes to collect those that
7086  // inherit constructors from. If there are none, we can forgo all further
7087  // processing.
7088  typedef SmallVector<const RecordType *, 4> BasesVector;
7089  BasesVector BasesToInheritFrom;
7090  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7091                                          BaseE = ClassDecl->bases_end();
7092         BaseIt != BaseE; ++BaseIt) {
7093    if (BaseIt->getInheritConstructors()) {
7094      QualType Base = BaseIt->getType();
7095      if (Base->isDependentType()) {
7096        // If we inherit constructors from anything that is dependent, just
7097        // abort processing altogether. We'll get another chance for the
7098        // instantiations.
7099        return;
7100      }
7101      BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7102    }
7103  }
7104  if (BasesToInheritFrom.empty())
7105    return;
7106
7107  // Now collect the constructors that we already have in the current class.
7108  // Those take precedence over inherited constructors.
7109  // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7110  //   unless there is a user-declared constructor with the same signature in
7111  //   the class where the using-declaration appears.
7112  llvm::SmallSet<const Type *, 8> ExistingConstructors;
7113  for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7114                                    CtorE = ClassDecl->ctor_end();
7115       CtorIt != CtorE; ++CtorIt) {
7116    ExistingConstructors.insert(
7117        Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7118  }
7119
7120  DeclarationName CreatedCtorName =
7121      Context.DeclarationNames.getCXXConstructorName(
7122          ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7123
7124  // Now comes the true work.
7125  // First, we keep a map from constructor types to the base that introduced
7126  // them. Needed for finding conflicting constructors. We also keep the
7127  // actually inserted declarations in there, for pretty diagnostics.
7128  typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7129  typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7130  ConstructorToSourceMap InheritedConstructors;
7131  for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7132                             BaseE = BasesToInheritFrom.end();
7133       BaseIt != BaseE; ++BaseIt) {
7134    const RecordType *Base = *BaseIt;
7135    CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7136    CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7137    for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7138                                      CtorE = BaseDecl->ctor_end();
7139         CtorIt != CtorE; ++CtorIt) {
7140      // Find the using declaration for inheriting this base's constructors.
7141      // FIXME: Don't perform name lookup just to obtain a source location!
7142      DeclarationName Name =
7143          Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7144      LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7145      LookupQualifiedName(Result, CurContext);
7146      UsingDecl *UD = Result.getAsSingle<UsingDecl>();
7147      SourceLocation UsingLoc = UD ? UD->getLocation() :
7148                                     ClassDecl->getLocation();
7149
7150      // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7151      //   from the class X named in the using-declaration consists of actual
7152      //   constructors and notional constructors that result from the
7153      //   transformation of defaulted parameters as follows:
7154      //   - all non-template default constructors of X, and
7155      //   - for each non-template constructor of X that has at least one
7156      //     parameter with a default argument, the set of constructors that
7157      //     results from omitting any ellipsis parameter specification and
7158      //     successively omitting parameters with a default argument from the
7159      //     end of the parameter-type-list.
7160      CXXConstructorDecl *BaseCtor = *CtorIt;
7161      bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7162      const FunctionProtoType *BaseCtorType =
7163          BaseCtor->getType()->getAs<FunctionProtoType>();
7164
7165      for (unsigned params = BaseCtor->getMinRequiredArguments(),
7166                    maxParams = BaseCtor->getNumParams();
7167           params <= maxParams; ++params) {
7168        // Skip default constructors. They're never inherited.
7169        if (params == 0)
7170          continue;
7171        // Skip copy and move constructors for the same reason.
7172        if (CanBeCopyOrMove && params == 1)
7173          continue;
7174
7175        // Build up a function type for this particular constructor.
7176        // FIXME: The working paper does not consider that the exception spec
7177        // for the inheriting constructor might be larger than that of the
7178        // source. This code doesn't yet, either. When it does, this code will
7179        // need to be delayed until after exception specifications and in-class
7180        // member initializers are attached.
7181        const Type *NewCtorType;
7182        if (params == maxParams)
7183          NewCtorType = BaseCtorType;
7184        else {
7185          SmallVector<QualType, 16> Args;
7186          for (unsigned i = 0; i < params; ++i) {
7187            Args.push_back(BaseCtorType->getArgType(i));
7188          }
7189          FunctionProtoType::ExtProtoInfo ExtInfo =
7190              BaseCtorType->getExtProtoInfo();
7191          ExtInfo.Variadic = false;
7192          NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7193                                                Args.data(), params, ExtInfo)
7194                       .getTypePtr();
7195        }
7196        const Type *CanonicalNewCtorType =
7197            Context.getCanonicalType(NewCtorType);
7198
7199        // Now that we have the type, first check if the class already has a
7200        // constructor with this signature.
7201        if (ExistingConstructors.count(CanonicalNewCtorType))
7202          continue;
7203
7204        // Then we check if we have already declared an inherited constructor
7205        // with this signature.
7206        std::pair<ConstructorToSourceMap::iterator, bool> result =
7207            InheritedConstructors.insert(std::make_pair(
7208                CanonicalNewCtorType,
7209                std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7210        if (!result.second) {
7211          // Already in the map. If it came from a different class, that's an
7212          // error. Not if it's from the same.
7213          CanQualType PreviousBase = result.first->second.first;
7214          if (CanonicalBase != PreviousBase) {
7215            const CXXConstructorDecl *PrevCtor = result.first->second.second;
7216            const CXXConstructorDecl *PrevBaseCtor =
7217                PrevCtor->getInheritedConstructor();
7218            assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7219
7220            Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7221            Diag(BaseCtor->getLocation(),
7222                 diag::note_using_decl_constructor_conflict_current_ctor);
7223            Diag(PrevBaseCtor->getLocation(),
7224                 diag::note_using_decl_constructor_conflict_previous_ctor);
7225            Diag(PrevCtor->getLocation(),
7226                 diag::note_using_decl_constructor_conflict_previous_using);
7227          }
7228          continue;
7229        }
7230
7231        // OK, we're there, now add the constructor.
7232        // C++0x [class.inhctor]p8: [...] that would be performed by a
7233        //   user-written inline constructor [...]
7234        DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7235        CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
7236            Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7237            /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
7238            /*ImplicitlyDeclared=*/true,
7239            // FIXME: Due to a defect in the standard, we treat inherited
7240            // constructors as constexpr even if that makes them ill-formed.
7241            /*Constexpr=*/BaseCtor->isConstexpr());
7242        NewCtor->setAccess(BaseCtor->getAccess());
7243
7244        // Build up the parameter decls and add them.
7245        SmallVector<ParmVarDecl *, 16> ParamDecls;
7246        for (unsigned i = 0; i < params; ++i) {
7247          ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7248                                                   UsingLoc, UsingLoc,
7249                                                   /*IdentifierInfo=*/0,
7250                                                   BaseCtorType->getArgType(i),
7251                                                   /*TInfo=*/0, SC_None,
7252                                                   SC_None, /*DefaultArg=*/0));
7253        }
7254        NewCtor->setParams(ParamDecls);
7255        NewCtor->setInheritedConstructor(BaseCtor);
7256
7257        ClassDecl->addDecl(NewCtor);
7258        result.first->second.second = NewCtor;
7259      }
7260    }
7261  }
7262}
7263
7264Sema::ImplicitExceptionSpecification
7265Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7266  CXXRecordDecl *ClassDecl = MD->getParent();
7267
7268  // C++ [except.spec]p14:
7269  //   An implicitly declared special member function (Clause 12) shall have
7270  //   an exception-specification.
7271  ImplicitExceptionSpecification ExceptSpec(*this);
7272  if (ClassDecl->isInvalidDecl())
7273    return ExceptSpec;
7274
7275  // Direct base-class destructors.
7276  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7277                                       BEnd = ClassDecl->bases_end();
7278       B != BEnd; ++B) {
7279    if (B->isVirtual()) // Handled below.
7280      continue;
7281
7282    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7283      ExceptSpec.CalledDecl(B->getLocStart(),
7284                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7285  }
7286
7287  // Virtual base-class destructors.
7288  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7289                                       BEnd = ClassDecl->vbases_end();
7290       B != BEnd; ++B) {
7291    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7292      ExceptSpec.CalledDecl(B->getLocStart(),
7293                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7294  }
7295
7296  // Field destructors.
7297  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7298                               FEnd = ClassDecl->field_end();
7299       F != FEnd; ++F) {
7300    if (const RecordType *RecordTy
7301        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7302      ExceptSpec.CalledDecl(F->getLocation(),
7303                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
7304  }
7305
7306  return ExceptSpec;
7307}
7308
7309CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7310  // C++ [class.dtor]p2:
7311  //   If a class has no user-declared destructor, a destructor is
7312  //   declared implicitly. An implicitly-declared destructor is an
7313  //   inline public member of its class.
7314  assert(!ClassDecl->hasDeclaredDestructor());
7315
7316  // Create the actual destructor declaration.
7317  CanQualType ClassType
7318    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7319  SourceLocation ClassLoc = ClassDecl->getLocation();
7320  DeclarationName Name
7321    = Context.DeclarationNames.getCXXDestructorName(ClassType);
7322  DeclarationNameInfo NameInfo(Name, ClassLoc);
7323  CXXDestructorDecl *Destructor
7324      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7325                                  QualType(), 0, /*isInline=*/true,
7326                                  /*isImplicitlyDeclared=*/true);
7327  Destructor->setAccess(AS_public);
7328  Destructor->setDefaulted();
7329  Destructor->setImplicit();
7330  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7331
7332  // Build an exception specification pointing back at this destructor.
7333  FunctionProtoType::ExtProtoInfo EPI;
7334  EPI.ExceptionSpecType = EST_Unevaluated;
7335  EPI.ExceptionSpecDecl = Destructor;
7336  Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7337
7338  // Note that we have declared this destructor.
7339  ++ASTContext::NumImplicitDestructorsDeclared;
7340
7341  // Introduce this destructor into its scope.
7342  if (Scope *S = getScopeForContext(ClassDecl))
7343    PushOnScopeChains(Destructor, S, false);
7344  ClassDecl->addDecl(Destructor);
7345
7346  AddOverriddenMethods(ClassDecl, Destructor);
7347
7348  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7349    Destructor->setDeletedAsWritten();
7350
7351  return Destructor;
7352}
7353
7354void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
7355                                    CXXDestructorDecl *Destructor) {
7356  assert((Destructor->isDefaulted() &&
7357          !Destructor->doesThisDeclarationHaveABody() &&
7358          !Destructor->isDeleted()) &&
7359         "DefineImplicitDestructor - call it for implicit default dtor");
7360  CXXRecordDecl *ClassDecl = Destructor->getParent();
7361  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
7362
7363  if (Destructor->isInvalidDecl())
7364    return;
7365
7366  SynthesizedFunctionScope Scope(*this, Destructor);
7367
7368  DiagnosticErrorTrap Trap(Diags);
7369  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7370                                         Destructor->getParent());
7371
7372  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
7373    Diag(CurrentLocation, diag::note_member_synthesized_at)
7374      << CXXDestructor << Context.getTagDeclType(ClassDecl);
7375
7376    Destructor->setInvalidDecl();
7377    return;
7378  }
7379
7380  SourceLocation Loc = Destructor->getLocation();
7381  Destructor->setBody(new (Context) CompoundStmt(Loc));
7382  Destructor->setImplicitlyDefined(true);
7383  Destructor->setUsed();
7384  MarkVTableUsed(CurrentLocation, ClassDecl);
7385
7386  if (ASTMutationListener *L = getASTMutationListener()) {
7387    L->CompletedImplicitDefinition(Destructor);
7388  }
7389}
7390
7391/// \brief Perform any semantic analysis which needs to be delayed until all
7392/// pending class member declarations have been parsed.
7393void Sema::ActOnFinishCXXMemberDecls() {
7394  // Perform any deferred checking of exception specifications for virtual
7395  // destructors.
7396  for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7397       i != e; ++i) {
7398    const CXXDestructorDecl *Dtor =
7399        DelayedDestructorExceptionSpecChecks[i].first;
7400    assert(!Dtor->getParent()->isDependentType() &&
7401           "Should not ever add destructors of templates into the list.");
7402    CheckOverridingFunctionExceptionSpec(Dtor,
7403        DelayedDestructorExceptionSpecChecks[i].second);
7404  }
7405  DelayedDestructorExceptionSpecChecks.clear();
7406}
7407
7408void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7409                                         CXXDestructorDecl *Destructor) {
7410  assert(getLangOpts().CPlusPlus0x &&
7411         "adjusting dtor exception specs was introduced in c++11");
7412
7413  // C++11 [class.dtor]p3:
7414  //   A declaration of a destructor that does not have an exception-
7415  //   specification is implicitly considered to have the same exception-
7416  //   specification as an implicit declaration.
7417  const FunctionProtoType *DtorType = Destructor->getType()->
7418                                        getAs<FunctionProtoType>();
7419  if (DtorType->hasExceptionSpec())
7420    return;
7421
7422  // Replace the destructor's type, building off the existing one. Fortunately,
7423  // the only thing of interest in the destructor type is its extended info.
7424  // The return and arguments are fixed.
7425  FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7426  EPI.ExceptionSpecType = EST_Unevaluated;
7427  EPI.ExceptionSpecDecl = Destructor;
7428  Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7429
7430  // FIXME: If the destructor has a body that could throw, and the newly created
7431  // spec doesn't allow exceptions, we should emit a warning, because this
7432  // change in behavior can break conforming C++03 programs at runtime.
7433  // However, we don't have a body or an exception specification yet, so it
7434  // needs to be done somewhere else.
7435}
7436
7437/// When generating a defaulted copy or move assignment operator, if a field
7438/// should be copied with __builtin_memcpy rather than via explicit assignments,
7439/// do so. This optimization only applies for arrays of scalars, and for arrays
7440/// of class type where the selected copy/move-assignment operator is trivial.
7441static StmtResult
7442buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
7443                           Expr *To, Expr *From) {
7444  // Compute the size of the memory buffer to be copied.
7445  QualType SizeType = S.Context.getSizeType();
7446  llvm::APInt Size(S.Context.getTypeSize(SizeType),
7447                   S.Context.getTypeSizeInChars(T).getQuantity());
7448
7449  // Take the address of the field references for "from" and "to". We
7450  // directly construct UnaryOperators here because semantic analysis
7451  // does not permit us to take the address of an xvalue.
7452  From = new (S.Context) UnaryOperator(From, UO_AddrOf,
7453                         S.Context.getPointerType(From->getType()),
7454                         VK_RValue, OK_Ordinary, Loc);
7455  To = new (S.Context) UnaryOperator(To, UO_AddrOf,
7456                       S.Context.getPointerType(To->getType()),
7457                       VK_RValue, OK_Ordinary, Loc);
7458
7459  const Type *E = T->getBaseElementTypeUnsafe();
7460  bool NeedsCollectableMemCpy =
7461    E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
7462
7463  // Create a reference to the __builtin_objc_memmove_collectable function
7464  StringRef MemCpyName = NeedsCollectableMemCpy ?
7465    "__builtin_objc_memmove_collectable" :
7466    "__builtin_memcpy";
7467  LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
7468                 Sema::LookupOrdinaryName);
7469  S.LookupName(R, S.TUScope, true);
7470
7471  FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
7472  if (!MemCpy)
7473    // Something went horribly wrong earlier, and we will have complained
7474    // about it.
7475    return StmtError();
7476
7477  ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
7478                                            VK_RValue, Loc, 0);
7479  assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
7480
7481  Expr *CallArgs[] = {
7482    To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
7483  };
7484  ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
7485                                    Loc, CallArgs, Loc);
7486
7487  assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7488  return S.Owned(Call.takeAs<Stmt>());
7489}
7490
7491/// \brief Builds a statement that copies/moves the given entity from \p From to
7492/// \c To.
7493///
7494/// This routine is used to copy/move the members of a class with an
7495/// implicitly-declared copy/move assignment operator. When the entities being
7496/// copied are arrays, this routine builds for loops to copy them.
7497///
7498/// \param S The Sema object used for type-checking.
7499///
7500/// \param Loc The location where the implicit copy/move is being generated.
7501///
7502/// \param T The type of the expressions being copied/moved. Both expressions
7503/// must have this type.
7504///
7505/// \param To The expression we are copying/moving to.
7506///
7507/// \param From The expression we are copying/moving from.
7508///
7509/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
7510/// Otherwise, it's a non-static member subobject.
7511///
7512/// \param Copying Whether we're copying or moving.
7513///
7514/// \param Depth Internal parameter recording the depth of the recursion.
7515///
7516/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
7517/// if a memcpy should be used instead.
7518static StmtResult
7519buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
7520                                 Expr *To, Expr *From,
7521                                 bool CopyingBaseSubobject, bool Copying,
7522                                 unsigned Depth = 0) {
7523  // C++11 [class.copy]p28:
7524  //   Each subobject is assigned in the manner appropriate to its type:
7525  //
7526  //     - if the subobject is of class type, as if by a call to operator= with
7527  //       the subobject as the object expression and the corresponding
7528  //       subobject of x as a single function argument (as if by explicit
7529  //       qualification; that is, ignoring any possible virtual overriding
7530  //       functions in more derived classes);
7531  //
7532  // C++03 [class.copy]p13:
7533  //     - if the subobject is of class type, the copy assignment operator for
7534  //       the class is used (as if by explicit qualification; that is,
7535  //       ignoring any possible virtual overriding functions in more derived
7536  //       classes);
7537  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7538    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7539
7540    // Look for operator=.
7541    DeclarationName Name
7542      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7543    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7544    S.LookupQualifiedName(OpLookup, ClassDecl, false);
7545
7546    // Prior to C++11, filter out any result that isn't a copy/move-assignment
7547    // operator.
7548    if (!S.getLangOpts().CPlusPlus0x) {
7549      LookupResult::Filter F = OpLookup.makeFilter();
7550      while (F.hasNext()) {
7551        NamedDecl *D = F.next();
7552        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
7553          if (Method->isCopyAssignmentOperator() ||
7554              (!Copying && Method->isMoveAssignmentOperator()))
7555            continue;
7556
7557        F.erase();
7558      }
7559      F.done();
7560    }
7561
7562    // Suppress the protected check (C++ [class.protected]) for each of the
7563    // assignment operators we found. This strange dance is required when
7564    // we're assigning via a base classes's copy-assignment operator. To
7565    // ensure that we're getting the right base class subobject (without
7566    // ambiguities), we need to cast "this" to that subobject type; to
7567    // ensure that we don't go through the virtual call mechanism, we need
7568    // to qualify the operator= name with the base class (see below). However,
7569    // this means that if the base class has a protected copy assignment
7570    // operator, the protected member access check will fail. So, we
7571    // rewrite "protected" access to "public" access in this case, since we
7572    // know by construction that we're calling from a derived class.
7573    if (CopyingBaseSubobject) {
7574      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7575           L != LEnd; ++L) {
7576        if (L.getAccess() == AS_protected)
7577          L.setAccess(AS_public);
7578      }
7579    }
7580
7581    // Create the nested-name-specifier that will be used to qualify the
7582    // reference to operator=; this is required to suppress the virtual
7583    // call mechanism.
7584    CXXScopeSpec SS;
7585    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
7586    SS.MakeTrivial(S.Context,
7587                   NestedNameSpecifier::Create(S.Context, 0, false,
7588                                               CanonicalT),
7589                   Loc);
7590
7591    // Create the reference to operator=.
7592    ExprResult OpEqualRef
7593      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
7594                                   /*TemplateKWLoc=*/SourceLocation(),
7595                                   /*FirstQualifierInScope=*/0,
7596                                   OpLookup,
7597                                   /*TemplateArgs=*/0,
7598                                   /*SuppressQualifierCheck=*/true);
7599    if (OpEqualRef.isInvalid())
7600      return StmtError();
7601
7602    // Build the call to the assignment operator.
7603
7604    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
7605                                                  OpEqualRef.takeAs<Expr>(),
7606                                                  Loc, &From, 1, Loc);
7607    if (Call.isInvalid())
7608      return StmtError();
7609
7610    // If we built a call to a trivial 'operator=' while copying an array,
7611    // bail out. We'll replace the whole shebang with a memcpy.
7612    CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
7613    if (CE && CE->getMethodDecl()->isTrivial() && Depth)
7614      return StmtResult((Stmt*)0);
7615
7616    // Convert to an expression-statement, and clean up any produced
7617    // temporaries.
7618    return S.ActOnExprStmt(S.MakeFullExpr(Call.take(), Loc));
7619  }
7620
7621  //     - if the subobject is of scalar type, the built-in assignment
7622  //       operator is used.
7623  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7624  if (!ArrayTy) {
7625    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
7626    if (Assignment.isInvalid())
7627      return StmtError();
7628    return S.ActOnExprStmt(S.MakeFullExpr(Assignment.take(), Loc));
7629  }
7630
7631  //     - if the subobject is an array, each element is assigned, in the
7632  //       manner appropriate to the element type;
7633
7634  // Construct a loop over the array bounds, e.g.,
7635  //
7636  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7637  //
7638  // that will copy each of the array elements.
7639  QualType SizeType = S.Context.getSizeType();
7640
7641  // Create the iteration variable.
7642  IdentifierInfo *IterationVarName = 0;
7643  {
7644    SmallString<8> Str;
7645    llvm::raw_svector_ostream OS(Str);
7646    OS << "__i" << Depth;
7647    IterationVarName = &S.Context.Idents.get(OS.str());
7648  }
7649  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
7650                                          IterationVarName, SizeType,
7651                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
7652                                          SC_None, SC_None);
7653
7654  // Initialize the iteration variable to zero.
7655  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
7656  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
7657
7658  // Create a reference to the iteration variable; we'll use this several
7659  // times throughout.
7660  Expr *IterationVarRef
7661    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
7662  assert(IterationVarRef && "Reference to invented variable cannot fail!");
7663  Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7664  assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7665
7666  // Create the DeclStmt that holds the iteration variable.
7667  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7668
7669  // Subscript the "from" and "to" expressions with the iteration variable.
7670  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7671                                                         IterationVarRefRVal,
7672                                                         Loc));
7673  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7674                                                       IterationVarRefRVal,
7675                                                       Loc));
7676  if (!Copying) // Cast to rvalue
7677    From = CastForMoving(S, From);
7678
7679  // Build the copy/move for an individual element of the array.
7680  StmtResult Copy =
7681    buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
7682                                     To, From, CopyingBaseSubobject,
7683                                     Copying, Depth + 1);
7684  // Bail out if copying fails or if we determined that we should use memcpy.
7685  if (Copy.isInvalid() || !Copy.get())
7686    return Copy;
7687
7688  // Create the comparison against the array bound.
7689  llvm::APInt Upper
7690    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
7691  Expr *Comparison
7692    = new (S.Context) BinaryOperator(IterationVarRefRVal,
7693                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7694                                     BO_NE, S.Context.BoolTy,
7695                                     VK_RValue, OK_Ordinary, Loc, false);
7696
7697  // Create the pre-increment of the iteration variable.
7698  Expr *Increment
7699    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7700                                    VK_LValue, OK_Ordinary, Loc);
7701
7702  // Construct the loop that copies all elements of this array.
7703  return S.ActOnForStmt(Loc, Loc, InitStmt,
7704                        S.MakeFullExpr(Comparison),
7705                        0, S.MakeFullExpr(Increment),
7706                        Loc, Copy.take());
7707}
7708
7709static StmtResult
7710buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
7711                      Expr *To, Expr *From,
7712                      bool CopyingBaseSubobject, bool Copying) {
7713  // Maybe we should use a memcpy?
7714  if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
7715      T.isTriviallyCopyableType(S.Context))
7716    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
7717
7718  StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
7719                                                     CopyingBaseSubobject,
7720                                                     Copying, 0));
7721
7722  // If we ended up picking a trivial assignment operator for an array of a
7723  // non-trivially-copyable class type, just emit a memcpy.
7724  if (!Result.isInvalid() && !Result.get())
7725    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
7726
7727  return Result;
7728}
7729
7730/// Determine whether an implicit copy assignment operator for ClassDecl has a
7731/// const argument.
7732/// FIXME: It ought to be possible to store this on the record.
7733static bool isImplicitCopyAssignmentArgConst(Sema &S,
7734                                             CXXRecordDecl *ClassDecl) {
7735  if (ClassDecl->isInvalidDecl())
7736    return true;
7737
7738  // C++ [class.copy]p10:
7739  //   If the class definition does not explicitly declare a copy
7740  //   assignment operator, one is declared implicitly.
7741  //   The implicitly-defined copy assignment operator for a class X
7742  //   will have the form
7743  //
7744  //       X& X::operator=(const X&)
7745  //
7746  //   if
7747  //       -- each direct base class B of X has a copy assignment operator
7748  //          whose parameter is of type const B&, const volatile B& or B,
7749  //          and
7750  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7751                                       BaseEnd = ClassDecl->bases_end();
7752       Base != BaseEnd; ++Base) {
7753    // We'll handle this below
7754    if (S.getLangOpts().CPlusPlus0x && Base->isVirtual())
7755      continue;
7756
7757    assert(!Base->getType()->isDependentType() &&
7758           "Cannot generate implicit members for class with dependent bases.");
7759    CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7760    if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0))
7761      return false;
7762  }
7763
7764  // In C++11, the above citation has "or virtual" added
7765  if (S.getLangOpts().CPlusPlus0x) {
7766    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7767                                         BaseEnd = ClassDecl->vbases_end();
7768         Base != BaseEnd; ++Base) {
7769      assert(!Base->getType()->isDependentType() &&
7770             "Cannot generate implicit members for class with dependent bases.");
7771      CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7772      if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7773                                     false, 0))
7774        return false;
7775    }
7776  }
7777
7778  //       -- for all the nonstatic data members of X that are of a class
7779  //          type M (or array thereof), each such class type has a copy
7780  //          assignment operator whose parameter is of type const M&,
7781  //          const volatile M& or M.
7782  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7783                                  FieldEnd = ClassDecl->field_end();
7784       Field != FieldEnd; ++Field) {
7785    QualType FieldType = S.Context.getBaseElementType(Field->getType());
7786    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl())
7787      if (!S.LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const,
7788                                     false, 0))
7789        return false;
7790  }
7791
7792  //   Otherwise, the implicitly declared copy assignment operator will
7793  //   have the form
7794  //
7795  //       X& X::operator=(X&)
7796
7797  return true;
7798}
7799
7800Sema::ImplicitExceptionSpecification
7801Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
7802  CXXRecordDecl *ClassDecl = MD->getParent();
7803
7804  ImplicitExceptionSpecification ExceptSpec(*this);
7805  if (ClassDecl->isInvalidDecl())
7806    return ExceptSpec;
7807
7808  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
7809  assert(T->getNumArgs() == 1 && "not a copy assignment op");
7810  unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
7811
7812  // C++ [except.spec]p14:
7813  //   An implicitly declared special member function (Clause 12) shall have an
7814  //   exception-specification. [...]
7815
7816  // It is unspecified whether or not an implicit copy assignment operator
7817  // attempts to deduplicate calls to assignment operators of virtual bases are
7818  // made. As such, this exception specification is effectively unspecified.
7819  // Based on a similar decision made for constness in C++0x, we're erring on
7820  // the side of assuming such calls to be made regardless of whether they
7821  // actually happen.
7822  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7823                                       BaseEnd = ClassDecl->bases_end();
7824       Base != BaseEnd; ++Base) {
7825    if (Base->isVirtual())
7826      continue;
7827
7828    CXXRecordDecl *BaseClassDecl
7829      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7830    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7831                                                            ArgQuals, false, 0))
7832      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
7833  }
7834
7835  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7836                                       BaseEnd = ClassDecl->vbases_end();
7837       Base != BaseEnd; ++Base) {
7838    CXXRecordDecl *BaseClassDecl
7839      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7840    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7841                                                            ArgQuals, false, 0))
7842      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
7843  }
7844
7845  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7846                                  FieldEnd = ClassDecl->field_end();
7847       Field != FieldEnd;
7848       ++Field) {
7849    QualType FieldType = Context.getBaseElementType(Field->getType());
7850    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7851      if (CXXMethodDecl *CopyAssign =
7852          LookupCopyingAssignment(FieldClassDecl,
7853                                  ArgQuals | FieldType.getCVRQualifiers(),
7854                                  false, 0))
7855        ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
7856    }
7857  }
7858
7859  return ExceptSpec;
7860}
7861
7862CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7863  // Note: The following rules are largely analoguous to the copy
7864  // constructor rules. Note that virtual bases are not taken into account
7865  // for determining the argument type of the operator. Note also that
7866  // operators taking an object instead of a reference are allowed.
7867  assert(!ClassDecl->hasDeclaredCopyAssignment());
7868
7869  QualType ArgType = Context.getTypeDeclType(ClassDecl);
7870  QualType RetType = Context.getLValueReferenceType(ArgType);
7871  if (isImplicitCopyAssignmentArgConst(*this, ClassDecl))
7872    ArgType = ArgType.withConst();
7873  ArgType = Context.getLValueReferenceType(ArgType);
7874
7875  //   An implicitly-declared copy assignment operator is an inline public
7876  //   member of its class.
7877  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7878  SourceLocation ClassLoc = ClassDecl->getLocation();
7879  DeclarationNameInfo NameInfo(Name, ClassLoc);
7880  CXXMethodDecl *CopyAssignment
7881    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
7882                            /*TInfo=*/0, /*isStatic=*/false,
7883                            /*StorageClassAsWritten=*/SC_None,
7884                            /*isInline=*/true, /*isConstexpr=*/false,
7885                            SourceLocation());
7886  CopyAssignment->setAccess(AS_public);
7887  CopyAssignment->setDefaulted();
7888  CopyAssignment->setImplicit();
7889  CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
7890
7891  // Build an exception specification pointing back at this member.
7892  FunctionProtoType::ExtProtoInfo EPI;
7893  EPI.ExceptionSpecType = EST_Unevaluated;
7894  EPI.ExceptionSpecDecl = CopyAssignment;
7895  CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
7896
7897  // Add the parameter to the operator.
7898  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
7899                                               ClassLoc, ClassLoc, /*Id=*/0,
7900                                               ArgType, /*TInfo=*/0,
7901                                               SC_None,
7902                                               SC_None, 0);
7903  CopyAssignment->setParams(FromParam);
7904
7905  // Note that we have added this copy-assignment operator.
7906  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
7907
7908  if (Scope *S = getScopeForContext(ClassDecl))
7909    PushOnScopeChains(CopyAssignment, S, false);
7910  ClassDecl->addDecl(CopyAssignment);
7911
7912  // C++0x [class.copy]p19:
7913  //   ....  If the class definition does not explicitly declare a copy
7914  //   assignment operator, there is no user-declared move constructor, and
7915  //   there is no user-declared move assignment operator, a copy assignment
7916  //   operator is implicitly declared as defaulted.
7917  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
7918    CopyAssignment->setDeletedAsWritten();
7919
7920  AddOverriddenMethods(ClassDecl, CopyAssignment);
7921  return CopyAssignment;
7922}
7923
7924void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7925                                        CXXMethodDecl *CopyAssignOperator) {
7926  assert((CopyAssignOperator->isDefaulted() &&
7927          CopyAssignOperator->isOverloadedOperator() &&
7928          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
7929          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7930          !CopyAssignOperator->isDeleted()) &&
7931         "DefineImplicitCopyAssignment called for wrong function");
7932
7933  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7934
7935  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7936    CopyAssignOperator->setInvalidDecl();
7937    return;
7938  }
7939
7940  CopyAssignOperator->setUsed();
7941
7942  SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
7943  DiagnosticErrorTrap Trap(Diags);
7944
7945  // C++0x [class.copy]p30:
7946  //   The implicitly-defined or explicitly-defaulted copy assignment operator
7947  //   for a non-union class X performs memberwise copy assignment of its
7948  //   subobjects. The direct base classes of X are assigned first, in the
7949  //   order of their declaration in the base-specifier-list, and then the
7950  //   immediate non-static data members of X are assigned, in the order in
7951  //   which they were declared in the class definition.
7952
7953  // The statements that form the synthesized function body.
7954  SmallVector<Stmt*, 8> Statements;
7955
7956  // The parameter for the "other" object, which we are copying from.
7957  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7958  Qualifiers OtherQuals = Other->getType().getQualifiers();
7959  QualType OtherRefType = Other->getType();
7960  if (const LValueReferenceType *OtherRef
7961                                = OtherRefType->getAs<LValueReferenceType>()) {
7962    OtherRefType = OtherRef->getPointeeType();
7963    OtherQuals = OtherRefType.getQualifiers();
7964  }
7965
7966  // Our location for everything implicitly-generated.
7967  SourceLocation Loc = CopyAssignOperator->getLocation();
7968
7969  // Construct a reference to the "other" object. We'll be using this
7970  // throughout the generated ASTs.
7971  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7972  assert(OtherRef && "Reference to parameter cannot fail!");
7973
7974  // Construct the "this" pointer. We'll be using this throughout the generated
7975  // ASTs.
7976  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7977  assert(This && "Reference to this cannot fail!");
7978
7979  // Assign base classes.
7980  bool Invalid = false;
7981  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7982       E = ClassDecl->bases_end(); Base != E; ++Base) {
7983    // Form the assignment:
7984    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7985    QualType BaseType = Base->getType().getUnqualifiedType();
7986    if (!BaseType->isRecordType()) {
7987      Invalid = true;
7988      continue;
7989    }
7990
7991    CXXCastPath BasePath;
7992    BasePath.push_back(Base);
7993
7994    // Construct the "from" expression, which is an implicit cast to the
7995    // appropriately-qualified base type.
7996    Expr *From = OtherRef;
7997    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7998                             CK_UncheckedDerivedToBase,
7999                             VK_LValue, &BasePath).take();
8000
8001    // Dereference "this".
8002    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8003
8004    // Implicitly cast "this" to the appropriately-qualified base type.
8005    To = ImpCastExprToType(To.take(),
8006                           Context.getCVRQualifiedType(BaseType,
8007                                     CopyAssignOperator->getTypeQualifiers()),
8008                           CK_UncheckedDerivedToBase,
8009                           VK_LValue, &BasePath);
8010
8011    // Build the copy.
8012    StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
8013                                            To.get(), From,
8014                                            /*CopyingBaseSubobject=*/true,
8015                                            /*Copying=*/true);
8016    if (Copy.isInvalid()) {
8017      Diag(CurrentLocation, diag::note_member_synthesized_at)
8018        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8019      CopyAssignOperator->setInvalidDecl();
8020      return;
8021    }
8022
8023    // Success! Record the copy.
8024    Statements.push_back(Copy.takeAs<Expr>());
8025  }
8026
8027  // Assign non-static members.
8028  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8029                                  FieldEnd = ClassDecl->field_end();
8030       Field != FieldEnd; ++Field) {
8031    if (Field->isUnnamedBitfield())
8032      continue;
8033
8034    // Check for members of reference type; we can't copy those.
8035    if (Field->getType()->isReferenceType()) {
8036      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8037        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8038      Diag(Field->getLocation(), diag::note_declared_at);
8039      Diag(CurrentLocation, diag::note_member_synthesized_at)
8040        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8041      Invalid = true;
8042      continue;
8043    }
8044
8045    // Check for members of const-qualified, non-class type.
8046    QualType BaseType = Context.getBaseElementType(Field->getType());
8047    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8048      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8049        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8050      Diag(Field->getLocation(), diag::note_declared_at);
8051      Diag(CurrentLocation, diag::note_member_synthesized_at)
8052        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8053      Invalid = true;
8054      continue;
8055    }
8056
8057    // Suppress assigning zero-width bitfields.
8058    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8059      continue;
8060
8061    QualType FieldType = Field->getType().getNonReferenceType();
8062    if (FieldType->isIncompleteArrayType()) {
8063      assert(ClassDecl->hasFlexibleArrayMember() &&
8064             "Incomplete array type is not valid");
8065      continue;
8066    }
8067
8068    // Build references to the field in the object we're copying from and to.
8069    CXXScopeSpec SS; // Intentionally empty
8070    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8071                              LookupMemberName);
8072    MemberLookup.addDecl(*Field);
8073    MemberLookup.resolveKind();
8074    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8075                                               Loc, /*IsArrow=*/false,
8076                                               SS, SourceLocation(), 0,
8077                                               MemberLookup, 0);
8078    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8079                                             Loc, /*IsArrow=*/true,
8080                                             SS, SourceLocation(), 0,
8081                                             MemberLookup, 0);
8082    assert(!From.isInvalid() && "Implicit field reference cannot fail");
8083    assert(!To.isInvalid() && "Implicit field reference cannot fail");
8084
8085    // Build the copy of this field.
8086    StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
8087                                            To.get(), From.get(),
8088                                            /*CopyingBaseSubobject=*/false,
8089                                            /*Copying=*/true);
8090    if (Copy.isInvalid()) {
8091      Diag(CurrentLocation, diag::note_member_synthesized_at)
8092        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8093      CopyAssignOperator->setInvalidDecl();
8094      return;
8095    }
8096
8097    // Success! Record the copy.
8098    Statements.push_back(Copy.takeAs<Stmt>());
8099  }
8100
8101  if (!Invalid) {
8102    // Add a "return *this;"
8103    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8104
8105    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8106    if (Return.isInvalid())
8107      Invalid = true;
8108    else {
8109      Statements.push_back(Return.takeAs<Stmt>());
8110
8111      if (Trap.hasErrorOccurred()) {
8112        Diag(CurrentLocation, diag::note_member_synthesized_at)
8113          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8114        Invalid = true;
8115      }
8116    }
8117  }
8118
8119  if (Invalid) {
8120    CopyAssignOperator->setInvalidDecl();
8121    return;
8122  }
8123
8124  StmtResult Body;
8125  {
8126    CompoundScopeRAII CompoundScope(*this);
8127    Body = ActOnCompoundStmt(Loc, Loc, Statements,
8128                             /*isStmtExpr=*/false);
8129    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8130  }
8131  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
8132
8133  if (ASTMutationListener *L = getASTMutationListener()) {
8134    L->CompletedImplicitDefinition(CopyAssignOperator);
8135  }
8136}
8137
8138Sema::ImplicitExceptionSpecification
8139Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8140  CXXRecordDecl *ClassDecl = MD->getParent();
8141
8142  ImplicitExceptionSpecification ExceptSpec(*this);
8143  if (ClassDecl->isInvalidDecl())
8144    return ExceptSpec;
8145
8146  // C++0x [except.spec]p14:
8147  //   An implicitly declared special member function (Clause 12) shall have an
8148  //   exception-specification. [...]
8149
8150  // It is unspecified whether or not an implicit move assignment operator
8151  // attempts to deduplicate calls to assignment operators of virtual bases are
8152  // made. As such, this exception specification is effectively unspecified.
8153  // Based on a similar decision made for constness in C++0x, we're erring on
8154  // the side of assuming such calls to be made regardless of whether they
8155  // actually happen.
8156  // Note that a move constructor is not implicitly declared when there are
8157  // virtual bases, but it can still be user-declared and explicitly defaulted.
8158  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8159                                       BaseEnd = ClassDecl->bases_end();
8160       Base != BaseEnd; ++Base) {
8161    if (Base->isVirtual())
8162      continue;
8163
8164    CXXRecordDecl *BaseClassDecl
8165      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8166    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8167                                                           0, false, 0))
8168      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8169  }
8170
8171  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8172                                       BaseEnd = ClassDecl->vbases_end();
8173       Base != BaseEnd; ++Base) {
8174    CXXRecordDecl *BaseClassDecl
8175      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8176    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8177                                                           0, false, 0))
8178      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8179  }
8180
8181  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8182                                  FieldEnd = ClassDecl->field_end();
8183       Field != FieldEnd;
8184       ++Field) {
8185    QualType FieldType = Context.getBaseElementType(Field->getType());
8186    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8187      if (CXXMethodDecl *MoveAssign =
8188              LookupMovingAssignment(FieldClassDecl,
8189                                     FieldType.getCVRQualifiers(),
8190                                     false, 0))
8191        ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
8192    }
8193  }
8194
8195  return ExceptSpec;
8196}
8197
8198/// Determine whether the class type has any direct or indirect virtual base
8199/// classes which have a non-trivial move assignment operator.
8200static bool
8201hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8202  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8203                                          BaseEnd = ClassDecl->vbases_end();
8204       Base != BaseEnd; ++Base) {
8205    CXXRecordDecl *BaseClass =
8206        cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8207
8208    // Try to declare the move assignment. If it would be deleted, then the
8209    // class does not have a non-trivial move assignment.
8210    if (BaseClass->needsImplicitMoveAssignment())
8211      S.DeclareImplicitMoveAssignment(BaseClass);
8212
8213    if (BaseClass->hasNonTrivialMoveAssignment())
8214      return true;
8215  }
8216
8217  return false;
8218}
8219
8220/// Determine whether the given type either has a move constructor or is
8221/// trivially copyable.
8222static bool
8223hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8224  Type = S.Context.getBaseElementType(Type);
8225
8226  // FIXME: Technically, non-trivially-copyable non-class types, such as
8227  // reference types, are supposed to return false here, but that appears
8228  // to be a standard defect.
8229  CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
8230  if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
8231    return true;
8232
8233  if (Type.isTriviallyCopyableType(S.Context))
8234    return true;
8235
8236  if (IsConstructor) {
8237    if (ClassDecl->needsImplicitMoveConstructor())
8238      S.DeclareImplicitMoveConstructor(ClassDecl);
8239    return ClassDecl->hasDeclaredMoveConstructor();
8240  }
8241
8242  if (ClassDecl->needsImplicitMoveAssignment())
8243    S.DeclareImplicitMoveAssignment(ClassDecl);
8244  return ClassDecl->hasDeclaredMoveAssignment();
8245}
8246
8247/// Determine whether all non-static data members and direct or virtual bases
8248/// of class \p ClassDecl have either a move operation, or are trivially
8249/// copyable.
8250static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8251                                            bool IsConstructor) {
8252  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8253                                          BaseEnd = ClassDecl->bases_end();
8254       Base != BaseEnd; ++Base) {
8255    if (Base->isVirtual())
8256      continue;
8257
8258    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8259      return false;
8260  }
8261
8262  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8263                                          BaseEnd = ClassDecl->vbases_end();
8264       Base != BaseEnd; ++Base) {
8265    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8266      return false;
8267  }
8268
8269  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8270                                     FieldEnd = ClassDecl->field_end();
8271       Field != FieldEnd; ++Field) {
8272    if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
8273      return false;
8274  }
8275
8276  return true;
8277}
8278
8279CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8280  // C++11 [class.copy]p20:
8281  //   If the definition of a class X does not explicitly declare a move
8282  //   assignment operator, one will be implicitly declared as defaulted
8283  //   if and only if:
8284  //
8285  //   - [first 4 bullets]
8286  assert(ClassDecl->needsImplicitMoveAssignment());
8287
8288  // [Checked after we build the declaration]
8289  //   - the move assignment operator would not be implicitly defined as
8290  //     deleted,
8291
8292  // [DR1402]:
8293  //   - X has no direct or indirect virtual base class with a non-trivial
8294  //     move assignment operator, and
8295  //   - each of X's non-static data members and direct or virtual base classes
8296  //     has a type that either has a move assignment operator or is trivially
8297  //     copyable.
8298  if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8299      !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8300    ClassDecl->setFailedImplicitMoveAssignment();
8301    return 0;
8302  }
8303
8304  // Note: The following rules are largely analoguous to the move
8305  // constructor rules.
8306
8307  QualType ArgType = Context.getTypeDeclType(ClassDecl);
8308  QualType RetType = Context.getLValueReferenceType(ArgType);
8309  ArgType = Context.getRValueReferenceType(ArgType);
8310
8311  //   An implicitly-declared move assignment operator is an inline public
8312  //   member of its class.
8313  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8314  SourceLocation ClassLoc = ClassDecl->getLocation();
8315  DeclarationNameInfo NameInfo(Name, ClassLoc);
8316  CXXMethodDecl *MoveAssignment
8317    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8318                            /*TInfo=*/0, /*isStatic=*/false,
8319                            /*StorageClassAsWritten=*/SC_None,
8320                            /*isInline=*/true,
8321                            /*isConstexpr=*/false,
8322                            SourceLocation());
8323  MoveAssignment->setAccess(AS_public);
8324  MoveAssignment->setDefaulted();
8325  MoveAssignment->setImplicit();
8326  MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8327
8328  // Build an exception specification pointing back at this member.
8329  FunctionProtoType::ExtProtoInfo EPI;
8330  EPI.ExceptionSpecType = EST_Unevaluated;
8331  EPI.ExceptionSpecDecl = MoveAssignment;
8332  MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8333
8334  // Add the parameter to the operator.
8335  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8336                                               ClassLoc, ClassLoc, /*Id=*/0,
8337                                               ArgType, /*TInfo=*/0,
8338                                               SC_None,
8339                                               SC_None, 0);
8340  MoveAssignment->setParams(FromParam);
8341
8342  // Note that we have added this copy-assignment operator.
8343  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8344
8345  // C++0x [class.copy]p9:
8346  //   If the definition of a class X does not explicitly declare a move
8347  //   assignment operator, one will be implicitly declared as defaulted if and
8348  //   only if:
8349  //   [...]
8350  //   - the move assignment operator would not be implicitly defined as
8351  //     deleted.
8352  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
8353    // Cache this result so that we don't try to generate this over and over
8354    // on every lookup, leaking memory and wasting time.
8355    ClassDecl->setFailedImplicitMoveAssignment();
8356    return 0;
8357  }
8358
8359  if (Scope *S = getScopeForContext(ClassDecl))
8360    PushOnScopeChains(MoveAssignment, S, false);
8361  ClassDecl->addDecl(MoveAssignment);
8362
8363  AddOverriddenMethods(ClassDecl, MoveAssignment);
8364  return MoveAssignment;
8365}
8366
8367void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8368                                        CXXMethodDecl *MoveAssignOperator) {
8369  assert((MoveAssignOperator->isDefaulted() &&
8370          MoveAssignOperator->isOverloadedOperator() &&
8371          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8372          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8373          !MoveAssignOperator->isDeleted()) &&
8374         "DefineImplicitMoveAssignment called for wrong function");
8375
8376  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8377
8378  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8379    MoveAssignOperator->setInvalidDecl();
8380    return;
8381  }
8382
8383  MoveAssignOperator->setUsed();
8384
8385  SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
8386  DiagnosticErrorTrap Trap(Diags);
8387
8388  // C++0x [class.copy]p28:
8389  //   The implicitly-defined or move assignment operator for a non-union class
8390  //   X performs memberwise move assignment of its subobjects. The direct base
8391  //   classes of X are assigned first, in the order of their declaration in the
8392  //   base-specifier-list, and then the immediate non-static data members of X
8393  //   are assigned, in the order in which they were declared in the class
8394  //   definition.
8395
8396  // The statements that form the synthesized function body.
8397  SmallVector<Stmt*, 8> Statements;
8398
8399  // The parameter for the "other" object, which we are move from.
8400  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8401  QualType OtherRefType = Other->getType()->
8402      getAs<RValueReferenceType>()->getPointeeType();
8403  assert(OtherRefType.getQualifiers() == 0 &&
8404         "Bad argument type of defaulted move assignment");
8405
8406  // Our location for everything implicitly-generated.
8407  SourceLocation Loc = MoveAssignOperator->getLocation();
8408
8409  // Construct a reference to the "other" object. We'll be using this
8410  // throughout the generated ASTs.
8411  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8412  assert(OtherRef && "Reference to parameter cannot fail!");
8413  // Cast to rvalue.
8414  OtherRef = CastForMoving(*this, OtherRef);
8415
8416  // Construct the "this" pointer. We'll be using this throughout the generated
8417  // ASTs.
8418  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8419  assert(This && "Reference to this cannot fail!");
8420
8421  // Assign base classes.
8422  bool Invalid = false;
8423  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8424       E = ClassDecl->bases_end(); Base != E; ++Base) {
8425    // Form the assignment:
8426    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8427    QualType BaseType = Base->getType().getUnqualifiedType();
8428    if (!BaseType->isRecordType()) {
8429      Invalid = true;
8430      continue;
8431    }
8432
8433    CXXCastPath BasePath;
8434    BasePath.push_back(Base);
8435
8436    // Construct the "from" expression, which is an implicit cast to the
8437    // appropriately-qualified base type.
8438    Expr *From = OtherRef;
8439    From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
8440                             VK_XValue, &BasePath).take();
8441
8442    // Dereference "this".
8443    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8444
8445    // Implicitly cast "this" to the appropriately-qualified base type.
8446    To = ImpCastExprToType(To.take(),
8447                           Context.getCVRQualifiedType(BaseType,
8448                                     MoveAssignOperator->getTypeQualifiers()),
8449                           CK_UncheckedDerivedToBase,
8450                           VK_LValue, &BasePath);
8451
8452    // Build the move.
8453    StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
8454                                            To.get(), From,
8455                                            /*CopyingBaseSubobject=*/true,
8456                                            /*Copying=*/false);
8457    if (Move.isInvalid()) {
8458      Diag(CurrentLocation, diag::note_member_synthesized_at)
8459        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8460      MoveAssignOperator->setInvalidDecl();
8461      return;
8462    }
8463
8464    // Success! Record the move.
8465    Statements.push_back(Move.takeAs<Expr>());
8466  }
8467
8468  // Assign non-static members.
8469  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8470                                  FieldEnd = ClassDecl->field_end();
8471       Field != FieldEnd; ++Field) {
8472    if (Field->isUnnamedBitfield())
8473      continue;
8474
8475    // Check for members of reference type; we can't move those.
8476    if (Field->getType()->isReferenceType()) {
8477      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8478        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8479      Diag(Field->getLocation(), diag::note_declared_at);
8480      Diag(CurrentLocation, diag::note_member_synthesized_at)
8481        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8482      Invalid = true;
8483      continue;
8484    }
8485
8486    // Check for members of const-qualified, non-class type.
8487    QualType BaseType = Context.getBaseElementType(Field->getType());
8488    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8489      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8490        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8491      Diag(Field->getLocation(), diag::note_declared_at);
8492      Diag(CurrentLocation, diag::note_member_synthesized_at)
8493        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8494      Invalid = true;
8495      continue;
8496    }
8497
8498    // Suppress assigning zero-width bitfields.
8499    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8500      continue;
8501
8502    QualType FieldType = Field->getType().getNonReferenceType();
8503    if (FieldType->isIncompleteArrayType()) {
8504      assert(ClassDecl->hasFlexibleArrayMember() &&
8505             "Incomplete array type is not valid");
8506      continue;
8507    }
8508
8509    // Build references to the field in the object we're copying from and to.
8510    CXXScopeSpec SS; // Intentionally empty
8511    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8512                              LookupMemberName);
8513    MemberLookup.addDecl(*Field);
8514    MemberLookup.resolveKind();
8515    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8516                                               Loc, /*IsArrow=*/false,
8517                                               SS, SourceLocation(), 0,
8518                                               MemberLookup, 0);
8519    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8520                                             Loc, /*IsArrow=*/true,
8521                                             SS, SourceLocation(), 0,
8522                                             MemberLookup, 0);
8523    assert(!From.isInvalid() && "Implicit field reference cannot fail");
8524    assert(!To.isInvalid() && "Implicit field reference cannot fail");
8525
8526    assert(!From.get()->isLValue() && // could be xvalue or prvalue
8527        "Member reference with rvalue base must be rvalue except for reference "
8528        "members, which aren't allowed for move assignment.");
8529
8530    // Build the move of this field.
8531    StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
8532                                            To.get(), From.get(),
8533                                            /*CopyingBaseSubobject=*/false,
8534                                            /*Copying=*/false);
8535    if (Move.isInvalid()) {
8536      Diag(CurrentLocation, diag::note_member_synthesized_at)
8537        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8538      MoveAssignOperator->setInvalidDecl();
8539      return;
8540    }
8541
8542    // Success! Record the copy.
8543    Statements.push_back(Move.takeAs<Stmt>());
8544  }
8545
8546  if (!Invalid) {
8547    // Add a "return *this;"
8548    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8549
8550    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8551    if (Return.isInvalid())
8552      Invalid = true;
8553    else {
8554      Statements.push_back(Return.takeAs<Stmt>());
8555
8556      if (Trap.hasErrorOccurred()) {
8557        Diag(CurrentLocation, diag::note_member_synthesized_at)
8558          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8559        Invalid = true;
8560      }
8561    }
8562  }
8563
8564  if (Invalid) {
8565    MoveAssignOperator->setInvalidDecl();
8566    return;
8567  }
8568
8569  StmtResult Body;
8570  {
8571    CompoundScopeRAII CompoundScope(*this);
8572    Body = ActOnCompoundStmt(Loc, Loc, Statements,
8573                             /*isStmtExpr=*/false);
8574    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8575  }
8576  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8577
8578  if (ASTMutationListener *L = getASTMutationListener()) {
8579    L->CompletedImplicitDefinition(MoveAssignOperator);
8580  }
8581}
8582
8583/// Determine whether an implicit copy constructor for ClassDecl has a const
8584/// argument.
8585/// FIXME: It ought to be possible to store this on the record.
8586static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl) {
8587  if (ClassDecl->isInvalidDecl())
8588    return true;
8589
8590  // C++ [class.copy]p5:
8591  //   The implicitly-declared copy constructor for a class X will
8592  //   have the form
8593  //
8594  //       X::X(const X&)
8595  //
8596  //   if
8597  //     -- each direct or virtual base class B of X has a copy
8598  //        constructor whose first parameter is of type const B& or
8599  //        const volatile B&, and
8600  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8601                                       BaseEnd = ClassDecl->bases_end();
8602       Base != BaseEnd; ++Base) {
8603    // Virtual bases are handled below.
8604    if (Base->isVirtual())
8605      continue;
8606
8607    CXXRecordDecl *BaseClassDecl
8608      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8609    // FIXME: This lookup is wrong. If the copy ctor for a member or base is
8610    // ambiguous, we should still produce a constructor with a const-qualified
8611    // parameter.
8612    if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8613      return false;
8614  }
8615
8616  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8617                                       BaseEnd = ClassDecl->vbases_end();
8618       Base != BaseEnd; ++Base) {
8619    CXXRecordDecl *BaseClassDecl
8620      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8621    if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8622      return false;
8623  }
8624
8625  //     -- for all the nonstatic data members of X that are of a
8626  //        class type M (or array thereof), each such class type
8627  //        has a copy constructor whose first parameter is of type
8628  //        const M& or const volatile M&.
8629  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8630                                  FieldEnd = ClassDecl->field_end();
8631       Field != FieldEnd; ++Field) {
8632    QualType FieldType = S.Context.getBaseElementType(Field->getType());
8633    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8634      if (!S.LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const))
8635        return false;
8636    }
8637  }
8638
8639  //   Otherwise, the implicitly declared copy constructor will have
8640  //   the form
8641  //
8642  //       X::X(X&)
8643
8644  return true;
8645}
8646
8647Sema::ImplicitExceptionSpecification
8648Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
8649  CXXRecordDecl *ClassDecl = MD->getParent();
8650
8651  ImplicitExceptionSpecification ExceptSpec(*this);
8652  if (ClassDecl->isInvalidDecl())
8653    return ExceptSpec;
8654
8655  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8656  assert(T->getNumArgs() >= 1 && "not a copy ctor");
8657  unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8658
8659  // C++ [except.spec]p14:
8660  //   An implicitly declared special member function (Clause 12) shall have an
8661  //   exception-specification. [...]
8662  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8663                                       BaseEnd = ClassDecl->bases_end();
8664       Base != BaseEnd;
8665       ++Base) {
8666    // Virtual bases are handled below.
8667    if (Base->isVirtual())
8668      continue;
8669
8670    CXXRecordDecl *BaseClassDecl
8671      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8672    if (CXXConstructorDecl *CopyConstructor =
8673          LookupCopyingConstructor(BaseClassDecl, Quals))
8674      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
8675  }
8676  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8677                                       BaseEnd = ClassDecl->vbases_end();
8678       Base != BaseEnd;
8679       ++Base) {
8680    CXXRecordDecl *BaseClassDecl
8681      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8682    if (CXXConstructorDecl *CopyConstructor =
8683          LookupCopyingConstructor(BaseClassDecl, Quals))
8684      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
8685  }
8686  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8687                                  FieldEnd = ClassDecl->field_end();
8688       Field != FieldEnd;
8689       ++Field) {
8690    QualType FieldType = Context.getBaseElementType(Field->getType());
8691    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8692      if (CXXConstructorDecl *CopyConstructor =
8693              LookupCopyingConstructor(FieldClassDecl,
8694                                       Quals | FieldType.getCVRQualifiers()))
8695      ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
8696    }
8697  }
8698
8699  return ExceptSpec;
8700}
8701
8702CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8703                                                    CXXRecordDecl *ClassDecl) {
8704  // C++ [class.copy]p4:
8705  //   If the class definition does not explicitly declare a copy
8706  //   constructor, one is declared implicitly.
8707  assert(!ClassDecl->hasDeclaredCopyConstructor());
8708
8709  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8710  QualType ArgType = ClassType;
8711  bool Const = isImplicitCopyCtorArgConst(*this, ClassDecl);
8712  if (Const)
8713    ArgType = ArgType.withConst();
8714  ArgType = Context.getLValueReferenceType(ArgType);
8715
8716  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8717                                                     CXXCopyConstructor,
8718                                                     Const);
8719
8720  DeclarationName Name
8721    = Context.DeclarationNames.getCXXConstructorName(
8722                                           Context.getCanonicalType(ClassType));
8723  SourceLocation ClassLoc = ClassDecl->getLocation();
8724  DeclarationNameInfo NameInfo(Name, ClassLoc);
8725
8726  //   An implicitly-declared copy constructor is an inline public
8727  //   member of its class.
8728  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8729      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
8730      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8731      Constexpr);
8732  CopyConstructor->setAccess(AS_public);
8733  CopyConstructor->setDefaulted();
8734  CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8735
8736  // Build an exception specification pointing back at this member.
8737  FunctionProtoType::ExtProtoInfo EPI;
8738  EPI.ExceptionSpecType = EST_Unevaluated;
8739  EPI.ExceptionSpecDecl = CopyConstructor;
8740  CopyConstructor->setType(
8741      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8742
8743  // Note that we have declared this constructor.
8744  ++ASTContext::NumImplicitCopyConstructorsDeclared;
8745
8746  // Add the parameter to the constructor.
8747  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
8748                                               ClassLoc, ClassLoc,
8749                                               /*IdentifierInfo=*/0,
8750                                               ArgType, /*TInfo=*/0,
8751                                               SC_None,
8752                                               SC_None, 0);
8753  CopyConstructor->setParams(FromParam);
8754
8755  if (Scope *S = getScopeForContext(ClassDecl))
8756    PushOnScopeChains(CopyConstructor, S, false);
8757  ClassDecl->addDecl(CopyConstructor);
8758
8759  // C++11 [class.copy]p8:
8760  //   ... If the class definition does not explicitly declare a copy
8761  //   constructor, there is no user-declared move constructor, and there is no
8762  //   user-declared move assignment operator, a copy constructor is implicitly
8763  //   declared as defaulted.
8764  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
8765    CopyConstructor->setDeletedAsWritten();
8766
8767  return CopyConstructor;
8768}
8769
8770void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
8771                                   CXXConstructorDecl *CopyConstructor) {
8772  assert((CopyConstructor->isDefaulted() &&
8773          CopyConstructor->isCopyConstructor() &&
8774          !CopyConstructor->doesThisDeclarationHaveABody() &&
8775          !CopyConstructor->isDeleted()) &&
8776         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
8777
8778  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
8779  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
8780
8781  SynthesizedFunctionScope Scope(*this, CopyConstructor);
8782  DiagnosticErrorTrap Trap(Diags);
8783
8784  if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
8785      Trap.hasErrorOccurred()) {
8786    Diag(CurrentLocation, diag::note_member_synthesized_at)
8787      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
8788    CopyConstructor->setInvalidDecl();
8789  }  else {
8790    Sema::CompoundScopeRAII CompoundScope(*this);
8791    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8792                                               CopyConstructor->getLocation(),
8793                                               MultiStmtArg(),
8794                                               /*isStmtExpr=*/false)
8795                                                              .takeAs<Stmt>());
8796    CopyConstructor->setImplicitlyDefined(true);
8797  }
8798
8799  CopyConstructor->setUsed();
8800  if (ASTMutationListener *L = getASTMutationListener()) {
8801    L->CompletedImplicitDefinition(CopyConstructor);
8802  }
8803}
8804
8805Sema::ImplicitExceptionSpecification
8806Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
8807  CXXRecordDecl *ClassDecl = MD->getParent();
8808
8809  // C++ [except.spec]p14:
8810  //   An implicitly declared special member function (Clause 12) shall have an
8811  //   exception-specification. [...]
8812  ImplicitExceptionSpecification ExceptSpec(*this);
8813  if (ClassDecl->isInvalidDecl())
8814    return ExceptSpec;
8815
8816  // Direct base-class constructors.
8817  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8818                                       BEnd = ClassDecl->bases_end();
8819       B != BEnd; ++B) {
8820    if (B->isVirtual()) // Handled below.
8821      continue;
8822
8823    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8824      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8825      CXXConstructorDecl *Constructor =
8826          LookupMovingConstructor(BaseClassDecl, 0);
8827      // If this is a deleted function, add it anyway. This might be conformant
8828      // with the standard. This might not. I'm not sure. It might not matter.
8829      if (Constructor)
8830        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8831    }
8832  }
8833
8834  // Virtual base-class constructors.
8835  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8836                                       BEnd = ClassDecl->vbases_end();
8837       B != BEnd; ++B) {
8838    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8839      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8840      CXXConstructorDecl *Constructor =
8841          LookupMovingConstructor(BaseClassDecl, 0);
8842      // If this is a deleted function, add it anyway. This might be conformant
8843      // with the standard. This might not. I'm not sure. It might not matter.
8844      if (Constructor)
8845        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8846    }
8847  }
8848
8849  // Field constructors.
8850  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8851                               FEnd = ClassDecl->field_end();
8852       F != FEnd; ++F) {
8853    QualType FieldType = Context.getBaseElementType(F->getType());
8854    if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
8855      CXXConstructorDecl *Constructor =
8856          LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
8857      // If this is a deleted function, add it anyway. This might be conformant
8858      // with the standard. This might not. I'm not sure. It might not matter.
8859      // In particular, the problem is that this function never gets called. It
8860      // might just be ill-formed because this function attempts to refer to
8861      // a deleted function here.
8862      if (Constructor)
8863        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8864    }
8865  }
8866
8867  return ExceptSpec;
8868}
8869
8870CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8871                                                    CXXRecordDecl *ClassDecl) {
8872  // C++11 [class.copy]p9:
8873  //   If the definition of a class X does not explicitly declare a move
8874  //   constructor, one will be implicitly declared as defaulted if and only if:
8875  //
8876  //   - [first 4 bullets]
8877  assert(ClassDecl->needsImplicitMoveConstructor());
8878
8879  // [Checked after we build the declaration]
8880  //   - the move assignment operator would not be implicitly defined as
8881  //     deleted,
8882
8883  // [DR1402]:
8884  //   - each of X's non-static data members and direct or virtual base classes
8885  //     has a type that either has a move constructor or is trivially copyable.
8886  if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8887    ClassDecl->setFailedImplicitMoveConstructor();
8888    return 0;
8889  }
8890
8891  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8892  QualType ArgType = Context.getRValueReferenceType(ClassType);
8893
8894  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8895                                                     CXXMoveConstructor,
8896                                                     false);
8897
8898  DeclarationName Name
8899    = Context.DeclarationNames.getCXXConstructorName(
8900                                           Context.getCanonicalType(ClassType));
8901  SourceLocation ClassLoc = ClassDecl->getLocation();
8902  DeclarationNameInfo NameInfo(Name, ClassLoc);
8903
8904  // C++0x [class.copy]p11:
8905  //   An implicitly-declared copy/move constructor is an inline public
8906  //   member of its class.
8907  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8908      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
8909      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8910      Constexpr);
8911  MoveConstructor->setAccess(AS_public);
8912  MoveConstructor->setDefaulted();
8913  MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8914
8915  // Build an exception specification pointing back at this member.
8916  FunctionProtoType::ExtProtoInfo EPI;
8917  EPI.ExceptionSpecType = EST_Unevaluated;
8918  EPI.ExceptionSpecDecl = MoveConstructor;
8919  MoveConstructor->setType(
8920      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8921
8922  // Add the parameter to the constructor.
8923  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8924                                               ClassLoc, ClassLoc,
8925                                               /*IdentifierInfo=*/0,
8926                                               ArgType, /*TInfo=*/0,
8927                                               SC_None,
8928                                               SC_None, 0);
8929  MoveConstructor->setParams(FromParam);
8930
8931  // C++0x [class.copy]p9:
8932  //   If the definition of a class X does not explicitly declare a move
8933  //   constructor, one will be implicitly declared as defaulted if and only if:
8934  //   [...]
8935  //   - the move constructor would not be implicitly defined as deleted.
8936  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
8937    // Cache this result so that we don't try to generate this over and over
8938    // on every lookup, leaking memory and wasting time.
8939    ClassDecl->setFailedImplicitMoveConstructor();
8940    return 0;
8941  }
8942
8943  // Note that we have declared this constructor.
8944  ++ASTContext::NumImplicitMoveConstructorsDeclared;
8945
8946  if (Scope *S = getScopeForContext(ClassDecl))
8947    PushOnScopeChains(MoveConstructor, S, false);
8948  ClassDecl->addDecl(MoveConstructor);
8949
8950  return MoveConstructor;
8951}
8952
8953void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8954                                   CXXConstructorDecl *MoveConstructor) {
8955  assert((MoveConstructor->isDefaulted() &&
8956          MoveConstructor->isMoveConstructor() &&
8957          !MoveConstructor->doesThisDeclarationHaveABody() &&
8958          !MoveConstructor->isDeleted()) &&
8959         "DefineImplicitMoveConstructor - call it for implicit move ctor");
8960
8961  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8962  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8963
8964  SynthesizedFunctionScope Scope(*this, MoveConstructor);
8965  DiagnosticErrorTrap Trap(Diags);
8966
8967  if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8968      Trap.hasErrorOccurred()) {
8969    Diag(CurrentLocation, diag::note_member_synthesized_at)
8970      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8971    MoveConstructor->setInvalidDecl();
8972  }  else {
8973    Sema::CompoundScopeRAII CompoundScope(*this);
8974    MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8975                                               MoveConstructor->getLocation(),
8976                                               MultiStmtArg(),
8977                                               /*isStmtExpr=*/false)
8978                                                              .takeAs<Stmt>());
8979    MoveConstructor->setImplicitlyDefined(true);
8980  }
8981
8982  MoveConstructor->setUsed();
8983
8984  if (ASTMutationListener *L = getASTMutationListener()) {
8985    L->CompletedImplicitDefinition(MoveConstructor);
8986  }
8987}
8988
8989bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8990  return FD->isDeleted() &&
8991         (FD->isDefaulted() || FD->isImplicit()) &&
8992         isa<CXXMethodDecl>(FD);
8993}
8994
8995/// \brief Mark the call operator of the given lambda closure type as "used".
8996static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8997  CXXMethodDecl *CallOperator
8998    = cast<CXXMethodDecl>(
8999        *Lambda->lookup(
9000          S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
9001  CallOperator->setReferenced();
9002  CallOperator->setUsed();
9003}
9004
9005void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9006       SourceLocation CurrentLocation,
9007       CXXConversionDecl *Conv)
9008{
9009  CXXRecordDecl *Lambda = Conv->getParent();
9010
9011  // Make sure that the lambda call operator is marked used.
9012  markLambdaCallOperatorUsed(*this, Lambda);
9013
9014  Conv->setUsed();
9015
9016  SynthesizedFunctionScope Scope(*this, Conv);
9017  DiagnosticErrorTrap Trap(Diags);
9018
9019  // Return the address of the __invoke function.
9020  DeclarationName InvokeName = &Context.Idents.get("__invoke");
9021  CXXMethodDecl *Invoke
9022    = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
9023  Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9024                                       VK_LValue, Conv->getLocation()).take();
9025  assert(FunctionRef && "Can't refer to __invoke function?");
9026  Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
9027  Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
9028                                           Conv->getLocation(),
9029                                           Conv->getLocation()));
9030
9031  // Fill in the __invoke function with a dummy implementation. IR generation
9032  // will fill in the actual details.
9033  Invoke->setUsed();
9034  Invoke->setReferenced();
9035  Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
9036
9037  if (ASTMutationListener *L = getASTMutationListener()) {
9038    L->CompletedImplicitDefinition(Conv);
9039    L->CompletedImplicitDefinition(Invoke);
9040  }
9041}
9042
9043void Sema::DefineImplicitLambdaToBlockPointerConversion(
9044       SourceLocation CurrentLocation,
9045       CXXConversionDecl *Conv)
9046{
9047  Conv->setUsed();
9048
9049  SynthesizedFunctionScope Scope(*this, Conv);
9050  DiagnosticErrorTrap Trap(Diags);
9051
9052  // Copy-initialize the lambda object as needed to capture it.
9053  Expr *This = ActOnCXXThis(CurrentLocation).take();
9054  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
9055
9056  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9057                                                        Conv->getLocation(),
9058                                                        Conv, DerefThis);
9059
9060  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9061  // behavior.  Note that only the general conversion function does this
9062  // (since it's unusable otherwise); in the case where we inline the
9063  // block literal, it has block literal lifetime semantics.
9064  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
9065    BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9066                                          CK_CopyAndAutoreleaseBlockObject,
9067                                          BuildBlock.get(), 0, VK_RValue);
9068
9069  if (BuildBlock.isInvalid()) {
9070    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9071    Conv->setInvalidDecl();
9072    return;
9073  }
9074
9075  // Create the return statement that returns the block from the conversion
9076  // function.
9077  StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
9078  if (Return.isInvalid()) {
9079    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9080    Conv->setInvalidDecl();
9081    return;
9082  }
9083
9084  // Set the body of the conversion function.
9085  Stmt *ReturnS = Return.take();
9086  Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9087                                           Conv->getLocation(),
9088                                           Conv->getLocation()));
9089
9090  // We're done; notify the mutation listener, if any.
9091  if (ASTMutationListener *L = getASTMutationListener()) {
9092    L->CompletedImplicitDefinition(Conv);
9093  }
9094}
9095
9096/// \brief Determine whether the given list arguments contains exactly one
9097/// "real" (non-default) argument.
9098static bool hasOneRealArgument(MultiExprArg Args) {
9099  switch (Args.size()) {
9100  case 0:
9101    return false;
9102
9103  default:
9104    if (!Args[1]->isDefaultArgument())
9105      return false;
9106
9107    // fall through
9108  case 1:
9109    return !Args[0]->isDefaultArgument();
9110  }
9111
9112  return false;
9113}
9114
9115ExprResult
9116Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9117                            CXXConstructorDecl *Constructor,
9118                            MultiExprArg ExprArgs,
9119                            bool HadMultipleCandidates,
9120                            bool RequiresZeroInit,
9121                            unsigned ConstructKind,
9122                            SourceRange ParenRange) {
9123  bool Elidable = false;
9124
9125  // C++0x [class.copy]p34:
9126  //   When certain criteria are met, an implementation is allowed to
9127  //   omit the copy/move construction of a class object, even if the
9128  //   copy/move constructor and/or destructor for the object have
9129  //   side effects. [...]
9130  //     - when a temporary class object that has not been bound to a
9131  //       reference (12.2) would be copied/moved to a class object
9132  //       with the same cv-unqualified type, the copy/move operation
9133  //       can be omitted by constructing the temporary object
9134  //       directly into the target of the omitted copy/move
9135  if (ConstructKind == CXXConstructExpr::CK_Complete &&
9136      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
9137    Expr *SubExpr = ExprArgs[0];
9138    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
9139  }
9140
9141  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
9142                               Elidable, ExprArgs, HadMultipleCandidates,
9143                               RequiresZeroInit, ConstructKind, ParenRange);
9144}
9145
9146/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9147/// including handling of its default argument expressions.
9148ExprResult
9149Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9150                            CXXConstructorDecl *Constructor, bool Elidable,
9151                            MultiExprArg ExprArgs,
9152                            bool HadMultipleCandidates,
9153                            bool RequiresZeroInit,
9154                            unsigned ConstructKind,
9155                            SourceRange ParenRange) {
9156  MarkFunctionReferenced(ConstructLoc, Constructor);
9157  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
9158                                        Constructor, Elidable, ExprArgs,
9159                                        HadMultipleCandidates, /*FIXME*/false,
9160                                        RequiresZeroInit,
9161              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9162                                        ParenRange));
9163}
9164
9165bool Sema::InitializeVarWithConstructor(VarDecl *VD,
9166                                        CXXConstructorDecl *Constructor,
9167                                        MultiExprArg Exprs,
9168                                        bool HadMultipleCandidates) {
9169  // FIXME: Provide the correct paren SourceRange when available.
9170  ExprResult TempResult =
9171    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
9172                          Exprs, HadMultipleCandidates, false,
9173                          CXXConstructExpr::CK_Complete, SourceRange());
9174  if (TempResult.isInvalid())
9175    return true;
9176
9177  Expr *Temp = TempResult.takeAs<Expr>();
9178  CheckImplicitConversions(Temp, VD->getLocation());
9179  MarkFunctionReferenced(VD->getLocation(), Constructor);
9180  Temp = MaybeCreateExprWithCleanups(Temp);
9181  VD->setInit(Temp);
9182
9183  return false;
9184}
9185
9186void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
9187  if (VD->isInvalidDecl()) return;
9188
9189  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
9190  if (ClassDecl->isInvalidDecl()) return;
9191  if (ClassDecl->hasIrrelevantDestructor()) return;
9192  if (ClassDecl->isDependentContext()) return;
9193
9194  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9195  MarkFunctionReferenced(VD->getLocation(), Destructor);
9196  CheckDestructorAccess(VD->getLocation(), Destructor,
9197                        PDiag(diag::err_access_dtor_var)
9198                        << VD->getDeclName()
9199                        << VD->getType());
9200  DiagnoseUseOfDecl(Destructor, VD->getLocation());
9201
9202  if (!VD->hasGlobalStorage()) return;
9203
9204  // Emit warning for non-trivial dtor in global scope (a real global,
9205  // class-static, function-static).
9206  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9207
9208  // TODO: this should be re-enabled for static locals by !CXAAtExit
9209  if (!VD->isStaticLocal())
9210    Diag(VD->getLocation(), diag::warn_global_destructor);
9211}
9212
9213/// \brief Given a constructor and the set of arguments provided for the
9214/// constructor, convert the arguments and add any required default arguments
9215/// to form a proper call to this constructor.
9216///
9217/// \returns true if an error occurred, false otherwise.
9218bool
9219Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9220                              MultiExprArg ArgsPtr,
9221                              SourceLocation Loc,
9222                              SmallVectorImpl<Expr*> &ConvertedArgs,
9223                              bool AllowExplicit) {
9224  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9225  unsigned NumArgs = ArgsPtr.size();
9226  Expr **Args = ArgsPtr.data();
9227
9228  const FunctionProtoType *Proto
9229    = Constructor->getType()->getAs<FunctionProtoType>();
9230  assert(Proto && "Constructor without a prototype?");
9231  unsigned NumArgsInProto = Proto->getNumArgs();
9232
9233  // If too few arguments are available, we'll fill in the rest with defaults.
9234  if (NumArgs < NumArgsInProto)
9235    ConvertedArgs.reserve(NumArgsInProto);
9236  else
9237    ConvertedArgs.reserve(NumArgs);
9238
9239  VariadicCallType CallType =
9240    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
9241  SmallVector<Expr *, 8> AllArgs;
9242  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9243                                        Proto, 0, Args, NumArgs, AllArgs,
9244                                        CallType, AllowExplicit);
9245  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
9246
9247  DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9248
9249  CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9250                       Proto, Loc);
9251
9252  return Invalid;
9253}
9254
9255static inline bool
9256CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9257                                       const FunctionDecl *FnDecl) {
9258  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
9259  if (isa<NamespaceDecl>(DC)) {
9260    return SemaRef.Diag(FnDecl->getLocation(),
9261                        diag::err_operator_new_delete_declared_in_namespace)
9262      << FnDecl->getDeclName();
9263  }
9264
9265  if (isa<TranslationUnitDecl>(DC) &&
9266      FnDecl->getStorageClass() == SC_Static) {
9267    return SemaRef.Diag(FnDecl->getLocation(),
9268                        diag::err_operator_new_delete_declared_static)
9269      << FnDecl->getDeclName();
9270  }
9271
9272  return false;
9273}
9274
9275static inline bool
9276CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9277                            CanQualType ExpectedResultType,
9278                            CanQualType ExpectedFirstParamType,
9279                            unsigned DependentParamTypeDiag,
9280                            unsigned InvalidParamTypeDiag) {
9281  QualType ResultType =
9282    FnDecl->getType()->getAs<FunctionType>()->getResultType();
9283
9284  // Check that the result type is not dependent.
9285  if (ResultType->isDependentType())
9286    return SemaRef.Diag(FnDecl->getLocation(),
9287                        diag::err_operator_new_delete_dependent_result_type)
9288    << FnDecl->getDeclName() << ExpectedResultType;
9289
9290  // Check that the result type is what we expect.
9291  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9292    return SemaRef.Diag(FnDecl->getLocation(),
9293                        diag::err_operator_new_delete_invalid_result_type)
9294    << FnDecl->getDeclName() << ExpectedResultType;
9295
9296  // A function template must have at least 2 parameters.
9297  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9298    return SemaRef.Diag(FnDecl->getLocation(),
9299                      diag::err_operator_new_delete_template_too_few_parameters)
9300        << FnDecl->getDeclName();
9301
9302  // The function decl must have at least 1 parameter.
9303  if (FnDecl->getNumParams() == 0)
9304    return SemaRef.Diag(FnDecl->getLocation(),
9305                        diag::err_operator_new_delete_too_few_parameters)
9306      << FnDecl->getDeclName();
9307
9308  // Check the first parameter type is not dependent.
9309  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9310  if (FirstParamType->isDependentType())
9311    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9312      << FnDecl->getDeclName() << ExpectedFirstParamType;
9313
9314  // Check that the first parameter type is what we expect.
9315  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
9316      ExpectedFirstParamType)
9317    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9318    << FnDecl->getDeclName() << ExpectedFirstParamType;
9319
9320  return false;
9321}
9322
9323static bool
9324CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9325  // C++ [basic.stc.dynamic.allocation]p1:
9326  //   A program is ill-formed if an allocation function is declared in a
9327  //   namespace scope other than global scope or declared static in global
9328  //   scope.
9329  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9330    return true;
9331
9332  CanQualType SizeTy =
9333    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9334
9335  // C++ [basic.stc.dynamic.allocation]p1:
9336  //  The return type shall be void*. The first parameter shall have type
9337  //  std::size_t.
9338  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9339                                  SizeTy,
9340                                  diag::err_operator_new_dependent_param_type,
9341                                  diag::err_operator_new_param_type))
9342    return true;
9343
9344  // C++ [basic.stc.dynamic.allocation]p1:
9345  //  The first parameter shall not have an associated default argument.
9346  if (FnDecl->getParamDecl(0)->hasDefaultArg())
9347    return SemaRef.Diag(FnDecl->getLocation(),
9348                        diag::err_operator_new_default_arg)
9349      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9350
9351  return false;
9352}
9353
9354static bool
9355CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
9356  // C++ [basic.stc.dynamic.deallocation]p1:
9357  //   A program is ill-formed if deallocation functions are declared in a
9358  //   namespace scope other than global scope or declared static in global
9359  //   scope.
9360  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9361    return true;
9362
9363  // C++ [basic.stc.dynamic.deallocation]p2:
9364  //   Each deallocation function shall return void and its first parameter
9365  //   shall be void*.
9366  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9367                                  SemaRef.Context.VoidPtrTy,
9368                                 diag::err_operator_delete_dependent_param_type,
9369                                 diag::err_operator_delete_param_type))
9370    return true;
9371
9372  return false;
9373}
9374
9375/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9376/// of this overloaded operator is well-formed. If so, returns false;
9377/// otherwise, emits appropriate diagnostics and returns true.
9378bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
9379  assert(FnDecl && FnDecl->isOverloadedOperator() &&
9380         "Expected an overloaded operator declaration");
9381
9382  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9383
9384  // C++ [over.oper]p5:
9385  //   The allocation and deallocation functions, operator new,
9386  //   operator new[], operator delete and operator delete[], are
9387  //   described completely in 3.7.3. The attributes and restrictions
9388  //   found in the rest of this subclause do not apply to them unless
9389  //   explicitly stated in 3.7.3.
9390  if (Op == OO_Delete || Op == OO_Array_Delete)
9391    return CheckOperatorDeleteDeclaration(*this, FnDecl);
9392
9393  if (Op == OO_New || Op == OO_Array_New)
9394    return CheckOperatorNewDeclaration(*this, FnDecl);
9395
9396  // C++ [over.oper]p6:
9397  //   An operator function shall either be a non-static member
9398  //   function or be a non-member function and have at least one
9399  //   parameter whose type is a class, a reference to a class, an
9400  //   enumeration, or a reference to an enumeration.
9401  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9402    if (MethodDecl->isStatic())
9403      return Diag(FnDecl->getLocation(),
9404                  diag::err_operator_overload_static) << FnDecl->getDeclName();
9405  } else {
9406    bool ClassOrEnumParam = false;
9407    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9408                                   ParamEnd = FnDecl->param_end();
9409         Param != ParamEnd; ++Param) {
9410      QualType ParamType = (*Param)->getType().getNonReferenceType();
9411      if (ParamType->isDependentType() || ParamType->isRecordType() ||
9412          ParamType->isEnumeralType()) {
9413        ClassOrEnumParam = true;
9414        break;
9415      }
9416    }
9417
9418    if (!ClassOrEnumParam)
9419      return Diag(FnDecl->getLocation(),
9420                  diag::err_operator_overload_needs_class_or_enum)
9421        << FnDecl->getDeclName();
9422  }
9423
9424  // C++ [over.oper]p8:
9425  //   An operator function cannot have default arguments (8.3.6),
9426  //   except where explicitly stated below.
9427  //
9428  // Only the function-call operator allows default arguments
9429  // (C++ [over.call]p1).
9430  if (Op != OO_Call) {
9431    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9432         Param != FnDecl->param_end(); ++Param) {
9433      if ((*Param)->hasDefaultArg())
9434        return Diag((*Param)->getLocation(),
9435                    diag::err_operator_overload_default_arg)
9436          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
9437    }
9438  }
9439
9440  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9441    { false, false, false }
9442#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9443    , { Unary, Binary, MemberOnly }
9444#include "clang/Basic/OperatorKinds.def"
9445  };
9446
9447  bool CanBeUnaryOperator = OperatorUses[Op][0];
9448  bool CanBeBinaryOperator = OperatorUses[Op][1];
9449  bool MustBeMemberOperator = OperatorUses[Op][2];
9450
9451  // C++ [over.oper]p8:
9452  //   [...] Operator functions cannot have more or fewer parameters
9453  //   than the number required for the corresponding operator, as
9454  //   described in the rest of this subclause.
9455  unsigned NumParams = FnDecl->getNumParams()
9456                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
9457  if (Op != OO_Call &&
9458      ((NumParams == 1 && !CanBeUnaryOperator) ||
9459       (NumParams == 2 && !CanBeBinaryOperator) ||
9460       (NumParams < 1) || (NumParams > 2))) {
9461    // We have the wrong number of parameters.
9462    unsigned ErrorKind;
9463    if (CanBeUnaryOperator && CanBeBinaryOperator) {
9464      ErrorKind = 2;  // 2 -> unary or binary.
9465    } else if (CanBeUnaryOperator) {
9466      ErrorKind = 0;  // 0 -> unary
9467    } else {
9468      assert(CanBeBinaryOperator &&
9469             "All non-call overloaded operators are unary or binary!");
9470      ErrorKind = 1;  // 1 -> binary
9471    }
9472
9473    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
9474      << FnDecl->getDeclName() << NumParams << ErrorKind;
9475  }
9476
9477  // Overloaded operators other than operator() cannot be variadic.
9478  if (Op != OO_Call &&
9479      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
9480    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
9481      << FnDecl->getDeclName();
9482  }
9483
9484  // Some operators must be non-static member functions.
9485  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9486    return Diag(FnDecl->getLocation(),
9487                diag::err_operator_overload_must_be_member)
9488      << FnDecl->getDeclName();
9489  }
9490
9491  // C++ [over.inc]p1:
9492  //   The user-defined function called operator++ implements the
9493  //   prefix and postfix ++ operator. If this function is a member
9494  //   function with no parameters, or a non-member function with one
9495  //   parameter of class or enumeration type, it defines the prefix
9496  //   increment operator ++ for objects of that type. If the function
9497  //   is a member function with one parameter (which shall be of type
9498  //   int) or a non-member function with two parameters (the second
9499  //   of which shall be of type int), it defines the postfix
9500  //   increment operator ++ for objects of that type.
9501  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9502    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9503    bool ParamIsInt = false;
9504    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
9505      ParamIsInt = BT->getKind() == BuiltinType::Int;
9506
9507    if (!ParamIsInt)
9508      return Diag(LastParam->getLocation(),
9509                  diag::err_operator_overload_post_incdec_must_be_int)
9510        << LastParam->getType() << (Op == OO_MinusMinus);
9511  }
9512
9513  return false;
9514}
9515
9516/// CheckLiteralOperatorDeclaration - Check whether the declaration
9517/// of this literal operator function is well-formed. If so, returns
9518/// false; otherwise, emits appropriate diagnostics and returns true.
9519bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9520  if (isa<CXXMethodDecl>(FnDecl)) {
9521    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9522      << FnDecl->getDeclName();
9523    return true;
9524  }
9525
9526  if (FnDecl->isExternC()) {
9527    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9528    return true;
9529  }
9530
9531  bool Valid = false;
9532
9533  // This might be the definition of a literal operator template.
9534  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9535  // This might be a specialization of a literal operator template.
9536  if (!TpDecl)
9537    TpDecl = FnDecl->getPrimaryTemplate();
9538
9539  // template <char...> type operator "" name() is the only valid template
9540  // signature, and the only valid signature with no parameters.
9541  if (TpDecl) {
9542    if (FnDecl->param_size() == 0) {
9543      // Must have only one template parameter
9544      TemplateParameterList *Params = TpDecl->getTemplateParameters();
9545      if (Params->size() == 1) {
9546        NonTypeTemplateParmDecl *PmDecl =
9547          dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
9548
9549        // The template parameter must be a char parameter pack.
9550        if (PmDecl && PmDecl->isTemplateParameterPack() &&
9551            Context.hasSameType(PmDecl->getType(), Context.CharTy))
9552          Valid = true;
9553      }
9554    }
9555  } else if (FnDecl->param_size()) {
9556    // Check the first parameter
9557    FunctionDecl::param_iterator Param = FnDecl->param_begin();
9558
9559    QualType T = (*Param)->getType().getUnqualifiedType();
9560
9561    // unsigned long long int, long double, and any character type are allowed
9562    // as the only parameters.
9563    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9564        Context.hasSameType(T, Context.LongDoubleTy) ||
9565        Context.hasSameType(T, Context.CharTy) ||
9566        Context.hasSameType(T, Context.WCharTy) ||
9567        Context.hasSameType(T, Context.Char16Ty) ||
9568        Context.hasSameType(T, Context.Char32Ty)) {
9569      if (++Param == FnDecl->param_end())
9570        Valid = true;
9571      goto FinishedParams;
9572    }
9573
9574    // Otherwise it must be a pointer to const; let's strip those qualifiers.
9575    const PointerType *PT = T->getAs<PointerType>();
9576    if (!PT)
9577      goto FinishedParams;
9578    T = PT->getPointeeType();
9579    if (!T.isConstQualified() || T.isVolatileQualified())
9580      goto FinishedParams;
9581    T = T.getUnqualifiedType();
9582
9583    // Move on to the second parameter;
9584    ++Param;
9585
9586    // If there is no second parameter, the first must be a const char *
9587    if (Param == FnDecl->param_end()) {
9588      if (Context.hasSameType(T, Context.CharTy))
9589        Valid = true;
9590      goto FinishedParams;
9591    }
9592
9593    // const char *, const wchar_t*, const char16_t*, and const char32_t*
9594    // are allowed as the first parameter to a two-parameter function
9595    if (!(Context.hasSameType(T, Context.CharTy) ||
9596          Context.hasSameType(T, Context.WCharTy) ||
9597          Context.hasSameType(T, Context.Char16Ty) ||
9598          Context.hasSameType(T, Context.Char32Ty)))
9599      goto FinishedParams;
9600
9601    // The second and final parameter must be an std::size_t
9602    T = (*Param)->getType().getUnqualifiedType();
9603    if (Context.hasSameType(T, Context.getSizeType()) &&
9604        ++Param == FnDecl->param_end())
9605      Valid = true;
9606  }
9607
9608  // FIXME: This diagnostic is absolutely terrible.
9609FinishedParams:
9610  if (!Valid) {
9611    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9612      << FnDecl->getDeclName();
9613    return true;
9614  }
9615
9616  // A parameter-declaration-clause containing a default argument is not
9617  // equivalent to any of the permitted forms.
9618  for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9619                                    ParamEnd = FnDecl->param_end();
9620       Param != ParamEnd; ++Param) {
9621    if ((*Param)->hasDefaultArg()) {
9622      Diag((*Param)->getDefaultArgRange().getBegin(),
9623           diag::err_literal_operator_default_argument)
9624        << (*Param)->getDefaultArgRange();
9625      break;
9626    }
9627  }
9628
9629  StringRef LiteralName
9630    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9631  if (LiteralName[0] != '_') {
9632    // C++11 [usrlit.suffix]p1:
9633    //   Literal suffix identifiers that do not start with an underscore
9634    //   are reserved for future standardization.
9635    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9636  }
9637
9638  return false;
9639}
9640
9641/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9642/// linkage specification, including the language and (if present)
9643/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9644/// the location of the language string literal, which is provided
9645/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9646/// the '{' brace. Otherwise, this linkage specification does not
9647/// have any braces.
9648Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9649                                           SourceLocation LangLoc,
9650                                           StringRef Lang,
9651                                           SourceLocation LBraceLoc) {
9652  LinkageSpecDecl::LanguageIDs Language;
9653  if (Lang == "\"C\"")
9654    Language = LinkageSpecDecl::lang_c;
9655  else if (Lang == "\"C++\"")
9656    Language = LinkageSpecDecl::lang_cxx;
9657  else {
9658    Diag(LangLoc, diag::err_bad_language);
9659    return 0;
9660  }
9661
9662  // FIXME: Add all the various semantics of linkage specifications
9663
9664  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
9665                                               ExternLoc, LangLoc, Language);
9666  CurContext->addDecl(D);
9667  PushDeclContext(S, D);
9668  return D;
9669}
9670
9671/// ActOnFinishLinkageSpecification - Complete the definition of
9672/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9673/// valid, it's the position of the closing '}' brace in a linkage
9674/// specification that uses braces.
9675Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
9676                                            Decl *LinkageSpec,
9677                                            SourceLocation RBraceLoc) {
9678  if (LinkageSpec) {
9679    if (RBraceLoc.isValid()) {
9680      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9681      LSDecl->setRBraceLoc(RBraceLoc);
9682    }
9683    PopDeclContext();
9684  }
9685  return LinkageSpec;
9686}
9687
9688/// \brief Perform semantic analysis for the variable declaration that
9689/// occurs within a C++ catch clause, returning the newly-created
9690/// variable.
9691VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
9692                                         TypeSourceInfo *TInfo,
9693                                         SourceLocation StartLoc,
9694                                         SourceLocation Loc,
9695                                         IdentifierInfo *Name) {
9696  bool Invalid = false;
9697  QualType ExDeclType = TInfo->getType();
9698
9699  // Arrays and functions decay.
9700  if (ExDeclType->isArrayType())
9701    ExDeclType = Context.getArrayDecayedType(ExDeclType);
9702  else if (ExDeclType->isFunctionType())
9703    ExDeclType = Context.getPointerType(ExDeclType);
9704
9705  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9706  // The exception-declaration shall not denote a pointer or reference to an
9707  // incomplete type, other than [cv] void*.
9708  // N2844 forbids rvalue references.
9709  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
9710    Diag(Loc, diag::err_catch_rvalue_ref);
9711    Invalid = true;
9712  }
9713
9714  QualType BaseType = ExDeclType;
9715  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
9716  unsigned DK = diag::err_catch_incomplete;
9717  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
9718    BaseType = Ptr->getPointeeType();
9719    Mode = 1;
9720    DK = diag::err_catch_incomplete_ptr;
9721  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
9722    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
9723    BaseType = Ref->getPointeeType();
9724    Mode = 2;
9725    DK = diag::err_catch_incomplete_ref;
9726  }
9727  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
9728      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
9729    Invalid = true;
9730
9731  if (!Invalid && !ExDeclType->isDependentType() &&
9732      RequireNonAbstractType(Loc, ExDeclType,
9733                             diag::err_abstract_type_in_decl,
9734                             AbstractVariableType))
9735    Invalid = true;
9736
9737  // Only the non-fragile NeXT runtime currently supports C++ catches
9738  // of ObjC types, and no runtime supports catching ObjC types by value.
9739  if (!Invalid && getLangOpts().ObjC1) {
9740    QualType T = ExDeclType;
9741    if (const ReferenceType *RT = T->getAs<ReferenceType>())
9742      T = RT->getPointeeType();
9743
9744    if (T->isObjCObjectType()) {
9745      Diag(Loc, diag::err_objc_object_catch);
9746      Invalid = true;
9747    } else if (T->isObjCObjectPointerType()) {
9748      // FIXME: should this be a test for macosx-fragile specifically?
9749      if (getLangOpts().ObjCRuntime.isFragile())
9750        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
9751    }
9752  }
9753
9754  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9755                                    ExDeclType, TInfo, SC_None, SC_None);
9756  ExDecl->setExceptionVariable(true);
9757
9758  // In ARC, infer 'retaining' for variables of retainable type.
9759  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9760    Invalid = true;
9761
9762  if (!Invalid && !ExDeclType->isDependentType()) {
9763    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
9764      // C++ [except.handle]p16:
9765      //   The object declared in an exception-declaration or, if the
9766      //   exception-declaration does not specify a name, a temporary (12.2) is
9767      //   copy-initialized (8.5) from the exception object. [...]
9768      //   The object is destroyed when the handler exits, after the destruction
9769      //   of any automatic objects initialized within the handler.
9770      //
9771      // We just pretend to initialize the object with itself, then make sure
9772      // it can be destroyed later.
9773      QualType initType = ExDeclType;
9774
9775      InitializedEntity entity =
9776        InitializedEntity::InitializeVariable(ExDecl);
9777      InitializationKind initKind =
9778        InitializationKind::CreateCopy(Loc, SourceLocation());
9779
9780      Expr *opaqueValue =
9781        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9782      InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9783      ExprResult result = sequence.Perform(*this, entity, initKind,
9784                                           MultiExprArg(&opaqueValue, 1));
9785      if (result.isInvalid())
9786        Invalid = true;
9787      else {
9788        // If the constructor used was non-trivial, set this as the
9789        // "initializer".
9790        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9791        if (!construct->getConstructor()->isTrivial()) {
9792          Expr *init = MaybeCreateExprWithCleanups(construct);
9793          ExDecl->setInit(init);
9794        }
9795
9796        // And make sure it's destructable.
9797        FinalizeVarWithDestructor(ExDecl, recordType);
9798      }
9799    }
9800  }
9801
9802  if (Invalid)
9803    ExDecl->setInvalidDecl();
9804
9805  return ExDecl;
9806}
9807
9808/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9809/// handler.
9810Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
9811  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9812  bool Invalid = D.isInvalidType();
9813
9814  // Check for unexpanded parameter packs.
9815  if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9816                                               UPPC_ExceptionType)) {
9817    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9818                                             D.getIdentifierLoc());
9819    Invalid = true;
9820  }
9821
9822  IdentifierInfo *II = D.getIdentifier();
9823  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
9824                                             LookupOrdinaryName,
9825                                             ForRedeclaration)) {
9826    // The scope should be freshly made just for us. There is just no way
9827    // it contains any previous declaration.
9828    assert(!S->isDeclScope(PrevDecl));
9829    if (PrevDecl->isTemplateParameter()) {
9830      // Maybe we will complain about the shadowed template parameter.
9831      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9832      PrevDecl = 0;
9833    }
9834  }
9835
9836  if (D.getCXXScopeSpec().isSet() && !Invalid) {
9837    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9838      << D.getCXXScopeSpec().getRange();
9839    Invalid = true;
9840  }
9841
9842  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
9843                                              D.getLocStart(),
9844                                              D.getIdentifierLoc(),
9845                                              D.getIdentifier());
9846  if (Invalid)
9847    ExDecl->setInvalidDecl();
9848
9849  // Add the exception declaration into this scope.
9850  if (II)
9851    PushOnScopeChains(ExDecl, S);
9852  else
9853    CurContext->addDecl(ExDecl);
9854
9855  ProcessDeclAttributes(S, ExDecl, D);
9856  return ExDecl;
9857}
9858
9859Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9860                                         Expr *AssertExpr,
9861                                         Expr *AssertMessageExpr,
9862                                         SourceLocation RParenLoc) {
9863  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
9864
9865  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9866    return 0;
9867
9868  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
9869                                      AssertMessage, RParenLoc, false);
9870}
9871
9872Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9873                                         Expr *AssertExpr,
9874                                         StringLiteral *AssertMessage,
9875                                         SourceLocation RParenLoc,
9876                                         bool Failed) {
9877  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
9878      !Failed) {
9879    // In a static_assert-declaration, the constant-expression shall be a
9880    // constant expression that can be contextually converted to bool.
9881    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9882    if (Converted.isInvalid())
9883      Failed = true;
9884
9885    llvm::APSInt Cond;
9886    if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
9887          diag::err_static_assert_expression_is_not_constant,
9888          /*AllowFold=*/false).isInvalid())
9889      Failed = true;
9890
9891    if (!Failed && !Cond) {
9892      llvm::SmallString<256> MsgBuffer;
9893      llvm::raw_svector_ostream Msg(MsgBuffer);
9894      AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
9895      Diag(StaticAssertLoc, diag::err_static_assert_failed)
9896        << Msg.str() << AssertExpr->getSourceRange();
9897      Failed = true;
9898    }
9899  }
9900
9901  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9902                                        AssertExpr, AssertMessage, RParenLoc,
9903                                        Failed);
9904
9905  CurContext->addDecl(Decl);
9906  return Decl;
9907}
9908
9909/// \brief Perform semantic analysis of the given friend type declaration.
9910///
9911/// \returns A friend declaration that.
9912FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
9913                                      SourceLocation FriendLoc,
9914                                      TypeSourceInfo *TSInfo) {
9915  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9916
9917  QualType T = TSInfo->getType();
9918  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
9919
9920  // C++03 [class.friend]p2:
9921  //   An elaborated-type-specifier shall be used in a friend declaration
9922  //   for a class.*
9923  //
9924  //   * The class-key of the elaborated-type-specifier is required.
9925  if (!ActiveTemplateInstantiations.empty()) {
9926    // Do not complain about the form of friend template types during
9927    // template instantiation; we will already have complained when the
9928    // template was declared.
9929  } else if (!T->isElaboratedTypeSpecifier()) {
9930    // If we evaluated the type to a record type, suggest putting
9931    // a tag in front.
9932    if (const RecordType *RT = T->getAs<RecordType>()) {
9933      RecordDecl *RD = RT->getDecl();
9934
9935      std::string InsertionText = std::string(" ") + RD->getKindName();
9936
9937      Diag(TypeRange.getBegin(),
9938           getLangOpts().CPlusPlus0x ?
9939             diag::warn_cxx98_compat_unelaborated_friend_type :
9940             diag::ext_unelaborated_friend_type)
9941        << (unsigned) RD->getTagKind()
9942        << T
9943        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9944                                      InsertionText);
9945    } else {
9946      Diag(FriendLoc,
9947           getLangOpts().CPlusPlus0x ?
9948             diag::warn_cxx98_compat_nonclass_type_friend :
9949             diag::ext_nonclass_type_friend)
9950        << T
9951        << TypeRange;
9952    }
9953  } else if (T->getAs<EnumType>()) {
9954    Diag(FriendLoc,
9955         getLangOpts().CPlusPlus0x ?
9956           diag::warn_cxx98_compat_enum_friend :
9957           diag::ext_enum_friend)
9958      << T
9959      << TypeRange;
9960  }
9961
9962  // C++11 [class.friend]p3:
9963  //   A friend declaration that does not declare a function shall have one
9964  //   of the following forms:
9965  //     friend elaborated-type-specifier ;
9966  //     friend simple-type-specifier ;
9967  //     friend typename-specifier ;
9968  if (getLangOpts().CPlusPlus0x && LocStart != FriendLoc)
9969    Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
9970
9971  //   If the type specifier in a friend declaration designates a (possibly
9972  //   cv-qualified) class type, that class is declared as a friend; otherwise,
9973  //   the friend declaration is ignored.
9974  return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
9975}
9976
9977/// Handle a friend tag declaration where the scope specifier was
9978/// templated.
9979Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9980                                    unsigned TagSpec, SourceLocation TagLoc,
9981                                    CXXScopeSpec &SS,
9982                                    IdentifierInfo *Name, SourceLocation NameLoc,
9983                                    AttributeList *Attr,
9984                                    MultiTemplateParamsArg TempParamLists) {
9985  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9986
9987  bool isExplicitSpecialization = false;
9988  bool Invalid = false;
9989
9990  if (TemplateParameterList *TemplateParams
9991        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
9992                                                  TempParamLists.data(),
9993                                                  TempParamLists.size(),
9994                                                  /*friend*/ true,
9995                                                  isExplicitSpecialization,
9996                                                  Invalid)) {
9997    if (TemplateParams->size() > 0) {
9998      // This is a declaration of a class template.
9999      if (Invalid)
10000        return 0;
10001
10002      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10003                                SS, Name, NameLoc, Attr,
10004                                TemplateParams, AS_public,
10005                                /*ModulePrivateLoc=*/SourceLocation(),
10006                                TempParamLists.size() - 1,
10007                                TempParamLists.data()).take();
10008    } else {
10009      // The "template<>" header is extraneous.
10010      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10011        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10012      isExplicitSpecialization = true;
10013    }
10014  }
10015
10016  if (Invalid) return 0;
10017
10018  bool isAllExplicitSpecializations = true;
10019  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
10020    if (TempParamLists[I]->size()) {
10021      isAllExplicitSpecializations = false;
10022      break;
10023    }
10024  }
10025
10026  // FIXME: don't ignore attributes.
10027
10028  // If it's explicit specializations all the way down, just forget
10029  // about the template header and build an appropriate non-templated
10030  // friend.  TODO: for source fidelity, remember the headers.
10031  if (isAllExplicitSpecializations) {
10032    if (SS.isEmpty()) {
10033      bool Owned = false;
10034      bool IsDependent = false;
10035      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10036                      Attr, AS_public,
10037                      /*ModulePrivateLoc=*/SourceLocation(),
10038                      MultiTemplateParamsArg(), Owned, IsDependent,
10039                      /*ScopedEnumKWLoc=*/SourceLocation(),
10040                      /*ScopedEnumUsesClassTag=*/false,
10041                      /*UnderlyingType=*/TypeResult());
10042    }
10043
10044    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10045    ElaboratedTypeKeyword Keyword
10046      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10047    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
10048                                   *Name, NameLoc);
10049    if (T.isNull())
10050      return 0;
10051
10052    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10053    if (isa<DependentNameType>(T)) {
10054      DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10055      TL.setElaboratedKeywordLoc(TagLoc);
10056      TL.setQualifierLoc(QualifierLoc);
10057      TL.setNameLoc(NameLoc);
10058    } else {
10059      ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
10060      TL.setElaboratedKeywordLoc(TagLoc);
10061      TL.setQualifierLoc(QualifierLoc);
10062      cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10063    }
10064
10065    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10066                                            TSI, FriendLoc);
10067    Friend->setAccess(AS_public);
10068    CurContext->addDecl(Friend);
10069    return Friend;
10070  }
10071
10072  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10073
10074
10075
10076  // Handle the case of a templated-scope friend class.  e.g.
10077  //   template <class T> class A<T>::B;
10078  // FIXME: we don't support these right now.
10079  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10080  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10081  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10082  DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10083  TL.setElaboratedKeywordLoc(TagLoc);
10084  TL.setQualifierLoc(SS.getWithLocInContext(Context));
10085  TL.setNameLoc(NameLoc);
10086
10087  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10088                                          TSI, FriendLoc);
10089  Friend->setAccess(AS_public);
10090  Friend->setUnsupportedFriend(true);
10091  CurContext->addDecl(Friend);
10092  return Friend;
10093}
10094
10095
10096/// Handle a friend type declaration.  This works in tandem with
10097/// ActOnTag.
10098///
10099/// Notes on friend class templates:
10100///
10101/// We generally treat friend class declarations as if they were
10102/// declaring a class.  So, for example, the elaborated type specifier
10103/// in a friend declaration is required to obey the restrictions of a
10104/// class-head (i.e. no typedefs in the scope chain), template
10105/// parameters are required to match up with simple template-ids, &c.
10106/// However, unlike when declaring a template specialization, it's
10107/// okay to refer to a template specialization without an empty
10108/// template parameter declaration, e.g.
10109///   friend class A<T>::B<unsigned>;
10110/// We permit this as a special case; if there are any template
10111/// parameters present at all, require proper matching, i.e.
10112///   template <> template \<class T> friend class A<int>::B;
10113Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
10114                                MultiTemplateParamsArg TempParams) {
10115  SourceLocation Loc = DS.getLocStart();
10116
10117  assert(DS.isFriendSpecified());
10118  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10119
10120  // Try to convert the decl specifier to a type.  This works for
10121  // friend templates because ActOnTag never produces a ClassTemplateDecl
10122  // for a TUK_Friend.
10123  Declarator TheDeclarator(DS, Declarator::MemberContext);
10124  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10125  QualType T = TSI->getType();
10126  if (TheDeclarator.isInvalidType())
10127    return 0;
10128
10129  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10130    return 0;
10131
10132  // This is definitely an error in C++98.  It's probably meant to
10133  // be forbidden in C++0x, too, but the specification is just
10134  // poorly written.
10135  //
10136  // The problem is with declarations like the following:
10137  //   template <T> friend A<T>::foo;
10138  // where deciding whether a class C is a friend or not now hinges
10139  // on whether there exists an instantiation of A that causes
10140  // 'foo' to equal C.  There are restrictions on class-heads
10141  // (which we declare (by fiat) elaborated friend declarations to
10142  // be) that makes this tractable.
10143  //
10144  // FIXME: handle "template <> friend class A<T>;", which
10145  // is possibly well-formed?  Who even knows?
10146  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
10147    Diag(Loc, diag::err_tagless_friend_type_template)
10148      << DS.getSourceRange();
10149    return 0;
10150  }
10151
10152  // C++98 [class.friend]p1: A friend of a class is a function
10153  //   or class that is not a member of the class . . .
10154  // This is fixed in DR77, which just barely didn't make the C++03
10155  // deadline.  It's also a very silly restriction that seriously
10156  // affects inner classes and which nobody else seems to implement;
10157  // thus we never diagnose it, not even in -pedantic.
10158  //
10159  // But note that we could warn about it: it's always useless to
10160  // friend one of your own members (it's not, however, worthless to
10161  // friend a member of an arbitrary specialization of your template).
10162
10163  Decl *D;
10164  if (unsigned NumTempParamLists = TempParams.size())
10165    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
10166                                   NumTempParamLists,
10167                                   TempParams.data(),
10168                                   TSI,
10169                                   DS.getFriendSpecLoc());
10170  else
10171    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
10172
10173  if (!D)
10174    return 0;
10175
10176  D->setAccess(AS_public);
10177  CurContext->addDecl(D);
10178
10179  return D;
10180}
10181
10182Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10183                                    MultiTemplateParamsArg TemplateParams) {
10184  const DeclSpec &DS = D.getDeclSpec();
10185
10186  assert(DS.isFriendSpecified());
10187  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10188
10189  SourceLocation Loc = D.getIdentifierLoc();
10190  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10191
10192  // C++ [class.friend]p1
10193  //   A friend of a class is a function or class....
10194  // Note that this sees through typedefs, which is intended.
10195  // It *doesn't* see through dependent types, which is correct
10196  // according to [temp.arg.type]p3:
10197  //   If a declaration acquires a function type through a
10198  //   type dependent on a template-parameter and this causes
10199  //   a declaration that does not use the syntactic form of a
10200  //   function declarator to have a function type, the program
10201  //   is ill-formed.
10202  if (!TInfo->getType()->isFunctionType()) {
10203    Diag(Loc, diag::err_unexpected_friend);
10204
10205    // It might be worthwhile to try to recover by creating an
10206    // appropriate declaration.
10207    return 0;
10208  }
10209
10210  // C++ [namespace.memdef]p3
10211  //  - If a friend declaration in a non-local class first declares a
10212  //    class or function, the friend class or function is a member
10213  //    of the innermost enclosing namespace.
10214  //  - The name of the friend is not found by simple name lookup
10215  //    until a matching declaration is provided in that namespace
10216  //    scope (either before or after the class declaration granting
10217  //    friendship).
10218  //  - If a friend function is called, its name may be found by the
10219  //    name lookup that considers functions from namespaces and
10220  //    classes associated with the types of the function arguments.
10221  //  - When looking for a prior declaration of a class or a function
10222  //    declared as a friend, scopes outside the innermost enclosing
10223  //    namespace scope are not considered.
10224
10225  CXXScopeSpec &SS = D.getCXXScopeSpec();
10226  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10227  DeclarationName Name = NameInfo.getName();
10228  assert(Name);
10229
10230  // Check for unexpanded parameter packs.
10231  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10232      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10233      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10234    return 0;
10235
10236  // The context we found the declaration in, or in which we should
10237  // create the declaration.
10238  DeclContext *DC;
10239  Scope *DCScope = S;
10240  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10241                        ForRedeclaration);
10242
10243  // FIXME: there are different rules in local classes
10244
10245  // There are four cases here.
10246  //   - There's no scope specifier, in which case we just go to the
10247  //     appropriate scope and look for a function or function template
10248  //     there as appropriate.
10249  // Recover from invalid scope qualifiers as if they just weren't there.
10250  if (SS.isInvalid() || !SS.isSet()) {
10251    // C++0x [namespace.memdef]p3:
10252    //   If the name in a friend declaration is neither qualified nor
10253    //   a template-id and the declaration is a function or an
10254    //   elaborated-type-specifier, the lookup to determine whether
10255    //   the entity has been previously declared shall not consider
10256    //   any scopes outside the innermost enclosing namespace.
10257    // C++0x [class.friend]p11:
10258    //   If a friend declaration appears in a local class and the name
10259    //   specified is an unqualified name, a prior declaration is
10260    //   looked up without considering scopes that are outside the
10261    //   innermost enclosing non-class scope. For a friend function
10262    //   declaration, if there is no prior declaration, the program is
10263    //   ill-formed.
10264    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
10265    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
10266
10267    // Find the appropriate context according to the above.
10268    DC = CurContext;
10269    while (true) {
10270      // Skip class contexts.  If someone can cite chapter and verse
10271      // for this behavior, that would be nice --- it's what GCC and
10272      // EDG do, and it seems like a reasonable intent, but the spec
10273      // really only says that checks for unqualified existing
10274      // declarations should stop at the nearest enclosing namespace,
10275      // not that they should only consider the nearest enclosing
10276      // namespace.
10277      while (DC->isRecord() || DC->isTransparentContext())
10278        DC = DC->getParent();
10279
10280      LookupQualifiedName(Previous, DC);
10281
10282      // TODO: decide what we think about using declarations.
10283      if (isLocal || !Previous.empty())
10284        break;
10285
10286      if (isTemplateId) {
10287        if (isa<TranslationUnitDecl>(DC)) break;
10288      } else {
10289        if (DC->isFileContext()) break;
10290      }
10291      DC = DC->getParent();
10292    }
10293
10294    // C++ [class.friend]p1: A friend of a class is a function or
10295    //   class that is not a member of the class . . .
10296    // C++11 changes this for both friend types and functions.
10297    // Most C++ 98 compilers do seem to give an error here, so
10298    // we do, too.
10299    if (!Previous.empty() && DC->Equals(CurContext))
10300      Diag(DS.getFriendSpecLoc(),
10301           getLangOpts().CPlusPlus0x ?
10302             diag::warn_cxx98_compat_friend_is_member :
10303             diag::err_friend_is_member);
10304
10305    DCScope = getScopeForDeclContext(S, DC);
10306
10307    // C++ [class.friend]p6:
10308    //   A function can be defined in a friend declaration of a class if and
10309    //   only if the class is a non-local class (9.8), the function name is
10310    //   unqualified, and the function has namespace scope.
10311    if (isLocal && D.isFunctionDefinition()) {
10312      Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10313    }
10314
10315  //   - There's a non-dependent scope specifier, in which case we
10316  //     compute it and do a previous lookup there for a function
10317  //     or function template.
10318  } else if (!SS.getScopeRep()->isDependent()) {
10319    DC = computeDeclContext(SS);
10320    if (!DC) return 0;
10321
10322    if (RequireCompleteDeclContext(SS, DC)) return 0;
10323
10324    LookupQualifiedName(Previous, DC);
10325
10326    // Ignore things found implicitly in the wrong scope.
10327    // TODO: better diagnostics for this case.  Suggesting the right
10328    // qualified scope would be nice...
10329    LookupResult::Filter F = Previous.makeFilter();
10330    while (F.hasNext()) {
10331      NamedDecl *D = F.next();
10332      if (!DC->InEnclosingNamespaceSetOf(
10333              D->getDeclContext()->getRedeclContext()))
10334        F.erase();
10335    }
10336    F.done();
10337
10338    if (Previous.empty()) {
10339      D.setInvalidType();
10340      Diag(Loc, diag::err_qualified_friend_not_found)
10341          << Name << TInfo->getType();
10342      return 0;
10343    }
10344
10345    // C++ [class.friend]p1: A friend of a class is a function or
10346    //   class that is not a member of the class . . .
10347    if (DC->Equals(CurContext))
10348      Diag(DS.getFriendSpecLoc(),
10349           getLangOpts().CPlusPlus0x ?
10350             diag::warn_cxx98_compat_friend_is_member :
10351             diag::err_friend_is_member);
10352
10353    if (D.isFunctionDefinition()) {
10354      // C++ [class.friend]p6:
10355      //   A function can be defined in a friend declaration of a class if and
10356      //   only if the class is a non-local class (9.8), the function name is
10357      //   unqualified, and the function has namespace scope.
10358      SemaDiagnosticBuilder DB
10359        = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10360
10361      DB << SS.getScopeRep();
10362      if (DC->isFileContext())
10363        DB << FixItHint::CreateRemoval(SS.getRange());
10364      SS.clear();
10365    }
10366
10367  //   - There's a scope specifier that does not match any template
10368  //     parameter lists, in which case we use some arbitrary context,
10369  //     create a method or method template, and wait for instantiation.
10370  //   - There's a scope specifier that does match some template
10371  //     parameter lists, which we don't handle right now.
10372  } else {
10373    if (D.isFunctionDefinition()) {
10374      // C++ [class.friend]p6:
10375      //   A function can be defined in a friend declaration of a class if and
10376      //   only if the class is a non-local class (9.8), the function name is
10377      //   unqualified, and the function has namespace scope.
10378      Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10379        << SS.getScopeRep();
10380    }
10381
10382    DC = CurContext;
10383    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
10384  }
10385
10386  if (!DC->isRecord()) {
10387    // This implies that it has to be an operator or function.
10388    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10389        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10390        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
10391      Diag(Loc, diag::err_introducing_special_friend) <<
10392        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10393         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
10394      return 0;
10395    }
10396  }
10397
10398  // FIXME: This is an egregious hack to cope with cases where the scope stack
10399  // does not contain the declaration context, i.e., in an out-of-line
10400  // definition of a class.
10401  Scope FakeDCScope(S, Scope::DeclScope, Diags);
10402  if (!DCScope) {
10403    FakeDCScope.setEntity(DC);
10404    DCScope = &FakeDCScope;
10405  }
10406
10407  bool AddToScope = true;
10408  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10409                                          TemplateParams, AddToScope);
10410  if (!ND) return 0;
10411
10412  assert(ND->getDeclContext() == DC);
10413  assert(ND->getLexicalDeclContext() == CurContext);
10414
10415  // Add the function declaration to the appropriate lookup tables,
10416  // adjusting the redeclarations list as necessary.  We don't
10417  // want to do this yet if the friending class is dependent.
10418  //
10419  // Also update the scope-based lookup if the target context's
10420  // lookup context is in lexical scope.
10421  if (!CurContext->isDependentContext()) {
10422    DC = DC->getRedeclContext();
10423    DC->makeDeclVisibleInContext(ND);
10424    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10425      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
10426  }
10427
10428  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
10429                                       D.getIdentifierLoc(), ND,
10430                                       DS.getFriendSpecLoc());
10431  FrD->setAccess(AS_public);
10432  CurContext->addDecl(FrD);
10433
10434  if (ND->isInvalidDecl()) {
10435    FrD->setInvalidDecl();
10436  } else {
10437    if (DC->isRecord()) CheckFriendAccess(ND);
10438
10439    FunctionDecl *FD;
10440    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10441      FD = FTD->getTemplatedDecl();
10442    else
10443      FD = cast<FunctionDecl>(ND);
10444
10445    // Mark templated-scope function declarations as unsupported.
10446    if (FD->getNumTemplateParameterLists())
10447      FrD->setUnsupportedFriend(true);
10448  }
10449
10450  return ND;
10451}
10452
10453void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10454  AdjustDeclIfTemplate(Dcl);
10455
10456  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10457  if (!Fn) {
10458    Diag(DelLoc, diag::err_deleted_non_function);
10459    return;
10460  }
10461  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
10462    // Don't consider the implicit declaration we generate for explicit
10463    // specializations. FIXME: Do not generate these implicit declarations.
10464    if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10465        || Prev->getPreviousDecl()) && !Prev->isDefined()) {
10466      Diag(DelLoc, diag::err_deleted_decl_not_first);
10467      Diag(Prev->getLocation(), diag::note_previous_declaration);
10468    }
10469    // If the declaration wasn't the first, we delete the function anyway for
10470    // recovery.
10471  }
10472  Fn->setDeletedAsWritten();
10473
10474  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10475  if (!MD)
10476    return;
10477
10478  // A deleted special member function is trivial if the corresponding
10479  // implicitly-declared function would have been.
10480  switch (getSpecialMember(MD)) {
10481  case CXXInvalid:
10482    break;
10483  case CXXDefaultConstructor:
10484    MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10485    break;
10486  case CXXCopyConstructor:
10487    MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10488    break;
10489  case CXXMoveConstructor:
10490    MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10491    break;
10492  case CXXCopyAssignment:
10493    MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10494    break;
10495  case CXXMoveAssignment:
10496    MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10497    break;
10498  case CXXDestructor:
10499    MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10500    break;
10501  }
10502}
10503
10504void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10505  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10506
10507  if (MD) {
10508    if (MD->getParent()->isDependentType()) {
10509      MD->setDefaulted();
10510      MD->setExplicitlyDefaulted();
10511      return;
10512    }
10513
10514    CXXSpecialMember Member = getSpecialMember(MD);
10515    if (Member == CXXInvalid) {
10516      Diag(DefaultLoc, diag::err_default_special_members);
10517      return;
10518    }
10519
10520    MD->setDefaulted();
10521    MD->setExplicitlyDefaulted();
10522
10523    // If this definition appears within the record, do the checking when
10524    // the record is complete.
10525    const FunctionDecl *Primary = MD;
10526    if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
10527      // Find the uninstantiated declaration that actually had the '= default'
10528      // on it.
10529      Pattern->isDefined(Primary);
10530
10531    if (Primary == Primary->getCanonicalDecl())
10532      return;
10533
10534    CheckExplicitlyDefaultedSpecialMember(MD);
10535
10536    switch (Member) {
10537    case CXXDefaultConstructor: {
10538      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10539      if (!CD->isInvalidDecl())
10540        DefineImplicitDefaultConstructor(DefaultLoc, CD);
10541      break;
10542    }
10543
10544    case CXXCopyConstructor: {
10545      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10546      if (!CD->isInvalidDecl())
10547        DefineImplicitCopyConstructor(DefaultLoc, CD);
10548      break;
10549    }
10550
10551    case CXXCopyAssignment: {
10552      if (!MD->isInvalidDecl())
10553        DefineImplicitCopyAssignment(DefaultLoc, MD);
10554      break;
10555    }
10556
10557    case CXXDestructor: {
10558      CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10559      if (!DD->isInvalidDecl())
10560        DefineImplicitDestructor(DefaultLoc, DD);
10561      break;
10562    }
10563
10564    case CXXMoveConstructor: {
10565      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10566      if (!CD->isInvalidDecl())
10567        DefineImplicitMoveConstructor(DefaultLoc, CD);
10568      break;
10569    }
10570
10571    case CXXMoveAssignment: {
10572      if (!MD->isInvalidDecl())
10573        DefineImplicitMoveAssignment(DefaultLoc, MD);
10574      break;
10575    }
10576
10577    case CXXInvalid:
10578      llvm_unreachable("Invalid special member.");
10579    }
10580  } else {
10581    Diag(DefaultLoc, diag::err_default_special_members);
10582  }
10583}
10584
10585static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
10586  for (Stmt::child_range CI = S->children(); CI; ++CI) {
10587    Stmt *SubStmt = *CI;
10588    if (!SubStmt)
10589      continue;
10590    if (isa<ReturnStmt>(SubStmt))
10591      Self.Diag(SubStmt->getLocStart(),
10592           diag::err_return_in_constructor_handler);
10593    if (!isa<Expr>(SubStmt))
10594      SearchForReturnInStmt(Self, SubStmt);
10595  }
10596}
10597
10598void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10599  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10600    CXXCatchStmt *Handler = TryBlock->getHandler(I);
10601    SearchForReturnInStmt(*this, Handler);
10602  }
10603}
10604
10605bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
10606                                             const CXXMethodDecl *Old) {
10607  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10608  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
10609
10610  if (Context.hasSameType(NewTy, OldTy) ||
10611      NewTy->isDependentType() || OldTy->isDependentType())
10612    return false;
10613
10614  // Check if the return types are covariant
10615  QualType NewClassTy, OldClassTy;
10616
10617  /// Both types must be pointers or references to classes.
10618  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10619    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
10620      NewClassTy = NewPT->getPointeeType();
10621      OldClassTy = OldPT->getPointeeType();
10622    }
10623  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10624    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10625      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10626        NewClassTy = NewRT->getPointeeType();
10627        OldClassTy = OldRT->getPointeeType();
10628      }
10629    }
10630  }
10631
10632  // The return types aren't either both pointers or references to a class type.
10633  if (NewClassTy.isNull()) {
10634    Diag(New->getLocation(),
10635         diag::err_different_return_type_for_overriding_virtual_function)
10636      << New->getDeclName() << NewTy << OldTy;
10637    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10638
10639    return true;
10640  }
10641
10642  // C++ [class.virtual]p6:
10643  //   If the return type of D::f differs from the return type of B::f, the
10644  //   class type in the return type of D::f shall be complete at the point of
10645  //   declaration of D::f or shall be the class type D.
10646  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10647    if (!RT->isBeingDefined() &&
10648        RequireCompleteType(New->getLocation(), NewClassTy,
10649                            diag::err_covariant_return_incomplete,
10650                            New->getDeclName()))
10651    return true;
10652  }
10653
10654  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
10655    // Check if the new class derives from the old class.
10656    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10657      Diag(New->getLocation(),
10658           diag::err_covariant_return_not_derived)
10659      << New->getDeclName() << NewTy << OldTy;
10660      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10661      return true;
10662    }
10663
10664    // Check if we the conversion from derived to base is valid.
10665    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
10666                    diag::err_covariant_return_inaccessible_base,
10667                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
10668                    // FIXME: Should this point to the return type?
10669                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
10670      // FIXME: this note won't trigger for delayed access control
10671      // diagnostics, and it's impossible to get an undelayed error
10672      // here from access control during the original parse because
10673      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
10674      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10675      return true;
10676    }
10677  }
10678
10679  // The qualifiers of the return types must be the same.
10680  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
10681    Diag(New->getLocation(),
10682         diag::err_covariant_return_type_different_qualifications)
10683    << New->getDeclName() << NewTy << OldTy;
10684    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10685    return true;
10686  };
10687
10688
10689  // The new class type must have the same or less qualifiers as the old type.
10690  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10691    Diag(New->getLocation(),
10692         diag::err_covariant_return_type_class_type_more_qualified)
10693    << New->getDeclName() << NewTy << OldTy;
10694    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10695    return true;
10696  };
10697
10698  return false;
10699}
10700
10701/// \brief Mark the given method pure.
10702///
10703/// \param Method the method to be marked pure.
10704///
10705/// \param InitRange the source range that covers the "0" initializer.
10706bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
10707  SourceLocation EndLoc = InitRange.getEnd();
10708  if (EndLoc.isValid())
10709    Method->setRangeEnd(EndLoc);
10710
10711  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10712    Method->setPure();
10713    return false;
10714  }
10715
10716  if (!Method->isInvalidDecl())
10717    Diag(Method->getLocation(), diag::err_non_virtual_pure)
10718      << Method->getDeclName() << InitRange;
10719  return true;
10720}
10721
10722/// \brief Determine whether the given declaration is a static data member.
10723static bool isStaticDataMember(Decl *D) {
10724  VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10725  if (!Var)
10726    return false;
10727
10728  return Var->isStaticDataMember();
10729}
10730/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10731/// an initializer for the out-of-line declaration 'Dcl'.  The scope
10732/// is a fresh scope pushed for just this purpose.
10733///
10734/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10735/// static data member of class X, names should be looked up in the scope of
10736/// class X.
10737void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
10738  // If there is no declaration, there was an error parsing it.
10739  if (D == 0 || D->isInvalidDecl()) return;
10740
10741  // We should only get called for declarations with scope specifiers, like:
10742  //   int foo::bar;
10743  assert(D->isOutOfLine());
10744  EnterDeclaratorContext(S, D->getDeclContext());
10745
10746  // If we are parsing the initializer for a static data member, push a
10747  // new expression evaluation context that is associated with this static
10748  // data member.
10749  if (isStaticDataMember(D))
10750    PushExpressionEvaluationContext(PotentiallyEvaluated, D);
10751}
10752
10753/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
10754/// initializer for the out-of-line declaration 'D'.
10755void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
10756  // If there is no declaration, there was an error parsing it.
10757  if (D == 0 || D->isInvalidDecl()) return;
10758
10759  if (isStaticDataMember(D))
10760    PopExpressionEvaluationContext();
10761
10762  assert(D->isOutOfLine());
10763  ExitDeclaratorContext(S);
10764}
10765
10766/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10767/// C++ if/switch/while/for statement.
10768/// e.g: "if (int x = f()) {...}"
10769DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
10770  // C++ 6.4p2:
10771  // The declarator shall not specify a function or an array.
10772  // The type-specifier-seq shall not contain typedef and shall not declare a
10773  // new class or enumeration.
10774  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10775         "Parser allowed 'typedef' as storage class of condition decl.");
10776
10777  Decl *Dcl = ActOnDeclarator(S, D);
10778  if (!Dcl)
10779    return true;
10780
10781  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10782    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
10783      << D.getSourceRange();
10784    return true;
10785  }
10786
10787  return Dcl;
10788}
10789
10790void Sema::LoadExternalVTableUses() {
10791  if (!ExternalSource)
10792    return;
10793
10794  SmallVector<ExternalVTableUse, 4> VTables;
10795  ExternalSource->ReadUsedVTables(VTables);
10796  SmallVector<VTableUse, 4> NewUses;
10797  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10798    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10799      = VTablesUsed.find(VTables[I].Record);
10800    // Even if a definition wasn't required before, it may be required now.
10801    if (Pos != VTablesUsed.end()) {
10802      if (!Pos->second && VTables[I].DefinitionRequired)
10803        Pos->second = true;
10804      continue;
10805    }
10806
10807    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10808    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10809  }
10810
10811  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10812}
10813
10814void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10815                          bool DefinitionRequired) {
10816  // Ignore any vtable uses in unevaluated operands or for classes that do
10817  // not have a vtable.
10818  if (!Class->isDynamicClass() || Class->isDependentContext() ||
10819      CurContext->isDependentContext() ||
10820      ExprEvalContexts.back().Context == Unevaluated)
10821    return;
10822
10823  // Try to insert this class into the map.
10824  LoadExternalVTableUses();
10825  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10826  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10827    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10828  if (!Pos.second) {
10829    // If we already had an entry, check to see if we are promoting this vtable
10830    // to required a definition. If so, we need to reappend to the VTableUses
10831    // list, since we may have already processed the first entry.
10832    if (DefinitionRequired && !Pos.first->second) {
10833      Pos.first->second = true;
10834    } else {
10835      // Otherwise, we can early exit.
10836      return;
10837    }
10838  }
10839
10840  // Local classes need to have their virtual members marked
10841  // immediately. For all other classes, we mark their virtual members
10842  // at the end of the translation unit.
10843  if (Class->isLocalClass())
10844    MarkVirtualMembersReferenced(Loc, Class);
10845  else
10846    VTableUses.push_back(std::make_pair(Class, Loc));
10847}
10848
10849bool Sema::DefineUsedVTables() {
10850  LoadExternalVTableUses();
10851  if (VTableUses.empty())
10852    return false;
10853
10854  // Note: The VTableUses vector could grow as a result of marking
10855  // the members of a class as "used", so we check the size each
10856  // time through the loop and prefer indices (which are stable) to
10857  // iterators (which are not).
10858  bool DefinedAnything = false;
10859  for (unsigned I = 0; I != VTableUses.size(); ++I) {
10860    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
10861    if (!Class)
10862      continue;
10863
10864    SourceLocation Loc = VTableUses[I].second;
10865
10866    bool DefineVTable = true;
10867
10868    // If this class has a key function, but that key function is
10869    // defined in another translation unit, we don't need to emit the
10870    // vtable even though we're using it.
10871    const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
10872    if (KeyFunction && !KeyFunction->hasBody()) {
10873      switch (KeyFunction->getTemplateSpecializationKind()) {
10874      case TSK_Undeclared:
10875      case TSK_ExplicitSpecialization:
10876      case TSK_ExplicitInstantiationDeclaration:
10877        // The key function is in another translation unit.
10878        DefineVTable = false;
10879        break;
10880
10881      case TSK_ExplicitInstantiationDefinition:
10882      case TSK_ImplicitInstantiation:
10883        // We will be instantiating the key function.
10884        break;
10885      }
10886    } else if (!KeyFunction) {
10887      // If we have a class with no key function that is the subject
10888      // of an explicit instantiation declaration, suppress the
10889      // vtable; it will live with the explicit instantiation
10890      // definition.
10891      bool IsExplicitInstantiationDeclaration
10892        = Class->getTemplateSpecializationKind()
10893                                      == TSK_ExplicitInstantiationDeclaration;
10894      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10895                                 REnd = Class->redecls_end();
10896           R != REnd; ++R) {
10897        TemplateSpecializationKind TSK
10898          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10899        if (TSK == TSK_ExplicitInstantiationDeclaration)
10900          IsExplicitInstantiationDeclaration = true;
10901        else if (TSK == TSK_ExplicitInstantiationDefinition) {
10902          IsExplicitInstantiationDeclaration = false;
10903          break;
10904        }
10905      }
10906
10907      if (IsExplicitInstantiationDeclaration)
10908        DefineVTable = false;
10909    }
10910
10911    // The exception specifications for all virtual members may be needed even
10912    // if we are not providing an authoritative form of the vtable in this TU.
10913    // We may choose to emit it available_externally anyway.
10914    if (!DefineVTable) {
10915      MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
10916      continue;
10917    }
10918
10919    // Mark all of the virtual members of this class as referenced, so
10920    // that we can build a vtable. Then, tell the AST consumer that a
10921    // vtable for this class is required.
10922    DefinedAnything = true;
10923    MarkVirtualMembersReferenced(Loc, Class);
10924    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10925    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10926
10927    // Optionally warn if we're emitting a weak vtable.
10928    if (Class->getLinkage() == ExternalLinkage &&
10929        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
10930      const FunctionDecl *KeyFunctionDef = 0;
10931      if (!KeyFunction ||
10932          (KeyFunction->hasBody(KeyFunctionDef) &&
10933           KeyFunctionDef->isInlined()))
10934        Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10935             TSK_ExplicitInstantiationDefinition
10936             ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10937          << Class;
10938    }
10939  }
10940  VTableUses.clear();
10941
10942  return DefinedAnything;
10943}
10944
10945void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
10946                                                 const CXXRecordDecl *RD) {
10947  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
10948                                      E = RD->method_end(); I != E; ++I)
10949    if ((*I)->isVirtual() && !(*I)->isPure())
10950      ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
10951}
10952
10953void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10954                                        const CXXRecordDecl *RD) {
10955  // Mark all functions which will appear in RD's vtable as used.
10956  CXXFinalOverriderMap FinalOverriders;
10957  RD->getFinalOverriders(FinalOverriders);
10958  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
10959                                            E = FinalOverriders.end();
10960       I != E; ++I) {
10961    for (OverridingMethods::const_iterator OI = I->second.begin(),
10962                                           OE = I->second.end();
10963         OI != OE; ++OI) {
10964      assert(OI->second.size() > 0 && "no final overrider");
10965      CXXMethodDecl *Overrider = OI->second.front().Method;
10966
10967      // C++ [basic.def.odr]p2:
10968      //   [...] A virtual member function is used if it is not pure. [...]
10969      if (!Overrider->isPure())
10970        MarkFunctionReferenced(Loc, Overrider);
10971    }
10972  }
10973
10974  // Only classes that have virtual bases need a VTT.
10975  if (RD->getNumVBases() == 0)
10976    return;
10977
10978  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10979           e = RD->bases_end(); i != e; ++i) {
10980    const CXXRecordDecl *Base =
10981        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
10982    if (Base->getNumVBases() == 0)
10983      continue;
10984    MarkVirtualMembersReferenced(Loc, Base);
10985  }
10986}
10987
10988/// SetIvarInitializers - This routine builds initialization ASTs for the
10989/// Objective-C implementation whose ivars need be initialized.
10990void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10991  if (!getLangOpts().CPlusPlus)
10992    return;
10993  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
10994    SmallVector<ObjCIvarDecl*, 8> ivars;
10995    CollectIvarsToConstructOrDestruct(OID, ivars);
10996    if (ivars.empty())
10997      return;
10998    SmallVector<CXXCtorInitializer*, 32> AllToInit;
10999    for (unsigned i = 0; i < ivars.size(); i++) {
11000      FieldDecl *Field = ivars[i];
11001      if (Field->isInvalidDecl())
11002        continue;
11003
11004      CXXCtorInitializer *Member;
11005      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11006      InitializationKind InitKind =
11007        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11008
11009      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
11010      ExprResult MemberInit =
11011        InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
11012      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
11013      // Note, MemberInit could actually come back empty if no initialization
11014      // is required (e.g., because it would call a trivial default constructor)
11015      if (!MemberInit.get() || MemberInit.isInvalid())
11016        continue;
11017
11018      Member =
11019        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11020                                         SourceLocation(),
11021                                         MemberInit.takeAs<Expr>(),
11022                                         SourceLocation());
11023      AllToInit.push_back(Member);
11024
11025      // Be sure that the destructor is accessible and is marked as referenced.
11026      if (const RecordType *RecordTy
11027                  = Context.getBaseElementType(Field->getType())
11028                                                        ->getAs<RecordType>()) {
11029                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
11030        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
11031          MarkFunctionReferenced(Field->getLocation(), Destructor);
11032          CheckDestructorAccess(Field->getLocation(), Destructor,
11033                            PDiag(diag::err_access_dtor_ivar)
11034                              << Context.getBaseElementType(Field->getType()));
11035        }
11036      }
11037    }
11038    ObjCImplementation->setIvarInitializers(Context,
11039                                            AllToInit.data(), AllToInit.size());
11040  }
11041}
11042
11043static
11044void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11045                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11046                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11047                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11048                           Sema &S) {
11049  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11050                                                   CE = Current.end();
11051  if (Ctor->isInvalidDecl())
11052    return;
11053
11054  CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11055
11056  // Target may not be determinable yet, for instance if this is a dependent
11057  // call in an uninstantiated template.
11058  if (Target) {
11059    const FunctionDecl *FNTarget = 0;
11060    (void)Target->hasBody(FNTarget);
11061    Target = const_cast<CXXConstructorDecl*>(
11062      cast_or_null<CXXConstructorDecl>(FNTarget));
11063  }
11064
11065  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11066                     // Avoid dereferencing a null pointer here.
11067                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11068
11069  if (!Current.insert(Canonical))
11070    return;
11071
11072  // We know that beyond here, we aren't chaining into a cycle.
11073  if (!Target || !Target->isDelegatingConstructor() ||
11074      Target->isInvalidDecl() || Valid.count(TCanonical)) {
11075    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11076      Valid.insert(*CI);
11077    Current.clear();
11078  // We've hit a cycle.
11079  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11080             Current.count(TCanonical)) {
11081    // If we haven't diagnosed this cycle yet, do so now.
11082    if (!Invalid.count(TCanonical)) {
11083      S.Diag((*Ctor->init_begin())->getSourceLocation(),
11084             diag::warn_delegating_ctor_cycle)
11085        << Ctor;
11086
11087      // Don't add a note for a function delegating directly to itself.
11088      if (TCanonical != Canonical)
11089        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11090
11091      CXXConstructorDecl *C = Target;
11092      while (C->getCanonicalDecl() != Canonical) {
11093        const FunctionDecl *FNTarget = 0;
11094        (void)C->getTargetConstructor()->hasBody(FNTarget);
11095        assert(FNTarget && "Ctor cycle through bodiless function");
11096
11097        C = const_cast<CXXConstructorDecl*>(
11098          cast<CXXConstructorDecl>(FNTarget));
11099        S.Diag(C->getLocation(), diag::note_which_delegates_to);
11100      }
11101    }
11102
11103    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11104      Invalid.insert(*CI);
11105    Current.clear();
11106  } else {
11107    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11108  }
11109}
11110
11111
11112void Sema::CheckDelegatingCtorCycles() {
11113  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11114
11115  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11116                                                   CE = Current.end();
11117
11118  for (DelegatingCtorDeclsType::iterator
11119         I = DelegatingCtorDecls.begin(ExternalSource),
11120         E = DelegatingCtorDecls.end();
11121       I != E; ++I)
11122    DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
11123
11124  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11125    (*CI)->setInvalidDecl();
11126}
11127
11128namespace {
11129  /// \brief AST visitor that finds references to the 'this' expression.
11130  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11131    Sema &S;
11132
11133  public:
11134    explicit FindCXXThisExpr(Sema &S) : S(S) { }
11135
11136    bool VisitCXXThisExpr(CXXThisExpr *E) {
11137      S.Diag(E->getLocation(), diag::err_this_static_member_func)
11138        << E->isImplicit();
11139      return false;
11140    }
11141  };
11142}
11143
11144bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11145  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11146  if (!TSInfo)
11147    return false;
11148
11149  TypeLoc TL = TSInfo->getTypeLoc();
11150  FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11151  if (!ProtoTL)
11152    return false;
11153
11154  // C++11 [expr.prim.general]p3:
11155  //   [The expression this] shall not appear before the optional
11156  //   cv-qualifier-seq and it shall not appear within the declaration of a
11157  //   static member function (although its type and value category are defined
11158  //   within a static member function as they are within a non-static member
11159  //   function). [ Note: this is because declaration matching does not occur
11160  //  until the complete declarator is known. - end note ]
11161  const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11162  FindCXXThisExpr Finder(*this);
11163
11164  // If the return type came after the cv-qualifier-seq, check it now.
11165  if (Proto->hasTrailingReturn() &&
11166      !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11167    return true;
11168
11169  // Check the exception specification.
11170  if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11171    return true;
11172
11173  return checkThisInStaticMemberFunctionAttributes(Method);
11174}
11175
11176bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11177  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11178  if (!TSInfo)
11179    return false;
11180
11181  TypeLoc TL = TSInfo->getTypeLoc();
11182  FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11183  if (!ProtoTL)
11184    return false;
11185
11186  const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11187  FindCXXThisExpr Finder(*this);
11188
11189  switch (Proto->getExceptionSpecType()) {
11190  case EST_Uninstantiated:
11191  case EST_Unevaluated:
11192  case EST_BasicNoexcept:
11193  case EST_DynamicNone:
11194  case EST_MSAny:
11195  case EST_None:
11196    break;
11197
11198  case EST_ComputedNoexcept:
11199    if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11200      return true;
11201
11202  case EST_Dynamic:
11203    for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
11204         EEnd = Proto->exception_end();
11205         E != EEnd; ++E) {
11206      if (!Finder.TraverseType(*E))
11207        return true;
11208    }
11209    break;
11210  }
11211
11212  return false;
11213}
11214
11215bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11216  FindCXXThisExpr Finder(*this);
11217
11218  // Check attributes.
11219  for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11220       A != AEnd; ++A) {
11221    // FIXME: This should be emitted by tblgen.
11222    Expr *Arg = 0;
11223    ArrayRef<Expr *> Args;
11224    if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11225      Arg = G->getArg();
11226    else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11227      Arg = G->getArg();
11228    else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11229      Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11230    else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11231      Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11232    else if (ExclusiveLockFunctionAttr *ELF
11233               = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11234      Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11235    else if (SharedLockFunctionAttr *SLF
11236               = dyn_cast<SharedLockFunctionAttr>(*A))
11237      Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11238    else if (ExclusiveTrylockFunctionAttr *ETLF
11239               = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11240      Arg = ETLF->getSuccessValue();
11241      Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11242    } else if (SharedTrylockFunctionAttr *STLF
11243                 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11244      Arg = STLF->getSuccessValue();
11245      Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11246    } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11247      Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11248    else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11249      Arg = LR->getArg();
11250    else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11251      Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11252    else if (ExclusiveLocksRequiredAttr *ELR
11253               = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11254      Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11255    else if (SharedLocksRequiredAttr *SLR
11256               = dyn_cast<SharedLocksRequiredAttr>(*A))
11257      Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11258
11259    if (Arg && !Finder.TraverseStmt(Arg))
11260      return true;
11261
11262    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11263      if (!Finder.TraverseStmt(Args[I]))
11264        return true;
11265    }
11266  }
11267
11268  return false;
11269}
11270
11271void
11272Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11273                                  ArrayRef<ParsedType> DynamicExceptions,
11274                                  ArrayRef<SourceRange> DynamicExceptionRanges,
11275                                  Expr *NoexceptExpr,
11276                                  llvm::SmallVectorImpl<QualType> &Exceptions,
11277                                  FunctionProtoType::ExtProtoInfo &EPI) {
11278  Exceptions.clear();
11279  EPI.ExceptionSpecType = EST;
11280  if (EST == EST_Dynamic) {
11281    Exceptions.reserve(DynamicExceptions.size());
11282    for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11283      // FIXME: Preserve type source info.
11284      QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11285
11286      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11287      collectUnexpandedParameterPacks(ET, Unexpanded);
11288      if (!Unexpanded.empty()) {
11289        DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11290                                         UPPC_ExceptionType,
11291                                         Unexpanded);
11292        continue;
11293      }
11294
11295      // Check that the type is valid for an exception spec, and
11296      // drop it if not.
11297      if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11298        Exceptions.push_back(ET);
11299    }
11300    EPI.NumExceptions = Exceptions.size();
11301    EPI.Exceptions = Exceptions.data();
11302    return;
11303  }
11304
11305  if (EST == EST_ComputedNoexcept) {
11306    // If an error occurred, there's no expression here.
11307    if (NoexceptExpr) {
11308      assert((NoexceptExpr->isTypeDependent() ||
11309              NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11310              Context.BoolTy) &&
11311             "Parser should have made sure that the expression is boolean");
11312      if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11313        EPI.ExceptionSpecType = EST_BasicNoexcept;
11314        return;
11315      }
11316
11317      if (!NoexceptExpr->isValueDependent())
11318        NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
11319                         diag::err_noexcept_needs_constant_expression,
11320                         /*AllowFold*/ false).take();
11321      EPI.NoexceptExpr = NoexceptExpr;
11322    }
11323    return;
11324  }
11325}
11326
11327/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11328Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11329  // Implicitly declared functions (e.g. copy constructors) are
11330  // __host__ __device__
11331  if (D->isImplicit())
11332    return CFT_HostDevice;
11333
11334  if (D->hasAttr<CUDAGlobalAttr>())
11335    return CFT_Global;
11336
11337  if (D->hasAttr<CUDADeviceAttr>()) {
11338    if (D->hasAttr<CUDAHostAttr>())
11339      return CFT_HostDevice;
11340    else
11341      return CFT_Device;
11342  }
11343
11344  return CFT_Host;
11345}
11346
11347bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11348                           CUDAFunctionTarget CalleeTarget) {
11349  // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11350  // Callable from the device only."
11351  if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11352    return true;
11353
11354  // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11355  // Callable from the host only."
11356  // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11357  // Callable from the host only."
11358  if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11359      (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11360    return true;
11361
11362  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11363    return true;
11364
11365  return false;
11366}
11367