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