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