SemaDeclCXX.cpp revision f961ea5716867b5e426fb2136edd6d1f04c3a7ca
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
15#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
17#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
19#include "clang/AST/ASTConsumer.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/ASTMutationListener.h"
22#include "clang/AST/CharUnits.h"
23#include "clang/AST/CXXInheritance.h"
24#include "clang/AST/DeclVisitor.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/AST/TypeOrdering.h"
30#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
32#include "clang/Basic/PartialDiagnostic.h"
33#include "clang/Lex/Preprocessor.h"
34#include "llvm/ADT/DenseSet.h"
35#include "llvm/ADT/STLExtras.h"
36#include <map>
37#include <set>
38
39using namespace clang;
40
41//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
45namespace {
46  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47  /// the default argument of a parameter to determine whether it
48  /// contains any ill-formed subexpressions. For example, this will
49  /// diagnose the use of local variables or parameters within the
50  /// default argument expression.
51  class CheckDefaultArgumentVisitor
52    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
53    Expr *DefaultArg;
54    Sema *S;
55
56  public:
57    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
58      : DefaultArg(defarg), S(s) {}
59
60    bool VisitExpr(Expr *Node);
61    bool VisitDeclRefExpr(DeclRefExpr *DRE);
62    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
63  };
64
65  /// VisitExpr - Visit all of the children of this expression.
66  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67    bool IsInvalid = false;
68    for (Stmt::child_range I = Node->children(); I; ++I)
69      IsInvalid |= Visit(*I);
70    return IsInvalid;
71  }
72
73  /// VisitDeclRefExpr - Visit a reference to a declaration, to
74  /// determine whether this declaration can be used in the default
75  /// argument expression.
76  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
77    NamedDecl *Decl = DRE->getDecl();
78    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79      // C++ [dcl.fct.default]p9
80      //   Default arguments are evaluated each time the function is
81      //   called. The order of evaluation of function arguments is
82      //   unspecified. Consequently, parameters of a function shall not
83      //   be used in default argument expressions, even if they are not
84      //   evaluated. Parameters of a function declared before a default
85      //   argument expression are in scope and can hide namespace and
86      //   class member names.
87      return S->Diag(DRE->getSourceRange().getBegin(),
88                     diag::err_param_default_argument_references_param)
89         << Param->getDeclName() << DefaultArg->getSourceRange();
90    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
91      // C++ [dcl.fct.default]p7
92      //   Local variables shall not be used in default argument
93      //   expressions.
94      if (VDecl->isLocalVarDecl())
95        return S->Diag(DRE->getSourceRange().getBegin(),
96                       diag::err_param_default_argument_references_local)
97          << VDecl->getDeclName() << DefaultArg->getSourceRange();
98    }
99
100    return false;
101  }
102
103  /// VisitCXXThisExpr - Visit a C++ "this" expression.
104  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105    // C++ [dcl.fct.default]p8:
106    //   The keyword this shall not be used in a default argument of a
107    //   member function.
108    return S->Diag(ThisE->getSourceRange().getBegin(),
109                   diag::err_param_default_argument_references_this)
110               << ThisE->getSourceRange();
111  }
112}
113
114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
115  // If we have an MSAny spec already, don't bother.
116  if (!Method || ComputedEST == EST_MSAny)
117    return;
118
119  const FunctionProtoType *Proto
120    = Method->getType()->getAs<FunctionProtoType>();
121
122  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
123
124  // If this function can throw any exceptions, make a note of that.
125  if (EST == EST_MSAny || EST == EST_None) {
126    ClearExceptions();
127    ComputedEST = EST;
128    return;
129  }
130
131  // If this function has a basic noexcept, it doesn't affect the outcome.
132  if (EST == EST_BasicNoexcept)
133    return;
134
135  // If we have a throw-all spec at this point, ignore the function.
136  if (ComputedEST == EST_None)
137    return;
138
139  // If we're still at noexcept(true) and there's a nothrow() callee,
140  // change to that specification.
141  if (EST == EST_DynamicNone) {
142    if (ComputedEST == EST_BasicNoexcept)
143      ComputedEST = EST_DynamicNone;
144    return;
145  }
146
147  // Check out noexcept specs.
148  if (EST == EST_ComputedNoexcept) {
149    FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(Context);
150    assert(NR != FunctionProtoType::NR_NoNoexcept &&
151           "Must have noexcept result for EST_ComputedNoexcept.");
152    assert(NR != FunctionProtoType::NR_Dependent &&
153           "Should not generate implicit declarations for dependent cases, "
154           "and don't know how to handle them anyway.");
155
156    // noexcept(false) -> no spec on the new function
157    if (NR == FunctionProtoType::NR_Throw) {
158      ClearExceptions();
159      ComputedEST = EST_None;
160    }
161    // noexcept(true) won't change anything either.
162    return;
163  }
164
165  assert(EST == EST_Dynamic && "EST case not considered earlier.");
166  assert(ComputedEST != EST_None &&
167         "Shouldn't collect exceptions when throw-all is guaranteed.");
168  ComputedEST = EST_Dynamic;
169  // Record the exceptions in this function's exception specification.
170  for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
171                                          EEnd = Proto->exception_end();
172       E != EEnd; ++E)
173    if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
174      Exceptions.push_back(*E);
175}
176
177bool
178Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
179                              SourceLocation EqualLoc) {
180  if (RequireCompleteType(Param->getLocation(), Param->getType(),
181                          diag::err_typecheck_decl_incomplete_type)) {
182    Param->setInvalidDecl();
183    return true;
184  }
185
186  // C++ [dcl.fct.default]p5
187  //   A default argument expression is implicitly converted (clause
188  //   4) to the parameter type. The default argument expression has
189  //   the same semantic constraints as the initializer expression in
190  //   a declaration of a variable of the parameter type, using the
191  //   copy-initialization semantics (8.5).
192  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
193                                                                    Param);
194  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
195                                                           EqualLoc);
196  InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
197  ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
198                                      MultiExprArg(*this, &Arg, 1));
199  if (Result.isInvalid())
200    return true;
201  Arg = Result.takeAs<Expr>();
202
203  CheckImplicitConversions(Arg, EqualLoc);
204  Arg = MaybeCreateExprWithCleanups(Arg);
205
206  // Okay: add the default argument to the parameter
207  Param->setDefaultArg(Arg);
208
209  // We have already instantiated this parameter; provide each of the
210  // instantiations with the uninstantiated default argument.
211  UnparsedDefaultArgInstantiationsMap::iterator InstPos
212    = UnparsedDefaultArgInstantiations.find(Param);
213  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
214    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
215      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
216
217    // We're done tracking this parameter's instantiations.
218    UnparsedDefaultArgInstantiations.erase(InstPos);
219  }
220
221  return false;
222}
223
224/// ActOnParamDefaultArgument - Check whether the default argument
225/// provided for a function parameter is well-formed. If so, attach it
226/// to the parameter declaration.
227void
228Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
229                                Expr *DefaultArg) {
230  if (!param || !DefaultArg)
231    return;
232
233  ParmVarDecl *Param = cast<ParmVarDecl>(param);
234  UnparsedDefaultArgLocs.erase(Param);
235
236  // Default arguments are only permitted in C++
237  if (!getLangOptions().CPlusPlus) {
238    Diag(EqualLoc, diag::err_param_default_argument)
239      << DefaultArg->getSourceRange();
240    Param->setInvalidDecl();
241    return;
242  }
243
244  // Check for unexpanded parameter packs.
245  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
246    Param->setInvalidDecl();
247    return;
248  }
249
250  // Check that the default argument is well-formed
251  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
252  if (DefaultArgChecker.Visit(DefaultArg)) {
253    Param->setInvalidDecl();
254    return;
255  }
256
257  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
258}
259
260/// ActOnParamUnparsedDefaultArgument - We've seen a default
261/// argument for a function parameter, but we can't parse it yet
262/// because we're inside a class definition. Note that this default
263/// argument will be parsed later.
264void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
265                                             SourceLocation EqualLoc,
266                                             SourceLocation ArgLoc) {
267  if (!param)
268    return;
269
270  ParmVarDecl *Param = cast<ParmVarDecl>(param);
271  if (Param)
272    Param->setUnparsedDefaultArg();
273
274  UnparsedDefaultArgLocs[Param] = ArgLoc;
275}
276
277/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
278/// the default argument for the parameter param failed.
279void Sema::ActOnParamDefaultArgumentError(Decl *param) {
280  if (!param)
281    return;
282
283  ParmVarDecl *Param = cast<ParmVarDecl>(param);
284
285  Param->setInvalidDecl();
286
287  UnparsedDefaultArgLocs.erase(Param);
288}
289
290/// CheckExtraCXXDefaultArguments - Check for any extra default
291/// arguments in the declarator, which is not a function declaration
292/// or definition and therefore is not permitted to have default
293/// arguments. This routine should be invoked for every declarator
294/// that is not a function declaration or definition.
295void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
296  // C++ [dcl.fct.default]p3
297  //   A default argument expression shall be specified only in the
298  //   parameter-declaration-clause of a function declaration or in a
299  //   template-parameter (14.1). It shall not be specified for a
300  //   parameter pack. If it is specified in a
301  //   parameter-declaration-clause, it shall not occur within a
302  //   declarator or abstract-declarator of a parameter-declaration.
303  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
304    DeclaratorChunk &chunk = D.getTypeObject(i);
305    if (chunk.Kind == DeclaratorChunk::Function) {
306      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
307        ParmVarDecl *Param =
308          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
309        if (Param->hasUnparsedDefaultArg()) {
310          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
311          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
312            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
313          delete Toks;
314          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
315        } else if (Param->getDefaultArg()) {
316          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
317            << Param->getDefaultArg()->getSourceRange();
318          Param->setDefaultArg(0);
319        }
320      }
321    }
322  }
323}
324
325// MergeCXXFunctionDecl - Merge two declarations of the same C++
326// function, once we already know that they have the same
327// type. Subroutine of MergeFunctionDecl. Returns true if there was an
328// error, false otherwise.
329bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
330  bool Invalid = false;
331
332  // C++ [dcl.fct.default]p4:
333  //   For non-template functions, default arguments can be added in
334  //   later declarations of a function in the same
335  //   scope. Declarations in different scopes have completely
336  //   distinct sets of default arguments. That is, declarations in
337  //   inner scopes do not acquire default arguments from
338  //   declarations in outer scopes, and vice versa. In a given
339  //   function declaration, all parameters subsequent to a
340  //   parameter with a default argument shall have default
341  //   arguments supplied in this or previous declarations. A
342  //   default argument shall not be redefined by a later
343  //   declaration (not even to the same value).
344  //
345  // C++ [dcl.fct.default]p6:
346  //   Except for member functions of class templates, the default arguments
347  //   in a member function definition that appears outside of the class
348  //   definition are added to the set of default arguments provided by the
349  //   member function declaration in the class definition.
350  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
351    ParmVarDecl *OldParam = Old->getParamDecl(p);
352    ParmVarDecl *NewParam = New->getParamDecl(p);
353
354    if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
355
356      unsigned DiagDefaultParamID =
357        diag::err_param_default_argument_redefinition;
358
359      // MSVC accepts that default parameters be redefined for member functions
360      // of template class. The new default parameter's value is ignored.
361      Invalid = true;
362      if (getLangOptions().Microsoft) {
363        CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
364        if (MD && MD->getParent()->getDescribedClassTemplate()) {
365          // Merge the old default argument into the new parameter.
366          NewParam->setHasInheritedDefaultArg();
367          if (OldParam->hasUninstantiatedDefaultArg())
368            NewParam->setUninstantiatedDefaultArg(
369                                      OldParam->getUninstantiatedDefaultArg());
370          else
371            NewParam->setDefaultArg(OldParam->getInit());
372          DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
373          Invalid = false;
374        }
375      }
376
377      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
378      // hint here. Alternatively, we could walk the type-source information
379      // for NewParam to find the last source location in the type... but it
380      // isn't worth the effort right now. This is the kind of test case that
381      // is hard to get right:
382      //   int f(int);
383      //   void g(int (*fp)(int) = f);
384      //   void g(int (*fp)(int) = &f);
385      Diag(NewParam->getLocation(), DiagDefaultParamID)
386        << NewParam->getDefaultArgRange();
387
388      // Look for the function declaration where the default argument was
389      // actually written, which may be a declaration prior to Old.
390      for (FunctionDecl *Older = Old->getPreviousDeclaration();
391           Older; Older = Older->getPreviousDeclaration()) {
392        if (!Older->getParamDecl(p)->hasDefaultArg())
393          break;
394
395        OldParam = Older->getParamDecl(p);
396      }
397
398      Diag(OldParam->getLocation(), diag::note_previous_definition)
399        << OldParam->getDefaultArgRange();
400    } else if (OldParam->hasDefaultArg()) {
401      // Merge the old default argument into the new parameter.
402      // It's important to use getInit() here;  getDefaultArg()
403      // strips off any top-level ExprWithCleanups.
404      NewParam->setHasInheritedDefaultArg();
405      if (OldParam->hasUninstantiatedDefaultArg())
406        NewParam->setUninstantiatedDefaultArg(
407                                      OldParam->getUninstantiatedDefaultArg());
408      else
409        NewParam->setDefaultArg(OldParam->getInit());
410    } else if (NewParam->hasDefaultArg()) {
411      if (New->getDescribedFunctionTemplate()) {
412        // Paragraph 4, quoted above, only applies to non-template functions.
413        Diag(NewParam->getLocation(),
414             diag::err_param_default_argument_template_redecl)
415          << NewParam->getDefaultArgRange();
416        Diag(Old->getLocation(), diag::note_template_prev_declaration)
417          << false;
418      } else if (New->getTemplateSpecializationKind()
419                   != TSK_ImplicitInstantiation &&
420                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
421        // C++ [temp.expr.spec]p21:
422        //   Default function arguments shall not be specified in a declaration
423        //   or a definition for one of the following explicit specializations:
424        //     - the explicit specialization of a function template;
425        //     - the explicit specialization of a member function template;
426        //     - the explicit specialization of a member function of a class
427        //       template where the class template specialization to which the
428        //       member function specialization belongs is implicitly
429        //       instantiated.
430        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
431          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
432          << New->getDeclName()
433          << NewParam->getDefaultArgRange();
434      } else if (New->getDeclContext()->isDependentContext()) {
435        // C++ [dcl.fct.default]p6 (DR217):
436        //   Default arguments for a member function of a class template shall
437        //   be specified on the initial declaration of the member function
438        //   within the class template.
439        //
440        // Reading the tea leaves a bit in DR217 and its reference to DR205
441        // leads me to the conclusion that one cannot add default function
442        // arguments for an out-of-line definition of a member function of a
443        // dependent type.
444        int WhichKind = 2;
445        if (CXXRecordDecl *Record
446              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
447          if (Record->getDescribedClassTemplate())
448            WhichKind = 0;
449          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
450            WhichKind = 1;
451          else
452            WhichKind = 2;
453        }
454
455        Diag(NewParam->getLocation(),
456             diag::err_param_default_argument_member_template_redecl)
457          << WhichKind
458          << NewParam->getDefaultArgRange();
459      }
460    }
461  }
462
463  if (CheckEquivalentExceptionSpec(Old, New))
464    Invalid = true;
465
466  return Invalid;
467}
468
469/// \brief Merge the exception specifications of two variable declarations.
470///
471/// This is called when there's a redeclaration of a VarDecl. The function
472/// checks if the redeclaration might have an exception specification and
473/// validates compatibility and merges the specs if necessary.
474void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
475  // Shortcut if exceptions are disabled.
476  if (!getLangOptions().CXXExceptions)
477    return;
478
479  assert(Context.hasSameType(New->getType(), Old->getType()) &&
480         "Should only be called if types are otherwise the same.");
481
482  QualType NewType = New->getType();
483  QualType OldType = Old->getType();
484
485  // We're only interested in pointers and references to functions, as well
486  // as pointers to member functions.
487  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
488    NewType = R->getPointeeType();
489    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
490  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
491    NewType = P->getPointeeType();
492    OldType = OldType->getAs<PointerType>()->getPointeeType();
493  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
494    NewType = M->getPointeeType();
495    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
496  }
497
498  if (!NewType->isFunctionProtoType())
499    return;
500
501  // There's lots of special cases for functions. For function pointers, system
502  // libraries are hopefully not as broken so that we don't need these
503  // workarounds.
504  if (CheckEquivalentExceptionSpec(
505        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
506        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
507    New->setInvalidDecl();
508  }
509}
510
511/// CheckCXXDefaultArguments - Verify that the default arguments for a
512/// function declaration are well-formed according to C++
513/// [dcl.fct.default].
514void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
515  unsigned NumParams = FD->getNumParams();
516  unsigned p;
517
518  // Find first parameter with a default argument
519  for (p = 0; p < NumParams; ++p) {
520    ParmVarDecl *Param = FD->getParamDecl(p);
521    if (Param->hasDefaultArg())
522      break;
523  }
524
525  // C++ [dcl.fct.default]p4:
526  //   In a given function declaration, all parameters
527  //   subsequent to a parameter with a default argument shall
528  //   have default arguments supplied in this or previous
529  //   declarations. A default argument shall not be redefined
530  //   by a later declaration (not even to the same value).
531  unsigned LastMissingDefaultArg = 0;
532  for (; p < NumParams; ++p) {
533    ParmVarDecl *Param = FD->getParamDecl(p);
534    if (!Param->hasDefaultArg()) {
535      if (Param->isInvalidDecl())
536        /* We already complained about this parameter. */;
537      else if (Param->getIdentifier())
538        Diag(Param->getLocation(),
539             diag::err_param_default_argument_missing_name)
540          << Param->getIdentifier();
541      else
542        Diag(Param->getLocation(),
543             diag::err_param_default_argument_missing);
544
545      LastMissingDefaultArg = p;
546    }
547  }
548
549  if (LastMissingDefaultArg > 0) {
550    // Some default arguments were missing. Clear out all of the
551    // default arguments up to (and including) the last missing
552    // default argument, so that we leave the function parameters
553    // in a semantically valid state.
554    for (p = 0; p <= LastMissingDefaultArg; ++p) {
555      ParmVarDecl *Param = FD->getParamDecl(p);
556      if (Param->hasDefaultArg()) {
557        Param->setDefaultArg(0);
558      }
559    }
560  }
561}
562
563/// isCurrentClassName - Determine whether the identifier II is the
564/// name of the class type currently being defined. In the case of
565/// nested classes, this will only return true if II is the name of
566/// the innermost class.
567bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
568                              const CXXScopeSpec *SS) {
569  assert(getLangOptions().CPlusPlus && "No class names in C!");
570
571  CXXRecordDecl *CurDecl;
572  if (SS && SS->isSet() && !SS->isInvalid()) {
573    DeclContext *DC = computeDeclContext(*SS, true);
574    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
575  } else
576    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
577
578  if (CurDecl && CurDecl->getIdentifier())
579    return &II == CurDecl->getIdentifier();
580  else
581    return false;
582}
583
584/// \brief Check the validity of a C++ base class specifier.
585///
586/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
587/// and returns NULL otherwise.
588CXXBaseSpecifier *
589Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
590                         SourceRange SpecifierRange,
591                         bool Virtual, AccessSpecifier Access,
592                         TypeSourceInfo *TInfo,
593                         SourceLocation EllipsisLoc) {
594  QualType BaseType = TInfo->getType();
595
596  // C++ [class.union]p1:
597  //   A union shall not have base classes.
598  if (Class->isUnion()) {
599    Diag(Class->getLocation(), diag::err_base_clause_on_union)
600      << SpecifierRange;
601    return 0;
602  }
603
604  if (EllipsisLoc.isValid() &&
605      !TInfo->getType()->containsUnexpandedParameterPack()) {
606    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
607      << TInfo->getTypeLoc().getSourceRange();
608    EllipsisLoc = SourceLocation();
609  }
610
611  if (BaseType->isDependentType())
612    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
613                                          Class->getTagKind() == TTK_Class,
614                                          Access, TInfo, EllipsisLoc);
615
616  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
617
618  // Base specifiers must be record types.
619  if (!BaseType->isRecordType()) {
620    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
621    return 0;
622  }
623
624  // C++ [class.union]p1:
625  //   A union shall not be used as a base class.
626  if (BaseType->isUnionType()) {
627    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
628    return 0;
629  }
630
631  // C++ [class.derived]p2:
632  //   The class-name in a base-specifier shall not be an incompletely
633  //   defined class.
634  if (RequireCompleteType(BaseLoc, BaseType,
635                          PDiag(diag::err_incomplete_base_class)
636                            << SpecifierRange)) {
637    Class->setInvalidDecl();
638    return 0;
639  }
640
641  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
642  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
643  assert(BaseDecl && "Record type has no declaration");
644  BaseDecl = BaseDecl->getDefinition();
645  assert(BaseDecl && "Base type is not incomplete, but has no definition");
646  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
647  assert(CXXBaseDecl && "Base type is not a C++ type");
648
649  // C++ [class]p3:
650  //   If a class is marked final and it appears as a base-type-specifier in
651  //   base-clause, the program is ill-formed.
652  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
653    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
654      << CXXBaseDecl->getDeclName();
655    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
656      << CXXBaseDecl->getDeclName();
657    return 0;
658  }
659
660  if (BaseDecl->isInvalidDecl())
661    Class->setInvalidDecl();
662
663  // Create the base specifier.
664  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
665                                        Class->getTagKind() == TTK_Class,
666                                        Access, TInfo, EllipsisLoc);
667}
668
669/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
670/// one entry in the base class list of a class specifier, for
671/// example:
672///    class foo : public bar, virtual private baz {
673/// 'public bar' and 'virtual private baz' are each base-specifiers.
674BaseResult
675Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
676                         bool Virtual, AccessSpecifier Access,
677                         ParsedType basetype, SourceLocation BaseLoc,
678                         SourceLocation EllipsisLoc) {
679  if (!classdecl)
680    return true;
681
682  AdjustDeclIfTemplate(classdecl);
683  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
684  if (!Class)
685    return true;
686
687  TypeSourceInfo *TInfo = 0;
688  GetTypeFromParser(basetype, &TInfo);
689
690  if (EllipsisLoc.isInvalid() &&
691      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
692                                      UPPC_BaseType))
693    return true;
694
695  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
696                                                      Virtual, Access, TInfo,
697                                                      EllipsisLoc))
698    return BaseSpec;
699
700  return true;
701}
702
703/// \brief Performs the actual work of attaching the given base class
704/// specifiers to a C++ class.
705bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
706                                unsigned NumBases) {
707 if (NumBases == 0)
708    return false;
709
710  // Used to keep track of which base types we have already seen, so
711  // that we can properly diagnose redundant direct base types. Note
712  // that the key is always the unqualified canonical type of the base
713  // class.
714  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
715
716  // Copy non-redundant base specifiers into permanent storage.
717  unsigned NumGoodBases = 0;
718  bool Invalid = false;
719  for (unsigned idx = 0; idx < NumBases; ++idx) {
720    QualType NewBaseType
721      = Context.getCanonicalType(Bases[idx]->getType());
722    NewBaseType = NewBaseType.getLocalUnqualifiedType();
723    if (!Class->hasObjectMember()) {
724      if (const RecordType *FDTTy =
725            NewBaseType.getTypePtr()->getAs<RecordType>())
726        if (FDTTy->getDecl()->hasObjectMember())
727          Class->setHasObjectMember(true);
728    }
729
730    if (KnownBaseTypes[NewBaseType]) {
731      // C++ [class.mi]p3:
732      //   A class shall not be specified as a direct base class of a
733      //   derived class more than once.
734      Diag(Bases[idx]->getSourceRange().getBegin(),
735           diag::err_duplicate_base_class)
736        << KnownBaseTypes[NewBaseType]->getType()
737        << Bases[idx]->getSourceRange();
738
739      // Delete the duplicate base class specifier; we're going to
740      // overwrite its pointer later.
741      Context.Deallocate(Bases[idx]);
742
743      Invalid = true;
744    } else {
745      // Okay, add this new base class.
746      KnownBaseTypes[NewBaseType] = Bases[idx];
747      Bases[NumGoodBases++] = Bases[idx];
748    }
749  }
750
751  // Attach the remaining base class specifiers to the derived class.
752  Class->setBases(Bases, NumGoodBases);
753
754  // Delete the remaining (good) base class specifiers, since their
755  // data has been copied into the CXXRecordDecl.
756  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
757    Context.Deallocate(Bases[idx]);
758
759  return Invalid;
760}
761
762/// ActOnBaseSpecifiers - Attach the given base specifiers to the
763/// class, after checking whether there are any duplicate base
764/// classes.
765void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
766                               unsigned NumBases) {
767  if (!ClassDecl || !Bases || !NumBases)
768    return;
769
770  AdjustDeclIfTemplate(ClassDecl);
771  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
772                       (CXXBaseSpecifier**)(Bases), NumBases);
773}
774
775static CXXRecordDecl *GetClassForType(QualType T) {
776  if (const RecordType *RT = T->getAs<RecordType>())
777    return cast<CXXRecordDecl>(RT->getDecl());
778  else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
779    return ICT->getDecl();
780  else
781    return 0;
782}
783
784/// \brief Determine whether the type \p Derived is a C++ class that is
785/// derived from the type \p Base.
786bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
787  if (!getLangOptions().CPlusPlus)
788    return false;
789
790  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
791  if (!DerivedRD)
792    return false;
793
794  CXXRecordDecl *BaseRD = GetClassForType(Base);
795  if (!BaseRD)
796    return false;
797
798  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
799  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
800}
801
802/// \brief Determine whether the type \p Derived is a C++ class that is
803/// derived from the type \p Base.
804bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
805  if (!getLangOptions().CPlusPlus)
806    return false;
807
808  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
809  if (!DerivedRD)
810    return false;
811
812  CXXRecordDecl *BaseRD = GetClassForType(Base);
813  if (!BaseRD)
814    return false;
815
816  return DerivedRD->isDerivedFrom(BaseRD, Paths);
817}
818
819void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
820                              CXXCastPath &BasePathArray) {
821  assert(BasePathArray.empty() && "Base path array must be empty!");
822  assert(Paths.isRecordingPaths() && "Must record paths!");
823
824  const CXXBasePath &Path = Paths.front();
825
826  // We first go backward and check if we have a virtual base.
827  // FIXME: It would be better if CXXBasePath had the base specifier for
828  // the nearest virtual base.
829  unsigned Start = 0;
830  for (unsigned I = Path.size(); I != 0; --I) {
831    if (Path[I - 1].Base->isVirtual()) {
832      Start = I - 1;
833      break;
834    }
835  }
836
837  // Now add all bases.
838  for (unsigned I = Start, E = Path.size(); I != E; ++I)
839    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
840}
841
842/// \brief Determine whether the given base path includes a virtual
843/// base class.
844bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
845  for (CXXCastPath::const_iterator B = BasePath.begin(),
846                                BEnd = BasePath.end();
847       B != BEnd; ++B)
848    if ((*B)->isVirtual())
849      return true;
850
851  return false;
852}
853
854/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
855/// conversion (where Derived and Base are class types) is
856/// well-formed, meaning that the conversion is unambiguous (and
857/// that all of the base classes are accessible). Returns true
858/// and emits a diagnostic if the code is ill-formed, returns false
859/// otherwise. Loc is the location where this routine should point to
860/// if there is an error, and Range is the source range to highlight
861/// if there is an error.
862bool
863Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
864                                   unsigned InaccessibleBaseID,
865                                   unsigned AmbigiousBaseConvID,
866                                   SourceLocation Loc, SourceRange Range,
867                                   DeclarationName Name,
868                                   CXXCastPath *BasePath) {
869  // First, determine whether the path from Derived to Base is
870  // ambiguous. This is slightly more expensive than checking whether
871  // the Derived to Base conversion exists, because here we need to
872  // explore multiple paths to determine if there is an ambiguity.
873  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
874                     /*DetectVirtual=*/false);
875  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
876  assert(DerivationOkay &&
877         "Can only be used with a derived-to-base conversion");
878  (void)DerivationOkay;
879
880  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
881    if (InaccessibleBaseID) {
882      // Check that the base class can be accessed.
883      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
884                                   InaccessibleBaseID)) {
885        case AR_inaccessible:
886          return true;
887        case AR_accessible:
888        case AR_dependent:
889        case AR_delayed:
890          break;
891      }
892    }
893
894    // Build a base path if necessary.
895    if (BasePath)
896      BuildBasePathArray(Paths, *BasePath);
897    return false;
898  }
899
900  // We know that the derived-to-base conversion is ambiguous, and
901  // we're going to produce a diagnostic. Perform the derived-to-base
902  // search just one more time to compute all of the possible paths so
903  // that we can print them out. This is more expensive than any of
904  // the previous derived-to-base checks we've done, but at this point
905  // performance isn't as much of an issue.
906  Paths.clear();
907  Paths.setRecordingPaths(true);
908  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
909  assert(StillOkay && "Can only be used with a derived-to-base conversion");
910  (void)StillOkay;
911
912  // Build up a textual representation of the ambiguous paths, e.g.,
913  // D -> B -> A, that will be used to illustrate the ambiguous
914  // conversions in the diagnostic. We only print one of the paths
915  // to each base class subobject.
916  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
917
918  Diag(Loc, AmbigiousBaseConvID)
919  << Derived << Base << PathDisplayStr << Range << Name;
920  return true;
921}
922
923bool
924Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
925                                   SourceLocation Loc, SourceRange Range,
926                                   CXXCastPath *BasePath,
927                                   bool IgnoreAccess) {
928  return CheckDerivedToBaseConversion(Derived, Base,
929                                      IgnoreAccess ? 0
930                                       : diag::err_upcast_to_inaccessible_base,
931                                      diag::err_ambiguous_derived_to_base_conv,
932                                      Loc, Range, DeclarationName(),
933                                      BasePath);
934}
935
936
937/// @brief Builds a string representing ambiguous paths from a
938/// specific derived class to different subobjects of the same base
939/// class.
940///
941/// This function builds a string that can be used in error messages
942/// to show the different paths that one can take through the
943/// inheritance hierarchy to go from the derived class to different
944/// subobjects of a base class. The result looks something like this:
945/// @code
946/// struct D -> struct B -> struct A
947/// struct D -> struct C -> struct A
948/// @endcode
949std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
950  std::string PathDisplayStr;
951  std::set<unsigned> DisplayedPaths;
952  for (CXXBasePaths::paths_iterator Path = Paths.begin();
953       Path != Paths.end(); ++Path) {
954    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
955      // We haven't displayed a path to this particular base
956      // class subobject yet.
957      PathDisplayStr += "\n    ";
958      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
959      for (CXXBasePath::const_iterator Element = Path->begin();
960           Element != Path->end(); ++Element)
961        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
962    }
963  }
964
965  return PathDisplayStr;
966}
967
968//===----------------------------------------------------------------------===//
969// C++ class member Handling
970//===----------------------------------------------------------------------===//
971
972/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
973Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
974                                 SourceLocation ASLoc,
975                                 SourceLocation ColonLoc) {
976  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
977  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
978                                                  ASLoc, ColonLoc);
979  CurContext->addHiddenDecl(ASDecl);
980  return ASDecl;
981}
982
983/// CheckOverrideControl - Check C++0x override control semantics.
984void Sema::CheckOverrideControl(const Decl *D) {
985  const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
986  if (!MD || !MD->isVirtual())
987    return;
988
989  if (MD->isDependentContext())
990    return;
991
992  // C++0x [class.virtual]p3:
993  //   If a virtual function is marked with the virt-specifier override and does
994  //   not override a member function of a base class,
995  //   the program is ill-formed.
996  bool HasOverriddenMethods =
997    MD->begin_overridden_methods() != MD->end_overridden_methods();
998  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
999    Diag(MD->getLocation(),
1000                 diag::err_function_marked_override_not_overriding)
1001      << MD->getDeclName();
1002    return;
1003  }
1004}
1005
1006/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1007/// function overrides a virtual member function marked 'final', according to
1008/// C++0x [class.virtual]p3.
1009bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1010                                                  const CXXMethodDecl *Old) {
1011  if (!Old->hasAttr<FinalAttr>())
1012    return false;
1013
1014  Diag(New->getLocation(), diag::err_final_function_overridden)
1015    << New->getDeclName();
1016  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1017  return true;
1018}
1019
1020/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1021/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1022/// bitfield width if there is one and 'InitExpr' specifies the initializer if
1023/// any.
1024Decl *
1025Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1026                               MultiTemplateParamsArg TemplateParameterLists,
1027                               ExprTy *BW, const VirtSpecifiers &VS,
1028                               ExprTy *InitExpr, bool IsDefinition,
1029                               bool Deleted, SourceLocation DefaultLoc) {
1030  const DeclSpec &DS = D.getDeclSpec();
1031  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1032  DeclarationName Name = NameInfo.getName();
1033  SourceLocation Loc = NameInfo.getLoc();
1034
1035  // For anonymous bitfields, the location should point to the type.
1036  if (Loc.isInvalid())
1037    Loc = D.getSourceRange().getBegin();
1038
1039  Expr *BitWidth = static_cast<Expr*>(BW);
1040  Expr *Init = static_cast<Expr*>(InitExpr);
1041
1042  assert(isa<CXXRecordDecl>(CurContext));
1043  assert(!DS.isFriendSpecified());
1044
1045  bool isFunc = false;
1046  if (D.isFunctionDeclarator())
1047    isFunc = true;
1048  else if (D.getNumTypeObjects() == 0 &&
1049           D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
1050    QualType TDType = GetTypeFromParser(DS.getRepAsType());
1051    isFunc = TDType->isFunctionType();
1052  }
1053
1054  // C++ 9.2p6: A member shall not be declared to have automatic storage
1055  // duration (auto, register) or with the extern storage-class-specifier.
1056  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1057  // data members and cannot be applied to names declared const or static,
1058  // and cannot be applied to reference members.
1059  switch (DS.getStorageClassSpec()) {
1060    case DeclSpec::SCS_unspecified:
1061    case DeclSpec::SCS_typedef:
1062    case DeclSpec::SCS_static:
1063      // FALL THROUGH.
1064      break;
1065    case DeclSpec::SCS_mutable:
1066      if (isFunc) {
1067        if (DS.getStorageClassSpecLoc().isValid())
1068          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1069        else
1070          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1071
1072        // FIXME: It would be nicer if the keyword was ignored only for this
1073        // declarator. Otherwise we could get follow-up errors.
1074        D.getMutableDeclSpec().ClearStorageClassSpecs();
1075      }
1076      break;
1077    default:
1078      if (DS.getStorageClassSpecLoc().isValid())
1079        Diag(DS.getStorageClassSpecLoc(),
1080             diag::err_storageclass_invalid_for_member);
1081      else
1082        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1083      D.getMutableDeclSpec().ClearStorageClassSpecs();
1084  }
1085
1086  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1087                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1088                      !isFunc);
1089
1090  Decl *Member;
1091  if (isInstField) {
1092    CXXScopeSpec &SS = D.getCXXScopeSpec();
1093
1094    if (DefaultLoc.isValid())
1095      Diag(DefaultLoc, diag::err_default_special_members);
1096
1097    if (SS.isSet() && !SS.isInvalid()) {
1098      // The user provided a superfluous scope specifier inside a class
1099      // definition:
1100      //
1101      // class X {
1102      //   int X::member;
1103      // };
1104      DeclContext *DC = 0;
1105      if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1106        Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1107        << Name << FixItHint::CreateRemoval(SS.getRange());
1108      else
1109        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1110          << Name << SS.getRange();
1111
1112      SS.clear();
1113    }
1114
1115    // FIXME: Check for template parameters!
1116    // FIXME: Check that the name is an identifier!
1117    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1118                         AS);
1119    assert(Member && "HandleField never returns null");
1120  } else {
1121    Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition,
1122                              DefaultLoc);
1123    if (!Member) {
1124      return 0;
1125    }
1126
1127    // Non-instance-fields can't have a bitfield.
1128    if (BitWidth) {
1129      if (Member->isInvalidDecl()) {
1130        // don't emit another diagnostic.
1131      } else if (isa<VarDecl>(Member)) {
1132        // C++ 9.6p3: A bit-field shall not be a static member.
1133        // "static member 'A' cannot be a bit-field"
1134        Diag(Loc, diag::err_static_not_bitfield)
1135          << Name << BitWidth->getSourceRange();
1136      } else if (isa<TypedefDecl>(Member)) {
1137        // "typedef member 'x' cannot be a bit-field"
1138        Diag(Loc, diag::err_typedef_not_bitfield)
1139          << Name << BitWidth->getSourceRange();
1140      } else {
1141        // A function typedef ("typedef int f(); f a;").
1142        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1143        Diag(Loc, diag::err_not_integral_type_bitfield)
1144          << Name << cast<ValueDecl>(Member)->getType()
1145          << BitWidth->getSourceRange();
1146      }
1147
1148      BitWidth = 0;
1149      Member->setInvalidDecl();
1150    }
1151
1152    Member->setAccess(AS);
1153
1154    // If we have declared a member function template, set the access of the
1155    // templated declaration as well.
1156    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1157      FunTmpl->getTemplatedDecl()->setAccess(AS);
1158  }
1159
1160  if (VS.isOverrideSpecified()) {
1161    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1162    if (!MD || !MD->isVirtual()) {
1163      Diag(Member->getLocStart(),
1164           diag::override_keyword_only_allowed_on_virtual_member_functions)
1165        << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
1166    } else
1167      MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1168  }
1169  if (VS.isFinalSpecified()) {
1170    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1171    if (!MD || !MD->isVirtual()) {
1172      Diag(Member->getLocStart(),
1173           diag::override_keyword_only_allowed_on_virtual_member_functions)
1174      << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
1175    } else
1176      MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1177  }
1178
1179  if (VS.getLastLocation().isValid()) {
1180    // Update the end location of a method that has a virt-specifiers.
1181    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1182      MD->setRangeEnd(VS.getLastLocation());
1183  }
1184
1185  CheckOverrideControl(Member);
1186
1187  assert((Name || isInstField) && "No identifier for non-field ?");
1188
1189  if (Init)
1190    AddInitializerToDecl(Member, Init, false,
1191                         DS.getTypeSpecType() == DeclSpec::TST_auto);
1192  if (Deleted) // FIXME: Source location is not very good.
1193    SetDeclDeleted(Member, D.getSourceRange().getBegin());
1194
1195  FinalizeDeclaration(Member);
1196
1197  if (isInstField)
1198    FieldCollector->Add(cast<FieldDecl>(Member));
1199  return Member;
1200}
1201
1202/// \brief Find the direct and/or virtual base specifiers that
1203/// correspond to the given base type, for use in base initialization
1204/// within a constructor.
1205static bool FindBaseInitializer(Sema &SemaRef,
1206                                CXXRecordDecl *ClassDecl,
1207                                QualType BaseType,
1208                                const CXXBaseSpecifier *&DirectBaseSpec,
1209                                const CXXBaseSpecifier *&VirtualBaseSpec) {
1210  // First, check for a direct base class.
1211  DirectBaseSpec = 0;
1212  for (CXXRecordDecl::base_class_const_iterator Base
1213         = ClassDecl->bases_begin();
1214       Base != ClassDecl->bases_end(); ++Base) {
1215    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1216      // We found a direct base of this type. That's what we're
1217      // initializing.
1218      DirectBaseSpec = &*Base;
1219      break;
1220    }
1221  }
1222
1223  // Check for a virtual base class.
1224  // FIXME: We might be able to short-circuit this if we know in advance that
1225  // there are no virtual bases.
1226  VirtualBaseSpec = 0;
1227  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1228    // We haven't found a base yet; search the class hierarchy for a
1229    // virtual base class.
1230    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1231                       /*DetectVirtual=*/false);
1232    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1233                              BaseType, Paths)) {
1234      for (CXXBasePaths::paths_iterator Path = Paths.begin();
1235           Path != Paths.end(); ++Path) {
1236        if (Path->back().Base->isVirtual()) {
1237          VirtualBaseSpec = Path->back().Base;
1238          break;
1239        }
1240      }
1241    }
1242  }
1243
1244  return DirectBaseSpec || VirtualBaseSpec;
1245}
1246
1247/// ActOnMemInitializer - Handle a C++ member initializer.
1248MemInitResult
1249Sema::ActOnMemInitializer(Decl *ConstructorD,
1250                          Scope *S,
1251                          CXXScopeSpec &SS,
1252                          IdentifierInfo *MemberOrBase,
1253                          ParsedType TemplateTypeTy,
1254                          SourceLocation IdLoc,
1255                          SourceLocation LParenLoc,
1256                          ExprTy **Args, unsigned NumArgs,
1257                          SourceLocation RParenLoc,
1258                          SourceLocation EllipsisLoc) {
1259  if (!ConstructorD)
1260    return true;
1261
1262  AdjustDeclIfTemplate(ConstructorD);
1263
1264  CXXConstructorDecl *Constructor
1265    = dyn_cast<CXXConstructorDecl>(ConstructorD);
1266  if (!Constructor) {
1267    // The user wrote a constructor initializer on a function that is
1268    // not a C++ constructor. Ignore the error for now, because we may
1269    // have more member initializers coming; we'll diagnose it just
1270    // once in ActOnMemInitializers.
1271    return true;
1272  }
1273
1274  CXXRecordDecl *ClassDecl = Constructor->getParent();
1275
1276  // C++ [class.base.init]p2:
1277  //   Names in a mem-initializer-id are looked up in the scope of the
1278  //   constructor's class and, if not found in that scope, are looked
1279  //   up in the scope containing the constructor's definition.
1280  //   [Note: if the constructor's class contains a member with the
1281  //   same name as a direct or virtual base class of the class, a
1282  //   mem-initializer-id naming the member or base class and composed
1283  //   of a single identifier refers to the class member. A
1284  //   mem-initializer-id for the hidden base class may be specified
1285  //   using a qualified name. ]
1286  if (!SS.getScopeRep() && !TemplateTypeTy) {
1287    // Look for a member, first.
1288    FieldDecl *Member = 0;
1289    DeclContext::lookup_result Result
1290      = ClassDecl->lookup(MemberOrBase);
1291    if (Result.first != Result.second) {
1292      Member = dyn_cast<FieldDecl>(*Result.first);
1293
1294      if (Member) {
1295        if (EllipsisLoc.isValid())
1296          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1297            << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1298
1299        return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1300                                    LParenLoc, RParenLoc);
1301      }
1302
1303      // Handle anonymous union case.
1304      if (IndirectFieldDecl* IndirectField
1305            = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1306        if (EllipsisLoc.isValid())
1307          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1308            << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1309
1310         return BuildMemberInitializer(IndirectField, (Expr**)Args,
1311                                       NumArgs, IdLoc,
1312                                       LParenLoc, RParenLoc);
1313      }
1314    }
1315  }
1316  // It didn't name a member, so see if it names a class.
1317  QualType BaseType;
1318  TypeSourceInfo *TInfo = 0;
1319
1320  if (TemplateTypeTy) {
1321    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1322  } else {
1323    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1324    LookupParsedName(R, S, &SS);
1325
1326    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1327    if (!TyD) {
1328      if (R.isAmbiguous()) return true;
1329
1330      // We don't want access-control diagnostics here.
1331      R.suppressDiagnostics();
1332
1333      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1334        bool NotUnknownSpecialization = false;
1335        DeclContext *DC = computeDeclContext(SS, false);
1336        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1337          NotUnknownSpecialization = !Record->hasAnyDependentBases();
1338
1339        if (!NotUnknownSpecialization) {
1340          // When the scope specifier can refer to a member of an unknown
1341          // specialization, we take it as a type name.
1342          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1343                                       SS.getWithLocInContext(Context),
1344                                       *MemberOrBase, IdLoc);
1345          if (BaseType.isNull())
1346            return true;
1347
1348          R.clear();
1349          R.setLookupName(MemberOrBase);
1350        }
1351      }
1352
1353      // If no results were found, try to correct typos.
1354      if (R.empty() && BaseType.isNull() &&
1355          CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1356          R.isSingleResult()) {
1357        if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1358          if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
1359            // We have found a non-static data member with a similar
1360            // name to what was typed; complain and initialize that
1361            // member.
1362            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1363              << MemberOrBase << true << R.getLookupName()
1364              << FixItHint::CreateReplacement(R.getNameLoc(),
1365                                              R.getLookupName().getAsString());
1366            Diag(Member->getLocation(), diag::note_previous_decl)
1367              << Member->getDeclName();
1368
1369            return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1370                                          LParenLoc, RParenLoc);
1371          }
1372        } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1373          const CXXBaseSpecifier *DirectBaseSpec;
1374          const CXXBaseSpecifier *VirtualBaseSpec;
1375          if (FindBaseInitializer(*this, ClassDecl,
1376                                  Context.getTypeDeclType(Type),
1377                                  DirectBaseSpec, VirtualBaseSpec)) {
1378            // We have found a direct or virtual base class with a
1379            // similar name to what was typed; complain and initialize
1380            // that base class.
1381            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1382              << MemberOrBase << false << R.getLookupName()
1383              << FixItHint::CreateReplacement(R.getNameLoc(),
1384                                              R.getLookupName().getAsString());
1385
1386            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1387                                                             : VirtualBaseSpec;
1388            Diag(BaseSpec->getSourceRange().getBegin(),
1389                 diag::note_base_class_specified_here)
1390              << BaseSpec->getType()
1391              << BaseSpec->getSourceRange();
1392
1393            TyD = Type;
1394          }
1395        }
1396      }
1397
1398      if (!TyD && BaseType.isNull()) {
1399        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1400          << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1401        return true;
1402      }
1403    }
1404
1405    if (BaseType.isNull()) {
1406      BaseType = Context.getTypeDeclType(TyD);
1407      if (SS.isSet()) {
1408        NestedNameSpecifier *Qualifier =
1409          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1410
1411        // FIXME: preserve source range information
1412        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
1413      }
1414    }
1415  }
1416
1417  if (!TInfo)
1418    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1419
1420  return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
1421                              LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
1422}
1423
1424/// Checks an initializer expression for use of uninitialized fields, such as
1425/// containing the field that is being initialized. Returns true if there is an
1426/// uninitialized field was used an updates the SourceLocation parameter; false
1427/// otherwise.
1428static bool InitExprContainsUninitializedFields(const Stmt *S,
1429                                                const ValueDecl *LhsField,
1430                                                SourceLocation *L) {
1431  assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1432
1433  if (isa<CallExpr>(S)) {
1434    // Do not descend into function calls or constructors, as the use
1435    // of an uninitialized field may be valid. One would have to inspect
1436    // the contents of the function/ctor to determine if it is safe or not.
1437    // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1438    // may be safe, depending on what the function/ctor does.
1439    return false;
1440  }
1441  if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1442    const NamedDecl *RhsField = ME->getMemberDecl();
1443
1444    if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1445      // The member expression points to a static data member.
1446      assert(VD->isStaticDataMember() &&
1447             "Member points to non-static data member!");
1448      (void)VD;
1449      return false;
1450    }
1451
1452    if (isa<EnumConstantDecl>(RhsField)) {
1453      // The member expression points to an enum.
1454      return false;
1455    }
1456
1457    if (RhsField == LhsField) {
1458      // Initializing a field with itself. Throw a warning.
1459      // But wait; there are exceptions!
1460      // Exception #1:  The field may not belong to this record.
1461      // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1462      const Expr *base = ME->getBase();
1463      if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1464        // Even though the field matches, it does not belong to this record.
1465        return false;
1466      }
1467      // None of the exceptions triggered; return true to indicate an
1468      // uninitialized field was used.
1469      *L = ME->getMemberLoc();
1470      return true;
1471    }
1472  } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
1473    // sizeof/alignof doesn't reference contents, do not warn.
1474    return false;
1475  } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1476    // address-of doesn't reference contents (the pointer may be dereferenced
1477    // in the same expression but it would be rare; and weird).
1478    if (UOE->getOpcode() == UO_AddrOf)
1479      return false;
1480  }
1481  for (Stmt::const_child_range it = S->children(); it; ++it) {
1482    if (!*it) {
1483      // An expression such as 'member(arg ?: "")' may trigger this.
1484      continue;
1485    }
1486    if (InitExprContainsUninitializedFields(*it, LhsField, L))
1487      return true;
1488  }
1489  return false;
1490}
1491
1492MemInitResult
1493Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
1494                             unsigned NumArgs, SourceLocation IdLoc,
1495                             SourceLocation LParenLoc,
1496                             SourceLocation RParenLoc) {
1497  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1498  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1499  assert((DirectMember || IndirectMember) &&
1500         "Member must be a FieldDecl or IndirectFieldDecl");
1501
1502  if (Member->isInvalidDecl())
1503    return true;
1504
1505  // Diagnose value-uses of fields to initialize themselves, e.g.
1506  //   foo(foo)
1507  // where foo is not also a parameter to the constructor.
1508  // TODO: implement -Wuninitialized and fold this into that framework.
1509  for (unsigned i = 0; i < NumArgs; ++i) {
1510    SourceLocation L;
1511    if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1512      // FIXME: Return true in the case when other fields are used before being
1513      // uninitialized. For example, let this field be the i'th field. When
1514      // initializing the i'th field, throw a warning if any of the >= i'th
1515      // fields are used, as they are not yet initialized.
1516      // Right now we are only handling the case where the i'th field uses
1517      // itself in its initializer.
1518      Diag(L, diag::warn_field_is_uninit);
1519    }
1520  }
1521
1522  bool HasDependentArg = false;
1523  for (unsigned i = 0; i < NumArgs; i++)
1524    HasDependentArg |= Args[i]->isTypeDependent();
1525
1526  Expr *Init;
1527  if (Member->getType()->isDependentType() || HasDependentArg) {
1528    // Can't check initialization for a member of dependent type or when
1529    // any of the arguments are type-dependent expressions.
1530    Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1531                                       RParenLoc);
1532
1533    // Erase any temporaries within this evaluation context; we're not
1534    // going to track them in the AST, since we'll be rebuilding the
1535    // ASTs during template instantiation.
1536    ExprTemporaries.erase(
1537              ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1538                          ExprTemporaries.end());
1539  } else {
1540    // Initialize the member.
1541    InitializedEntity MemberEntity =
1542      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1543                   : InitializedEntity::InitializeMember(IndirectMember, 0);
1544    InitializationKind Kind =
1545      InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1546
1547    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1548
1549    ExprResult MemberInit =
1550      InitSeq.Perform(*this, MemberEntity, Kind,
1551                      MultiExprArg(*this, Args, NumArgs), 0);
1552    if (MemberInit.isInvalid())
1553      return true;
1554
1555    CheckImplicitConversions(MemberInit.get(), LParenLoc);
1556
1557    // C++0x [class.base.init]p7:
1558    //   The initialization of each base and member constitutes a
1559    //   full-expression.
1560    MemberInit = MaybeCreateExprWithCleanups(MemberInit);
1561    if (MemberInit.isInvalid())
1562      return true;
1563
1564    // If we are in a dependent context, template instantiation will
1565    // perform this type-checking again. Just save the arguments that we
1566    // received in a ParenListExpr.
1567    // FIXME: This isn't quite ideal, since our ASTs don't capture all
1568    // of the information that we have about the member
1569    // initializer. However, deconstructing the ASTs is a dicey process,
1570    // and this approach is far more likely to get the corner cases right.
1571    if (CurContext->isDependentContext())
1572      Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1573                                               RParenLoc);
1574    else
1575      Init = MemberInit.get();
1576  }
1577
1578  if (DirectMember) {
1579    return new (Context) CXXCtorInitializer(Context, DirectMember,
1580                                                    IdLoc, LParenLoc, Init,
1581                                                    RParenLoc);
1582  } else {
1583    return new (Context) CXXCtorInitializer(Context, IndirectMember,
1584                                                    IdLoc, LParenLoc, Init,
1585                                                    RParenLoc);
1586  }
1587}
1588
1589MemInitResult
1590Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1591                                 Expr **Args, unsigned NumArgs,
1592                                 SourceLocation NameLoc,
1593                                 SourceLocation LParenLoc,
1594                                 SourceLocation RParenLoc,
1595                                 CXXRecordDecl *ClassDecl) {
1596  SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1597  if (!LangOpts.CPlusPlus0x)
1598    return Diag(Loc, diag::err_delegation_0x_only)
1599      << TInfo->getTypeLoc().getLocalSourceRange();
1600
1601  // Initialize the object.
1602  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1603                                     QualType(ClassDecl->getTypeForDecl(), 0));
1604  InitializationKind Kind =
1605    InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1606
1607  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1608
1609  ExprResult DelegationInit =
1610    InitSeq.Perform(*this, DelegationEntity, Kind,
1611                    MultiExprArg(*this, Args, NumArgs), 0);
1612  if (DelegationInit.isInvalid())
1613    return true;
1614
1615  CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
1616  CXXConstructorDecl *Constructor
1617    = ConExpr->getConstructor();
1618  assert(Constructor && "Delegating constructor with no target?");
1619
1620  CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1621
1622  // C++0x [class.base.init]p7:
1623  //   The initialization of each base and member constitutes a
1624  //   full-expression.
1625  DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1626  if (DelegationInit.isInvalid())
1627    return true;
1628
1629  // If we are in a dependent context, template instantiation will
1630  // perform this type-checking again. Just save the arguments that we
1631  // received in a ParenListExpr.
1632  // FIXME: This isn't quite ideal, since our ASTs don't capture all
1633  // of the information that we have about the base
1634  // initializer. However, deconstructing the ASTs is a dicey process,
1635  // and this approach is far more likely to get the corner cases right.
1636  if (CurContext->isDependentContext()) {
1637    ExprResult Init
1638      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1639                                          NumArgs, RParenLoc));
1640    return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1641                                            Constructor, Init.takeAs<Expr>(),
1642                                            RParenLoc);
1643  }
1644
1645  return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1646                                          DelegationInit.takeAs<Expr>(),
1647                                          RParenLoc);
1648}
1649
1650MemInitResult
1651Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
1652                           Expr **Args, unsigned NumArgs,
1653                           SourceLocation LParenLoc, SourceLocation RParenLoc,
1654                           CXXRecordDecl *ClassDecl,
1655                           SourceLocation EllipsisLoc) {
1656  bool HasDependentArg = false;
1657  for (unsigned i = 0; i < NumArgs; i++)
1658    HasDependentArg |= Args[i]->isTypeDependent();
1659
1660  SourceLocation BaseLoc
1661    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1662
1663  if (!BaseType->isDependentType() && !BaseType->isRecordType())
1664    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1665             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1666
1667  // C++ [class.base.init]p2:
1668  //   [...] Unless the mem-initializer-id names a nonstatic data
1669  //   member of the constructor's class or a direct or virtual base
1670  //   of that class, the mem-initializer is ill-formed. A
1671  //   mem-initializer-list can initialize a base class using any
1672  //   name that denotes that base class type.
1673  bool Dependent = BaseType->isDependentType() || HasDependentArg;
1674
1675  if (EllipsisLoc.isValid()) {
1676    // This is a pack expansion.
1677    if (!BaseType->containsUnexpandedParameterPack())  {
1678      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1679        << SourceRange(BaseLoc, RParenLoc);
1680
1681      EllipsisLoc = SourceLocation();
1682    }
1683  } else {
1684    // Check for any unexpanded parameter packs.
1685    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1686      return true;
1687
1688    for (unsigned I = 0; I != NumArgs; ++I)
1689      if (DiagnoseUnexpandedParameterPack(Args[I]))
1690        return true;
1691  }
1692
1693  // Check for direct and virtual base classes.
1694  const CXXBaseSpecifier *DirectBaseSpec = 0;
1695  const CXXBaseSpecifier *VirtualBaseSpec = 0;
1696  if (!Dependent) {
1697    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1698                                       BaseType))
1699      return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1700                                        LParenLoc, RParenLoc, ClassDecl);
1701
1702    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1703                        VirtualBaseSpec);
1704
1705    // C++ [base.class.init]p2:
1706    // Unless the mem-initializer-id names a nonstatic data member of the
1707    // constructor's class or a direct or virtual base of that class, the
1708    // mem-initializer is ill-formed.
1709    if (!DirectBaseSpec && !VirtualBaseSpec) {
1710      // If the class has any dependent bases, then it's possible that
1711      // one of those types will resolve to the same type as
1712      // BaseType. Therefore, just treat this as a dependent base
1713      // class initialization.  FIXME: Should we try to check the
1714      // initialization anyway? It seems odd.
1715      if (ClassDecl->hasAnyDependentBases())
1716        Dependent = true;
1717      else
1718        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1719          << BaseType << Context.getTypeDeclType(ClassDecl)
1720          << BaseTInfo->getTypeLoc().getLocalSourceRange();
1721    }
1722  }
1723
1724  if (Dependent) {
1725    // Can't check initialization for a base of dependent type or when
1726    // any of the arguments are type-dependent expressions.
1727    ExprResult BaseInit
1728      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1729                                          RParenLoc));
1730
1731    // Erase any temporaries within this evaluation context; we're not
1732    // going to track them in the AST, since we'll be rebuilding the
1733    // ASTs during template instantiation.
1734    ExprTemporaries.erase(
1735              ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1736                          ExprTemporaries.end());
1737
1738    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1739                                                    /*IsVirtual=*/false,
1740                                                    LParenLoc,
1741                                                    BaseInit.takeAs<Expr>(),
1742                                                    RParenLoc,
1743                                                    EllipsisLoc);
1744  }
1745
1746  // C++ [base.class.init]p2:
1747  //   If a mem-initializer-id is ambiguous because it designates both
1748  //   a direct non-virtual base class and an inherited virtual base
1749  //   class, the mem-initializer is ill-formed.
1750  if (DirectBaseSpec && VirtualBaseSpec)
1751    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1752      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1753
1754  CXXBaseSpecifier *BaseSpec
1755    = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1756  if (!BaseSpec)
1757    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1758
1759  // Initialize the base.
1760  InitializedEntity BaseEntity =
1761    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
1762  InitializationKind Kind =
1763    InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1764
1765  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1766
1767  ExprResult BaseInit =
1768    InitSeq.Perform(*this, BaseEntity, Kind,
1769                    MultiExprArg(*this, Args, NumArgs), 0);
1770  if (BaseInit.isInvalid())
1771    return true;
1772
1773  CheckImplicitConversions(BaseInit.get(), LParenLoc);
1774
1775  // C++0x [class.base.init]p7:
1776  //   The initialization of each base and member constitutes a
1777  //   full-expression.
1778  BaseInit = MaybeCreateExprWithCleanups(BaseInit);
1779  if (BaseInit.isInvalid())
1780    return true;
1781
1782  // If we are in a dependent context, template instantiation will
1783  // perform this type-checking again. Just save the arguments that we
1784  // received in a ParenListExpr.
1785  // FIXME: This isn't quite ideal, since our ASTs don't capture all
1786  // of the information that we have about the base
1787  // initializer. However, deconstructing the ASTs is a dicey process,
1788  // and this approach is far more likely to get the corner cases right.
1789  if (CurContext->isDependentContext()) {
1790    ExprResult Init
1791      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1792                                          RParenLoc));
1793    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1794                                                    BaseSpec->isVirtual(),
1795                                                    LParenLoc,
1796                                                    Init.takeAs<Expr>(),
1797                                                    RParenLoc,
1798                                                    EllipsisLoc);
1799  }
1800
1801  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1802                                                  BaseSpec->isVirtual(),
1803                                                  LParenLoc,
1804                                                  BaseInit.takeAs<Expr>(),
1805                                                  RParenLoc,
1806                                                  EllipsisLoc);
1807}
1808
1809/// ImplicitInitializerKind - How an implicit base or member initializer should
1810/// initialize its base or member.
1811enum ImplicitInitializerKind {
1812  IIK_Default,
1813  IIK_Copy,
1814  IIK_Move
1815};
1816
1817static bool
1818BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1819                             ImplicitInitializerKind ImplicitInitKind,
1820                             CXXBaseSpecifier *BaseSpec,
1821                             bool IsInheritedVirtualBase,
1822                             CXXCtorInitializer *&CXXBaseInit) {
1823  InitializedEntity InitEntity
1824    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1825                                        IsInheritedVirtualBase);
1826
1827  ExprResult BaseInit;
1828
1829  switch (ImplicitInitKind) {
1830  case IIK_Default: {
1831    InitializationKind InitKind
1832      = InitializationKind::CreateDefault(Constructor->getLocation());
1833    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1834    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1835                               MultiExprArg(SemaRef, 0, 0));
1836    break;
1837  }
1838
1839  case IIK_Copy: {
1840    ParmVarDecl *Param = Constructor->getParamDecl(0);
1841    QualType ParamType = Param->getType().getNonReferenceType();
1842
1843    Expr *CopyCtorArg =
1844      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
1845                          Constructor->getLocation(), ParamType,
1846                          VK_LValue, 0);
1847
1848    // Cast to the base class to avoid ambiguities.
1849    QualType ArgTy =
1850      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1851                                       ParamType.getQualifiers());
1852
1853    CXXCastPath BasePath;
1854    BasePath.push_back(BaseSpec);
1855    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1856                                            CK_UncheckedDerivedToBase,
1857                                            VK_LValue, &BasePath).take();
1858
1859    InitializationKind InitKind
1860      = InitializationKind::CreateDirect(Constructor->getLocation(),
1861                                         SourceLocation(), SourceLocation());
1862    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1863                                   &CopyCtorArg, 1);
1864    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1865                               MultiExprArg(&CopyCtorArg, 1));
1866    break;
1867  }
1868
1869  case IIK_Move:
1870    assert(false && "Unhandled initializer kind!");
1871  }
1872
1873  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
1874  if (BaseInit.isInvalid())
1875    return true;
1876
1877  CXXBaseInit =
1878    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
1879               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1880                                                        SourceLocation()),
1881                                             BaseSpec->isVirtual(),
1882                                             SourceLocation(),
1883                                             BaseInit.takeAs<Expr>(),
1884                                             SourceLocation(),
1885                                             SourceLocation());
1886
1887  return false;
1888}
1889
1890static bool
1891BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1892                               ImplicitInitializerKind ImplicitInitKind,
1893                               FieldDecl *Field,
1894                               CXXCtorInitializer *&CXXMemberInit) {
1895  if (Field->isInvalidDecl())
1896    return true;
1897
1898  SourceLocation Loc = Constructor->getLocation();
1899
1900  if (ImplicitInitKind == IIK_Copy) {
1901    ParmVarDecl *Param = Constructor->getParamDecl(0);
1902    QualType ParamType = Param->getType().getNonReferenceType();
1903
1904    Expr *MemberExprBase =
1905      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
1906                          Loc, ParamType, VK_LValue, 0);
1907
1908    // Build a reference to this field within the parameter.
1909    CXXScopeSpec SS;
1910    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1911                              Sema::LookupMemberName);
1912    MemberLookup.addDecl(Field, AS_public);
1913    MemberLookup.resolveKind();
1914    ExprResult CopyCtorArg
1915      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
1916                                         ParamType, Loc,
1917                                         /*IsArrow=*/false,
1918                                         SS,
1919                                         /*FirstQualifierInScope=*/0,
1920                                         MemberLookup,
1921                                         /*TemplateArgs=*/0);
1922    if (CopyCtorArg.isInvalid())
1923      return true;
1924
1925    // When the field we are copying is an array, create index variables for
1926    // each dimension of the array. We use these index variables to subscript
1927    // the source array, and other clients (e.g., CodeGen) will perform the
1928    // necessary iteration with these index variables.
1929    llvm::SmallVector<VarDecl *, 4> IndexVariables;
1930    QualType BaseType = Field->getType();
1931    QualType SizeType = SemaRef.Context.getSizeType();
1932    while (const ConstantArrayType *Array
1933                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1934      // Create the iteration variable for this array index.
1935      IdentifierInfo *IterationVarName = 0;
1936      {
1937        llvm::SmallString<8> Str;
1938        llvm::raw_svector_ostream OS(Str);
1939        OS << "__i" << IndexVariables.size();
1940        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1941      }
1942      VarDecl *IterationVar
1943        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
1944                          IterationVarName, SizeType,
1945                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
1946                          SC_None, SC_None);
1947      IndexVariables.push_back(IterationVar);
1948
1949      // Create a reference to the iteration variable.
1950      ExprResult IterationVarRef
1951        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
1952      assert(!IterationVarRef.isInvalid() &&
1953             "Reference to invented variable cannot fail!");
1954
1955      // Subscript the array with this iteration variable.
1956      CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
1957                                                            Loc,
1958                                                        IterationVarRef.take(),
1959                                                            Loc);
1960      if (CopyCtorArg.isInvalid())
1961        return true;
1962
1963      BaseType = Array->getElementType();
1964    }
1965
1966    // Construct the entity that we will be initializing. For an array, this
1967    // will be first element in the array, which may require several levels
1968    // of array-subscript entities.
1969    llvm::SmallVector<InitializedEntity, 4> Entities;
1970    Entities.reserve(1 + IndexVariables.size());
1971    Entities.push_back(InitializedEntity::InitializeMember(Field));
1972    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1973      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1974                                                              0,
1975                                                              Entities.back()));
1976
1977    // Direct-initialize to use the copy constructor.
1978    InitializationKind InitKind =
1979      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1980
1981    Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1982    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1983                                   &CopyCtorArgE, 1);
1984
1985    ExprResult MemberInit
1986      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
1987                        MultiExprArg(&CopyCtorArgE, 1));
1988    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
1989    if (MemberInit.isInvalid())
1990      return true;
1991
1992    CXXMemberInit
1993      = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1994                                           MemberInit.takeAs<Expr>(), Loc,
1995                                           IndexVariables.data(),
1996                                           IndexVariables.size());
1997    return false;
1998  }
1999
2000  assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2001
2002  QualType FieldBaseElementType =
2003    SemaRef.Context.getBaseElementType(Field->getType());
2004
2005  if (FieldBaseElementType->isRecordType()) {
2006    InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
2007    InitializationKind InitKind =
2008      InitializationKind::CreateDefault(Loc);
2009
2010    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2011    ExprResult MemberInit =
2012      InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2013
2014    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2015    if (MemberInit.isInvalid())
2016      return true;
2017
2018    CXXMemberInit =
2019      new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2020                                                       Field, Loc, Loc,
2021                                                       MemberInit.get(),
2022                                                       Loc);
2023    return false;
2024  }
2025
2026  if (FieldBaseElementType->isReferenceType()) {
2027    SemaRef.Diag(Constructor->getLocation(),
2028                 diag::err_uninitialized_member_in_ctor)
2029    << (int)Constructor->isImplicit()
2030    << SemaRef.Context.getTagDeclType(Constructor->getParent())
2031    << 0 << Field->getDeclName();
2032    SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2033    return true;
2034  }
2035
2036  if (FieldBaseElementType.isConstQualified()) {
2037    SemaRef.Diag(Constructor->getLocation(),
2038                 diag::err_uninitialized_member_in_ctor)
2039    << (int)Constructor->isImplicit()
2040    << SemaRef.Context.getTagDeclType(Constructor->getParent())
2041    << 1 << Field->getDeclName();
2042    SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2043    return true;
2044  }
2045
2046  // Nothing to initialize.
2047  CXXMemberInit = 0;
2048  return false;
2049}
2050
2051namespace {
2052struct BaseAndFieldInfo {
2053  Sema &S;
2054  CXXConstructorDecl *Ctor;
2055  bool AnyErrorsInInits;
2056  ImplicitInitializerKind IIK;
2057  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2058  llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
2059
2060  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2061    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2062    // FIXME: Handle implicit move constructors.
2063    if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2064      IIK = IIK_Copy;
2065    else
2066      IIK = IIK_Default;
2067  }
2068};
2069}
2070
2071static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
2072                                    FieldDecl *Top, FieldDecl *Field) {
2073
2074  // Overwhelmingly common case: we have a direct initializer for this field.
2075  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
2076    Info.AllToInit.push_back(Init);
2077    return false;
2078  }
2079
2080  if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2081    const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2082    assert(FieldClassType && "anonymous struct/union without record type");
2083    CXXRecordDecl *FieldClassDecl
2084      = cast<CXXRecordDecl>(FieldClassType->getDecl());
2085
2086    // Even though union members never have non-trivial default
2087    // constructions in C++03, we still build member initializers for aggregate
2088    // record types which can be union members, and C++0x allows non-trivial
2089    // default constructors for union members, so we ensure that only one
2090    // member is initialized for these.
2091    if (FieldClassDecl->isUnion()) {
2092      // First check for an explicit initializer for one field.
2093      for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2094           EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2095        if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
2096          Info.AllToInit.push_back(Init);
2097
2098          // Once we've initialized a field of an anonymous union, the union
2099          // field in the class is also initialized, so exit immediately.
2100          return false;
2101        } else if ((*FA)->isAnonymousStructOrUnion()) {
2102          if (CollectFieldInitializer(Info, Top, *FA))
2103            return true;
2104        }
2105      }
2106
2107      // Fallthrough and construct a default initializer for the union as
2108      // a whole, which can call its default constructor if such a thing exists
2109      // (C++0x perhaps). FIXME: It's not clear that this is the correct
2110      // behavior going forward with C++0x, when anonymous unions there are
2111      // finalized, we should revisit this.
2112    } else {
2113      // For structs, we simply descend through to initialize all members where
2114      // necessary.
2115      for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2116           EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2117        if (CollectFieldInitializer(Info, Top, *FA))
2118          return true;
2119      }
2120    }
2121  }
2122
2123  // Don't try to build an implicit initializer if there were semantic
2124  // errors in any of the initializers (and therefore we might be
2125  // missing some that the user actually wrote).
2126  if (Info.AnyErrorsInInits)
2127    return false;
2128
2129  CXXCtorInitializer *Init = 0;
2130  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2131    return true;
2132
2133  if (Init)
2134    Info.AllToInit.push_back(Init);
2135
2136  return false;
2137}
2138
2139bool
2140Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2141                               CXXCtorInitializer *Initializer) {
2142  assert(Initializer->isDelegatingInitializer());
2143  Constructor->setNumCtorInitializers(1);
2144  CXXCtorInitializer **initializer =
2145    new (Context) CXXCtorInitializer*[1];
2146  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2147  Constructor->setCtorInitializers(initializer);
2148
2149  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2150    MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2151    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2152  }
2153
2154  DelegatingCtorDecls.push_back(Constructor);
2155
2156  return false;
2157}
2158
2159bool
2160Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2161                                  CXXCtorInitializer **Initializers,
2162                                  unsigned NumInitializers,
2163                                  bool AnyErrors) {
2164  if (Constructor->getDeclContext()->isDependentContext()) {
2165    // Just store the initializers as written, they will be checked during
2166    // instantiation.
2167    if (NumInitializers > 0) {
2168      Constructor->setNumCtorInitializers(NumInitializers);
2169      CXXCtorInitializer **baseOrMemberInitializers =
2170        new (Context) CXXCtorInitializer*[NumInitializers];
2171      memcpy(baseOrMemberInitializers, Initializers,
2172             NumInitializers * sizeof(CXXCtorInitializer*));
2173      Constructor->setCtorInitializers(baseOrMemberInitializers);
2174    }
2175
2176    return false;
2177  }
2178
2179  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
2180
2181  // We need to build the initializer AST according to order of construction
2182  // and not what user specified in the Initializers list.
2183  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
2184  if (!ClassDecl)
2185    return true;
2186
2187  bool HadError = false;
2188
2189  for (unsigned i = 0; i < NumInitializers; i++) {
2190    CXXCtorInitializer *Member = Initializers[i];
2191
2192    if (Member->isBaseInitializer())
2193      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
2194    else
2195      Info.AllBaseFields[Member->getAnyMember()] = Member;
2196  }
2197
2198  // Keep track of the direct virtual bases.
2199  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2200  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2201       E = ClassDecl->bases_end(); I != E; ++I) {
2202    if (I->isVirtual())
2203      DirectVBases.insert(I);
2204  }
2205
2206  // Push virtual bases before others.
2207  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2208       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2209
2210    if (CXXCtorInitializer *Value
2211        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2212      Info.AllToInit.push_back(Value);
2213    } else if (!AnyErrors) {
2214      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
2215      CXXCtorInitializer *CXXBaseInit;
2216      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2217                                       VBase, IsInheritedVirtualBase,
2218                                       CXXBaseInit)) {
2219        HadError = true;
2220        continue;
2221      }
2222
2223      Info.AllToInit.push_back(CXXBaseInit);
2224    }
2225  }
2226
2227  // Non-virtual bases.
2228  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2229       E = ClassDecl->bases_end(); Base != E; ++Base) {
2230    // Virtuals are in the virtual base list and already constructed.
2231    if (Base->isVirtual())
2232      continue;
2233
2234    if (CXXCtorInitializer *Value
2235          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2236      Info.AllToInit.push_back(Value);
2237    } else if (!AnyErrors) {
2238      CXXCtorInitializer *CXXBaseInit;
2239      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2240                                       Base, /*IsInheritedVirtualBase=*/false,
2241                                       CXXBaseInit)) {
2242        HadError = true;
2243        continue;
2244      }
2245
2246      Info.AllToInit.push_back(CXXBaseInit);
2247    }
2248  }
2249
2250  // Fields.
2251  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2252       E = ClassDecl->field_end(); Field != E; ++Field) {
2253    if ((*Field)->getType()->isIncompleteArrayType()) {
2254      assert(ClassDecl->hasFlexibleArrayMember() &&
2255             "Incomplete array type is not valid");
2256      continue;
2257    }
2258    if (CollectFieldInitializer(Info, *Field, *Field))
2259      HadError = true;
2260  }
2261
2262  NumInitializers = Info.AllToInit.size();
2263  if (NumInitializers > 0) {
2264    Constructor->setNumCtorInitializers(NumInitializers);
2265    CXXCtorInitializer **baseOrMemberInitializers =
2266      new (Context) CXXCtorInitializer*[NumInitializers];
2267    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
2268           NumInitializers * sizeof(CXXCtorInitializer*));
2269    Constructor->setCtorInitializers(baseOrMemberInitializers);
2270
2271    // Constructors implicitly reference the base and member
2272    // destructors.
2273    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2274                                           Constructor->getParent());
2275  }
2276
2277  return HadError;
2278}
2279
2280static void *GetKeyForTopLevelField(FieldDecl *Field) {
2281  // For anonymous unions, use the class declaration as the key.
2282  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
2283    if (RT->getDecl()->isAnonymousStructOrUnion())
2284      return static_cast<void *>(RT->getDecl());
2285  }
2286  return static_cast<void *>(Field);
2287}
2288
2289static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
2290  return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
2291}
2292
2293static void *GetKeyForMember(ASTContext &Context,
2294                             CXXCtorInitializer *Member) {
2295  if (!Member->isAnyMemberInitializer())
2296    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
2297
2298  // For fields injected into the class via declaration of an anonymous union,
2299  // use its anonymous union class declaration as the unique key.
2300  FieldDecl *Field = Member->getAnyMember();
2301
2302  // If the field is a member of an anonymous struct or union, our key
2303  // is the anonymous record decl that's a direct child of the class.
2304  RecordDecl *RD = Field->getParent();
2305  if (RD->isAnonymousStructOrUnion()) {
2306    while (true) {
2307      RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2308      if (Parent->isAnonymousStructOrUnion())
2309        RD = Parent;
2310      else
2311        break;
2312    }
2313
2314    return static_cast<void *>(RD);
2315  }
2316
2317  return static_cast<void *>(Field);
2318}
2319
2320static void
2321DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
2322                                  const CXXConstructorDecl *Constructor,
2323                                  CXXCtorInitializer **Inits,
2324                                  unsigned NumInits) {
2325  if (Constructor->getDeclContext()->isDependentContext())
2326    return;
2327
2328  // Don't check initializers order unless the warning is enabled at the
2329  // location of at least one initializer.
2330  bool ShouldCheckOrder = false;
2331  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2332    CXXCtorInitializer *Init = Inits[InitIndex];
2333    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2334                                         Init->getSourceLocation())
2335          != Diagnostic::Ignored) {
2336      ShouldCheckOrder = true;
2337      break;
2338    }
2339  }
2340  if (!ShouldCheckOrder)
2341    return;
2342
2343  // Build the list of bases and members in the order that they'll
2344  // actually be initialized.  The explicit initializers should be in
2345  // this same order but may be missing things.
2346  llvm::SmallVector<const void*, 32> IdealInitKeys;
2347
2348  const CXXRecordDecl *ClassDecl = Constructor->getParent();
2349
2350  // 1. Virtual bases.
2351  for (CXXRecordDecl::base_class_const_iterator VBase =
2352       ClassDecl->vbases_begin(),
2353       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
2354    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
2355
2356  // 2. Non-virtual bases.
2357  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
2358       E = ClassDecl->bases_end(); Base != E; ++Base) {
2359    if (Base->isVirtual())
2360      continue;
2361    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
2362  }
2363
2364  // 3. Direct fields.
2365  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2366       E = ClassDecl->field_end(); Field != E; ++Field)
2367    IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
2368
2369  unsigned NumIdealInits = IdealInitKeys.size();
2370  unsigned IdealIndex = 0;
2371
2372  CXXCtorInitializer *PrevInit = 0;
2373  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2374    CXXCtorInitializer *Init = Inits[InitIndex];
2375    void *InitKey = GetKeyForMember(SemaRef.Context, Init);
2376
2377    // Scan forward to try to find this initializer in the idealized
2378    // initializers list.
2379    for (; IdealIndex != NumIdealInits; ++IdealIndex)
2380      if (InitKey == IdealInitKeys[IdealIndex])
2381        break;
2382
2383    // If we didn't find this initializer, it must be because we
2384    // scanned past it on a previous iteration.  That can only
2385    // happen if we're out of order;  emit a warning.
2386    if (IdealIndex == NumIdealInits && PrevInit) {
2387      Sema::SemaDiagnosticBuilder D =
2388        SemaRef.Diag(PrevInit->getSourceLocation(),
2389                     diag::warn_initializer_out_of_order);
2390
2391      if (PrevInit->isAnyMemberInitializer())
2392        D << 0 << PrevInit->getAnyMember()->getDeclName();
2393      else
2394        D << 1 << PrevInit->getBaseClassInfo()->getType();
2395
2396      if (Init->isAnyMemberInitializer())
2397        D << 0 << Init->getAnyMember()->getDeclName();
2398      else
2399        D << 1 << Init->getBaseClassInfo()->getType();
2400
2401      // Move back to the initializer's location in the ideal list.
2402      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2403        if (InitKey == IdealInitKeys[IdealIndex])
2404          break;
2405
2406      assert(IdealIndex != NumIdealInits &&
2407             "initializer not found in initializer list");
2408    }
2409
2410    PrevInit = Init;
2411  }
2412}
2413
2414namespace {
2415bool CheckRedundantInit(Sema &S,
2416                        CXXCtorInitializer *Init,
2417                        CXXCtorInitializer *&PrevInit) {
2418  if (!PrevInit) {
2419    PrevInit = Init;
2420    return false;
2421  }
2422
2423  if (FieldDecl *Field = Init->getMember())
2424    S.Diag(Init->getSourceLocation(),
2425           diag::err_multiple_mem_initialization)
2426      << Field->getDeclName()
2427      << Init->getSourceRange();
2428  else {
2429    const Type *BaseClass = Init->getBaseClass();
2430    assert(BaseClass && "neither field nor base");
2431    S.Diag(Init->getSourceLocation(),
2432           diag::err_multiple_base_initialization)
2433      << QualType(BaseClass, 0)
2434      << Init->getSourceRange();
2435  }
2436  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2437    << 0 << PrevInit->getSourceRange();
2438
2439  return true;
2440}
2441
2442typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
2443typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2444
2445bool CheckRedundantUnionInit(Sema &S,
2446                             CXXCtorInitializer *Init,
2447                             RedundantUnionMap &Unions) {
2448  FieldDecl *Field = Init->getAnyMember();
2449  RecordDecl *Parent = Field->getParent();
2450  if (!Parent->isAnonymousStructOrUnion())
2451    return false;
2452
2453  NamedDecl *Child = Field;
2454  do {
2455    if (Parent->isUnion()) {
2456      UnionEntry &En = Unions[Parent];
2457      if (En.first && En.first != Child) {
2458        S.Diag(Init->getSourceLocation(),
2459               diag::err_multiple_mem_union_initialization)
2460          << Field->getDeclName()
2461          << Init->getSourceRange();
2462        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2463          << 0 << En.second->getSourceRange();
2464        return true;
2465      } else if (!En.first) {
2466        En.first = Child;
2467        En.second = Init;
2468      }
2469    }
2470
2471    Child = Parent;
2472    Parent = cast<RecordDecl>(Parent->getDeclContext());
2473  } while (Parent->isAnonymousStructOrUnion());
2474
2475  return false;
2476}
2477}
2478
2479/// ActOnMemInitializers - Handle the member initializers for a constructor.
2480void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
2481                                SourceLocation ColonLoc,
2482                                MemInitTy **meminits, unsigned NumMemInits,
2483                                bool AnyErrors) {
2484  if (!ConstructorDecl)
2485    return;
2486
2487  AdjustDeclIfTemplate(ConstructorDecl);
2488
2489  CXXConstructorDecl *Constructor
2490    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
2491
2492  if (!Constructor) {
2493    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2494    return;
2495  }
2496
2497  CXXCtorInitializer **MemInits =
2498    reinterpret_cast<CXXCtorInitializer **>(meminits);
2499
2500  // Mapping for the duplicate initializers check.
2501  // For member initializers, this is keyed with a FieldDecl*.
2502  // For base initializers, this is keyed with a Type*.
2503  llvm::DenseMap<void*, CXXCtorInitializer *> Members;
2504
2505  // Mapping for the inconsistent anonymous-union initializers check.
2506  RedundantUnionMap MemberUnions;
2507
2508  bool HadError = false;
2509  for (unsigned i = 0; i < NumMemInits; i++) {
2510    CXXCtorInitializer *Init = MemInits[i];
2511
2512    // Set the source order index.
2513    Init->setSourceOrder(i);
2514
2515    if (Init->isAnyMemberInitializer()) {
2516      FieldDecl *Field = Init->getAnyMember();
2517      if (CheckRedundantInit(*this, Init, Members[Field]) ||
2518          CheckRedundantUnionInit(*this, Init, MemberUnions))
2519        HadError = true;
2520    } else if (Init->isBaseInitializer()) {
2521      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2522      if (CheckRedundantInit(*this, Init, Members[Key]))
2523        HadError = true;
2524    } else {
2525      assert(Init->isDelegatingInitializer());
2526      // This must be the only initializer
2527      if (i != 0 || NumMemInits > 1) {
2528        Diag(MemInits[0]->getSourceLocation(),
2529             diag::err_delegating_initializer_alone)
2530          << MemInits[0]->getSourceRange();
2531        HadError = true;
2532        // We will treat this as being the only initializer.
2533      }
2534      SetDelegatingInitializer(Constructor, MemInits[i]);
2535      // Return immediately as the initializer is set.
2536      return;
2537    }
2538  }
2539
2540  if (HadError)
2541    return;
2542
2543  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
2544
2545  SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
2546}
2547
2548void
2549Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2550                                             CXXRecordDecl *ClassDecl) {
2551  // Ignore dependent contexts.
2552  if (ClassDecl->isDependentContext())
2553    return;
2554
2555  // FIXME: all the access-control diagnostics are positioned on the
2556  // field/base declaration.  That's probably good; that said, the
2557  // user might reasonably want to know why the destructor is being
2558  // emitted, and we currently don't say.
2559
2560  // Non-static data members.
2561  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2562       E = ClassDecl->field_end(); I != E; ++I) {
2563    FieldDecl *Field = *I;
2564    if (Field->isInvalidDecl())
2565      continue;
2566    QualType FieldType = Context.getBaseElementType(Field->getType());
2567
2568    const RecordType* RT = FieldType->getAs<RecordType>();
2569    if (!RT)
2570      continue;
2571
2572    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2573    if (FieldClassDecl->isInvalidDecl())
2574      continue;
2575    if (FieldClassDecl->hasTrivialDestructor())
2576      continue;
2577
2578    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
2579    assert(Dtor && "No dtor found for FieldClassDecl!");
2580    CheckDestructorAccess(Field->getLocation(), Dtor,
2581                          PDiag(diag::err_access_dtor_field)
2582                            << Field->getDeclName()
2583                            << FieldType);
2584
2585    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2586  }
2587
2588  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2589
2590  // Bases.
2591  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2592       E = ClassDecl->bases_end(); Base != E; ++Base) {
2593    // Bases are always records in a well-formed non-dependent class.
2594    const RecordType *RT = Base->getType()->getAs<RecordType>();
2595
2596    // Remember direct virtual bases.
2597    if (Base->isVirtual())
2598      DirectVirtualBases.insert(RT);
2599
2600    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2601    // If our base class is invalid, we probably can't get its dtor anyway.
2602    if (BaseClassDecl->isInvalidDecl())
2603      continue;
2604    // Ignore trivial destructors.
2605    if (BaseClassDecl->hasTrivialDestructor())
2606      continue;
2607
2608    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2609    assert(Dtor && "No dtor found for BaseClassDecl!");
2610
2611    // FIXME: caret should be on the start of the class name
2612    CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
2613                          PDiag(diag::err_access_dtor_base)
2614                            << Base->getType()
2615                            << Base->getSourceRange());
2616
2617    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2618  }
2619
2620  // Virtual bases.
2621  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2622       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2623
2624    // Bases are always records in a well-formed non-dependent class.
2625    const RecordType *RT = VBase->getType()->getAs<RecordType>();
2626
2627    // Ignore direct virtual bases.
2628    if (DirectVirtualBases.count(RT))
2629      continue;
2630
2631    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2632    // If our base class is invalid, we probably can't get its dtor anyway.
2633    if (BaseClassDecl->isInvalidDecl())
2634      continue;
2635    // Ignore trivial destructors.
2636    if (BaseClassDecl->hasTrivialDestructor())
2637      continue;
2638
2639    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2640    assert(Dtor && "No dtor found for BaseClassDecl!");
2641    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
2642                          PDiag(diag::err_access_dtor_vbase)
2643                            << VBase->getType());
2644
2645    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2646  }
2647}
2648
2649void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
2650  if (!CDtorDecl)
2651    return;
2652
2653  if (CXXConstructorDecl *Constructor
2654      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
2655    SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
2656}
2657
2658bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2659                                  unsigned DiagID, AbstractDiagSelID SelID) {
2660  if (SelID == -1)
2661    return RequireNonAbstractType(Loc, T, PDiag(DiagID));
2662  else
2663    return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
2664}
2665
2666bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2667                                  const PartialDiagnostic &PD) {
2668  if (!getLangOptions().CPlusPlus)
2669    return false;
2670
2671  if (const ArrayType *AT = Context.getAsArrayType(T))
2672    return RequireNonAbstractType(Loc, AT->getElementType(), PD);
2673
2674  if (const PointerType *PT = T->getAs<PointerType>()) {
2675    // Find the innermost pointer type.
2676    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
2677      PT = T;
2678
2679    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
2680      return RequireNonAbstractType(Loc, AT->getElementType(), PD);
2681  }
2682
2683  const RecordType *RT = T->getAs<RecordType>();
2684  if (!RT)
2685    return false;
2686
2687  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2688
2689  // We can't answer whether something is abstract until it has a
2690  // definition.  If it's currently being defined, we'll walk back
2691  // over all the declarations when we have a full definition.
2692  const CXXRecordDecl *Def = RD->getDefinition();
2693  if (!Def || Def->isBeingDefined())
2694    return false;
2695
2696  if (!RD->isAbstract())
2697    return false;
2698
2699  Diag(Loc, PD) << RD->getDeclName();
2700  DiagnoseAbstractType(RD);
2701
2702  return true;
2703}
2704
2705void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2706  // Check if we've already emitted the list of pure virtual functions
2707  // for this class.
2708  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2709    return;
2710
2711  CXXFinalOverriderMap FinalOverriders;
2712  RD->getFinalOverriders(FinalOverriders);
2713
2714  // Keep a set of seen pure methods so we won't diagnose the same method
2715  // more than once.
2716  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2717
2718  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2719                                   MEnd = FinalOverriders.end();
2720       M != MEnd;
2721       ++M) {
2722    for (OverridingMethods::iterator SO = M->second.begin(),
2723                                  SOEnd = M->second.end();
2724         SO != SOEnd; ++SO) {
2725      // C++ [class.abstract]p4:
2726      //   A class is abstract if it contains or inherits at least one
2727      //   pure virtual function for which the final overrider is pure
2728      //   virtual.
2729
2730      //
2731      if (SO->second.size() != 1)
2732        continue;
2733
2734      if (!SO->second.front().Method->isPure())
2735        continue;
2736
2737      if (!SeenPureMethods.insert(SO->second.front().Method))
2738        continue;
2739
2740      Diag(SO->second.front().Method->getLocation(),
2741           diag::note_pure_virtual_function)
2742        << SO->second.front().Method->getDeclName() << RD->getDeclName();
2743    }
2744  }
2745
2746  if (!PureVirtualClassDiagSet)
2747    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2748  PureVirtualClassDiagSet->insert(RD);
2749}
2750
2751namespace {
2752struct AbstractUsageInfo {
2753  Sema &S;
2754  CXXRecordDecl *Record;
2755  CanQualType AbstractType;
2756  bool Invalid;
2757
2758  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2759    : S(S), Record(Record),
2760      AbstractType(S.Context.getCanonicalType(
2761                   S.Context.getTypeDeclType(Record))),
2762      Invalid(false) {}
2763
2764  void DiagnoseAbstractType() {
2765    if (Invalid) return;
2766    S.DiagnoseAbstractType(Record);
2767    Invalid = true;
2768  }
2769
2770  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2771};
2772
2773struct CheckAbstractUsage {
2774  AbstractUsageInfo &Info;
2775  const NamedDecl *Ctx;
2776
2777  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2778    : Info(Info), Ctx(Ctx) {}
2779
2780  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2781    switch (TL.getTypeLocClass()) {
2782#define ABSTRACT_TYPELOC(CLASS, PARENT)
2783#define TYPELOC(CLASS, PARENT) \
2784    case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2785#include "clang/AST/TypeLocNodes.def"
2786    }
2787  }
2788
2789  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2790    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2791    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2792      if (!TL.getArg(I))
2793        continue;
2794
2795      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2796      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
2797    }
2798  }
2799
2800  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2801    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2802  }
2803
2804  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2805    // Visit the type parameters from a permissive context.
2806    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2807      TemplateArgumentLoc TAL = TL.getArgLoc(I);
2808      if (TAL.getArgument().getKind() == TemplateArgument::Type)
2809        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2810          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2811      // TODO: other template argument types?
2812    }
2813  }
2814
2815  // Visit pointee types from a permissive context.
2816#define CheckPolymorphic(Type) \
2817  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2818    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2819  }
2820  CheckPolymorphic(PointerTypeLoc)
2821  CheckPolymorphic(ReferenceTypeLoc)
2822  CheckPolymorphic(MemberPointerTypeLoc)
2823  CheckPolymorphic(BlockPointerTypeLoc)
2824
2825  /// Handle all the types we haven't given a more specific
2826  /// implementation for above.
2827  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2828    // Every other kind of type that we haven't called out already
2829    // that has an inner type is either (1) sugar or (2) contains that
2830    // inner type in some way as a subobject.
2831    if (TypeLoc Next = TL.getNextTypeLoc())
2832      return Visit(Next, Sel);
2833
2834    // If there's no inner type and we're in a permissive context,
2835    // don't diagnose.
2836    if (Sel == Sema::AbstractNone) return;
2837
2838    // Check whether the type matches the abstract type.
2839    QualType T = TL.getType();
2840    if (T->isArrayType()) {
2841      Sel = Sema::AbstractArrayType;
2842      T = Info.S.Context.getBaseElementType(T);
2843    }
2844    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2845    if (CT != Info.AbstractType) return;
2846
2847    // It matched; do some magic.
2848    if (Sel == Sema::AbstractArrayType) {
2849      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2850        << T << TL.getSourceRange();
2851    } else {
2852      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2853        << Sel << T << TL.getSourceRange();
2854    }
2855    Info.DiagnoseAbstractType();
2856  }
2857};
2858
2859void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2860                                  Sema::AbstractDiagSelID Sel) {
2861  CheckAbstractUsage(*this, D).Visit(TL, Sel);
2862}
2863
2864}
2865
2866/// Check for invalid uses of an abstract type in a method declaration.
2867static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2868                                    CXXMethodDecl *MD) {
2869  // No need to do the check on definitions, which require that
2870  // the return/param types be complete.
2871  if (MD->doesThisDeclarationHaveABody())
2872    return;
2873
2874  // For safety's sake, just ignore it if we don't have type source
2875  // information.  This should never happen for non-implicit methods,
2876  // but...
2877  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2878    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2879}
2880
2881/// Check for invalid uses of an abstract type within a class definition.
2882static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2883                                    CXXRecordDecl *RD) {
2884  for (CXXRecordDecl::decl_iterator
2885         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2886    Decl *D = *I;
2887    if (D->isImplicit()) continue;
2888
2889    // Methods and method templates.
2890    if (isa<CXXMethodDecl>(D)) {
2891      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2892    } else if (isa<FunctionTemplateDecl>(D)) {
2893      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2894      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2895
2896    // Fields and static variables.
2897    } else if (isa<FieldDecl>(D)) {
2898      FieldDecl *FD = cast<FieldDecl>(D);
2899      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2900        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2901    } else if (isa<VarDecl>(D)) {
2902      VarDecl *VD = cast<VarDecl>(D);
2903      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2904        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2905
2906    // Nested classes and class templates.
2907    } else if (isa<CXXRecordDecl>(D)) {
2908      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2909    } else if (isa<ClassTemplateDecl>(D)) {
2910      CheckAbstractClassUsage(Info,
2911                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2912    }
2913  }
2914}
2915
2916/// \brief Perform semantic checks on a class definition that has been
2917/// completing, introducing implicitly-declared members, checking for
2918/// abstract types, etc.
2919void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
2920  if (!Record)
2921    return;
2922
2923  if (Record->isAbstract() && !Record->isInvalidDecl()) {
2924    AbstractUsageInfo Info(*this, Record);
2925    CheckAbstractClassUsage(Info, Record);
2926  }
2927
2928  // If this is not an aggregate type and has no user-declared constructor,
2929  // complain about any non-static data members of reference or const scalar
2930  // type, since they will never get initializers.
2931  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2932      !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2933    bool Complained = false;
2934    for (RecordDecl::field_iterator F = Record->field_begin(),
2935                                 FEnd = Record->field_end();
2936         F != FEnd; ++F) {
2937      if (F->getType()->isReferenceType() ||
2938          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
2939        if (!Complained) {
2940          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2941            << Record->getTagKind() << Record;
2942          Complained = true;
2943        }
2944
2945        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2946          << F->getType()->isReferenceType()
2947          << F->getDeclName();
2948      }
2949    }
2950  }
2951
2952  if (Record->isDynamicClass() && !Record->isDependentType())
2953    DynamicClasses.push_back(Record);
2954
2955  if (Record->getIdentifier()) {
2956    // C++ [class.mem]p13:
2957    //   If T is the name of a class, then each of the following shall have a
2958    //   name different from T:
2959    //     - every member of every anonymous union that is a member of class T.
2960    //
2961    // C++ [class.mem]p14:
2962    //   In addition, if class T has a user-declared constructor (12.1), every
2963    //   non-static data member of class T shall have a name different from T.
2964    for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
2965         R.first != R.second; ++R.first) {
2966      NamedDecl *D = *R.first;
2967      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2968          isa<IndirectFieldDecl>(D)) {
2969        Diag(D->getLocation(), diag::err_member_name_of_class)
2970          << D->getDeclName();
2971        break;
2972      }
2973    }
2974  }
2975
2976  // Warn if the class has virtual methods but non-virtual public destructor.
2977  if (Record->isPolymorphic() && !Record->isDependentType()) {
2978    CXXDestructorDecl *dtor = Record->getDestructor();
2979    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
2980      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2981           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2982  }
2983
2984  // See if a method overloads virtual methods in a base
2985  /// class without overriding any.
2986  if (!Record->isDependentType()) {
2987    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2988                                     MEnd = Record->method_end();
2989         M != MEnd; ++M) {
2990      if (!(*M)->isStatic())
2991        DiagnoseHiddenVirtualMethods(Record, *M);
2992    }
2993  }
2994
2995  // Declare inherited constructors. We do this eagerly here because:
2996  // - The standard requires an eager diagnostic for conflicting inherited
2997  //   constructors from different classes.
2998  // - The lazy declaration of the other implicit constructors is so as to not
2999  //   waste space and performance on classes that are not meant to be
3000  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
3001  //   have inherited constructors.
3002  DeclareInheritedConstructors(Record);
3003
3004  CheckExplicitlyDefaultedMethods(Record);
3005}
3006
3007void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3008  for (CXXRecordDecl::ctor_iterator CI = Record->ctor_begin(),
3009                                    CE = Record->ctor_end();
3010       CI != CE; ++CI) {
3011    if (!CI->isInvalidDecl() && CI->isExplicitlyDefaulted()) {
3012      if (CI->isDefaultConstructor()) {
3013        CheckExplicitlyDefaultedDefaultConstructor(*CI);
3014      }
3015
3016      // FIXME: Do copy and move constructors
3017    }
3018  }
3019
3020  // FIXME: Do copy and move assignment and destructors
3021}
3022
3023void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3024  assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3025
3026  // Whether this was the first-declared instance of the constructor.
3027  // This affects whether we implicitly add an exception spec (and, eventually,
3028  // constexpr). It is also ill-formed to explicitly default a constructor such
3029  // that it would be deleted. (C++0x [decl.fct.def.default])
3030  bool First = CD == CD->getCanonicalDecl();
3031
3032  if (CD->getNumParams() != 0) {
3033    Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3034      << CD->getSourceRange();
3035    CD->setInvalidDecl();
3036    return;
3037  }
3038
3039  ImplicitExceptionSpecification Spec
3040    = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3041  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3042  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3043                          *ExceptionType = Context.getFunctionType(
3044                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3045
3046  if (CtorType->hasExceptionSpec()) {
3047    if (CheckEquivalentExceptionSpec(
3048          PDiag(diag::err_incorrect_defaulted_exception_spec),
3049          PDiag(),
3050          ExceptionType, SourceLocation(),
3051          CtorType, CD->getLocation())) {
3052      CD->setInvalidDecl();
3053      return;
3054    }
3055  } else if (First) {
3056    // We set the declaration to have the computed exception spec here.
3057    // We know there are no parameters.
3058    CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3059  }
3060
3061}
3062
3063/// \brief Data used with FindHiddenVirtualMethod
3064namespace {
3065  struct FindHiddenVirtualMethodData {
3066    Sema *S;
3067    CXXMethodDecl *Method;
3068    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
3069    llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3070  };
3071}
3072
3073/// \brief Member lookup function that determines whether a given C++
3074/// method overloads virtual methods in a base class without overriding any,
3075/// to be used with CXXRecordDecl::lookupInBases().
3076static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
3077                                    CXXBasePath &Path,
3078                                    void *UserData) {
3079  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
3080
3081  FindHiddenVirtualMethodData &Data
3082    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
3083
3084  DeclarationName Name = Data.Method->getDeclName();
3085  assert(Name.getNameKind() == DeclarationName::Identifier);
3086
3087  bool foundSameNameMethod = false;
3088  llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
3089  for (Path.Decls = BaseRecord->lookup(Name);
3090       Path.Decls.first != Path.Decls.second;
3091       ++Path.Decls.first) {
3092    NamedDecl *D = *Path.Decls.first;
3093    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
3094      MD = MD->getCanonicalDecl();
3095      foundSameNameMethod = true;
3096      // Interested only in hidden virtual methods.
3097      if (!MD->isVirtual())
3098        continue;
3099      // If the method we are checking overrides a method from its base
3100      // don't warn about the other overloaded methods.
3101      if (!Data.S->IsOverload(Data.Method, MD, false))
3102        return true;
3103      // Collect the overload only if its hidden.
3104      if (!Data.OverridenAndUsingBaseMethods.count(MD))
3105        overloadedMethods.push_back(MD);
3106    }
3107  }
3108
3109  if (foundSameNameMethod)
3110    Data.OverloadedMethods.append(overloadedMethods.begin(),
3111                                   overloadedMethods.end());
3112  return foundSameNameMethod;
3113}
3114
3115/// \brief See if a method overloads virtual methods in a base class without
3116/// overriding any.
3117void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
3118  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
3119                               MD->getLocation()) == Diagnostic::Ignored)
3120    return;
3121  if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
3122    return;
3123
3124  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
3125                     /*bool RecordPaths=*/false,
3126                     /*bool DetectVirtual=*/false);
3127  FindHiddenVirtualMethodData Data;
3128  Data.Method = MD;
3129  Data.S = this;
3130
3131  // Keep the base methods that were overriden or introduced in the subclass
3132  // by 'using' in a set. A base method not in this set is hidden.
3133  for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
3134       res.first != res.second; ++res.first) {
3135    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
3136      for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
3137                                          E = MD->end_overridden_methods();
3138           I != E; ++I)
3139        Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
3140    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
3141      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
3142        Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
3143  }
3144
3145  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
3146      !Data.OverloadedMethods.empty()) {
3147    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
3148      << MD << (Data.OverloadedMethods.size() > 1);
3149
3150    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
3151      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
3152      Diag(overloadedMD->getLocation(),
3153           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
3154    }
3155  }
3156}
3157
3158void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
3159                                             Decl *TagDecl,
3160                                             SourceLocation LBrac,
3161                                             SourceLocation RBrac,
3162                                             AttributeList *AttrList) {
3163  if (!TagDecl)
3164    return;
3165
3166  AdjustDeclIfTemplate(TagDecl);
3167
3168  ActOnFields(S, RLoc, TagDecl,
3169              // strict aliasing violation!
3170              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
3171              FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
3172
3173  CheckCompletedCXXClass(
3174                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
3175}
3176
3177/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
3178/// special functions, such as the default constructor, copy
3179/// constructor, or destructor, to the given C++ class (C++
3180/// [special]p1).  This routine can only be executed just before the
3181/// definition of the class is complete.
3182void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
3183  if (!ClassDecl->hasUserDeclaredConstructor())
3184    ++ASTContext::NumImplicitDefaultConstructors;
3185
3186  if (!ClassDecl->hasUserDeclaredCopyConstructor())
3187    ++ASTContext::NumImplicitCopyConstructors;
3188
3189  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
3190    ++ASTContext::NumImplicitCopyAssignmentOperators;
3191
3192    // If we have a dynamic class, then the copy assignment operator may be
3193    // virtual, so we have to declare it immediately. This ensures that, e.g.,
3194    // it shows up in the right place in the vtable and that we diagnose
3195    // problems with the implicit exception specification.
3196    if (ClassDecl->isDynamicClass())
3197      DeclareImplicitCopyAssignment(ClassDecl);
3198  }
3199
3200  if (!ClassDecl->hasUserDeclaredDestructor()) {
3201    ++ASTContext::NumImplicitDestructors;
3202
3203    // If we have a dynamic class, then the destructor may be virtual, so we
3204    // have to declare the destructor immediately. This ensures that, e.g., it
3205    // shows up in the right place in the vtable and that we diagnose problems
3206    // with the implicit exception specification.
3207    if (ClassDecl->isDynamicClass())
3208      DeclareImplicitDestructor(ClassDecl);
3209  }
3210}
3211
3212void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
3213  if (!D)
3214    return;
3215
3216  int NumParamList = D->getNumTemplateParameterLists();
3217  for (int i = 0; i < NumParamList; i++) {
3218    TemplateParameterList* Params = D->getTemplateParameterList(i);
3219    for (TemplateParameterList::iterator Param = Params->begin(),
3220                                      ParamEnd = Params->end();
3221          Param != ParamEnd; ++Param) {
3222      NamedDecl *Named = cast<NamedDecl>(*Param);
3223      if (Named->getDeclName()) {
3224        S->AddDecl(Named);
3225        IdResolver.AddDecl(Named);
3226      }
3227    }
3228  }
3229}
3230
3231void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
3232  if (!D)
3233    return;
3234
3235  TemplateParameterList *Params = 0;
3236  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3237    Params = Template->getTemplateParameters();
3238  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3239           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3240    Params = PartialSpec->getTemplateParameters();
3241  else
3242    return;
3243
3244  for (TemplateParameterList::iterator Param = Params->begin(),
3245                                    ParamEnd = Params->end();
3246       Param != ParamEnd; ++Param) {
3247    NamedDecl *Named = cast<NamedDecl>(*Param);
3248    if (Named->getDeclName()) {
3249      S->AddDecl(Named);
3250      IdResolver.AddDecl(Named);
3251    }
3252  }
3253}
3254
3255void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
3256  if (!RecordD) return;
3257  AdjustDeclIfTemplate(RecordD);
3258  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
3259  PushDeclContext(S, Record);
3260}
3261
3262void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
3263  if (!RecordD) return;
3264  PopDeclContext();
3265}
3266
3267/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3268/// parsing a top-level (non-nested) C++ class, and we are now
3269/// parsing those parts of the given Method declaration that could
3270/// not be parsed earlier (C++ [class.mem]p2), such as default
3271/// arguments. This action should enter the scope of the given
3272/// Method declaration as if we had just parsed the qualified method
3273/// name. However, it should not bring the parameters into scope;
3274/// that will be performed by ActOnDelayedCXXMethodParameter.
3275void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
3276}
3277
3278/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3279/// C++ method declaration. We're (re-)introducing the given
3280/// function parameter into scope for use in parsing later parts of
3281/// the method declaration. For example, we could see an
3282/// ActOnParamDefaultArgument event for this parameter.
3283void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
3284  if (!ParamD)
3285    return;
3286
3287  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
3288
3289  // If this parameter has an unparsed default argument, clear it out
3290  // to make way for the parsed default argument.
3291  if (Param->hasUnparsedDefaultArg())
3292    Param->setDefaultArg(0);
3293
3294  S->AddDecl(Param);
3295  if (Param->getDeclName())
3296    IdResolver.AddDecl(Param);
3297}
3298
3299/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3300/// processing the delayed method declaration for Method. The method
3301/// declaration is now considered finished. There may be a separate
3302/// ActOnStartOfFunctionDef action later (not necessarily
3303/// immediately!) for this method, if it was also defined inside the
3304/// class body.
3305void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
3306  if (!MethodD)
3307    return;
3308
3309  AdjustDeclIfTemplate(MethodD);
3310
3311  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
3312
3313  // Now that we have our default arguments, check the constructor
3314  // again. It could produce additional diagnostics or affect whether
3315  // the class has implicitly-declared destructors, among other
3316  // things.
3317  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3318    CheckConstructor(Constructor);
3319
3320  // Check the default arguments, which we may have added.
3321  if (!Method->isInvalidDecl())
3322    CheckCXXDefaultArguments(Method);
3323}
3324
3325/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
3326/// the well-formedness of the constructor declarator @p D with type @p
3327/// R. If there are any errors in the declarator, this routine will
3328/// emit diagnostics and set the invalid bit to true.  In any case, the type
3329/// will be updated to reflect a well-formed type for the constructor and
3330/// returned.
3331QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
3332                                          StorageClass &SC) {
3333  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
3334
3335  // C++ [class.ctor]p3:
3336  //   A constructor shall not be virtual (10.3) or static (9.4). A
3337  //   constructor can be invoked for a const, volatile or const
3338  //   volatile object. A constructor shall not be declared const,
3339  //   volatile, or const volatile (9.3.2).
3340  if (isVirtual) {
3341    if (!D.isInvalidType())
3342      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3343        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3344        << SourceRange(D.getIdentifierLoc());
3345    D.setInvalidType();
3346  }
3347  if (SC == SC_Static) {
3348    if (!D.isInvalidType())
3349      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3350        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3351        << SourceRange(D.getIdentifierLoc());
3352    D.setInvalidType();
3353    SC = SC_None;
3354  }
3355
3356  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
3357  if (FTI.TypeQuals != 0) {
3358    if (FTI.TypeQuals & Qualifiers::Const)
3359      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3360        << "const" << SourceRange(D.getIdentifierLoc());
3361    if (FTI.TypeQuals & Qualifiers::Volatile)
3362      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3363        << "volatile" << SourceRange(D.getIdentifierLoc());
3364    if (FTI.TypeQuals & Qualifiers::Restrict)
3365      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3366        << "restrict" << SourceRange(D.getIdentifierLoc());
3367    D.setInvalidType();
3368  }
3369
3370  // C++0x [class.ctor]p4:
3371  //   A constructor shall not be declared with a ref-qualifier.
3372  if (FTI.hasRefQualifier()) {
3373    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3374      << FTI.RefQualifierIsLValueRef
3375      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3376    D.setInvalidType();
3377  }
3378
3379  // Rebuild the function type "R" without any type qualifiers (in
3380  // case any of the errors above fired) and with "void" as the
3381  // return type, since constructors don't have return types.
3382  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3383  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3384    return R;
3385
3386  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3387  EPI.TypeQuals = 0;
3388  EPI.RefQualifier = RQ_None;
3389
3390  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
3391                                 Proto->getNumArgs(), EPI);
3392}
3393
3394/// CheckConstructor - Checks a fully-formed constructor for
3395/// well-formedness, issuing any diagnostics required. Returns true if
3396/// the constructor declarator is invalid.
3397void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
3398  CXXRecordDecl *ClassDecl
3399    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3400  if (!ClassDecl)
3401    return Constructor->setInvalidDecl();
3402
3403  // C++ [class.copy]p3:
3404  //   A declaration of a constructor for a class X is ill-formed if
3405  //   its first parameter is of type (optionally cv-qualified) X and
3406  //   either there are no other parameters or else all other
3407  //   parameters have default arguments.
3408  if (!Constructor->isInvalidDecl() &&
3409      ((Constructor->getNumParams() == 1) ||
3410       (Constructor->getNumParams() > 1 &&
3411        Constructor->getParamDecl(1)->hasDefaultArg())) &&
3412      Constructor->getTemplateSpecializationKind()
3413                                              != TSK_ImplicitInstantiation) {
3414    QualType ParamType = Constructor->getParamDecl(0)->getType();
3415    QualType ClassTy = Context.getTagDeclType(ClassDecl);
3416    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
3417      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
3418      const char *ConstRef
3419        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3420                                                        : " const &";
3421      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
3422        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
3423
3424      // FIXME: Rather that making the constructor invalid, we should endeavor
3425      // to fix the type.
3426      Constructor->setInvalidDecl();
3427    }
3428  }
3429}
3430
3431/// CheckDestructor - Checks a fully-formed destructor definition for
3432/// well-formedness, issuing any diagnostics required.  Returns true
3433/// on error.
3434bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
3435  CXXRecordDecl *RD = Destructor->getParent();
3436
3437  if (Destructor->isVirtual()) {
3438    SourceLocation Loc;
3439
3440    if (!Destructor->isImplicit())
3441      Loc = Destructor->getLocation();
3442    else
3443      Loc = RD->getLocation();
3444
3445    // If we have a virtual destructor, look up the deallocation function
3446    FunctionDecl *OperatorDelete = 0;
3447    DeclarationName Name =
3448    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
3449    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3450      return true;
3451
3452    MarkDeclarationReferenced(Loc, OperatorDelete);
3453
3454    Destructor->setOperatorDelete(OperatorDelete);
3455  }
3456
3457  return false;
3458}
3459
3460static inline bool
3461FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3462  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3463          FTI.ArgInfo[0].Param &&
3464          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
3465}
3466
3467/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3468/// the well-formednes of the destructor declarator @p D with type @p
3469/// R. If there are any errors in the declarator, this routine will
3470/// emit diagnostics and set the declarator to invalid.  Even if this happens,
3471/// will be updated to reflect a well-formed type for the destructor and
3472/// returned.
3473QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
3474                                         StorageClass& SC) {
3475  // C++ [class.dtor]p1:
3476  //   [...] A typedef-name that names a class is a class-name
3477  //   (7.1.3); however, a typedef-name that names a class shall not
3478  //   be used as the identifier in the declarator for a destructor
3479  //   declaration.
3480  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
3481  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
3482    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
3483      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
3484  else if (const TemplateSpecializationType *TST =
3485             DeclaratorType->getAs<TemplateSpecializationType>())
3486    if (TST->isTypeAlias())
3487      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
3488        << DeclaratorType << 1;
3489
3490  // C++ [class.dtor]p2:
3491  //   A destructor is used to destroy objects of its class type. A
3492  //   destructor takes no parameters, and no return type can be
3493  //   specified for it (not even void). The address of a destructor
3494  //   shall not be taken. A destructor shall not be static. A
3495  //   destructor can be invoked for a const, volatile or const
3496  //   volatile object. A destructor shall not be declared const,
3497  //   volatile or const volatile (9.3.2).
3498  if (SC == SC_Static) {
3499    if (!D.isInvalidType())
3500      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3501        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3502        << SourceRange(D.getIdentifierLoc())
3503        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3504
3505    SC = SC_None;
3506  }
3507  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
3508    // Destructors don't have return types, but the parser will
3509    // happily parse something like:
3510    //
3511    //   class X {
3512    //     float ~X();
3513    //   };
3514    //
3515    // The return type will be eliminated later.
3516    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3517      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3518      << SourceRange(D.getIdentifierLoc());
3519  }
3520
3521  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
3522  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
3523    if (FTI.TypeQuals & Qualifiers::Const)
3524      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3525        << "const" << SourceRange(D.getIdentifierLoc());
3526    if (FTI.TypeQuals & Qualifiers::Volatile)
3527      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3528        << "volatile" << SourceRange(D.getIdentifierLoc());
3529    if (FTI.TypeQuals & Qualifiers::Restrict)
3530      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3531        << "restrict" << SourceRange(D.getIdentifierLoc());
3532    D.setInvalidType();
3533  }
3534
3535  // C++0x [class.dtor]p2:
3536  //   A destructor shall not be declared with a ref-qualifier.
3537  if (FTI.hasRefQualifier()) {
3538    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3539      << FTI.RefQualifierIsLValueRef
3540      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3541    D.setInvalidType();
3542  }
3543
3544  // Make sure we don't have any parameters.
3545  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
3546    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3547
3548    // Delete the parameters.
3549    FTI.freeArgs();
3550    D.setInvalidType();
3551  }
3552
3553  // Make sure the destructor isn't variadic.
3554  if (FTI.isVariadic) {
3555    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
3556    D.setInvalidType();
3557  }
3558
3559  // Rebuild the function type "R" without any type qualifiers or
3560  // parameters (in case any of the errors above fired) and with
3561  // "void" as the return type, since destructors don't have return
3562  // types.
3563  if (!D.isInvalidType())
3564    return R;
3565
3566  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3567  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3568  EPI.Variadic = false;
3569  EPI.TypeQuals = 0;
3570  EPI.RefQualifier = RQ_None;
3571  return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
3572}
3573
3574/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3575/// well-formednes of the conversion function declarator @p D with
3576/// type @p R. If there are any errors in the declarator, this routine
3577/// will emit diagnostics and return true. Otherwise, it will return
3578/// false. Either way, the type @p R will be updated to reflect a
3579/// well-formed type for the conversion operator.
3580void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
3581                                     StorageClass& SC) {
3582  // C++ [class.conv.fct]p1:
3583  //   Neither parameter types nor return type can be specified. The
3584  //   type of a conversion function (8.3.5) is "function taking no
3585  //   parameter returning conversion-type-id."
3586  if (SC == SC_Static) {
3587    if (!D.isInvalidType())
3588      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3589        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3590        << SourceRange(D.getIdentifierLoc());
3591    D.setInvalidType();
3592    SC = SC_None;
3593  }
3594
3595  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3596
3597  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
3598    // Conversion functions don't have return types, but the parser will
3599    // happily parse something like:
3600    //
3601    //   class X {
3602    //     float operator bool();
3603    //   };
3604    //
3605    // The return type will be changed later anyway.
3606    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3607      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3608      << SourceRange(D.getIdentifierLoc());
3609    D.setInvalidType();
3610  }
3611
3612  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3613
3614  // Make sure we don't have any parameters.
3615  if (Proto->getNumArgs() > 0) {
3616    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3617
3618    // Delete the parameters.
3619    D.getFunctionTypeInfo().freeArgs();
3620    D.setInvalidType();
3621  } else if (Proto->isVariadic()) {
3622    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
3623    D.setInvalidType();
3624  }
3625
3626  // Diagnose "&operator bool()" and other such nonsense.  This
3627  // is actually a gcc extension which we don't support.
3628  if (Proto->getResultType() != ConvType) {
3629    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3630      << Proto->getResultType();
3631    D.setInvalidType();
3632    ConvType = Proto->getResultType();
3633  }
3634
3635  // C++ [class.conv.fct]p4:
3636  //   The conversion-type-id shall not represent a function type nor
3637  //   an array type.
3638  if (ConvType->isArrayType()) {
3639    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3640    ConvType = Context.getPointerType(ConvType);
3641    D.setInvalidType();
3642  } else if (ConvType->isFunctionType()) {
3643    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3644    ConvType = Context.getPointerType(ConvType);
3645    D.setInvalidType();
3646  }
3647
3648  // Rebuild the function type "R" without any parameters (in case any
3649  // of the errors above fired) and with the conversion type as the
3650  // return type.
3651  if (D.isInvalidType())
3652    R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
3653
3654  // C++0x explicit conversion operators.
3655  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
3656    Diag(D.getDeclSpec().getExplicitSpecLoc(),
3657         diag::warn_explicit_conversion_functions)
3658      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
3659}
3660
3661/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3662/// the declaration of the given C++ conversion function. This routine
3663/// is responsible for recording the conversion function in the C++
3664/// class, if possible.
3665Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
3666  assert(Conversion && "Expected to receive a conversion function declaration");
3667
3668  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
3669
3670  // Make sure we aren't redeclaring the conversion function.
3671  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
3672
3673  // C++ [class.conv.fct]p1:
3674  //   [...] A conversion function is never used to convert a
3675  //   (possibly cv-qualified) object to the (possibly cv-qualified)
3676  //   same object type (or a reference to it), to a (possibly
3677  //   cv-qualified) base class of that type (or a reference to it),
3678  //   or to (possibly cv-qualified) void.
3679  // FIXME: Suppress this warning if the conversion function ends up being a
3680  // virtual function that overrides a virtual function in a base class.
3681  QualType ClassType
3682    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
3683  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
3684    ConvType = ConvTypeRef->getPointeeType();
3685  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3686      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
3687    /* Suppress diagnostics for instantiations. */;
3688  else if (ConvType->isRecordType()) {
3689    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3690    if (ConvType == ClassType)
3691      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
3692        << ClassType;
3693    else if (IsDerivedFrom(ClassType, ConvType))
3694      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
3695        <<  ClassType << ConvType;
3696  } else if (ConvType->isVoidType()) {
3697    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
3698      << ClassType << ConvType;
3699  }
3700
3701  if (FunctionTemplateDecl *ConversionTemplate
3702                                = Conversion->getDescribedFunctionTemplate())
3703    return ConversionTemplate;
3704
3705  return Conversion;
3706}
3707
3708//===----------------------------------------------------------------------===//
3709// Namespace Handling
3710//===----------------------------------------------------------------------===//
3711
3712
3713
3714/// ActOnStartNamespaceDef - This is called at the start of a namespace
3715/// definition.
3716Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
3717                                   SourceLocation InlineLoc,
3718                                   SourceLocation NamespaceLoc,
3719                                   SourceLocation IdentLoc,
3720                                   IdentifierInfo *II,
3721                                   SourceLocation LBrace,
3722                                   AttributeList *AttrList) {
3723  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
3724  // For anonymous namespace, take the location of the left brace.
3725  SourceLocation Loc = II ? IdentLoc : LBrace;
3726  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3727                                                 StartLoc, Loc, II);
3728  Namespc->setInline(InlineLoc.isValid());
3729
3730  Scope *DeclRegionScope = NamespcScope->getParent();
3731
3732  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3733
3734  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3735    PushNamespaceVisibilityAttr(Attr);
3736
3737  if (II) {
3738    // C++ [namespace.def]p2:
3739    //   The identifier in an original-namespace-definition shall not
3740    //   have been previously defined in the declarative region in
3741    //   which the original-namespace-definition appears. The
3742    //   identifier in an original-namespace-definition is the name of
3743    //   the namespace. Subsequently in that declarative region, it is
3744    //   treated as an original-namespace-name.
3745    //
3746    // Since namespace names are unique in their scope, and we don't
3747    // look through using directives, just look for any ordinary names.
3748
3749    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
3750      Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
3751      Decl::IDNS_Namespace;
3752    NamedDecl *PrevDecl = 0;
3753    for (DeclContext::lookup_result R
3754            = CurContext->getRedeclContext()->lookup(II);
3755         R.first != R.second; ++R.first) {
3756      if ((*R.first)->getIdentifierNamespace() & IDNS) {
3757        PrevDecl = *R.first;
3758        break;
3759      }
3760    }
3761
3762    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3763      // This is an extended namespace definition.
3764      if (Namespc->isInline() != OrigNS->isInline()) {
3765        // inline-ness must match
3766        Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3767          << Namespc->isInline();
3768        Diag(OrigNS->getLocation(), diag::note_previous_definition);
3769        Namespc->setInvalidDecl();
3770        // Recover by ignoring the new namespace's inline status.
3771        Namespc->setInline(OrigNS->isInline());
3772      }
3773
3774      // Attach this namespace decl to the chain of extended namespace
3775      // definitions.
3776      OrigNS->setNextNamespace(Namespc);
3777      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
3778
3779      // Remove the previous declaration from the scope.
3780      if (DeclRegionScope->isDeclScope(OrigNS)) {
3781        IdResolver.RemoveDecl(OrigNS);
3782        DeclRegionScope->RemoveDecl(OrigNS);
3783      }
3784    } else if (PrevDecl) {
3785      // This is an invalid name redefinition.
3786      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3787       << Namespc->getDeclName();
3788      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3789      Namespc->setInvalidDecl();
3790      // Continue on to push Namespc as current DeclContext and return it.
3791    } else if (II->isStr("std") &&
3792               CurContext->getRedeclContext()->isTranslationUnit()) {
3793      // This is the first "real" definition of the namespace "std", so update
3794      // our cache of the "std" namespace to point at this definition.
3795      if (NamespaceDecl *StdNS = getStdNamespace()) {
3796        // We had already defined a dummy namespace "std". Link this new
3797        // namespace definition to the dummy namespace "std".
3798        StdNS->setNextNamespace(Namespc);
3799        StdNS->setLocation(IdentLoc);
3800        Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
3801      }
3802
3803      // Make our StdNamespace cache point at the first real definition of the
3804      // "std" namespace.
3805      StdNamespace = Namespc;
3806    }
3807
3808    PushOnScopeChains(Namespc, DeclRegionScope);
3809  } else {
3810    // Anonymous namespaces.
3811    assert(Namespc->isAnonymousNamespace());
3812
3813    // Link the anonymous namespace into its parent.
3814    NamespaceDecl *PrevDecl;
3815    DeclContext *Parent = CurContext->getRedeclContext();
3816    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3817      PrevDecl = TU->getAnonymousNamespace();
3818      TU->setAnonymousNamespace(Namespc);
3819    } else {
3820      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3821      PrevDecl = ND->getAnonymousNamespace();
3822      ND->setAnonymousNamespace(Namespc);
3823    }
3824
3825    // Link the anonymous namespace with its previous declaration.
3826    if (PrevDecl) {
3827      assert(PrevDecl->isAnonymousNamespace());
3828      assert(!PrevDecl->getNextNamespace());
3829      Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3830      PrevDecl->setNextNamespace(Namespc);
3831
3832      if (Namespc->isInline() != PrevDecl->isInline()) {
3833        // inline-ness must match
3834        Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3835          << Namespc->isInline();
3836        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3837        Namespc->setInvalidDecl();
3838        // Recover by ignoring the new namespace's inline status.
3839        Namespc->setInline(PrevDecl->isInline());
3840      }
3841    }
3842
3843    CurContext->addDecl(Namespc);
3844
3845    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
3846    //   behaves as if it were replaced by
3847    //     namespace unique { /* empty body */ }
3848    //     using namespace unique;
3849    //     namespace unique { namespace-body }
3850    //   where all occurrences of 'unique' in a translation unit are
3851    //   replaced by the same identifier and this identifier differs
3852    //   from all other identifiers in the entire program.
3853
3854    // We just create the namespace with an empty name and then add an
3855    // implicit using declaration, just like the standard suggests.
3856    //
3857    // CodeGen enforces the "universally unique" aspect by giving all
3858    // declarations semantically contained within an anonymous
3859    // namespace internal linkage.
3860
3861    if (!PrevDecl) {
3862      UsingDirectiveDecl* UD
3863        = UsingDirectiveDecl::Create(Context, CurContext,
3864                                     /* 'using' */ LBrace,
3865                                     /* 'namespace' */ SourceLocation(),
3866                                     /* qualifier */ NestedNameSpecifierLoc(),
3867                                     /* identifier */ SourceLocation(),
3868                                     Namespc,
3869                                     /* Ancestor */ CurContext);
3870      UD->setImplicit();
3871      CurContext->addDecl(UD);
3872    }
3873  }
3874
3875  // Although we could have an invalid decl (i.e. the namespace name is a
3876  // redefinition), push it as current DeclContext and try to continue parsing.
3877  // FIXME: We should be able to push Namespc here, so that the each DeclContext
3878  // for the namespace has the declarations that showed up in that particular
3879  // namespace definition.
3880  PushDeclContext(NamespcScope, Namespc);
3881  return Namespc;
3882}
3883
3884/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3885/// is a namespace alias, returns the namespace it points to.
3886static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3887  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3888    return AD->getNamespace();
3889  return dyn_cast_or_null<NamespaceDecl>(D);
3890}
3891
3892/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3893/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
3894void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
3895  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3896  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3897  Namespc->setRBraceLoc(RBrace);
3898  PopDeclContext();
3899  if (Namespc->hasAttr<VisibilityAttr>())
3900    PopPragmaVisibility();
3901}
3902
3903CXXRecordDecl *Sema::getStdBadAlloc() const {
3904  return cast_or_null<CXXRecordDecl>(
3905                                  StdBadAlloc.get(Context.getExternalSource()));
3906}
3907
3908NamespaceDecl *Sema::getStdNamespace() const {
3909  return cast_or_null<NamespaceDecl>(
3910                                 StdNamespace.get(Context.getExternalSource()));
3911}
3912
3913/// \brief Retrieve the special "std" namespace, which may require us to
3914/// implicitly define the namespace.
3915NamespaceDecl *Sema::getOrCreateStdNamespace() {
3916  if (!StdNamespace) {
3917    // The "std" namespace has not yet been defined, so build one implicitly.
3918    StdNamespace = NamespaceDecl::Create(Context,
3919                                         Context.getTranslationUnitDecl(),
3920                                         SourceLocation(), SourceLocation(),
3921                                         &PP.getIdentifierTable().get("std"));
3922    getStdNamespace()->setImplicit(true);
3923  }
3924
3925  return getStdNamespace();
3926}
3927
3928/// \brief Determine whether a using statement is in a context where it will be
3929/// apply in all contexts.
3930static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
3931  switch (CurContext->getDeclKind()) {
3932    case Decl::TranslationUnit:
3933      return true;
3934    case Decl::LinkageSpec:
3935      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
3936    default:
3937      return false;
3938  }
3939}
3940
3941Decl *Sema::ActOnUsingDirective(Scope *S,
3942                                          SourceLocation UsingLoc,
3943                                          SourceLocation NamespcLoc,
3944                                          CXXScopeSpec &SS,
3945                                          SourceLocation IdentLoc,
3946                                          IdentifierInfo *NamespcName,
3947                                          AttributeList *AttrList) {
3948  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3949  assert(NamespcName && "Invalid NamespcName.");
3950  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
3951
3952  // This can only happen along a recovery path.
3953  while (S->getFlags() & Scope::TemplateParamScope)
3954    S = S->getParent();
3955  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
3956
3957  UsingDirectiveDecl *UDir = 0;
3958  NestedNameSpecifier *Qualifier = 0;
3959  if (SS.isSet())
3960    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3961
3962  // Lookup namespace name.
3963  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3964  LookupParsedName(R, S, &SS);
3965  if (R.isAmbiguous())
3966    return 0;
3967
3968  if (R.empty()) {
3969    // Allow "using namespace std;" or "using namespace ::std;" even if
3970    // "std" hasn't been defined yet, for GCC compatibility.
3971    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3972        NamespcName->isStr("std")) {
3973      Diag(IdentLoc, diag::ext_using_undefined_std);
3974      R.addDecl(getOrCreateStdNamespace());
3975      R.resolveKind();
3976    }
3977    // Otherwise, attempt typo correction.
3978    else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3979                                                       CTC_NoKeywords, 0)) {
3980      if (R.getAsSingle<NamespaceDecl>() ||
3981          R.getAsSingle<NamespaceAliasDecl>()) {
3982        if (DeclContext *DC = computeDeclContext(SS, false))
3983          Diag(IdentLoc, diag::err_using_directive_member_suggest)
3984            << NamespcName << DC << Corrected << SS.getRange()
3985            << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3986        else
3987          Diag(IdentLoc, diag::err_using_directive_suggest)
3988            << NamespcName << Corrected
3989            << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3990        Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3991          << Corrected;
3992
3993        NamespcName = Corrected.getAsIdentifierInfo();
3994      } else {
3995        R.clear();
3996        R.setLookupName(NamespcName);
3997      }
3998    }
3999  }
4000
4001  if (!R.empty()) {
4002    NamedDecl *Named = R.getFoundDecl();
4003    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
4004        && "expected namespace decl");
4005    // C++ [namespace.udir]p1:
4006    //   A using-directive specifies that the names in the nominated
4007    //   namespace can be used in the scope in which the
4008    //   using-directive appears after the using-directive. During
4009    //   unqualified name lookup (3.4.1), the names appear as if they
4010    //   were declared in the nearest enclosing namespace which
4011    //   contains both the using-directive and the nominated
4012    //   namespace. [Note: in this context, "contains" means "contains
4013    //   directly or indirectly". ]
4014
4015    // Find enclosing context containing both using-directive and
4016    // nominated namespace.
4017    NamespaceDecl *NS = getNamespaceDecl(Named);
4018    DeclContext *CommonAncestor = cast<DeclContext>(NS);
4019    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
4020      CommonAncestor = CommonAncestor->getParent();
4021
4022    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
4023                                      SS.getWithLocInContext(Context),
4024                                      IdentLoc, Named, CommonAncestor);
4025
4026    if (IsUsingDirectiveInToplevelContext(CurContext) &&
4027        !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
4028      Diag(IdentLoc, diag::warn_using_directive_in_header);
4029    }
4030
4031    PushUsingDirective(S, UDir);
4032  } else {
4033    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
4034  }
4035
4036  // FIXME: We ignore attributes for now.
4037  return UDir;
4038}
4039
4040void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
4041  // If scope has associated entity, then using directive is at namespace
4042  // or translation unit scope. We add UsingDirectiveDecls, into
4043  // it's lookup structure.
4044  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
4045    Ctx->addDecl(UDir);
4046  else
4047    // Otherwise it is block-sope. using-directives will affect lookup
4048    // only to the end of scope.
4049    S->PushUsingDirective(UDir);
4050}
4051
4052
4053Decl *Sema::ActOnUsingDeclaration(Scope *S,
4054                                  AccessSpecifier AS,
4055                                  bool HasUsingKeyword,
4056                                  SourceLocation UsingLoc,
4057                                  CXXScopeSpec &SS,
4058                                  UnqualifiedId &Name,
4059                                  AttributeList *AttrList,
4060                                  bool IsTypeName,
4061                                  SourceLocation TypenameLoc) {
4062  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
4063
4064  switch (Name.getKind()) {
4065  case UnqualifiedId::IK_Identifier:
4066  case UnqualifiedId::IK_OperatorFunctionId:
4067  case UnqualifiedId::IK_LiteralOperatorId:
4068  case UnqualifiedId::IK_ConversionFunctionId:
4069    break;
4070
4071  case UnqualifiedId::IK_ConstructorName:
4072  case UnqualifiedId::IK_ConstructorTemplateId:
4073    // C++0x inherited constructors.
4074    if (getLangOptions().CPlusPlus0x) break;
4075
4076    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
4077      << SS.getRange();
4078    return 0;
4079
4080  case UnqualifiedId::IK_DestructorName:
4081    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
4082      << SS.getRange();
4083    return 0;
4084
4085  case UnqualifiedId::IK_TemplateId:
4086    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
4087      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
4088    return 0;
4089  }
4090
4091  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4092  DeclarationName TargetName = TargetNameInfo.getName();
4093  if (!TargetName)
4094    return 0;
4095
4096  // Warn about using declarations.
4097  // TODO: store that the declaration was written without 'using' and
4098  // talk about access decls instead of using decls in the
4099  // diagnostics.
4100  if (!HasUsingKeyword) {
4101    UsingLoc = Name.getSourceRange().getBegin();
4102
4103    Diag(UsingLoc, diag::warn_access_decl_deprecated)
4104      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
4105  }
4106
4107  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
4108      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
4109    return 0;
4110
4111  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
4112                                        TargetNameInfo, AttrList,
4113                                        /* IsInstantiation */ false,
4114                                        IsTypeName, TypenameLoc);
4115  if (UD)
4116    PushOnScopeChains(UD, S, /*AddToContext*/ false);
4117
4118  return UD;
4119}
4120
4121/// \brief Determine whether a using declaration considers the given
4122/// declarations as "equivalent", e.g., if they are redeclarations of
4123/// the same entity or are both typedefs of the same type.
4124static bool
4125IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
4126                         bool &SuppressRedeclaration) {
4127  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
4128    SuppressRedeclaration = false;
4129    return true;
4130  }
4131
4132  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
4133    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
4134      SuppressRedeclaration = true;
4135      return Context.hasSameType(TD1->getUnderlyingType(),
4136                                 TD2->getUnderlyingType());
4137    }
4138
4139  return false;
4140}
4141
4142
4143/// Determines whether to create a using shadow decl for a particular
4144/// decl, given the set of decls existing prior to this using lookup.
4145bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
4146                                const LookupResult &Previous) {
4147  // Diagnose finding a decl which is not from a base class of the
4148  // current class.  We do this now because there are cases where this
4149  // function will silently decide not to build a shadow decl, which
4150  // will pre-empt further diagnostics.
4151  //
4152  // We don't need to do this in C++0x because we do the check once on
4153  // the qualifier.
4154  //
4155  // FIXME: diagnose the following if we care enough:
4156  //   struct A { int foo; };
4157  //   struct B : A { using A::foo; };
4158  //   template <class T> struct C : A {};
4159  //   template <class T> struct D : C<T> { using B::foo; } // <---
4160  // This is invalid (during instantiation) in C++03 because B::foo
4161  // resolves to the using decl in B, which is not a base class of D<T>.
4162  // We can't diagnose it immediately because C<T> is an unknown
4163  // specialization.  The UsingShadowDecl in D<T> then points directly
4164  // to A::foo, which will look well-formed when we instantiate.
4165  // The right solution is to not collapse the shadow-decl chain.
4166  if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
4167    DeclContext *OrigDC = Orig->getDeclContext();
4168
4169    // Handle enums and anonymous structs.
4170    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
4171    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
4172    while (OrigRec->isAnonymousStructOrUnion())
4173      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
4174
4175    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
4176      if (OrigDC == CurContext) {
4177        Diag(Using->getLocation(),
4178             diag::err_using_decl_nested_name_specifier_is_current_class)
4179          << Using->getQualifierLoc().getSourceRange();
4180        Diag(Orig->getLocation(), diag::note_using_decl_target);
4181        return true;
4182      }
4183
4184      Diag(Using->getQualifierLoc().getBeginLoc(),
4185           diag::err_using_decl_nested_name_specifier_is_not_base_class)
4186        << Using->getQualifier()
4187        << cast<CXXRecordDecl>(CurContext)
4188        << Using->getQualifierLoc().getSourceRange();
4189      Diag(Orig->getLocation(), diag::note_using_decl_target);
4190      return true;
4191    }
4192  }
4193
4194  if (Previous.empty()) return false;
4195
4196  NamedDecl *Target = Orig;
4197  if (isa<UsingShadowDecl>(Target))
4198    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4199
4200  // If the target happens to be one of the previous declarations, we
4201  // don't have a conflict.
4202  //
4203  // FIXME: but we might be increasing its access, in which case we
4204  // should redeclare it.
4205  NamedDecl *NonTag = 0, *Tag = 0;
4206  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4207         I != E; ++I) {
4208    NamedDecl *D = (*I)->getUnderlyingDecl();
4209    bool Result;
4210    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
4211      return Result;
4212
4213    (isa<TagDecl>(D) ? Tag : NonTag) = D;
4214  }
4215
4216  if (Target->isFunctionOrFunctionTemplate()) {
4217    FunctionDecl *FD;
4218    if (isa<FunctionTemplateDecl>(Target))
4219      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
4220    else
4221      FD = cast<FunctionDecl>(Target);
4222
4223    NamedDecl *OldDecl = 0;
4224    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
4225    case Ovl_Overload:
4226      return false;
4227
4228    case Ovl_NonFunction:
4229      Diag(Using->getLocation(), diag::err_using_decl_conflict);
4230      break;
4231
4232    // We found a decl with the exact signature.
4233    case Ovl_Match:
4234      // If we're in a record, we want to hide the target, so we
4235      // return true (without a diagnostic) to tell the caller not to
4236      // build a shadow decl.
4237      if (CurContext->isRecord())
4238        return true;
4239
4240      // If we're not in a record, this is an error.
4241      Diag(Using->getLocation(), diag::err_using_decl_conflict);
4242      break;
4243    }
4244
4245    Diag(Target->getLocation(), diag::note_using_decl_target);
4246    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
4247    return true;
4248  }
4249
4250  // Target is not a function.
4251
4252  if (isa<TagDecl>(Target)) {
4253    // No conflict between a tag and a non-tag.
4254    if (!Tag) return false;
4255
4256    Diag(Using->getLocation(), diag::err_using_decl_conflict);
4257    Diag(Target->getLocation(), diag::note_using_decl_target);
4258    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
4259    return true;
4260  }
4261
4262  // No conflict between a tag and a non-tag.
4263  if (!NonTag) return false;
4264
4265  Diag(Using->getLocation(), diag::err_using_decl_conflict);
4266  Diag(Target->getLocation(), diag::note_using_decl_target);
4267  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4268  return true;
4269}
4270
4271/// Builds a shadow declaration corresponding to a 'using' declaration.
4272UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
4273                                            UsingDecl *UD,
4274                                            NamedDecl *Orig) {
4275
4276  // If we resolved to another shadow declaration, just coalesce them.
4277  NamedDecl *Target = Orig;
4278  if (isa<UsingShadowDecl>(Target)) {
4279    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4280    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
4281  }
4282
4283  UsingShadowDecl *Shadow
4284    = UsingShadowDecl::Create(Context, CurContext,
4285                              UD->getLocation(), UD, Target);
4286  UD->addShadowDecl(Shadow);
4287
4288  Shadow->setAccess(UD->getAccess());
4289  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4290    Shadow->setInvalidDecl();
4291
4292  if (S)
4293    PushOnScopeChains(Shadow, S);
4294  else
4295    CurContext->addDecl(Shadow);
4296
4297
4298  return Shadow;
4299}
4300
4301/// Hides a using shadow declaration.  This is required by the current
4302/// using-decl implementation when a resolvable using declaration in a
4303/// class is followed by a declaration which would hide or override
4304/// one or more of the using decl's targets; for example:
4305///
4306///   struct Base { void foo(int); };
4307///   struct Derived : Base {
4308///     using Base::foo;
4309///     void foo(int);
4310///   };
4311///
4312/// The governing language is C++03 [namespace.udecl]p12:
4313///
4314///   When a using-declaration brings names from a base class into a
4315///   derived class scope, member functions in the derived class
4316///   override and/or hide member functions with the same name and
4317///   parameter types in a base class (rather than conflicting).
4318///
4319/// There are two ways to implement this:
4320///   (1) optimistically create shadow decls when they're not hidden
4321///       by existing declarations, or
4322///   (2) don't create any shadow decls (or at least don't make them
4323///       visible) until we've fully parsed/instantiated the class.
4324/// The problem with (1) is that we might have to retroactively remove
4325/// a shadow decl, which requires several O(n) operations because the
4326/// decl structures are (very reasonably) not designed for removal.
4327/// (2) avoids this but is very fiddly and phase-dependent.
4328void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
4329  if (Shadow->getDeclName().getNameKind() ==
4330        DeclarationName::CXXConversionFunctionName)
4331    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4332
4333  // Remove it from the DeclContext...
4334  Shadow->getDeclContext()->removeDecl(Shadow);
4335
4336  // ...and the scope, if applicable...
4337  if (S) {
4338    S->RemoveDecl(Shadow);
4339    IdResolver.RemoveDecl(Shadow);
4340  }
4341
4342  // ...and the using decl.
4343  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4344
4345  // TODO: complain somehow if Shadow was used.  It shouldn't
4346  // be possible for this to happen, because...?
4347}
4348
4349/// Builds a using declaration.
4350///
4351/// \param IsInstantiation - Whether this call arises from an
4352///   instantiation of an unresolved using declaration.  We treat
4353///   the lookup differently for these declarations.
4354NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4355                                       SourceLocation UsingLoc,
4356                                       CXXScopeSpec &SS,
4357                                       const DeclarationNameInfo &NameInfo,
4358                                       AttributeList *AttrList,
4359                                       bool IsInstantiation,
4360                                       bool IsTypeName,
4361                                       SourceLocation TypenameLoc) {
4362  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4363  SourceLocation IdentLoc = NameInfo.getLoc();
4364  assert(IdentLoc.isValid() && "Invalid TargetName location.");
4365
4366  // FIXME: We ignore attributes for now.
4367
4368  if (SS.isEmpty()) {
4369    Diag(IdentLoc, diag::err_using_requires_qualname);
4370    return 0;
4371  }
4372
4373  // Do the redeclaration lookup in the current scope.
4374  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
4375                        ForRedeclaration);
4376  Previous.setHideTags(false);
4377  if (S) {
4378    LookupName(Previous, S);
4379
4380    // It is really dumb that we have to do this.
4381    LookupResult::Filter F = Previous.makeFilter();
4382    while (F.hasNext()) {
4383      NamedDecl *D = F.next();
4384      if (!isDeclInScope(D, CurContext, S))
4385        F.erase();
4386    }
4387    F.done();
4388  } else {
4389    assert(IsInstantiation && "no scope in non-instantiation");
4390    assert(CurContext->isRecord() && "scope not record in instantiation");
4391    LookupQualifiedName(Previous, CurContext);
4392  }
4393
4394  // Check for invalid redeclarations.
4395  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4396    return 0;
4397
4398  // Check for bad qualifiers.
4399  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4400    return 0;
4401
4402  DeclContext *LookupContext = computeDeclContext(SS);
4403  NamedDecl *D;
4404  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
4405  if (!LookupContext) {
4406    if (IsTypeName) {
4407      // FIXME: not all declaration name kinds are legal here
4408      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4409                                              UsingLoc, TypenameLoc,
4410                                              QualifierLoc,
4411                                              IdentLoc, NameInfo.getName());
4412    } else {
4413      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
4414                                           QualifierLoc, NameInfo);
4415    }
4416  } else {
4417    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
4418                          NameInfo, IsTypeName);
4419  }
4420  D->setAccess(AS);
4421  CurContext->addDecl(D);
4422
4423  if (!LookupContext) return D;
4424  UsingDecl *UD = cast<UsingDecl>(D);
4425
4426  if (RequireCompleteDeclContext(SS, LookupContext)) {
4427    UD->setInvalidDecl();
4428    return UD;
4429  }
4430
4431  // Constructor inheriting using decls get special treatment.
4432  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
4433    if (CheckInheritedConstructorUsingDecl(UD))
4434      UD->setInvalidDecl();
4435    return UD;
4436  }
4437
4438  // Otherwise, look up the target name.
4439
4440  LookupResult R(*this, NameInfo, LookupOrdinaryName);
4441
4442  // Unlike most lookups, we don't always want to hide tag
4443  // declarations: tag names are visible through the using declaration
4444  // even if hidden by ordinary names, *except* in a dependent context
4445  // where it's important for the sanity of two-phase lookup.
4446  if (!IsInstantiation)
4447    R.setHideTags(false);
4448
4449  LookupQualifiedName(R, LookupContext);
4450
4451  if (R.empty()) {
4452    Diag(IdentLoc, diag::err_no_member)
4453      << NameInfo.getName() << LookupContext << SS.getRange();
4454    UD->setInvalidDecl();
4455    return UD;
4456  }
4457
4458  if (R.isAmbiguous()) {
4459    UD->setInvalidDecl();
4460    return UD;
4461  }
4462
4463  if (IsTypeName) {
4464    // If we asked for a typename and got a non-type decl, error out.
4465    if (!R.getAsSingle<TypeDecl>()) {
4466      Diag(IdentLoc, diag::err_using_typename_non_type);
4467      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4468        Diag((*I)->getUnderlyingDecl()->getLocation(),
4469             diag::note_using_decl_target);
4470      UD->setInvalidDecl();
4471      return UD;
4472    }
4473  } else {
4474    // If we asked for a non-typename and we got a type, error out,
4475    // but only if this is an instantiation of an unresolved using
4476    // decl.  Otherwise just silently find the type name.
4477    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
4478      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4479      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
4480      UD->setInvalidDecl();
4481      return UD;
4482    }
4483  }
4484
4485  // C++0x N2914 [namespace.udecl]p6:
4486  // A using-declaration shall not name a namespace.
4487  if (R.getAsSingle<NamespaceDecl>()) {
4488    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4489      << SS.getRange();
4490    UD->setInvalidDecl();
4491    return UD;
4492  }
4493
4494  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4495    if (!CheckUsingShadowDecl(UD, *I, Previous))
4496      BuildUsingShadowDecl(S, UD, *I);
4497  }
4498
4499  return UD;
4500}
4501
4502/// Additional checks for a using declaration referring to a constructor name.
4503bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4504  if (UD->isTypeName()) {
4505    // FIXME: Cannot specify typename when specifying constructor
4506    return true;
4507  }
4508
4509  const Type *SourceType = UD->getQualifier()->getAsType();
4510  assert(SourceType &&
4511         "Using decl naming constructor doesn't have type in scope spec.");
4512  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4513
4514  // Check whether the named type is a direct base class.
4515  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4516  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4517  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4518       BaseIt != BaseE; ++BaseIt) {
4519    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4520    if (CanonicalSourceType == BaseType)
4521      break;
4522  }
4523
4524  if (BaseIt == BaseE) {
4525    // Did not find SourceType in the bases.
4526    Diag(UD->getUsingLocation(),
4527         diag::err_using_decl_constructor_not_in_direct_base)
4528      << UD->getNameInfo().getSourceRange()
4529      << QualType(SourceType, 0) << TargetClass;
4530    return true;
4531  }
4532
4533  BaseIt->setInheritConstructors();
4534
4535  return false;
4536}
4537
4538/// Checks that the given using declaration is not an invalid
4539/// redeclaration.  Note that this is checking only for the using decl
4540/// itself, not for any ill-formedness among the UsingShadowDecls.
4541bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4542                                       bool isTypeName,
4543                                       const CXXScopeSpec &SS,
4544                                       SourceLocation NameLoc,
4545                                       const LookupResult &Prev) {
4546  // C++03 [namespace.udecl]p8:
4547  // C++0x [namespace.udecl]p10:
4548  //   A using-declaration is a declaration and can therefore be used
4549  //   repeatedly where (and only where) multiple declarations are
4550  //   allowed.
4551  //
4552  // That's in non-member contexts.
4553  if (!CurContext->getRedeclContext()->isRecord())
4554    return false;
4555
4556  NestedNameSpecifier *Qual
4557    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4558
4559  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4560    NamedDecl *D = *I;
4561
4562    bool DTypename;
4563    NestedNameSpecifier *DQual;
4564    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4565      DTypename = UD->isTypeName();
4566      DQual = UD->getQualifier();
4567    } else if (UnresolvedUsingValueDecl *UD
4568                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4569      DTypename = false;
4570      DQual = UD->getQualifier();
4571    } else if (UnresolvedUsingTypenameDecl *UD
4572                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4573      DTypename = true;
4574      DQual = UD->getQualifier();
4575    } else continue;
4576
4577    // using decls differ if one says 'typename' and the other doesn't.
4578    // FIXME: non-dependent using decls?
4579    if (isTypeName != DTypename) continue;
4580
4581    // using decls differ if they name different scopes (but note that
4582    // template instantiation can cause this check to trigger when it
4583    // didn't before instantiation).
4584    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4585        Context.getCanonicalNestedNameSpecifier(DQual))
4586      continue;
4587
4588    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
4589    Diag(D->getLocation(), diag::note_using_decl) << 1;
4590    return true;
4591  }
4592
4593  return false;
4594}
4595
4596
4597/// Checks that the given nested-name qualifier used in a using decl
4598/// in the current context is appropriately related to the current
4599/// scope.  If an error is found, diagnoses it and returns true.
4600bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4601                                   const CXXScopeSpec &SS,
4602                                   SourceLocation NameLoc) {
4603  DeclContext *NamedContext = computeDeclContext(SS);
4604
4605  if (!CurContext->isRecord()) {
4606    // C++03 [namespace.udecl]p3:
4607    // C++0x [namespace.udecl]p8:
4608    //   A using-declaration for a class member shall be a member-declaration.
4609
4610    // If we weren't able to compute a valid scope, it must be a
4611    // dependent class scope.
4612    if (!NamedContext || NamedContext->isRecord()) {
4613      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4614        << SS.getRange();
4615      return true;
4616    }
4617
4618    // Otherwise, everything is known to be fine.
4619    return false;
4620  }
4621
4622  // The current scope is a record.
4623
4624  // If the named context is dependent, we can't decide much.
4625  if (!NamedContext) {
4626    // FIXME: in C++0x, we can diagnose if we can prove that the
4627    // nested-name-specifier does not refer to a base class, which is
4628    // still possible in some cases.
4629
4630    // Otherwise we have to conservatively report that things might be
4631    // okay.
4632    return false;
4633  }
4634
4635  if (!NamedContext->isRecord()) {
4636    // Ideally this would point at the last name in the specifier,
4637    // but we don't have that level of source info.
4638    Diag(SS.getRange().getBegin(),
4639         diag::err_using_decl_nested_name_specifier_is_not_class)
4640      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4641    return true;
4642  }
4643
4644  if (!NamedContext->isDependentContext() &&
4645      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4646    return true;
4647
4648  if (getLangOptions().CPlusPlus0x) {
4649    // C++0x [namespace.udecl]p3:
4650    //   In a using-declaration used as a member-declaration, the
4651    //   nested-name-specifier shall name a base class of the class
4652    //   being defined.
4653
4654    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4655                                 cast<CXXRecordDecl>(NamedContext))) {
4656      if (CurContext == NamedContext) {
4657        Diag(NameLoc,
4658             diag::err_using_decl_nested_name_specifier_is_current_class)
4659          << SS.getRange();
4660        return true;
4661      }
4662
4663      Diag(SS.getRange().getBegin(),
4664           diag::err_using_decl_nested_name_specifier_is_not_base_class)
4665        << (NestedNameSpecifier*) SS.getScopeRep()
4666        << cast<CXXRecordDecl>(CurContext)
4667        << SS.getRange();
4668      return true;
4669    }
4670
4671    return false;
4672  }
4673
4674  // C++03 [namespace.udecl]p4:
4675  //   A using-declaration used as a member-declaration shall refer
4676  //   to a member of a base class of the class being defined [etc.].
4677
4678  // Salient point: SS doesn't have to name a base class as long as
4679  // lookup only finds members from base classes.  Therefore we can
4680  // diagnose here only if we can prove that that can't happen,
4681  // i.e. if the class hierarchies provably don't intersect.
4682
4683  // TODO: it would be nice if "definitely valid" results were cached
4684  // in the UsingDecl and UsingShadowDecl so that these checks didn't
4685  // need to be repeated.
4686
4687  struct UserData {
4688    llvm::DenseSet<const CXXRecordDecl*> Bases;
4689
4690    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4691      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4692      Data->Bases.insert(Base);
4693      return true;
4694    }
4695
4696    bool hasDependentBases(const CXXRecordDecl *Class) {
4697      return !Class->forallBases(collect, this);
4698    }
4699
4700    /// Returns true if the base is dependent or is one of the
4701    /// accumulated base classes.
4702    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4703      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4704      return !Data->Bases.count(Base);
4705    }
4706
4707    bool mightShareBases(const CXXRecordDecl *Class) {
4708      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4709    }
4710  };
4711
4712  UserData Data;
4713
4714  // Returns false if we find a dependent base.
4715  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4716    return false;
4717
4718  // Returns false if the class has a dependent base or if it or one
4719  // of its bases is present in the base set of the current context.
4720  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4721    return false;
4722
4723  Diag(SS.getRange().getBegin(),
4724       diag::err_using_decl_nested_name_specifier_is_not_base_class)
4725    << (NestedNameSpecifier*) SS.getScopeRep()
4726    << cast<CXXRecordDecl>(CurContext)
4727    << SS.getRange();
4728
4729  return true;
4730}
4731
4732Decl *Sema::ActOnAliasDeclaration(Scope *S,
4733                                  AccessSpecifier AS,
4734                                  MultiTemplateParamsArg TemplateParamLists,
4735                                  SourceLocation UsingLoc,
4736                                  UnqualifiedId &Name,
4737                                  TypeResult Type) {
4738  // Skip up to the relevant declaration scope.
4739  while (S->getFlags() & Scope::TemplateParamScope)
4740    S = S->getParent();
4741  assert((S->getFlags() & Scope::DeclScope) &&
4742         "got alias-declaration outside of declaration scope");
4743
4744  if (Type.isInvalid())
4745    return 0;
4746
4747  bool Invalid = false;
4748  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
4749  TypeSourceInfo *TInfo = 0;
4750  GetTypeFromParser(Type.get(), &TInfo);
4751
4752  if (DiagnoseClassNameShadow(CurContext, NameInfo))
4753    return 0;
4754
4755  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
4756                                      UPPC_DeclarationType)) {
4757    Invalid = true;
4758    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
4759                                             TInfo->getTypeLoc().getBeginLoc());
4760  }
4761
4762  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
4763  LookupName(Previous, S);
4764
4765  // Warn about shadowing the name of a template parameter.
4766  if (Previous.isSingleResult() &&
4767      Previous.getFoundDecl()->isTemplateParameter()) {
4768    if (DiagnoseTemplateParameterShadow(Name.StartLocation,
4769                                        Previous.getFoundDecl()))
4770      Invalid = true;
4771    Previous.clear();
4772  }
4773
4774  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
4775         "name in alias declaration must be an identifier");
4776  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
4777                                               Name.StartLocation,
4778                                               Name.Identifier, TInfo);
4779
4780  NewTD->setAccess(AS);
4781
4782  if (Invalid)
4783    NewTD->setInvalidDecl();
4784
4785  CheckTypedefForVariablyModifiedType(S, NewTD);
4786  Invalid |= NewTD->isInvalidDecl();
4787
4788  bool Redeclaration = false;
4789
4790  NamedDecl *NewND;
4791  if (TemplateParamLists.size()) {
4792    TypeAliasTemplateDecl *OldDecl = 0;
4793    TemplateParameterList *OldTemplateParams = 0;
4794
4795    if (TemplateParamLists.size() != 1) {
4796      Diag(UsingLoc, diag::err_alias_template_extra_headers)
4797        << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
4798         TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
4799    }
4800    TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
4801
4802    // Only consider previous declarations in the same scope.
4803    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
4804                         /*ExplicitInstantiationOrSpecialization*/false);
4805    if (!Previous.empty()) {
4806      Redeclaration = true;
4807
4808      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
4809      if (!OldDecl && !Invalid) {
4810        Diag(UsingLoc, diag::err_redefinition_different_kind)
4811          << Name.Identifier;
4812
4813        NamedDecl *OldD = Previous.getRepresentativeDecl();
4814        if (OldD->getLocation().isValid())
4815          Diag(OldD->getLocation(), diag::note_previous_definition);
4816
4817        Invalid = true;
4818      }
4819
4820      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
4821        if (TemplateParameterListsAreEqual(TemplateParams,
4822                                           OldDecl->getTemplateParameters(),
4823                                           /*Complain=*/true,
4824                                           TPL_TemplateMatch))
4825          OldTemplateParams = OldDecl->getTemplateParameters();
4826        else
4827          Invalid = true;
4828
4829        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
4830        if (!Invalid &&
4831            !Context.hasSameType(OldTD->getUnderlyingType(),
4832                                 NewTD->getUnderlyingType())) {
4833          // FIXME: The C++0x standard does not clearly say this is ill-formed,
4834          // but we can't reasonably accept it.
4835          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
4836            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
4837          if (OldTD->getLocation().isValid())
4838            Diag(OldTD->getLocation(), diag::note_previous_definition);
4839          Invalid = true;
4840        }
4841      }
4842    }
4843
4844    // Merge any previous default template arguments into our parameters,
4845    // and check the parameter list.
4846    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
4847                                   TPC_TypeAliasTemplate))
4848      return 0;
4849
4850    TypeAliasTemplateDecl *NewDecl =
4851      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
4852                                    Name.Identifier, TemplateParams,
4853                                    NewTD);
4854
4855    NewDecl->setAccess(AS);
4856
4857    if (Invalid)
4858      NewDecl->setInvalidDecl();
4859    else if (OldDecl)
4860      NewDecl->setPreviousDeclaration(OldDecl);
4861
4862    NewND = NewDecl;
4863  } else {
4864    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
4865    NewND = NewTD;
4866  }
4867
4868  if (!Redeclaration)
4869    PushOnScopeChains(NewND, S);
4870
4871  return NewND;
4872}
4873
4874Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
4875                                             SourceLocation NamespaceLoc,
4876                                             SourceLocation AliasLoc,
4877                                             IdentifierInfo *Alias,
4878                                             CXXScopeSpec &SS,
4879                                             SourceLocation IdentLoc,
4880                                             IdentifierInfo *Ident) {
4881
4882  // Lookup the namespace name.
4883  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4884  LookupParsedName(R, S, &SS);
4885
4886  // Check if we have a previous declaration with the same name.
4887  NamedDecl *PrevDecl
4888    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4889                       ForRedeclaration);
4890  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4891    PrevDecl = 0;
4892
4893  if (PrevDecl) {
4894    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
4895      // We already have an alias with the same name that points to the same
4896      // namespace, so don't create a new one.
4897      // FIXME: At some point, we'll want to create the (redundant)
4898      // declaration to maintain better source information.
4899      if (!R.isAmbiguous() && !R.empty() &&
4900          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
4901        return 0;
4902    }
4903
4904    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4905      diag::err_redefinition_different_kind;
4906    Diag(AliasLoc, DiagID) << Alias;
4907    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4908    return 0;
4909  }
4910
4911  if (R.isAmbiguous())
4912    return 0;
4913
4914  if (R.empty()) {
4915    if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4916                                                CTC_NoKeywords, 0)) {
4917      if (R.getAsSingle<NamespaceDecl>() ||
4918          R.getAsSingle<NamespaceAliasDecl>()) {
4919        if (DeclContext *DC = computeDeclContext(SS, false))
4920          Diag(IdentLoc, diag::err_using_directive_member_suggest)
4921            << Ident << DC << Corrected << SS.getRange()
4922            << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4923        else
4924          Diag(IdentLoc, diag::err_using_directive_suggest)
4925            << Ident << Corrected
4926            << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4927
4928        Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4929          << Corrected;
4930
4931        Ident = Corrected.getAsIdentifierInfo();
4932      } else {
4933        R.clear();
4934        R.setLookupName(Ident);
4935      }
4936    }
4937
4938    if (R.empty()) {
4939      Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
4940      return 0;
4941    }
4942  }
4943
4944  NamespaceAliasDecl *AliasDecl =
4945    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4946                               Alias, SS.getWithLocInContext(Context),
4947                               IdentLoc, R.getFoundDecl());
4948
4949  PushOnScopeChains(AliasDecl, S);
4950  return AliasDecl;
4951}
4952
4953namespace {
4954  /// \brief Scoped object used to handle the state changes required in Sema
4955  /// to implicitly define the body of a C++ member function;
4956  class ImplicitlyDefinedFunctionScope {
4957    Sema &S;
4958    Sema::ContextRAII SavedContext;
4959
4960  public:
4961    ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4962      : S(S), SavedContext(S, Method)
4963    {
4964      S.PushFunctionScope();
4965      S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4966    }
4967
4968    ~ImplicitlyDefinedFunctionScope() {
4969      S.PopExpressionEvaluationContext();
4970      S.PopFunctionOrBlockScope();
4971    }
4972  };
4973}
4974
4975static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4976                                                       CXXRecordDecl *D) {
4977  ASTContext &Context = Self.Context;
4978  QualType ClassType = Context.getTypeDeclType(D);
4979  DeclarationName ConstructorName
4980    = Context.DeclarationNames.getCXXConstructorName(
4981                      Context.getCanonicalType(ClassType.getUnqualifiedType()));
4982
4983  DeclContext::lookup_const_iterator Con, ConEnd;
4984  for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4985       Con != ConEnd; ++Con) {
4986    // FIXME: In C++0x, a constructor template can be a default constructor.
4987    if (isa<FunctionTemplateDecl>(*Con))
4988      continue;
4989
4990    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4991    if (Constructor->isDefaultConstructor())
4992      return Constructor;
4993  }
4994  return 0;
4995}
4996
4997Sema::ImplicitExceptionSpecification
4998Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
4999  // C++ [except.spec]p14:
5000  //   An implicitly declared special member function (Clause 12) shall have an
5001  //   exception-specification. [...]
5002  ImplicitExceptionSpecification ExceptSpec(Context);
5003
5004  // Direct base-class constructors.
5005  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5006                                       BEnd = ClassDecl->bases_end();
5007       B != BEnd; ++B) {
5008    if (B->isVirtual()) // Handled below.
5009      continue;
5010
5011    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5012      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5013      if (!BaseClassDecl->needsImplicitDefaultConstructor())
5014        ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
5015      else if (CXXConstructorDecl *Constructor
5016                            = getDefaultConstructorUnsafe(*this, BaseClassDecl))
5017        ExceptSpec.CalledDecl(Constructor);
5018    }
5019  }
5020
5021  // Virtual base-class constructors.
5022  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5023                                       BEnd = ClassDecl->vbases_end();
5024       B != BEnd; ++B) {
5025    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5026      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5027      if (!BaseClassDecl->needsImplicitDefaultConstructor())
5028        ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
5029      else if (CXXConstructorDecl *Constructor
5030                            = getDefaultConstructorUnsafe(*this, BaseClassDecl))
5031        ExceptSpec.CalledDecl(Constructor);
5032    }
5033  }
5034
5035  // Field constructors.
5036  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5037                               FEnd = ClassDecl->field_end();
5038       F != FEnd; ++F) {
5039    if (const RecordType *RecordTy
5040              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
5041      CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5042      if (!FieldClassDecl->needsImplicitDefaultConstructor())
5043        ExceptSpec.CalledDecl(
5044                            DeclareImplicitDefaultConstructor(FieldClassDecl));
5045      else if (CXXConstructorDecl *Constructor
5046                           = getDefaultConstructorUnsafe(*this, FieldClassDecl))
5047        ExceptSpec.CalledDecl(Constructor);
5048    }
5049  }
5050
5051  return ExceptSpec;
5052}
5053
5054CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
5055                                                     CXXRecordDecl *ClassDecl) {
5056  // C++ [class.ctor]p5:
5057  //   A default constructor for a class X is a constructor of class X
5058  //   that can be called without an argument. If there is no
5059  //   user-declared constructor for class X, a default constructor is
5060  //   implicitly declared. An implicitly-declared default constructor
5061  //   is an inline public member of its class.
5062  assert(!ClassDecl->hasUserDeclaredConstructor() &&
5063         "Should not build implicit default constructor!");
5064
5065  ImplicitExceptionSpecification Spec =
5066    ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
5067  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
5068
5069  // Create the actual constructor declaration.
5070  CanQualType ClassType
5071    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5072  SourceLocation ClassLoc = ClassDecl->getLocation();
5073  DeclarationName Name
5074    = Context.DeclarationNames.getCXXConstructorName(ClassType);
5075  DeclarationNameInfo NameInfo(Name, ClassLoc);
5076  CXXConstructorDecl *DefaultCon
5077    = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
5078                                 Context.getFunctionType(Context.VoidTy,
5079                                                         0, 0, EPI),
5080                                 /*TInfo=*/0,
5081                                 /*isExplicit=*/false,
5082                                 /*isInline=*/true,
5083                                 /*isImplicitlyDeclared=*/true);
5084  DefaultCon->setAccess(AS_public);
5085  DefaultCon->setImplicit();
5086  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
5087
5088  // Note that we have declared this constructor.
5089  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
5090
5091  if (Scope *S = getScopeForContext(ClassDecl))
5092    PushOnScopeChains(DefaultCon, S, false);
5093  ClassDecl->addDecl(DefaultCon);
5094
5095  return DefaultCon;
5096}
5097
5098void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5099                                            CXXConstructorDecl *Constructor) {
5100  assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
5101          !Constructor->isUsed(false)) &&
5102    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
5103
5104  CXXRecordDecl *ClassDecl = Constructor->getParent();
5105  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
5106
5107  ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
5108  DiagnosticErrorTrap Trap(Diags);
5109  if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
5110      Trap.hasErrorOccurred()) {
5111    Diag(CurrentLocation, diag::note_member_synthesized_at)
5112      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
5113    Constructor->setInvalidDecl();
5114    return;
5115  }
5116
5117  SourceLocation Loc = Constructor->getLocation();
5118  Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5119
5120  Constructor->setUsed();
5121  MarkVTableUsed(CurrentLocation, ClassDecl);
5122
5123  if (ASTMutationListener *L = getASTMutationListener()) {
5124    L->CompletedImplicitDefinition(Constructor);
5125  }
5126}
5127
5128void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
5129  // We start with an initial pass over the base classes to collect those that
5130  // inherit constructors from. If there are none, we can forgo all further
5131  // processing.
5132  typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
5133  BasesVector BasesToInheritFrom;
5134  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
5135                                          BaseE = ClassDecl->bases_end();
5136         BaseIt != BaseE; ++BaseIt) {
5137    if (BaseIt->getInheritConstructors()) {
5138      QualType Base = BaseIt->getType();
5139      if (Base->isDependentType()) {
5140        // If we inherit constructors from anything that is dependent, just
5141        // abort processing altogether. We'll get another chance for the
5142        // instantiations.
5143        return;
5144      }
5145      BasesToInheritFrom.push_back(Base->castAs<RecordType>());
5146    }
5147  }
5148  if (BasesToInheritFrom.empty())
5149    return;
5150
5151  // Now collect the constructors that we already have in the current class.
5152  // Those take precedence over inherited constructors.
5153  // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
5154  //   unless there is a user-declared constructor with the same signature in
5155  //   the class where the using-declaration appears.
5156  llvm::SmallSet<const Type *, 8> ExistingConstructors;
5157  for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
5158                                    CtorE = ClassDecl->ctor_end();
5159       CtorIt != CtorE; ++CtorIt) {
5160    ExistingConstructors.insert(
5161        Context.getCanonicalType(CtorIt->getType()).getTypePtr());
5162  }
5163
5164  Scope *S = getScopeForContext(ClassDecl);
5165  DeclarationName CreatedCtorName =
5166      Context.DeclarationNames.getCXXConstructorName(
5167          ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
5168
5169  // Now comes the true work.
5170  // First, we keep a map from constructor types to the base that introduced
5171  // them. Needed for finding conflicting constructors. We also keep the
5172  // actually inserted declarations in there, for pretty diagnostics.
5173  typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
5174  typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
5175  ConstructorToSourceMap InheritedConstructors;
5176  for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
5177                             BaseE = BasesToInheritFrom.end();
5178       BaseIt != BaseE; ++BaseIt) {
5179    const RecordType *Base = *BaseIt;
5180    CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
5181    CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
5182    for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
5183                                      CtorE = BaseDecl->ctor_end();
5184         CtorIt != CtorE; ++CtorIt) {
5185      // Find the using declaration for inheriting this base's constructors.
5186      DeclarationName Name =
5187          Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
5188      UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
5189          LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
5190      SourceLocation UsingLoc = UD ? UD->getLocation() :
5191                                     ClassDecl->getLocation();
5192
5193      // C++0x [class.inhctor]p1: The candidate set of inherited constructors
5194      //   from the class X named in the using-declaration consists of actual
5195      //   constructors and notional constructors that result from the
5196      //   transformation of defaulted parameters as follows:
5197      //   - all non-template default constructors of X, and
5198      //   - for each non-template constructor of X that has at least one
5199      //     parameter with a default argument, the set of constructors that
5200      //     results from omitting any ellipsis parameter specification and
5201      //     successively omitting parameters with a default argument from the
5202      //     end of the parameter-type-list.
5203      CXXConstructorDecl *BaseCtor = *CtorIt;
5204      bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
5205      const FunctionProtoType *BaseCtorType =
5206          BaseCtor->getType()->getAs<FunctionProtoType>();
5207
5208      for (unsigned params = BaseCtor->getMinRequiredArguments(),
5209                    maxParams = BaseCtor->getNumParams();
5210           params <= maxParams; ++params) {
5211        // Skip default constructors. They're never inherited.
5212        if (params == 0)
5213          continue;
5214        // Skip copy and move constructors for the same reason.
5215        if (CanBeCopyOrMove && params == 1)
5216          continue;
5217
5218        // Build up a function type for this particular constructor.
5219        // FIXME: The working paper does not consider that the exception spec
5220        // for the inheriting constructor might be larger than that of the
5221        // source. This code doesn't yet, either.
5222        const Type *NewCtorType;
5223        if (params == maxParams)
5224          NewCtorType = BaseCtorType;
5225        else {
5226          llvm::SmallVector<QualType, 16> Args;
5227          for (unsigned i = 0; i < params; ++i) {
5228            Args.push_back(BaseCtorType->getArgType(i));
5229          }
5230          FunctionProtoType::ExtProtoInfo ExtInfo =
5231              BaseCtorType->getExtProtoInfo();
5232          ExtInfo.Variadic = false;
5233          NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
5234                                                Args.data(), params, ExtInfo)
5235                       .getTypePtr();
5236        }
5237        const Type *CanonicalNewCtorType =
5238            Context.getCanonicalType(NewCtorType);
5239
5240        // Now that we have the type, first check if the class already has a
5241        // constructor with this signature.
5242        if (ExistingConstructors.count(CanonicalNewCtorType))
5243          continue;
5244
5245        // Then we check if we have already declared an inherited constructor
5246        // with this signature.
5247        std::pair<ConstructorToSourceMap::iterator, bool> result =
5248            InheritedConstructors.insert(std::make_pair(
5249                CanonicalNewCtorType,
5250                std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
5251        if (!result.second) {
5252          // Already in the map. If it came from a different class, that's an
5253          // error. Not if it's from the same.
5254          CanQualType PreviousBase = result.first->second.first;
5255          if (CanonicalBase != PreviousBase) {
5256            const CXXConstructorDecl *PrevCtor = result.first->second.second;
5257            const CXXConstructorDecl *PrevBaseCtor =
5258                PrevCtor->getInheritedConstructor();
5259            assert(PrevBaseCtor && "Conflicting constructor was not inherited");
5260
5261            Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
5262            Diag(BaseCtor->getLocation(),
5263                 diag::note_using_decl_constructor_conflict_current_ctor);
5264            Diag(PrevBaseCtor->getLocation(),
5265                 diag::note_using_decl_constructor_conflict_previous_ctor);
5266            Diag(PrevCtor->getLocation(),
5267                 diag::note_using_decl_constructor_conflict_previous_using);
5268          }
5269          continue;
5270        }
5271
5272        // OK, we're there, now add the constructor.
5273        // C++0x [class.inhctor]p8: [...] that would be performed by a
5274        //   user-writtern inline constructor [...]
5275        DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
5276        CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
5277            Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
5278            /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
5279            /*ImplicitlyDeclared=*/true);
5280        NewCtor->setAccess(BaseCtor->getAccess());
5281
5282        // Build up the parameter decls and add them.
5283        llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
5284        for (unsigned i = 0; i < params; ++i) {
5285          ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
5286                                                   UsingLoc, UsingLoc,
5287                                                   /*IdentifierInfo=*/0,
5288                                                   BaseCtorType->getArgType(i),
5289                                                   /*TInfo=*/0, SC_None,
5290                                                   SC_None, /*DefaultArg=*/0));
5291        }
5292        NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
5293        NewCtor->setInheritedConstructor(BaseCtor);
5294
5295        PushOnScopeChains(NewCtor, S, false);
5296        ClassDecl->addDecl(NewCtor);
5297        result.first->second.second = NewCtor;
5298      }
5299    }
5300  }
5301}
5302
5303CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
5304  // C++ [class.dtor]p2:
5305  //   If a class has no user-declared destructor, a destructor is
5306  //   declared implicitly. An implicitly-declared destructor is an
5307  //   inline public member of its class.
5308
5309  // C++ [except.spec]p14:
5310  //   An implicitly declared special member function (Clause 12) shall have
5311  //   an exception-specification.
5312  ImplicitExceptionSpecification ExceptSpec(Context);
5313
5314  // Direct base-class destructors.
5315  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5316                                       BEnd = ClassDecl->bases_end();
5317       B != BEnd; ++B) {
5318    if (B->isVirtual()) // Handled below.
5319      continue;
5320
5321    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5322      ExceptSpec.CalledDecl(
5323                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
5324  }
5325
5326  // Virtual base-class destructors.
5327  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5328                                       BEnd = ClassDecl->vbases_end();
5329       B != BEnd; ++B) {
5330    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5331      ExceptSpec.CalledDecl(
5332                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
5333  }
5334
5335  // Field destructors.
5336  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5337                               FEnd = ClassDecl->field_end();
5338       F != FEnd; ++F) {
5339    if (const RecordType *RecordTy
5340        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
5341      ExceptSpec.CalledDecl(
5342                    LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
5343  }
5344
5345  // Create the actual destructor declaration.
5346  FunctionProtoType::ExtProtoInfo EPI;
5347  EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
5348  EPI.NumExceptions = ExceptSpec.size();
5349  EPI.Exceptions = ExceptSpec.data();
5350  QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
5351
5352  CanQualType ClassType
5353    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5354  SourceLocation ClassLoc = ClassDecl->getLocation();
5355  DeclarationName Name
5356    = Context.DeclarationNames.getCXXDestructorName(ClassType);
5357  DeclarationNameInfo NameInfo(Name, ClassLoc);
5358  CXXDestructorDecl *Destructor
5359      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
5360                                  /*isInline=*/true,
5361                                  /*isImplicitlyDeclared=*/true);
5362  Destructor->setAccess(AS_public);
5363  Destructor->setImplicit();
5364  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
5365
5366  // Note that we have declared this destructor.
5367  ++ASTContext::NumImplicitDestructorsDeclared;
5368
5369  // Introduce this destructor into its scope.
5370  if (Scope *S = getScopeForContext(ClassDecl))
5371    PushOnScopeChains(Destructor, S, false);
5372  ClassDecl->addDecl(Destructor);
5373
5374  // This could be uniqued if it ever proves significant.
5375  Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
5376
5377  AddOverriddenMethods(ClassDecl, Destructor);
5378
5379  return Destructor;
5380}
5381
5382void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
5383                                    CXXDestructorDecl *Destructor) {
5384  assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
5385         "DefineImplicitDestructor - call it for implicit default dtor");
5386  CXXRecordDecl *ClassDecl = Destructor->getParent();
5387  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
5388
5389  if (Destructor->isInvalidDecl())
5390    return;
5391
5392  ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
5393
5394  DiagnosticErrorTrap Trap(Diags);
5395  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5396                                         Destructor->getParent());
5397
5398  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
5399    Diag(CurrentLocation, diag::note_member_synthesized_at)
5400      << CXXDestructor << Context.getTagDeclType(ClassDecl);
5401
5402    Destructor->setInvalidDecl();
5403    return;
5404  }
5405
5406  SourceLocation Loc = Destructor->getLocation();
5407  Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5408
5409  Destructor->setUsed();
5410  MarkVTableUsed(CurrentLocation, ClassDecl);
5411
5412  if (ASTMutationListener *L = getASTMutationListener()) {
5413    L->CompletedImplicitDefinition(Destructor);
5414  }
5415}
5416
5417/// \brief Builds a statement that copies the given entity from \p From to
5418/// \c To.
5419///
5420/// This routine is used to copy the members of a class with an
5421/// implicitly-declared copy assignment operator. When the entities being
5422/// copied are arrays, this routine builds for loops to copy them.
5423///
5424/// \param S The Sema object used for type-checking.
5425///
5426/// \param Loc The location where the implicit copy is being generated.
5427///
5428/// \param T The type of the expressions being copied. Both expressions must
5429/// have this type.
5430///
5431/// \param To The expression we are copying to.
5432///
5433/// \param From The expression we are copying from.
5434///
5435/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5436/// Otherwise, it's a non-static member subobject.
5437///
5438/// \param Depth Internal parameter recording the depth of the recursion.
5439///
5440/// \returns A statement or a loop that copies the expressions.
5441static StmtResult
5442BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
5443                      Expr *To, Expr *From,
5444                      bool CopyingBaseSubobject, unsigned Depth = 0) {
5445  // C++0x [class.copy]p30:
5446  //   Each subobject is assigned in the manner appropriate to its type:
5447  //
5448  //     - if the subobject is of class type, the copy assignment operator
5449  //       for the class is used (as if by explicit qualification; that is,
5450  //       ignoring any possible virtual overriding functions in more derived
5451  //       classes);
5452  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5453    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5454
5455    // Look for operator=.
5456    DeclarationName Name
5457      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5458    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5459    S.LookupQualifiedName(OpLookup, ClassDecl, false);
5460
5461    // Filter out any result that isn't a copy-assignment operator.
5462    LookupResult::Filter F = OpLookup.makeFilter();
5463    while (F.hasNext()) {
5464      NamedDecl *D = F.next();
5465      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5466        if (Method->isCopyAssignmentOperator())
5467          continue;
5468
5469      F.erase();
5470    }
5471    F.done();
5472
5473    // Suppress the protected check (C++ [class.protected]) for each of the
5474    // assignment operators we found. This strange dance is required when
5475    // we're assigning via a base classes's copy-assignment operator. To
5476    // ensure that we're getting the right base class subobject (without
5477    // ambiguities), we need to cast "this" to that subobject type; to
5478    // ensure that we don't go through the virtual call mechanism, we need
5479    // to qualify the operator= name with the base class (see below). However,
5480    // this means that if the base class has a protected copy assignment
5481    // operator, the protected member access check will fail. So, we
5482    // rewrite "protected" access to "public" access in this case, since we
5483    // know by construction that we're calling from a derived class.
5484    if (CopyingBaseSubobject) {
5485      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5486           L != LEnd; ++L) {
5487        if (L.getAccess() == AS_protected)
5488          L.setAccess(AS_public);
5489      }
5490    }
5491
5492    // Create the nested-name-specifier that will be used to qualify the
5493    // reference to operator=; this is required to suppress the virtual
5494    // call mechanism.
5495    CXXScopeSpec SS;
5496    SS.MakeTrivial(S.Context,
5497                   NestedNameSpecifier::Create(S.Context, 0, false,
5498                                               T.getTypePtr()),
5499                   Loc);
5500
5501    // Create the reference to operator=.
5502    ExprResult OpEqualRef
5503      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
5504                                   /*FirstQualifierInScope=*/0, OpLookup,
5505                                   /*TemplateArgs=*/0,
5506                                   /*SuppressQualifierCheck=*/true);
5507    if (OpEqualRef.isInvalid())
5508      return StmtError();
5509
5510    // Build the call to the assignment operator.
5511
5512    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
5513                                                  OpEqualRef.takeAs<Expr>(),
5514                                                  Loc, &From, 1, Loc);
5515    if (Call.isInvalid())
5516      return StmtError();
5517
5518    return S.Owned(Call.takeAs<Stmt>());
5519  }
5520
5521  //     - if the subobject is of scalar type, the built-in assignment
5522  //       operator is used.
5523  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5524  if (!ArrayTy) {
5525    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
5526    if (Assignment.isInvalid())
5527      return StmtError();
5528
5529    return S.Owned(Assignment.takeAs<Stmt>());
5530  }
5531
5532  //     - if the subobject is an array, each element is assigned, in the
5533  //       manner appropriate to the element type;
5534
5535  // Construct a loop over the array bounds, e.g.,
5536  //
5537  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5538  //
5539  // that will copy each of the array elements.
5540  QualType SizeType = S.Context.getSizeType();
5541
5542  // Create the iteration variable.
5543  IdentifierInfo *IterationVarName = 0;
5544  {
5545    llvm::SmallString<8> Str;
5546    llvm::raw_svector_ostream OS(Str);
5547    OS << "__i" << Depth;
5548    IterationVarName = &S.Context.Idents.get(OS.str());
5549  }
5550  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
5551                                          IterationVarName, SizeType,
5552                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
5553                                          SC_None, SC_None);
5554
5555  // Initialize the iteration variable to zero.
5556  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
5557  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
5558
5559  // Create a reference to the iteration variable; we'll use this several
5560  // times throughout.
5561  Expr *IterationVarRef
5562    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
5563  assert(IterationVarRef && "Reference to invented variable cannot fail!");
5564
5565  // Create the DeclStmt that holds the iteration variable.
5566  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5567
5568  // Create the comparison against the array bound.
5569  llvm::APInt Upper
5570    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
5571  Expr *Comparison
5572    = new (S.Context) BinaryOperator(IterationVarRef,
5573                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5574                                     BO_NE, S.Context.BoolTy,
5575                                     VK_RValue, OK_Ordinary, Loc);
5576
5577  // Create the pre-increment of the iteration variable.
5578  Expr *Increment
5579    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5580                                    VK_LValue, OK_Ordinary, Loc);
5581
5582  // Subscript the "from" and "to" expressions with the iteration variable.
5583  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5584                                                         IterationVarRef, Loc));
5585  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5586                                                       IterationVarRef, Loc));
5587
5588  // Build the copy for an individual element of the array.
5589  StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5590                                          To, From, CopyingBaseSubobject,
5591                                          Depth + 1);
5592  if (Copy.isInvalid())
5593    return StmtError();
5594
5595  // Construct the loop that copies all elements of this array.
5596  return S.ActOnForStmt(Loc, Loc, InitStmt,
5597                        S.MakeFullExpr(Comparison),
5598                        0, S.MakeFullExpr(Increment),
5599                        Loc, Copy.take());
5600}
5601
5602/// \brief Determine whether the given class has a copy assignment operator
5603/// that accepts a const-qualified argument.
5604static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5605  CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5606
5607  if (!Class->hasDeclaredCopyAssignment())
5608    S.DeclareImplicitCopyAssignment(Class);
5609
5610  QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5611  DeclarationName OpName
5612    = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5613
5614  DeclContext::lookup_const_iterator Op, OpEnd;
5615  for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5616    // C++ [class.copy]p9:
5617    //   A user-declared copy assignment operator is a non-static non-template
5618    //   member function of class X with exactly one parameter of type X, X&,
5619    //   const X&, volatile X& or const volatile X&.
5620    const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5621    if (!Method)
5622      continue;
5623
5624    if (Method->isStatic())
5625      continue;
5626    if (Method->getPrimaryTemplate())
5627      continue;
5628    const FunctionProtoType *FnType =
5629    Method->getType()->getAs<FunctionProtoType>();
5630    assert(FnType && "Overloaded operator has no prototype.");
5631    // Don't assert on this; an invalid decl might have been left in the AST.
5632    if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5633      continue;
5634    bool AcceptsConst = true;
5635    QualType ArgType = FnType->getArgType(0);
5636    if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5637      ArgType = Ref->getPointeeType();
5638      // Is it a non-const lvalue reference?
5639      if (!ArgType.isConstQualified())
5640        AcceptsConst = false;
5641    }
5642    if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5643      continue;
5644
5645    // We have a single argument of type cv X or cv X&, i.e. we've found the
5646    // copy assignment operator. Return whether it accepts const arguments.
5647    return AcceptsConst;
5648  }
5649  assert(Class->isInvalidDecl() &&
5650         "No copy assignment operator declared in valid code.");
5651  return false;
5652}
5653
5654CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
5655  // Note: The following rules are largely analoguous to the copy
5656  // constructor rules. Note that virtual bases are not taken into account
5657  // for determining the argument type of the operator. Note also that
5658  // operators taking an object instead of a reference are allowed.
5659
5660
5661  // C++ [class.copy]p10:
5662  //   If the class definition does not explicitly declare a copy
5663  //   assignment operator, one is declared implicitly.
5664  //   The implicitly-defined copy assignment operator for a class X
5665  //   will have the form
5666  //
5667  //       X& X::operator=(const X&)
5668  //
5669  //   if
5670  bool HasConstCopyAssignment = true;
5671
5672  //       -- each direct base class B of X has a copy assignment operator
5673  //          whose parameter is of type const B&, const volatile B& or B,
5674  //          and
5675  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5676                                       BaseEnd = ClassDecl->bases_end();
5677       HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5678    assert(!Base->getType()->isDependentType() &&
5679           "Cannot generate implicit members for class with dependent bases.");
5680    const CXXRecordDecl *BaseClassDecl
5681      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
5682    HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
5683  }
5684
5685  //       -- for all the nonstatic data members of X that are of a class
5686  //          type M (or array thereof), each such class type has a copy
5687  //          assignment operator whose parameter is of type const M&,
5688  //          const volatile M& or M.
5689  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5690                                  FieldEnd = ClassDecl->field_end();
5691       HasConstCopyAssignment && Field != FieldEnd;
5692       ++Field) {
5693    QualType FieldType = Context.getBaseElementType((*Field)->getType());
5694    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5695      const CXXRecordDecl *FieldClassDecl
5696        = cast<CXXRecordDecl>(FieldClassType->getDecl());
5697      HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
5698    }
5699  }
5700
5701  //   Otherwise, the implicitly declared copy assignment operator will
5702  //   have the form
5703  //
5704  //       X& X::operator=(X&)
5705  QualType ArgType = Context.getTypeDeclType(ClassDecl);
5706  QualType RetType = Context.getLValueReferenceType(ArgType);
5707  if (HasConstCopyAssignment)
5708    ArgType = ArgType.withConst();
5709  ArgType = Context.getLValueReferenceType(ArgType);
5710
5711  // C++ [except.spec]p14:
5712  //   An implicitly declared special member function (Clause 12) shall have an
5713  //   exception-specification. [...]
5714  ImplicitExceptionSpecification ExceptSpec(Context);
5715  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5716                                       BaseEnd = ClassDecl->bases_end();
5717       Base != BaseEnd; ++Base) {
5718    CXXRecordDecl *BaseClassDecl
5719      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
5720
5721    if (!BaseClassDecl->hasDeclaredCopyAssignment())
5722      DeclareImplicitCopyAssignment(BaseClassDecl);
5723
5724    if (CXXMethodDecl *CopyAssign
5725           = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5726      ExceptSpec.CalledDecl(CopyAssign);
5727  }
5728  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5729                                  FieldEnd = ClassDecl->field_end();
5730       Field != FieldEnd;
5731       ++Field) {
5732    QualType FieldType = Context.getBaseElementType((*Field)->getType());
5733    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5734      CXXRecordDecl *FieldClassDecl
5735        = cast<CXXRecordDecl>(FieldClassType->getDecl());
5736
5737      if (!FieldClassDecl->hasDeclaredCopyAssignment())
5738        DeclareImplicitCopyAssignment(FieldClassDecl);
5739
5740      if (CXXMethodDecl *CopyAssign
5741            = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5742        ExceptSpec.CalledDecl(CopyAssign);
5743    }
5744  }
5745
5746  //   An implicitly-declared copy assignment operator is an inline public
5747  //   member of its class.
5748  FunctionProtoType::ExtProtoInfo EPI;
5749  EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
5750  EPI.NumExceptions = ExceptSpec.size();
5751  EPI.Exceptions = ExceptSpec.data();
5752  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5753  SourceLocation ClassLoc = ClassDecl->getLocation();
5754  DeclarationNameInfo NameInfo(Name, ClassLoc);
5755  CXXMethodDecl *CopyAssignment
5756    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
5757                            Context.getFunctionType(RetType, &ArgType, 1, EPI),
5758                            /*TInfo=*/0, /*isStatic=*/false,
5759                            /*StorageClassAsWritten=*/SC_None,
5760                            /*isInline=*/true,
5761                            SourceLocation());
5762  CopyAssignment->setAccess(AS_public);
5763  CopyAssignment->setImplicit();
5764  CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
5765
5766  // Add the parameter to the operator.
5767  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
5768                                               ClassLoc, ClassLoc, /*Id=*/0,
5769                                               ArgType, /*TInfo=*/0,
5770                                               SC_None,
5771                                               SC_None, 0);
5772  CopyAssignment->setParams(&FromParam, 1);
5773
5774  // Note that we have added this copy-assignment operator.
5775  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5776
5777  if (Scope *S = getScopeForContext(ClassDecl))
5778    PushOnScopeChains(CopyAssignment, S, false);
5779  ClassDecl->addDecl(CopyAssignment);
5780
5781  AddOverriddenMethods(ClassDecl, CopyAssignment);
5782  return CopyAssignment;
5783}
5784
5785void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5786                                        CXXMethodDecl *CopyAssignOperator) {
5787  assert((CopyAssignOperator->isImplicit() &&
5788          CopyAssignOperator->isOverloadedOperator() &&
5789          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
5790          !CopyAssignOperator->isUsed(false)) &&
5791         "DefineImplicitCopyAssignment called for wrong function");
5792
5793  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5794
5795  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5796    CopyAssignOperator->setInvalidDecl();
5797    return;
5798  }
5799
5800  CopyAssignOperator->setUsed();
5801
5802  ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
5803  DiagnosticErrorTrap Trap(Diags);
5804
5805  // C++0x [class.copy]p30:
5806  //   The implicitly-defined or explicitly-defaulted copy assignment operator
5807  //   for a non-union class X performs memberwise copy assignment of its
5808  //   subobjects. The direct base classes of X are assigned first, in the
5809  //   order of their declaration in the base-specifier-list, and then the
5810  //   immediate non-static data members of X are assigned, in the order in
5811  //   which they were declared in the class definition.
5812
5813  // The statements that form the synthesized function body.
5814  ASTOwningVector<Stmt*> Statements(*this);
5815
5816  // The parameter for the "other" object, which we are copying from.
5817  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5818  Qualifiers OtherQuals = Other->getType().getQualifiers();
5819  QualType OtherRefType = Other->getType();
5820  if (const LValueReferenceType *OtherRef
5821                                = OtherRefType->getAs<LValueReferenceType>()) {
5822    OtherRefType = OtherRef->getPointeeType();
5823    OtherQuals = OtherRefType.getQualifiers();
5824  }
5825
5826  // Our location for everything implicitly-generated.
5827  SourceLocation Loc = CopyAssignOperator->getLocation();
5828
5829  // Construct a reference to the "other" object. We'll be using this
5830  // throughout the generated ASTs.
5831  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
5832  assert(OtherRef && "Reference to parameter cannot fail!");
5833
5834  // Construct the "this" pointer. We'll be using this throughout the generated
5835  // ASTs.
5836  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5837  assert(This && "Reference to this cannot fail!");
5838
5839  // Assign base classes.
5840  bool Invalid = false;
5841  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5842       E = ClassDecl->bases_end(); Base != E; ++Base) {
5843    // Form the assignment:
5844    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5845    QualType BaseType = Base->getType().getUnqualifiedType();
5846    if (!BaseType->isRecordType()) {
5847      Invalid = true;
5848      continue;
5849    }
5850
5851    CXXCastPath BasePath;
5852    BasePath.push_back(Base);
5853
5854    // Construct the "from" expression, which is an implicit cast to the
5855    // appropriately-qualified base type.
5856    Expr *From = OtherRef;
5857    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
5858                             CK_UncheckedDerivedToBase,
5859                             VK_LValue, &BasePath).take();
5860
5861    // Dereference "this".
5862    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
5863
5864    // Implicitly cast "this" to the appropriately-qualified base type.
5865    To = ImpCastExprToType(To.take(),
5866                           Context.getCVRQualifiedType(BaseType,
5867                                     CopyAssignOperator->getTypeQualifiers()),
5868                           CK_UncheckedDerivedToBase,
5869                           VK_LValue, &BasePath);
5870
5871    // Build the copy.
5872    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
5873                                            To.get(), From,
5874                                            /*CopyingBaseSubobject=*/true);
5875    if (Copy.isInvalid()) {
5876      Diag(CurrentLocation, diag::note_member_synthesized_at)
5877        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5878      CopyAssignOperator->setInvalidDecl();
5879      return;
5880    }
5881
5882    // Success! Record the copy.
5883    Statements.push_back(Copy.takeAs<Expr>());
5884  }
5885
5886  // \brief Reference to the __builtin_memcpy function.
5887  Expr *BuiltinMemCpyRef = 0;
5888  // \brief Reference to the __builtin_objc_memmove_collectable function.
5889  Expr *CollectableMemCpyRef = 0;
5890
5891  // Assign non-static members.
5892  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5893                                  FieldEnd = ClassDecl->field_end();
5894       Field != FieldEnd; ++Field) {
5895    // Check for members of reference type; we can't copy those.
5896    if (Field->getType()->isReferenceType()) {
5897      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5898        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5899      Diag(Field->getLocation(), diag::note_declared_at);
5900      Diag(CurrentLocation, diag::note_member_synthesized_at)
5901        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5902      Invalid = true;
5903      continue;
5904    }
5905
5906    // Check for members of const-qualified, non-class type.
5907    QualType BaseType = Context.getBaseElementType(Field->getType());
5908    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5909      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5910        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5911      Diag(Field->getLocation(), diag::note_declared_at);
5912      Diag(CurrentLocation, diag::note_member_synthesized_at)
5913        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5914      Invalid = true;
5915      continue;
5916    }
5917
5918    QualType FieldType = Field->getType().getNonReferenceType();
5919    if (FieldType->isIncompleteArrayType()) {
5920      assert(ClassDecl->hasFlexibleArrayMember() &&
5921             "Incomplete array type is not valid");
5922      continue;
5923    }
5924
5925    // Build references to the field in the object we're copying from and to.
5926    CXXScopeSpec SS; // Intentionally empty
5927    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5928                              LookupMemberName);
5929    MemberLookup.addDecl(*Field);
5930    MemberLookup.resolveKind();
5931    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
5932                                               Loc, /*IsArrow=*/false,
5933                                               SS, 0, MemberLookup, 0);
5934    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
5935                                             Loc, /*IsArrow=*/true,
5936                                             SS, 0, MemberLookup, 0);
5937    assert(!From.isInvalid() && "Implicit field reference cannot fail");
5938    assert(!To.isInvalid() && "Implicit field reference cannot fail");
5939
5940    // If the field should be copied with __builtin_memcpy rather than via
5941    // explicit assignments, do so. This optimization only applies for arrays
5942    // of scalars and arrays of class type with trivial copy-assignment
5943    // operators.
5944    if (FieldType->isArrayType() &&
5945        (!BaseType->isRecordType() ||
5946         cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5947           ->hasTrivialCopyAssignment())) {
5948      // Compute the size of the memory buffer to be copied.
5949      QualType SizeType = Context.getSizeType();
5950      llvm::APInt Size(Context.getTypeSize(SizeType),
5951                       Context.getTypeSizeInChars(BaseType).getQuantity());
5952      for (const ConstantArrayType *Array
5953              = Context.getAsConstantArrayType(FieldType);
5954           Array;
5955           Array = Context.getAsConstantArrayType(Array->getElementType())) {
5956        llvm::APInt ArraySize
5957          = Array->getSize().zextOrTrunc(Size.getBitWidth());
5958        Size *= ArraySize;
5959      }
5960
5961      // Take the address of the field references for "from" and "to".
5962      From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5963      To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
5964
5965      bool NeedsCollectableMemCpy =
5966          (BaseType->isRecordType() &&
5967           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5968
5969      if (NeedsCollectableMemCpy) {
5970        if (!CollectableMemCpyRef) {
5971          // Create a reference to the __builtin_objc_memmove_collectable function.
5972          LookupResult R(*this,
5973                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
5974                         Loc, LookupOrdinaryName);
5975          LookupName(R, TUScope, true);
5976
5977          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5978          if (!CollectableMemCpy) {
5979            // Something went horribly wrong earlier, and we will have
5980            // complained about it.
5981            Invalid = true;
5982            continue;
5983          }
5984
5985          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5986                                                  CollectableMemCpy->getType(),
5987                                                  VK_LValue, Loc, 0).take();
5988          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5989        }
5990      }
5991      // Create a reference to the __builtin_memcpy builtin function.
5992      else if (!BuiltinMemCpyRef) {
5993        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5994                       LookupOrdinaryName);
5995        LookupName(R, TUScope, true);
5996
5997        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5998        if (!BuiltinMemCpy) {
5999          // Something went horribly wrong earlier, and we will have complained
6000          // about it.
6001          Invalid = true;
6002          continue;
6003        }
6004
6005        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
6006                                            BuiltinMemCpy->getType(),
6007                                            VK_LValue, Loc, 0).take();
6008        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
6009      }
6010
6011      ASTOwningVector<Expr*> CallArgs(*this);
6012      CallArgs.push_back(To.takeAs<Expr>());
6013      CallArgs.push_back(From.takeAs<Expr>());
6014      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
6015      ExprResult Call = ExprError();
6016      if (NeedsCollectableMemCpy)
6017        Call = ActOnCallExpr(/*Scope=*/0,
6018                             CollectableMemCpyRef,
6019                             Loc, move_arg(CallArgs),
6020                             Loc);
6021      else
6022        Call = ActOnCallExpr(/*Scope=*/0,
6023                             BuiltinMemCpyRef,
6024                             Loc, move_arg(CallArgs),
6025                             Loc);
6026
6027      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
6028      Statements.push_back(Call.takeAs<Expr>());
6029      continue;
6030    }
6031
6032    // Build the copy of this field.
6033    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
6034                                                  To.get(), From.get(),
6035                                              /*CopyingBaseSubobject=*/false);
6036    if (Copy.isInvalid()) {
6037      Diag(CurrentLocation, diag::note_member_synthesized_at)
6038        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6039      CopyAssignOperator->setInvalidDecl();
6040      return;
6041    }
6042
6043    // Success! Record the copy.
6044    Statements.push_back(Copy.takeAs<Stmt>());
6045  }
6046
6047  if (!Invalid) {
6048    // Add a "return *this;"
6049    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
6050
6051    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
6052    if (Return.isInvalid())
6053      Invalid = true;
6054    else {
6055      Statements.push_back(Return.takeAs<Stmt>());
6056
6057      if (Trap.hasErrorOccurred()) {
6058        Diag(CurrentLocation, diag::note_member_synthesized_at)
6059          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6060        Invalid = true;
6061      }
6062    }
6063  }
6064
6065  if (Invalid) {
6066    CopyAssignOperator->setInvalidDecl();
6067    return;
6068  }
6069
6070  StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
6071                                            /*isStmtExpr=*/false);
6072  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
6073  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
6074
6075  if (ASTMutationListener *L = getASTMutationListener()) {
6076    L->CompletedImplicitDefinition(CopyAssignOperator);
6077  }
6078}
6079
6080CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
6081                                                    CXXRecordDecl *ClassDecl) {
6082  // C++ [class.copy]p4:
6083  //   If the class definition does not explicitly declare a copy
6084  //   constructor, one is declared implicitly.
6085
6086  // C++ [class.copy]p5:
6087  //   The implicitly-declared copy constructor for a class X will
6088  //   have the form
6089  //
6090  //       X::X(const X&)
6091  //
6092  //   if
6093  bool HasConstCopyConstructor = true;
6094
6095  //     -- each direct or virtual base class B of X has a copy
6096  //        constructor whose first parameter is of type const B& or
6097  //        const volatile B&, and
6098  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6099                                       BaseEnd = ClassDecl->bases_end();
6100       HasConstCopyConstructor && Base != BaseEnd;
6101       ++Base) {
6102    // Virtual bases are handled below.
6103    if (Base->isVirtual())
6104      continue;
6105
6106    CXXRecordDecl *BaseClassDecl
6107      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6108    if (!BaseClassDecl->hasDeclaredCopyConstructor())
6109      DeclareImplicitCopyConstructor(BaseClassDecl);
6110
6111    HasConstCopyConstructor
6112      = BaseClassDecl->hasConstCopyConstructor(Context);
6113  }
6114
6115  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6116                                       BaseEnd = ClassDecl->vbases_end();
6117       HasConstCopyConstructor && Base != BaseEnd;
6118       ++Base) {
6119    CXXRecordDecl *BaseClassDecl
6120      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6121    if (!BaseClassDecl->hasDeclaredCopyConstructor())
6122      DeclareImplicitCopyConstructor(BaseClassDecl);
6123
6124    HasConstCopyConstructor
6125      = BaseClassDecl->hasConstCopyConstructor(Context);
6126  }
6127
6128  //     -- for all the nonstatic data members of X that are of a
6129  //        class type M (or array thereof), each such class type
6130  //        has a copy constructor whose first parameter is of type
6131  //        const M& or const volatile M&.
6132  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6133                                  FieldEnd = ClassDecl->field_end();
6134       HasConstCopyConstructor && Field != FieldEnd;
6135       ++Field) {
6136    QualType FieldType = Context.getBaseElementType((*Field)->getType());
6137    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6138      CXXRecordDecl *FieldClassDecl
6139        = cast<CXXRecordDecl>(FieldClassType->getDecl());
6140      if (!FieldClassDecl->hasDeclaredCopyConstructor())
6141        DeclareImplicitCopyConstructor(FieldClassDecl);
6142
6143      HasConstCopyConstructor
6144        = FieldClassDecl->hasConstCopyConstructor(Context);
6145    }
6146  }
6147
6148  //   Otherwise, the implicitly declared copy constructor will have
6149  //   the form
6150  //
6151  //       X::X(X&)
6152  QualType ClassType = Context.getTypeDeclType(ClassDecl);
6153  QualType ArgType = ClassType;
6154  if (HasConstCopyConstructor)
6155    ArgType = ArgType.withConst();
6156  ArgType = Context.getLValueReferenceType(ArgType);
6157
6158  // C++ [except.spec]p14:
6159  //   An implicitly declared special member function (Clause 12) shall have an
6160  //   exception-specification. [...]
6161  ImplicitExceptionSpecification ExceptSpec(Context);
6162  unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
6163  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6164                                       BaseEnd = ClassDecl->bases_end();
6165       Base != BaseEnd;
6166       ++Base) {
6167    // Virtual bases are handled below.
6168    if (Base->isVirtual())
6169      continue;
6170
6171    CXXRecordDecl *BaseClassDecl
6172      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6173    if (!BaseClassDecl->hasDeclaredCopyConstructor())
6174      DeclareImplicitCopyConstructor(BaseClassDecl);
6175
6176    if (CXXConstructorDecl *CopyConstructor
6177                          = BaseClassDecl->getCopyConstructor(Context, Quals))
6178      ExceptSpec.CalledDecl(CopyConstructor);
6179  }
6180  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6181                                       BaseEnd = ClassDecl->vbases_end();
6182       Base != BaseEnd;
6183       ++Base) {
6184    CXXRecordDecl *BaseClassDecl
6185      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6186    if (!BaseClassDecl->hasDeclaredCopyConstructor())
6187      DeclareImplicitCopyConstructor(BaseClassDecl);
6188
6189    if (CXXConstructorDecl *CopyConstructor
6190                          = BaseClassDecl->getCopyConstructor(Context, Quals))
6191      ExceptSpec.CalledDecl(CopyConstructor);
6192  }
6193  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6194                                  FieldEnd = ClassDecl->field_end();
6195       Field != FieldEnd;
6196       ++Field) {
6197    QualType FieldType = Context.getBaseElementType((*Field)->getType());
6198    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6199      CXXRecordDecl *FieldClassDecl
6200        = cast<CXXRecordDecl>(FieldClassType->getDecl());
6201      if (!FieldClassDecl->hasDeclaredCopyConstructor())
6202        DeclareImplicitCopyConstructor(FieldClassDecl);
6203
6204      if (CXXConstructorDecl *CopyConstructor
6205                          = FieldClassDecl->getCopyConstructor(Context, Quals))
6206        ExceptSpec.CalledDecl(CopyConstructor);
6207    }
6208  }
6209
6210  //   An implicitly-declared copy constructor is an inline public
6211  //   member of its class.
6212  FunctionProtoType::ExtProtoInfo EPI;
6213  EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
6214  EPI.NumExceptions = ExceptSpec.size();
6215  EPI.Exceptions = ExceptSpec.data();
6216  DeclarationName Name
6217    = Context.DeclarationNames.getCXXConstructorName(
6218                                           Context.getCanonicalType(ClassType));
6219  SourceLocation ClassLoc = ClassDecl->getLocation();
6220  DeclarationNameInfo NameInfo(Name, ClassLoc);
6221  CXXConstructorDecl *CopyConstructor
6222    = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
6223                                 Context.getFunctionType(Context.VoidTy,
6224                                                         &ArgType, 1, EPI),
6225                                 /*TInfo=*/0,
6226                                 /*isExplicit=*/false,
6227                                 /*isInline=*/true,
6228                                 /*isImplicitlyDeclared=*/true);
6229  CopyConstructor->setAccess(AS_public);
6230  CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
6231
6232  // Note that we have declared this constructor.
6233  ++ASTContext::NumImplicitCopyConstructorsDeclared;
6234
6235  // Add the parameter to the constructor.
6236  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
6237                                               ClassLoc, ClassLoc,
6238                                               /*IdentifierInfo=*/0,
6239                                               ArgType, /*TInfo=*/0,
6240                                               SC_None,
6241                                               SC_None, 0);
6242  CopyConstructor->setParams(&FromParam, 1);
6243  if (Scope *S = getScopeForContext(ClassDecl))
6244    PushOnScopeChains(CopyConstructor, S, false);
6245  ClassDecl->addDecl(CopyConstructor);
6246
6247  return CopyConstructor;
6248}
6249
6250void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6251                                   CXXConstructorDecl *CopyConstructor,
6252                                   unsigned TypeQuals) {
6253  assert((CopyConstructor->isImplicit() &&
6254          CopyConstructor->isCopyConstructor(TypeQuals) &&
6255          !CopyConstructor->isUsed(false)) &&
6256         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
6257
6258  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
6259  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
6260
6261  ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
6262  DiagnosticErrorTrap Trap(Diags);
6263
6264  if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
6265      Trap.hasErrorOccurred()) {
6266    Diag(CurrentLocation, diag::note_member_synthesized_at)
6267      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
6268    CopyConstructor->setInvalidDecl();
6269  }  else {
6270    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
6271                                               CopyConstructor->getLocation(),
6272                                               MultiStmtArg(*this, 0, 0),
6273                                               /*isStmtExpr=*/false)
6274                                                              .takeAs<Stmt>());
6275  }
6276
6277  CopyConstructor->setUsed();
6278
6279  if (ASTMutationListener *L = getASTMutationListener()) {
6280    L->CompletedImplicitDefinition(CopyConstructor);
6281  }
6282}
6283
6284ExprResult
6285Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6286                            CXXConstructorDecl *Constructor,
6287                            MultiExprArg ExprArgs,
6288                            bool RequiresZeroInit,
6289                            unsigned ConstructKind,
6290                            SourceRange ParenRange) {
6291  bool Elidable = false;
6292
6293  // C++0x [class.copy]p34:
6294  //   When certain criteria are met, an implementation is allowed to
6295  //   omit the copy/move construction of a class object, even if the
6296  //   copy/move constructor and/or destructor for the object have
6297  //   side effects. [...]
6298  //     - when a temporary class object that has not been bound to a
6299  //       reference (12.2) would be copied/moved to a class object
6300  //       with the same cv-unqualified type, the copy/move operation
6301  //       can be omitted by constructing the temporary object
6302  //       directly into the target of the omitted copy/move
6303  if (ConstructKind == CXXConstructExpr::CK_Complete &&
6304      Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
6305    Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
6306    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
6307  }
6308
6309  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
6310                               Elidable, move(ExprArgs), RequiresZeroInit,
6311                               ConstructKind, ParenRange);
6312}
6313
6314/// BuildCXXConstructExpr - Creates a complete call to a constructor,
6315/// including handling of its default argument expressions.
6316ExprResult
6317Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6318                            CXXConstructorDecl *Constructor, bool Elidable,
6319                            MultiExprArg ExprArgs,
6320                            bool RequiresZeroInit,
6321                            unsigned ConstructKind,
6322                            SourceRange ParenRange) {
6323  unsigned NumExprs = ExprArgs.size();
6324  Expr **Exprs = (Expr **)ExprArgs.release();
6325
6326  for (specific_attr_iterator<NonNullAttr>
6327           i = Constructor->specific_attr_begin<NonNullAttr>(),
6328           e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
6329    const NonNullAttr *NonNull = *i;
6330    CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
6331  }
6332
6333  MarkDeclarationReferenced(ConstructLoc, Constructor);
6334  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
6335                                        Constructor, Elidable, Exprs, NumExprs,
6336                                        RequiresZeroInit,
6337              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
6338                                        ParenRange));
6339}
6340
6341bool Sema::InitializeVarWithConstructor(VarDecl *VD,
6342                                        CXXConstructorDecl *Constructor,
6343                                        MultiExprArg Exprs) {
6344  // FIXME: Provide the correct paren SourceRange when available.
6345  ExprResult TempResult =
6346    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
6347                          move(Exprs), false, CXXConstructExpr::CK_Complete,
6348                          SourceRange());
6349  if (TempResult.isInvalid())
6350    return true;
6351
6352  Expr *Temp = TempResult.takeAs<Expr>();
6353  CheckImplicitConversions(Temp, VD->getLocation());
6354  MarkDeclarationReferenced(VD->getLocation(), Constructor);
6355  Temp = MaybeCreateExprWithCleanups(Temp);
6356  VD->setInit(Temp);
6357
6358  return false;
6359}
6360
6361void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
6362  if (VD->isInvalidDecl()) return;
6363
6364  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
6365  if (ClassDecl->isInvalidDecl()) return;
6366  if (ClassDecl->hasTrivialDestructor()) return;
6367  if (ClassDecl->isDependentContext()) return;
6368
6369  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6370  MarkDeclarationReferenced(VD->getLocation(), Destructor);
6371  CheckDestructorAccess(VD->getLocation(), Destructor,
6372                        PDiag(diag::err_access_dtor_var)
6373                        << VD->getDeclName()
6374                        << VD->getType());
6375
6376  if (!VD->hasGlobalStorage()) return;
6377
6378  // Emit warning for non-trivial dtor in global scope (a real global,
6379  // class-static, function-static).
6380  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
6381
6382  // TODO: this should be re-enabled for static locals by !CXAAtExit
6383  if (!VD->isStaticLocal())
6384    Diag(VD->getLocation(), diag::warn_global_destructor);
6385}
6386
6387/// AddCXXDirectInitializerToDecl - This action is called immediately after
6388/// ActOnDeclarator, when a C++ direct initializer is present.
6389/// e.g: "int x(1);"
6390void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
6391                                         SourceLocation LParenLoc,
6392                                         MultiExprArg Exprs,
6393                                         SourceLocation RParenLoc,
6394                                         bool TypeMayContainAuto) {
6395  assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
6396
6397  // If there is no declaration, there was an error parsing it.  Just ignore
6398  // the initializer.
6399  if (RealDecl == 0)
6400    return;
6401
6402  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6403  if (!VDecl) {
6404    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6405    RealDecl->setInvalidDecl();
6406    return;
6407  }
6408
6409  // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6410  if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
6411    // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
6412    if (Exprs.size() > 1) {
6413      Diag(Exprs.get()[1]->getSourceRange().getBegin(),
6414           diag::err_auto_var_init_multiple_expressions)
6415        << VDecl->getDeclName() << VDecl->getType()
6416        << VDecl->getSourceRange();
6417      RealDecl->setInvalidDecl();
6418      return;
6419    }
6420
6421    Expr *Init = Exprs.get()[0];
6422    TypeSourceInfo *DeducedType = 0;
6423    if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
6424      Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
6425        << VDecl->getDeclName() << VDecl->getType() << Init->getType()
6426        << Init->getSourceRange();
6427    if (!DeducedType) {
6428      RealDecl->setInvalidDecl();
6429      return;
6430    }
6431    VDecl->setTypeSourceInfo(DeducedType);
6432    VDecl->setType(DeducedType->getType());
6433
6434    // If this is a redeclaration, check that the type we just deduced matches
6435    // the previously declared type.
6436    if (VarDecl *Old = VDecl->getPreviousDeclaration())
6437      MergeVarDeclTypes(VDecl, Old);
6438  }
6439
6440  // We will represent direct-initialization similarly to copy-initialization:
6441  //    int x(1);  -as-> int x = 1;
6442  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6443  //
6444  // Clients that want to distinguish between the two forms, can check for
6445  // direct initializer using VarDecl::hasCXXDirectInitializer().
6446  // A major benefit is that clients that don't particularly care about which
6447  // exactly form was it (like the CodeGen) can handle both cases without
6448  // special case code.
6449
6450  // C++ 8.5p11:
6451  // The form of initialization (using parentheses or '=') is generally
6452  // insignificant, but does matter when the entity being initialized has a
6453  // class type.
6454
6455  if (!VDecl->getType()->isDependentType() &&
6456      RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
6457                          diag::err_typecheck_decl_incomplete_type)) {
6458    VDecl->setInvalidDecl();
6459    return;
6460  }
6461
6462  // The variable can not have an abstract class type.
6463  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6464                             diag::err_abstract_type_in_decl,
6465                             AbstractVariableType))
6466    VDecl->setInvalidDecl();
6467
6468  const VarDecl *Def;
6469  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
6470    Diag(VDecl->getLocation(), diag::err_redefinition)
6471    << VDecl->getDeclName();
6472    Diag(Def->getLocation(), diag::note_previous_definition);
6473    VDecl->setInvalidDecl();
6474    return;
6475  }
6476
6477  // C++ [class.static.data]p4
6478  //   If a static data member is of const integral or const
6479  //   enumeration type, its declaration in the class definition can
6480  //   specify a constant-initializer which shall be an integral
6481  //   constant expression (5.19). In that case, the member can appear
6482  //   in integral constant expressions. The member shall still be
6483  //   defined in a namespace scope if it is used in the program and the
6484  //   namespace scope definition shall not contain an initializer.
6485  //
6486  // We already performed a redefinition check above, but for static
6487  // data members we also need to check whether there was an in-class
6488  // declaration with an initializer.
6489  const VarDecl* PrevInit = 0;
6490  if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6491    Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6492    Diag(PrevInit->getLocation(), diag::note_previous_definition);
6493    return;
6494  }
6495
6496  bool IsDependent = false;
6497  for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6498    if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6499      VDecl->setInvalidDecl();
6500      return;
6501    }
6502
6503    if (Exprs.get()[I]->isTypeDependent())
6504      IsDependent = true;
6505  }
6506
6507  // If either the declaration has a dependent type or if any of the
6508  // expressions is type-dependent, we represent the initialization
6509  // via a ParenListExpr for later use during template instantiation.
6510  if (VDecl->getType()->isDependentType() || IsDependent) {
6511    // Let clients know that initialization was done with a direct initializer.
6512    VDecl->setCXXDirectInitializer(true);
6513
6514    // Store the initialization expressions as a ParenListExpr.
6515    unsigned NumExprs = Exprs.size();
6516    VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6517                                               (Expr **)Exprs.release(),
6518                                               NumExprs, RParenLoc));
6519    return;
6520  }
6521
6522  // Capture the variable that is being initialized and the style of
6523  // initialization.
6524  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6525
6526  // FIXME: Poor source location information.
6527  InitializationKind Kind
6528    = InitializationKind::CreateDirect(VDecl->getLocation(),
6529                                       LParenLoc, RParenLoc);
6530
6531  InitializationSequence InitSeq(*this, Entity, Kind,
6532                                 Exprs.get(), Exprs.size());
6533  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
6534  if (Result.isInvalid()) {
6535    VDecl->setInvalidDecl();
6536    return;
6537  }
6538
6539  CheckImplicitConversions(Result.get(), LParenLoc);
6540
6541  Result = MaybeCreateExprWithCleanups(Result);
6542  VDecl->setInit(Result.takeAs<Expr>());
6543  VDecl->setCXXDirectInitializer(true);
6544
6545  CheckCompleteVariableDeclaration(VDecl);
6546}
6547
6548/// \brief Given a constructor and the set of arguments provided for the
6549/// constructor, convert the arguments and add any required default arguments
6550/// to form a proper call to this constructor.
6551///
6552/// \returns true if an error occurred, false otherwise.
6553bool
6554Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6555                              MultiExprArg ArgsPtr,
6556                              SourceLocation Loc,
6557                              ASTOwningVector<Expr*> &ConvertedArgs) {
6558  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6559  unsigned NumArgs = ArgsPtr.size();
6560  Expr **Args = (Expr **)ArgsPtr.get();
6561
6562  const FunctionProtoType *Proto
6563    = Constructor->getType()->getAs<FunctionProtoType>();
6564  assert(Proto && "Constructor without a prototype?");
6565  unsigned NumArgsInProto = Proto->getNumArgs();
6566
6567  // If too few arguments are available, we'll fill in the rest with defaults.
6568  if (NumArgs < NumArgsInProto)
6569    ConvertedArgs.reserve(NumArgsInProto);
6570  else
6571    ConvertedArgs.reserve(NumArgs);
6572
6573  VariadicCallType CallType =
6574    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6575  llvm::SmallVector<Expr *, 8> AllArgs;
6576  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6577                                        Proto, 0, Args, NumArgs, AllArgs,
6578                                        CallType);
6579  for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6580    ConvertedArgs.push_back(AllArgs[i]);
6581  return Invalid;
6582}
6583
6584static inline bool
6585CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6586                                       const FunctionDecl *FnDecl) {
6587  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
6588  if (isa<NamespaceDecl>(DC)) {
6589    return SemaRef.Diag(FnDecl->getLocation(),
6590                        diag::err_operator_new_delete_declared_in_namespace)
6591      << FnDecl->getDeclName();
6592  }
6593
6594  if (isa<TranslationUnitDecl>(DC) &&
6595      FnDecl->getStorageClass() == SC_Static) {
6596    return SemaRef.Diag(FnDecl->getLocation(),
6597                        diag::err_operator_new_delete_declared_static)
6598      << FnDecl->getDeclName();
6599  }
6600
6601  return false;
6602}
6603
6604static inline bool
6605CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6606                            CanQualType ExpectedResultType,
6607                            CanQualType ExpectedFirstParamType,
6608                            unsigned DependentParamTypeDiag,
6609                            unsigned InvalidParamTypeDiag) {
6610  QualType ResultType =
6611    FnDecl->getType()->getAs<FunctionType>()->getResultType();
6612
6613  // Check that the result type is not dependent.
6614  if (ResultType->isDependentType())
6615    return SemaRef.Diag(FnDecl->getLocation(),
6616                        diag::err_operator_new_delete_dependent_result_type)
6617    << FnDecl->getDeclName() << ExpectedResultType;
6618
6619  // Check that the result type is what we expect.
6620  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6621    return SemaRef.Diag(FnDecl->getLocation(),
6622                        diag::err_operator_new_delete_invalid_result_type)
6623    << FnDecl->getDeclName() << ExpectedResultType;
6624
6625  // A function template must have at least 2 parameters.
6626  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6627    return SemaRef.Diag(FnDecl->getLocation(),
6628                      diag::err_operator_new_delete_template_too_few_parameters)
6629        << FnDecl->getDeclName();
6630
6631  // The function decl must have at least 1 parameter.
6632  if (FnDecl->getNumParams() == 0)
6633    return SemaRef.Diag(FnDecl->getLocation(),
6634                        diag::err_operator_new_delete_too_few_parameters)
6635      << FnDecl->getDeclName();
6636
6637  // Check the the first parameter type is not dependent.
6638  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6639  if (FirstParamType->isDependentType())
6640    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6641      << FnDecl->getDeclName() << ExpectedFirstParamType;
6642
6643  // Check that the first parameter type is what we expect.
6644  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
6645      ExpectedFirstParamType)
6646    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6647    << FnDecl->getDeclName() << ExpectedFirstParamType;
6648
6649  return false;
6650}
6651
6652static bool
6653CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6654  // C++ [basic.stc.dynamic.allocation]p1:
6655  //   A program is ill-formed if an allocation function is declared in a
6656  //   namespace scope other than global scope or declared static in global
6657  //   scope.
6658  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6659    return true;
6660
6661  CanQualType SizeTy =
6662    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
6663
6664  // C++ [basic.stc.dynamic.allocation]p1:
6665  //  The return type shall be void*. The first parameter shall have type
6666  //  std::size_t.
6667  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
6668                                  SizeTy,
6669                                  diag::err_operator_new_dependent_param_type,
6670                                  diag::err_operator_new_param_type))
6671    return true;
6672
6673  // C++ [basic.stc.dynamic.allocation]p1:
6674  //  The first parameter shall not have an associated default argument.
6675  if (FnDecl->getParamDecl(0)->hasDefaultArg())
6676    return SemaRef.Diag(FnDecl->getLocation(),
6677                        diag::err_operator_new_default_arg)
6678      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
6679
6680  return false;
6681}
6682
6683static bool
6684CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6685  // C++ [basic.stc.dynamic.deallocation]p1:
6686  //   A program is ill-formed if deallocation functions are declared in a
6687  //   namespace scope other than global scope or declared static in global
6688  //   scope.
6689  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6690    return true;
6691
6692  // C++ [basic.stc.dynamic.deallocation]p2:
6693  //   Each deallocation function shall return void and its first parameter
6694  //   shall be void*.
6695  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6696                                  SemaRef.Context.VoidPtrTy,
6697                                 diag::err_operator_delete_dependent_param_type,
6698                                 diag::err_operator_delete_param_type))
6699    return true;
6700
6701  return false;
6702}
6703
6704/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6705/// of this overloaded operator is well-formed. If so, returns false;
6706/// otherwise, emits appropriate diagnostics and returns true.
6707bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
6708  assert(FnDecl && FnDecl->isOverloadedOperator() &&
6709         "Expected an overloaded operator declaration");
6710
6711  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6712
6713  // C++ [over.oper]p5:
6714  //   The allocation and deallocation functions, operator new,
6715  //   operator new[], operator delete and operator delete[], are
6716  //   described completely in 3.7.3. The attributes and restrictions
6717  //   found in the rest of this subclause do not apply to them unless
6718  //   explicitly stated in 3.7.3.
6719  if (Op == OO_Delete || Op == OO_Array_Delete)
6720    return CheckOperatorDeleteDeclaration(*this, FnDecl);
6721
6722  if (Op == OO_New || Op == OO_Array_New)
6723    return CheckOperatorNewDeclaration(*this, FnDecl);
6724
6725  // C++ [over.oper]p6:
6726  //   An operator function shall either be a non-static member
6727  //   function or be a non-member function and have at least one
6728  //   parameter whose type is a class, a reference to a class, an
6729  //   enumeration, or a reference to an enumeration.
6730  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6731    if (MethodDecl->isStatic())
6732      return Diag(FnDecl->getLocation(),
6733                  diag::err_operator_overload_static) << FnDecl->getDeclName();
6734  } else {
6735    bool ClassOrEnumParam = false;
6736    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6737                                   ParamEnd = FnDecl->param_end();
6738         Param != ParamEnd; ++Param) {
6739      QualType ParamType = (*Param)->getType().getNonReferenceType();
6740      if (ParamType->isDependentType() || ParamType->isRecordType() ||
6741          ParamType->isEnumeralType()) {
6742        ClassOrEnumParam = true;
6743        break;
6744      }
6745    }
6746
6747    if (!ClassOrEnumParam)
6748      return Diag(FnDecl->getLocation(),
6749                  diag::err_operator_overload_needs_class_or_enum)
6750        << FnDecl->getDeclName();
6751  }
6752
6753  // C++ [over.oper]p8:
6754  //   An operator function cannot have default arguments (8.3.6),
6755  //   except where explicitly stated below.
6756  //
6757  // Only the function-call operator allows default arguments
6758  // (C++ [over.call]p1).
6759  if (Op != OO_Call) {
6760    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6761         Param != FnDecl->param_end(); ++Param) {
6762      if ((*Param)->hasDefaultArg())
6763        return Diag((*Param)->getLocation(),
6764                    diag::err_operator_overload_default_arg)
6765          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
6766    }
6767  }
6768
6769  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6770    { false, false, false }
6771#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6772    , { Unary, Binary, MemberOnly }
6773#include "clang/Basic/OperatorKinds.def"
6774  };
6775
6776  bool CanBeUnaryOperator = OperatorUses[Op][0];
6777  bool CanBeBinaryOperator = OperatorUses[Op][1];
6778  bool MustBeMemberOperator = OperatorUses[Op][2];
6779
6780  // C++ [over.oper]p8:
6781  //   [...] Operator functions cannot have more or fewer parameters
6782  //   than the number required for the corresponding operator, as
6783  //   described in the rest of this subclause.
6784  unsigned NumParams = FnDecl->getNumParams()
6785                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
6786  if (Op != OO_Call &&
6787      ((NumParams == 1 && !CanBeUnaryOperator) ||
6788       (NumParams == 2 && !CanBeBinaryOperator) ||
6789       (NumParams < 1) || (NumParams > 2))) {
6790    // We have the wrong number of parameters.
6791    unsigned ErrorKind;
6792    if (CanBeUnaryOperator && CanBeBinaryOperator) {
6793      ErrorKind = 2;  // 2 -> unary or binary.
6794    } else if (CanBeUnaryOperator) {
6795      ErrorKind = 0;  // 0 -> unary
6796    } else {
6797      assert(CanBeBinaryOperator &&
6798             "All non-call overloaded operators are unary or binary!");
6799      ErrorKind = 1;  // 1 -> binary
6800    }
6801
6802    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
6803      << FnDecl->getDeclName() << NumParams << ErrorKind;
6804  }
6805
6806  // Overloaded operators other than operator() cannot be variadic.
6807  if (Op != OO_Call &&
6808      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
6809    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
6810      << FnDecl->getDeclName();
6811  }
6812
6813  // Some operators must be non-static member functions.
6814  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6815    return Diag(FnDecl->getLocation(),
6816                diag::err_operator_overload_must_be_member)
6817      << FnDecl->getDeclName();
6818  }
6819
6820  // C++ [over.inc]p1:
6821  //   The user-defined function called operator++ implements the
6822  //   prefix and postfix ++ operator. If this function is a member
6823  //   function with no parameters, or a non-member function with one
6824  //   parameter of class or enumeration type, it defines the prefix
6825  //   increment operator ++ for objects of that type. If the function
6826  //   is a member function with one parameter (which shall be of type
6827  //   int) or a non-member function with two parameters (the second
6828  //   of which shall be of type int), it defines the postfix
6829  //   increment operator ++ for objects of that type.
6830  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6831    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6832    bool ParamIsInt = false;
6833    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
6834      ParamIsInt = BT->getKind() == BuiltinType::Int;
6835
6836    if (!ParamIsInt)
6837      return Diag(LastParam->getLocation(),
6838                  diag::err_operator_overload_post_incdec_must_be_int)
6839        << LastParam->getType() << (Op == OO_MinusMinus);
6840  }
6841
6842  return false;
6843}
6844
6845/// CheckLiteralOperatorDeclaration - Check whether the declaration
6846/// of this literal operator function is well-formed. If so, returns
6847/// false; otherwise, emits appropriate diagnostics and returns true.
6848bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6849  DeclContext *DC = FnDecl->getDeclContext();
6850  Decl::Kind Kind = DC->getDeclKind();
6851  if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6852      Kind != Decl::LinkageSpec) {
6853    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6854      << FnDecl->getDeclName();
6855    return true;
6856  }
6857
6858  bool Valid = false;
6859
6860  // template <char...> type operator "" name() is the only valid template
6861  // signature, and the only valid signature with no parameters.
6862  if (FnDecl->param_size() == 0) {
6863    if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6864      // Must have only one template parameter
6865      TemplateParameterList *Params = TpDecl->getTemplateParameters();
6866      if (Params->size() == 1) {
6867        NonTypeTemplateParmDecl *PmDecl =
6868          cast<NonTypeTemplateParmDecl>(Params->getParam(0));
6869
6870        // The template parameter must be a char parameter pack.
6871        if (PmDecl && PmDecl->isTemplateParameterPack() &&
6872            Context.hasSameType(PmDecl->getType(), Context.CharTy))
6873          Valid = true;
6874      }
6875    }
6876  } else {
6877    // Check the first parameter
6878    FunctionDecl::param_iterator Param = FnDecl->param_begin();
6879
6880    QualType T = (*Param)->getType();
6881
6882    // unsigned long long int, long double, and any character type are allowed
6883    // as the only parameters.
6884    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6885        Context.hasSameType(T, Context.LongDoubleTy) ||
6886        Context.hasSameType(T, Context.CharTy) ||
6887        Context.hasSameType(T, Context.WCharTy) ||
6888        Context.hasSameType(T, Context.Char16Ty) ||
6889        Context.hasSameType(T, Context.Char32Ty)) {
6890      if (++Param == FnDecl->param_end())
6891        Valid = true;
6892      goto FinishedParams;
6893    }
6894
6895    // Otherwise it must be a pointer to const; let's strip those qualifiers.
6896    const PointerType *PT = T->getAs<PointerType>();
6897    if (!PT)
6898      goto FinishedParams;
6899    T = PT->getPointeeType();
6900    if (!T.isConstQualified())
6901      goto FinishedParams;
6902    T = T.getUnqualifiedType();
6903
6904    // Move on to the second parameter;
6905    ++Param;
6906
6907    // If there is no second parameter, the first must be a const char *
6908    if (Param == FnDecl->param_end()) {
6909      if (Context.hasSameType(T, Context.CharTy))
6910        Valid = true;
6911      goto FinishedParams;
6912    }
6913
6914    // const char *, const wchar_t*, const char16_t*, and const char32_t*
6915    // are allowed as the first parameter to a two-parameter function
6916    if (!(Context.hasSameType(T, Context.CharTy) ||
6917          Context.hasSameType(T, Context.WCharTy) ||
6918          Context.hasSameType(T, Context.Char16Ty) ||
6919          Context.hasSameType(T, Context.Char32Ty)))
6920      goto FinishedParams;
6921
6922    // The second and final parameter must be an std::size_t
6923    T = (*Param)->getType().getUnqualifiedType();
6924    if (Context.hasSameType(T, Context.getSizeType()) &&
6925        ++Param == FnDecl->param_end())
6926      Valid = true;
6927  }
6928
6929  // FIXME: This diagnostic is absolutely terrible.
6930FinishedParams:
6931  if (!Valid) {
6932    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6933      << FnDecl->getDeclName();
6934    return true;
6935  }
6936
6937  return false;
6938}
6939
6940/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6941/// linkage specification, including the language and (if present)
6942/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6943/// the location of the language string literal, which is provided
6944/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6945/// the '{' brace. Otherwise, this linkage specification does not
6946/// have any braces.
6947Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6948                                           SourceLocation LangLoc,
6949                                           llvm::StringRef Lang,
6950                                           SourceLocation LBraceLoc) {
6951  LinkageSpecDecl::LanguageIDs Language;
6952  if (Lang == "\"C\"")
6953    Language = LinkageSpecDecl::lang_c;
6954  else if (Lang == "\"C++\"")
6955    Language = LinkageSpecDecl::lang_cxx;
6956  else {
6957    Diag(LangLoc, diag::err_bad_language);
6958    return 0;
6959  }
6960
6961  // FIXME: Add all the various semantics of linkage specifications
6962
6963  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
6964                                               ExternLoc, LangLoc, Language);
6965  CurContext->addDecl(D);
6966  PushDeclContext(S, D);
6967  return D;
6968}
6969
6970/// ActOnFinishLinkageSpecification - Complete the definition of
6971/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6972/// valid, it's the position of the closing '}' brace in a linkage
6973/// specification that uses braces.
6974Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
6975                                            Decl *LinkageSpec,
6976                                            SourceLocation RBraceLoc) {
6977  if (LinkageSpec) {
6978    if (RBraceLoc.isValid()) {
6979      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
6980      LSDecl->setRBraceLoc(RBraceLoc);
6981    }
6982    PopDeclContext();
6983  }
6984  return LinkageSpec;
6985}
6986
6987/// \brief Perform semantic analysis for the variable declaration that
6988/// occurs within a C++ catch clause, returning the newly-created
6989/// variable.
6990VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
6991                                         TypeSourceInfo *TInfo,
6992                                         SourceLocation StartLoc,
6993                                         SourceLocation Loc,
6994                                         IdentifierInfo *Name) {
6995  bool Invalid = false;
6996  QualType ExDeclType = TInfo->getType();
6997
6998  // Arrays and functions decay.
6999  if (ExDeclType->isArrayType())
7000    ExDeclType = Context.getArrayDecayedType(ExDeclType);
7001  else if (ExDeclType->isFunctionType())
7002    ExDeclType = Context.getPointerType(ExDeclType);
7003
7004  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
7005  // The exception-declaration shall not denote a pointer or reference to an
7006  // incomplete type, other than [cv] void*.
7007  // N2844 forbids rvalue references.
7008  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
7009    Diag(Loc, diag::err_catch_rvalue_ref);
7010    Invalid = true;
7011  }
7012
7013  // GCC allows catching pointers and references to incomplete types
7014  // as an extension; so do we, but we warn by default.
7015
7016  QualType BaseType = ExDeclType;
7017  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
7018  unsigned DK = diag::err_catch_incomplete;
7019  bool IncompleteCatchIsInvalid = true;
7020  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
7021    BaseType = Ptr->getPointeeType();
7022    Mode = 1;
7023    DK = diag::ext_catch_incomplete_ptr;
7024    IncompleteCatchIsInvalid = false;
7025  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
7026    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
7027    BaseType = Ref->getPointeeType();
7028    Mode = 2;
7029    DK = diag::ext_catch_incomplete_ref;
7030    IncompleteCatchIsInvalid = false;
7031  }
7032  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
7033      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
7034      IncompleteCatchIsInvalid)
7035    Invalid = true;
7036
7037  if (!Invalid && !ExDeclType->isDependentType() &&
7038      RequireNonAbstractType(Loc, ExDeclType,
7039                             diag::err_abstract_type_in_decl,
7040                             AbstractVariableType))
7041    Invalid = true;
7042
7043  // Only the non-fragile NeXT runtime currently supports C++ catches
7044  // of ObjC types, and no runtime supports catching ObjC types by value.
7045  if (!Invalid && getLangOptions().ObjC1) {
7046    QualType T = ExDeclType;
7047    if (const ReferenceType *RT = T->getAs<ReferenceType>())
7048      T = RT->getPointeeType();
7049
7050    if (T->isObjCObjectType()) {
7051      Diag(Loc, diag::err_objc_object_catch);
7052      Invalid = true;
7053    } else if (T->isObjCObjectPointerType()) {
7054      if (!getLangOptions().ObjCNonFragileABI) {
7055        Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
7056        Invalid = true;
7057      }
7058    }
7059  }
7060
7061  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
7062                                    ExDeclType, TInfo, SC_None, SC_None);
7063  ExDecl->setExceptionVariable(true);
7064
7065  if (!Invalid) {
7066    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
7067      // C++ [except.handle]p16:
7068      //   The object declared in an exception-declaration or, if the
7069      //   exception-declaration does not specify a name, a temporary (12.2) is
7070      //   copy-initialized (8.5) from the exception object. [...]
7071      //   The object is destroyed when the handler exits, after the destruction
7072      //   of any automatic objects initialized within the handler.
7073      //
7074      // We just pretend to initialize the object with itself, then make sure
7075      // it can be destroyed later.
7076      QualType initType = ExDeclType;
7077
7078      InitializedEntity entity =
7079        InitializedEntity::InitializeVariable(ExDecl);
7080      InitializationKind initKind =
7081        InitializationKind::CreateCopy(Loc, SourceLocation());
7082
7083      Expr *opaqueValue =
7084        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
7085      InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
7086      ExprResult result = sequence.Perform(*this, entity, initKind,
7087                                           MultiExprArg(&opaqueValue, 1));
7088      if (result.isInvalid())
7089        Invalid = true;
7090      else {
7091        // If the constructor used was non-trivial, set this as the
7092        // "initializer".
7093        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
7094        if (!construct->getConstructor()->isTrivial()) {
7095          Expr *init = MaybeCreateExprWithCleanups(construct);
7096          ExDecl->setInit(init);
7097        }
7098
7099        // And make sure it's destructable.
7100        FinalizeVarWithDestructor(ExDecl, recordType);
7101      }
7102    }
7103  }
7104
7105  if (Invalid)
7106    ExDecl->setInvalidDecl();
7107
7108  return ExDecl;
7109}
7110
7111/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
7112/// handler.
7113Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
7114  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7115  bool Invalid = D.isInvalidType();
7116
7117  // Check for unexpanded parameter packs.
7118  if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
7119                                               UPPC_ExceptionType)) {
7120    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7121                                             D.getIdentifierLoc());
7122    Invalid = true;
7123  }
7124
7125  IdentifierInfo *II = D.getIdentifier();
7126  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
7127                                             LookupOrdinaryName,
7128                                             ForRedeclaration)) {
7129    // The scope should be freshly made just for us. There is just no way
7130    // it contains any previous declaration.
7131    assert(!S->isDeclScope(PrevDecl));
7132    if (PrevDecl->isTemplateParameter()) {
7133      // Maybe we will complain about the shadowed template parameter.
7134      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
7135    }
7136  }
7137
7138  if (D.getCXXScopeSpec().isSet() && !Invalid) {
7139    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
7140      << D.getCXXScopeSpec().getRange();
7141    Invalid = true;
7142  }
7143
7144  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
7145                                              D.getSourceRange().getBegin(),
7146                                              D.getIdentifierLoc(),
7147                                              D.getIdentifier());
7148  if (Invalid)
7149    ExDecl->setInvalidDecl();
7150
7151  // Add the exception declaration into this scope.
7152  if (II)
7153    PushOnScopeChains(ExDecl, S);
7154  else
7155    CurContext->addDecl(ExDecl);
7156
7157  ProcessDeclAttributes(S, ExDecl, D);
7158  return ExDecl;
7159}
7160
7161Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7162                                         Expr *AssertExpr,
7163                                         Expr *AssertMessageExpr_,
7164                                         SourceLocation RParenLoc) {
7165  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
7166
7167  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
7168    llvm::APSInt Value(32);
7169    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
7170      Diag(StaticAssertLoc,
7171           diag::err_static_assert_expression_is_not_constant) <<
7172        AssertExpr->getSourceRange();
7173      return 0;
7174    }
7175
7176    if (Value == 0) {
7177      Diag(StaticAssertLoc, diag::err_static_assert_failed)
7178        << AssertMessage->getString() << AssertExpr->getSourceRange();
7179    }
7180  }
7181
7182  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
7183    return 0;
7184
7185  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
7186                                        AssertExpr, AssertMessage, RParenLoc);
7187
7188  CurContext->addDecl(Decl);
7189  return Decl;
7190}
7191
7192/// \brief Perform semantic analysis of the given friend type declaration.
7193///
7194/// \returns A friend declaration that.
7195FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
7196                                      TypeSourceInfo *TSInfo) {
7197  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
7198
7199  QualType T = TSInfo->getType();
7200  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
7201
7202  if (!getLangOptions().CPlusPlus0x) {
7203    // C++03 [class.friend]p2:
7204    //   An elaborated-type-specifier shall be used in a friend declaration
7205    //   for a class.*
7206    //
7207    //   * The class-key of the elaborated-type-specifier is required.
7208    if (!ActiveTemplateInstantiations.empty()) {
7209      // Do not complain about the form of friend template types during
7210      // template instantiation; we will already have complained when the
7211      // template was declared.
7212    } else if (!T->isElaboratedTypeSpecifier()) {
7213      // If we evaluated the type to a record type, suggest putting
7214      // a tag in front.
7215      if (const RecordType *RT = T->getAs<RecordType>()) {
7216        RecordDecl *RD = RT->getDecl();
7217
7218        std::string InsertionText = std::string(" ") + RD->getKindName();
7219
7220        Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
7221          << (unsigned) RD->getTagKind()
7222          << T
7223          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
7224                                        InsertionText);
7225      } else {
7226        Diag(FriendLoc, diag::ext_nonclass_type_friend)
7227          << T
7228          << SourceRange(FriendLoc, TypeRange.getEnd());
7229      }
7230    } else if (T->getAs<EnumType>()) {
7231      Diag(FriendLoc, diag::ext_enum_friend)
7232        << T
7233        << SourceRange(FriendLoc, TypeRange.getEnd());
7234    }
7235  }
7236
7237  // C++0x [class.friend]p3:
7238  //   If the type specifier in a friend declaration designates a (possibly
7239  //   cv-qualified) class type, that class is declared as a friend; otherwise,
7240  //   the friend declaration is ignored.
7241
7242  // FIXME: C++0x has some syntactic restrictions on friend type declarations
7243  // in [class.friend]p3 that we do not implement.
7244
7245  return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
7246}
7247
7248/// Handle a friend tag declaration where the scope specifier was
7249/// templated.
7250Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
7251                                    unsigned TagSpec, SourceLocation TagLoc,
7252                                    CXXScopeSpec &SS,
7253                                    IdentifierInfo *Name, SourceLocation NameLoc,
7254                                    AttributeList *Attr,
7255                                    MultiTemplateParamsArg TempParamLists) {
7256  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7257
7258  bool isExplicitSpecialization = false;
7259  bool Invalid = false;
7260
7261  if (TemplateParameterList *TemplateParams
7262        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
7263                                                  TempParamLists.get(),
7264                                                  TempParamLists.size(),
7265                                                  /*friend*/ true,
7266                                                  isExplicitSpecialization,
7267                                                  Invalid)) {
7268    if (TemplateParams->size() > 0) {
7269      // This is a declaration of a class template.
7270      if (Invalid)
7271        return 0;
7272
7273      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
7274                                SS, Name, NameLoc, Attr,
7275                                TemplateParams, AS_public,
7276                                TempParamLists.size() - 1,
7277                   (TemplateParameterList**) TempParamLists.release()).take();
7278    } else {
7279      // The "template<>" header is extraneous.
7280      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
7281        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
7282      isExplicitSpecialization = true;
7283    }
7284  }
7285
7286  if (Invalid) return 0;
7287
7288  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
7289
7290  bool isAllExplicitSpecializations = true;
7291  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
7292    if (TempParamLists.get()[I]->size()) {
7293      isAllExplicitSpecializations = false;
7294      break;
7295    }
7296  }
7297
7298  // FIXME: don't ignore attributes.
7299
7300  // If it's explicit specializations all the way down, just forget
7301  // about the template header and build an appropriate non-templated
7302  // friend.  TODO: for source fidelity, remember the headers.
7303  if (isAllExplicitSpecializations) {
7304    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7305    ElaboratedTypeKeyword Keyword
7306      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7307    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
7308                                   *Name, NameLoc);
7309    if (T.isNull())
7310      return 0;
7311
7312    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7313    if (isa<DependentNameType>(T)) {
7314      DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7315      TL.setKeywordLoc(TagLoc);
7316      TL.setQualifierLoc(QualifierLoc);
7317      TL.setNameLoc(NameLoc);
7318    } else {
7319      ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
7320      TL.setKeywordLoc(TagLoc);
7321      TL.setQualifierLoc(QualifierLoc);
7322      cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
7323    }
7324
7325    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7326                                            TSI, FriendLoc);
7327    Friend->setAccess(AS_public);
7328    CurContext->addDecl(Friend);
7329    return Friend;
7330  }
7331
7332  // Handle the case of a templated-scope friend class.  e.g.
7333  //   template <class T> class A<T>::B;
7334  // FIXME: we don't support these right now.
7335  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7336  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
7337  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7338  DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7339  TL.setKeywordLoc(TagLoc);
7340  TL.setQualifierLoc(SS.getWithLocInContext(Context));
7341  TL.setNameLoc(NameLoc);
7342
7343  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7344                                          TSI, FriendLoc);
7345  Friend->setAccess(AS_public);
7346  Friend->setUnsupportedFriend(true);
7347  CurContext->addDecl(Friend);
7348  return Friend;
7349}
7350
7351
7352/// Handle a friend type declaration.  This works in tandem with
7353/// ActOnTag.
7354///
7355/// Notes on friend class templates:
7356///
7357/// We generally treat friend class declarations as if they were
7358/// declaring a class.  So, for example, the elaborated type specifier
7359/// in a friend declaration is required to obey the restrictions of a
7360/// class-head (i.e. no typedefs in the scope chain), template
7361/// parameters are required to match up with simple template-ids, &c.
7362/// However, unlike when declaring a template specialization, it's
7363/// okay to refer to a template specialization without an empty
7364/// template parameter declaration, e.g.
7365///   friend class A<T>::B<unsigned>;
7366/// We permit this as a special case; if there are any template
7367/// parameters present at all, require proper matching, i.e.
7368///   template <> template <class T> friend class A<int>::B;
7369Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
7370                                MultiTemplateParamsArg TempParams) {
7371  SourceLocation Loc = DS.getSourceRange().getBegin();
7372
7373  assert(DS.isFriendSpecified());
7374  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7375
7376  // Try to convert the decl specifier to a type.  This works for
7377  // friend templates because ActOnTag never produces a ClassTemplateDecl
7378  // for a TUK_Friend.
7379  Declarator TheDeclarator(DS, Declarator::MemberContext);
7380  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
7381  QualType T = TSI->getType();
7382  if (TheDeclarator.isInvalidType())
7383    return 0;
7384
7385  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
7386    return 0;
7387
7388  // This is definitely an error in C++98.  It's probably meant to
7389  // be forbidden in C++0x, too, but the specification is just
7390  // poorly written.
7391  //
7392  // The problem is with declarations like the following:
7393  //   template <T> friend A<T>::foo;
7394  // where deciding whether a class C is a friend or not now hinges
7395  // on whether there exists an instantiation of A that causes
7396  // 'foo' to equal C.  There are restrictions on class-heads
7397  // (which we declare (by fiat) elaborated friend declarations to
7398  // be) that makes this tractable.
7399  //
7400  // FIXME: handle "template <> friend class A<T>;", which
7401  // is possibly well-formed?  Who even knows?
7402  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
7403    Diag(Loc, diag::err_tagless_friend_type_template)
7404      << DS.getSourceRange();
7405    return 0;
7406  }
7407
7408  // C++98 [class.friend]p1: A friend of a class is a function
7409  //   or class that is not a member of the class . . .
7410  // This is fixed in DR77, which just barely didn't make the C++03
7411  // deadline.  It's also a very silly restriction that seriously
7412  // affects inner classes and which nobody else seems to implement;
7413  // thus we never diagnose it, not even in -pedantic.
7414  //
7415  // But note that we could warn about it: it's always useless to
7416  // friend one of your own members (it's not, however, worthless to
7417  // friend a member of an arbitrary specialization of your template).
7418
7419  Decl *D;
7420  if (unsigned NumTempParamLists = TempParams.size())
7421    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
7422                                   NumTempParamLists,
7423                                   TempParams.release(),
7424                                   TSI,
7425                                   DS.getFriendSpecLoc());
7426  else
7427    D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
7428
7429  if (!D)
7430    return 0;
7431
7432  D->setAccess(AS_public);
7433  CurContext->addDecl(D);
7434
7435  return D;
7436}
7437
7438Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
7439                                    MultiTemplateParamsArg TemplateParams) {
7440  const DeclSpec &DS = D.getDeclSpec();
7441
7442  assert(DS.isFriendSpecified());
7443  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7444
7445  SourceLocation Loc = D.getIdentifierLoc();
7446  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7447  QualType T = TInfo->getType();
7448
7449  // C++ [class.friend]p1
7450  //   A friend of a class is a function or class....
7451  // Note that this sees through typedefs, which is intended.
7452  // It *doesn't* see through dependent types, which is correct
7453  // according to [temp.arg.type]p3:
7454  //   If a declaration acquires a function type through a
7455  //   type dependent on a template-parameter and this causes
7456  //   a declaration that does not use the syntactic form of a
7457  //   function declarator to have a function type, the program
7458  //   is ill-formed.
7459  if (!T->isFunctionType()) {
7460    Diag(Loc, diag::err_unexpected_friend);
7461
7462    // It might be worthwhile to try to recover by creating an
7463    // appropriate declaration.
7464    return 0;
7465  }
7466
7467  // C++ [namespace.memdef]p3
7468  //  - If a friend declaration in a non-local class first declares a
7469  //    class or function, the friend class or function is a member
7470  //    of the innermost enclosing namespace.
7471  //  - The name of the friend is not found by simple name lookup
7472  //    until a matching declaration is provided in that namespace
7473  //    scope (either before or after the class declaration granting
7474  //    friendship).
7475  //  - If a friend function is called, its name may be found by the
7476  //    name lookup that considers functions from namespaces and
7477  //    classes associated with the types of the function arguments.
7478  //  - When looking for a prior declaration of a class or a function
7479  //    declared as a friend, scopes outside the innermost enclosing
7480  //    namespace scope are not considered.
7481
7482  CXXScopeSpec &SS = D.getCXXScopeSpec();
7483  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7484  DeclarationName Name = NameInfo.getName();
7485  assert(Name);
7486
7487  // Check for unexpanded parameter packs.
7488  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7489      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7490      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7491    return 0;
7492
7493  // The context we found the declaration in, or in which we should
7494  // create the declaration.
7495  DeclContext *DC;
7496  Scope *DCScope = S;
7497  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
7498                        ForRedeclaration);
7499
7500  // FIXME: there are different rules in local classes
7501
7502  // There are four cases here.
7503  //   - There's no scope specifier, in which case we just go to the
7504  //     appropriate scope and look for a function or function template
7505  //     there as appropriate.
7506  // Recover from invalid scope qualifiers as if they just weren't there.
7507  if (SS.isInvalid() || !SS.isSet()) {
7508    // C++0x [namespace.memdef]p3:
7509    //   If the name in a friend declaration is neither qualified nor
7510    //   a template-id and the declaration is a function or an
7511    //   elaborated-type-specifier, the lookup to determine whether
7512    //   the entity has been previously declared shall not consider
7513    //   any scopes outside the innermost enclosing namespace.
7514    // C++0x [class.friend]p11:
7515    //   If a friend declaration appears in a local class and the name
7516    //   specified is an unqualified name, a prior declaration is
7517    //   looked up without considering scopes that are outside the
7518    //   innermost enclosing non-class scope. For a friend function
7519    //   declaration, if there is no prior declaration, the program is
7520    //   ill-formed.
7521    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
7522    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
7523
7524    // Find the appropriate context according to the above.
7525    DC = CurContext;
7526    while (true) {
7527      // Skip class contexts.  If someone can cite chapter and verse
7528      // for this behavior, that would be nice --- it's what GCC and
7529      // EDG do, and it seems like a reasonable intent, but the spec
7530      // really only says that checks for unqualified existing
7531      // declarations should stop at the nearest enclosing namespace,
7532      // not that they should only consider the nearest enclosing
7533      // namespace.
7534      while (DC->isRecord())
7535        DC = DC->getParent();
7536
7537      LookupQualifiedName(Previous, DC);
7538
7539      // TODO: decide what we think about using declarations.
7540      if (isLocal || !Previous.empty())
7541        break;
7542
7543      if (isTemplateId) {
7544        if (isa<TranslationUnitDecl>(DC)) break;
7545      } else {
7546        if (DC->isFileContext()) break;
7547      }
7548      DC = DC->getParent();
7549    }
7550
7551    // C++ [class.friend]p1: A friend of a class is a function or
7552    //   class that is not a member of the class . . .
7553    // C++0x changes this for both friend types and functions.
7554    // Most C++ 98 compilers do seem to give an error here, so
7555    // we do, too.
7556    if (!Previous.empty() && DC->Equals(CurContext)
7557        && !getLangOptions().CPlusPlus0x)
7558      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7559
7560    DCScope = getScopeForDeclContext(S, DC);
7561
7562  //   - There's a non-dependent scope specifier, in which case we
7563  //     compute it and do a previous lookup there for a function
7564  //     or function template.
7565  } else if (!SS.getScopeRep()->isDependent()) {
7566    DC = computeDeclContext(SS);
7567    if (!DC) return 0;
7568
7569    if (RequireCompleteDeclContext(SS, DC)) return 0;
7570
7571    LookupQualifiedName(Previous, DC);
7572
7573    // Ignore things found implicitly in the wrong scope.
7574    // TODO: better diagnostics for this case.  Suggesting the right
7575    // qualified scope would be nice...
7576    LookupResult::Filter F = Previous.makeFilter();
7577    while (F.hasNext()) {
7578      NamedDecl *D = F.next();
7579      if (!DC->InEnclosingNamespaceSetOf(
7580              D->getDeclContext()->getRedeclContext()))
7581        F.erase();
7582    }
7583    F.done();
7584
7585    if (Previous.empty()) {
7586      D.setInvalidType();
7587      Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7588      return 0;
7589    }
7590
7591    // C++ [class.friend]p1: A friend of a class is a function or
7592    //   class that is not a member of the class . . .
7593    if (DC->Equals(CurContext))
7594      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7595
7596  //   - There's a scope specifier that does not match any template
7597  //     parameter lists, in which case we use some arbitrary context,
7598  //     create a method or method template, and wait for instantiation.
7599  //   - There's a scope specifier that does match some template
7600  //     parameter lists, which we don't handle right now.
7601  } else {
7602    DC = CurContext;
7603    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
7604  }
7605
7606  if (!DC->isRecord()) {
7607    // This implies that it has to be an operator or function.
7608    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7609        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7610        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
7611      Diag(Loc, diag::err_introducing_special_friend) <<
7612        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7613         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
7614      return 0;
7615    }
7616  }
7617
7618  bool Redeclaration = false;
7619  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
7620                                          move(TemplateParams),
7621                                          IsDefinition,
7622                                          Redeclaration);
7623  if (!ND) return 0;
7624
7625  assert(ND->getDeclContext() == DC);
7626  assert(ND->getLexicalDeclContext() == CurContext);
7627
7628  // Add the function declaration to the appropriate lookup tables,
7629  // adjusting the redeclarations list as necessary.  We don't
7630  // want to do this yet if the friending class is dependent.
7631  //
7632  // Also update the scope-based lookup if the target context's
7633  // lookup context is in lexical scope.
7634  if (!CurContext->isDependentContext()) {
7635    DC = DC->getRedeclContext();
7636    DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
7637    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
7638      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
7639  }
7640
7641  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
7642                                       D.getIdentifierLoc(), ND,
7643                                       DS.getFriendSpecLoc());
7644  FrD->setAccess(AS_public);
7645  CurContext->addDecl(FrD);
7646
7647  if (ND->isInvalidDecl())
7648    FrD->setInvalidDecl();
7649  else {
7650    FunctionDecl *FD;
7651    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7652      FD = FTD->getTemplatedDecl();
7653    else
7654      FD = cast<FunctionDecl>(ND);
7655
7656    // Mark templated-scope function declarations as unsupported.
7657    if (FD->getNumTemplateParameterLists())
7658      FrD->setUnsupportedFriend(true);
7659  }
7660
7661  return ND;
7662}
7663
7664void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
7665  AdjustDeclIfTemplate(Dcl);
7666
7667  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
7668  if (!Fn) {
7669    Diag(DelLoc, diag::err_deleted_non_function);
7670    return;
7671  }
7672  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
7673    Diag(DelLoc, diag::err_deleted_decl_not_first);
7674    Diag(Prev->getLocation(), diag::note_previous_declaration);
7675    // If the declaration wasn't the first, we delete the function anyway for
7676    // recovery.
7677  }
7678  Fn->setDeletedAsWritten();
7679}
7680
7681static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
7682  for (Stmt::child_range CI = S->children(); CI; ++CI) {
7683    Stmt *SubStmt = *CI;
7684    if (!SubStmt)
7685      continue;
7686    if (isa<ReturnStmt>(SubStmt))
7687      Self.Diag(SubStmt->getSourceRange().getBegin(),
7688           diag::err_return_in_constructor_handler);
7689    if (!isa<Expr>(SubStmt))
7690      SearchForReturnInStmt(Self, SubStmt);
7691  }
7692}
7693
7694void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
7695  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
7696    CXXCatchStmt *Handler = TryBlock->getHandler(I);
7697    SearchForReturnInStmt(*this, Handler);
7698  }
7699}
7700
7701bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
7702                                             const CXXMethodDecl *Old) {
7703  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7704  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
7705
7706  if (Context.hasSameType(NewTy, OldTy) ||
7707      NewTy->isDependentType() || OldTy->isDependentType())
7708    return false;
7709
7710  // Check if the return types are covariant
7711  QualType NewClassTy, OldClassTy;
7712
7713  /// Both types must be pointers or references to classes.
7714  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7715    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
7716      NewClassTy = NewPT->getPointeeType();
7717      OldClassTy = OldPT->getPointeeType();
7718    }
7719  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7720    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7721      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7722        NewClassTy = NewRT->getPointeeType();
7723        OldClassTy = OldRT->getPointeeType();
7724      }
7725    }
7726  }
7727
7728  // The return types aren't either both pointers or references to a class type.
7729  if (NewClassTy.isNull()) {
7730    Diag(New->getLocation(),
7731         diag::err_different_return_type_for_overriding_virtual_function)
7732      << New->getDeclName() << NewTy << OldTy;
7733    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7734
7735    return true;
7736  }
7737
7738  // C++ [class.virtual]p6:
7739  //   If the return type of D::f differs from the return type of B::f, the
7740  //   class type in the return type of D::f shall be complete at the point of
7741  //   declaration of D::f or shall be the class type D.
7742  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7743    if (!RT->isBeingDefined() &&
7744        RequireCompleteType(New->getLocation(), NewClassTy,
7745                            PDiag(diag::err_covariant_return_incomplete)
7746                              << New->getDeclName()))
7747    return true;
7748  }
7749
7750  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
7751    // Check if the new class derives from the old class.
7752    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7753      Diag(New->getLocation(),
7754           diag::err_covariant_return_not_derived)
7755      << New->getDeclName() << NewTy << OldTy;
7756      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7757      return true;
7758    }
7759
7760    // Check if we the conversion from derived to base is valid.
7761    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
7762                    diag::err_covariant_return_inaccessible_base,
7763                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
7764                    // FIXME: Should this point to the return type?
7765                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
7766      // FIXME: this note won't trigger for delayed access control
7767      // diagnostics, and it's impossible to get an undelayed error
7768      // here from access control during the original parse because
7769      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
7770      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7771      return true;
7772    }
7773  }
7774
7775  // The qualifiers of the return types must be the same.
7776  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
7777    Diag(New->getLocation(),
7778         diag::err_covariant_return_type_different_qualifications)
7779    << New->getDeclName() << NewTy << OldTy;
7780    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7781    return true;
7782  };
7783
7784
7785  // The new class type must have the same or less qualifiers as the old type.
7786  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
7787    Diag(New->getLocation(),
7788         diag::err_covariant_return_type_class_type_more_qualified)
7789    << New->getDeclName() << NewTy << OldTy;
7790    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7791    return true;
7792  };
7793
7794  return false;
7795}
7796
7797/// \brief Mark the given method pure.
7798///
7799/// \param Method the method to be marked pure.
7800///
7801/// \param InitRange the source range that covers the "0" initializer.
7802bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
7803  SourceLocation EndLoc = InitRange.getEnd();
7804  if (EndLoc.isValid())
7805    Method->setRangeEnd(EndLoc);
7806
7807  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
7808    Method->setPure();
7809    return false;
7810  }
7811
7812  if (!Method->isInvalidDecl())
7813    Diag(Method->getLocation(), diag::err_non_virtual_pure)
7814      << Method->getDeclName() << InitRange;
7815  return true;
7816}
7817
7818/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7819/// an initializer for the out-of-line declaration 'Dcl'.  The scope
7820/// is a fresh scope pushed for just this purpose.
7821///
7822/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7823/// static data member of class X, names should be looked up in the scope of
7824/// class X.
7825void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
7826  // If there is no declaration, there was an error parsing it.
7827  if (D == 0 || D->isInvalidDecl()) return;
7828
7829  // We should only get called for declarations with scope specifiers, like:
7830  //   int foo::bar;
7831  assert(D->isOutOfLine());
7832  EnterDeclaratorContext(S, D->getDeclContext());
7833}
7834
7835/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
7836/// initializer for the out-of-line declaration 'D'.
7837void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
7838  // If there is no declaration, there was an error parsing it.
7839  if (D == 0 || D->isInvalidDecl()) return;
7840
7841  assert(D->isOutOfLine());
7842  ExitDeclaratorContext(S);
7843}
7844
7845/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7846/// C++ if/switch/while/for statement.
7847/// e.g: "if (int x = f()) {...}"
7848DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
7849  // C++ 6.4p2:
7850  // The declarator shall not specify a function or an array.
7851  // The type-specifier-seq shall not contain typedef and shall not declare a
7852  // new class or enumeration.
7853  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7854         "Parser allowed 'typedef' as storage class of condition decl.");
7855
7856  TagDecl *OwnedTag = 0;
7857  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7858  QualType Ty = TInfo->getType();
7859
7860  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7861                              // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7862                              // would be created and CXXConditionDeclExpr wants a VarDecl.
7863    Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7864      << D.getSourceRange();
7865    return DeclResult();
7866  } else if (OwnedTag && OwnedTag->isDefinition()) {
7867    // The type-specifier-seq shall not declare a new class or enumeration.
7868    Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7869  }
7870
7871  Decl *Dcl = ActOnDeclarator(S, D);
7872  if (!Dcl)
7873    return DeclResult();
7874
7875  return Dcl;
7876}
7877
7878void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7879                          bool DefinitionRequired) {
7880  // Ignore any vtable uses in unevaluated operands or for classes that do
7881  // not have a vtable.
7882  if (!Class->isDynamicClass() || Class->isDependentContext() ||
7883      CurContext->isDependentContext() ||
7884      ExprEvalContexts.back().Context == Unevaluated)
7885    return;
7886
7887  // Try to insert this class into the map.
7888  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7889  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7890    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7891  if (!Pos.second) {
7892    // If we already had an entry, check to see if we are promoting this vtable
7893    // to required a definition. If so, we need to reappend to the VTableUses
7894    // list, since we may have already processed the first entry.
7895    if (DefinitionRequired && !Pos.first->second) {
7896      Pos.first->second = true;
7897    } else {
7898      // Otherwise, we can early exit.
7899      return;
7900    }
7901  }
7902
7903  // Local classes need to have their virtual members marked
7904  // immediately. For all other classes, we mark their virtual members
7905  // at the end of the translation unit.
7906  if (Class->isLocalClass())
7907    MarkVirtualMembersReferenced(Loc, Class);
7908  else
7909    VTableUses.push_back(std::make_pair(Class, Loc));
7910}
7911
7912bool Sema::DefineUsedVTables() {
7913  if (VTableUses.empty())
7914    return false;
7915
7916  // Note: The VTableUses vector could grow as a result of marking
7917  // the members of a class as "used", so we check the size each
7918  // time through the loop and prefer indices (with are stable) to
7919  // iterators (which are not).
7920  bool DefinedAnything = false;
7921  for (unsigned I = 0; I != VTableUses.size(); ++I) {
7922    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
7923    if (!Class)
7924      continue;
7925
7926    SourceLocation Loc = VTableUses[I].second;
7927
7928    // If this class has a key function, but that key function is
7929    // defined in another translation unit, we don't need to emit the
7930    // vtable even though we're using it.
7931    const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
7932    if (KeyFunction && !KeyFunction->hasBody()) {
7933      switch (KeyFunction->getTemplateSpecializationKind()) {
7934      case TSK_Undeclared:
7935      case TSK_ExplicitSpecialization:
7936      case TSK_ExplicitInstantiationDeclaration:
7937        // The key function is in another translation unit.
7938        continue;
7939
7940      case TSK_ExplicitInstantiationDefinition:
7941      case TSK_ImplicitInstantiation:
7942        // We will be instantiating the key function.
7943        break;
7944      }
7945    } else if (!KeyFunction) {
7946      // If we have a class with no key function that is the subject
7947      // of an explicit instantiation declaration, suppress the
7948      // vtable; it will live with the explicit instantiation
7949      // definition.
7950      bool IsExplicitInstantiationDeclaration
7951        = Class->getTemplateSpecializationKind()
7952                                      == TSK_ExplicitInstantiationDeclaration;
7953      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7954                                 REnd = Class->redecls_end();
7955           R != REnd; ++R) {
7956        TemplateSpecializationKind TSK
7957          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7958        if (TSK == TSK_ExplicitInstantiationDeclaration)
7959          IsExplicitInstantiationDeclaration = true;
7960        else if (TSK == TSK_ExplicitInstantiationDefinition) {
7961          IsExplicitInstantiationDeclaration = false;
7962          break;
7963        }
7964      }
7965
7966      if (IsExplicitInstantiationDeclaration)
7967        continue;
7968    }
7969
7970    // Mark all of the virtual members of this class as referenced, so
7971    // that we can build a vtable. Then, tell the AST consumer that a
7972    // vtable for this class is required.
7973    DefinedAnything = true;
7974    MarkVirtualMembersReferenced(Loc, Class);
7975    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7976    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7977
7978    // Optionally warn if we're emitting a weak vtable.
7979    if (Class->getLinkage() == ExternalLinkage &&
7980        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
7981      if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
7982        Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7983    }
7984  }
7985  VTableUses.clear();
7986
7987  return DefinedAnything;
7988}
7989
7990void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7991                                        const CXXRecordDecl *RD) {
7992  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7993       e = RD->method_end(); i != e; ++i) {
7994    CXXMethodDecl *MD = *i;
7995
7996    // C++ [basic.def.odr]p2:
7997    //   [...] A virtual member function is used if it is not pure. [...]
7998    if (MD->isVirtual() && !MD->isPure())
7999      MarkDeclarationReferenced(Loc, MD);
8000  }
8001
8002  // Only classes that have virtual bases need a VTT.
8003  if (RD->getNumVBases() == 0)
8004    return;
8005
8006  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
8007           e = RD->bases_end(); i != e; ++i) {
8008    const CXXRecordDecl *Base =
8009        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
8010    if (Base->getNumVBases() == 0)
8011      continue;
8012    MarkVirtualMembersReferenced(Loc, Base);
8013  }
8014}
8015
8016/// SetIvarInitializers - This routine builds initialization ASTs for the
8017/// Objective-C implementation whose ivars need be initialized.
8018void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
8019  if (!getLangOptions().CPlusPlus)
8020    return;
8021  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
8022    llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
8023    CollectIvarsToConstructOrDestruct(OID, ivars);
8024    if (ivars.empty())
8025      return;
8026    llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
8027    for (unsigned i = 0; i < ivars.size(); i++) {
8028      FieldDecl *Field = ivars[i];
8029      if (Field->isInvalidDecl())
8030        continue;
8031
8032      CXXCtorInitializer *Member;
8033      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
8034      InitializationKind InitKind =
8035        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
8036
8037      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
8038      ExprResult MemberInit =
8039        InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
8040      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
8041      // Note, MemberInit could actually come back empty if no initialization
8042      // is required (e.g., because it would call a trivial default constructor)
8043      if (!MemberInit.get() || MemberInit.isInvalid())
8044        continue;
8045
8046      Member =
8047        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
8048                                         SourceLocation(),
8049                                         MemberInit.takeAs<Expr>(),
8050                                         SourceLocation());
8051      AllToInit.push_back(Member);
8052
8053      // Be sure that the destructor is accessible and is marked as referenced.
8054      if (const RecordType *RecordTy
8055                  = Context.getBaseElementType(Field->getType())
8056                                                        ->getAs<RecordType>()) {
8057                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
8058        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
8059          MarkDeclarationReferenced(Field->getLocation(), Destructor);
8060          CheckDestructorAccess(Field->getLocation(), Destructor,
8061                            PDiag(diag::err_access_dtor_ivar)
8062                              << Context.getBaseElementType(Field->getType()));
8063        }
8064      }
8065    }
8066    ObjCImplementation->setIvarInitializers(Context,
8067                                            AllToInit.data(), AllToInit.size());
8068  }
8069}
8070
8071static
8072void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
8073                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
8074                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
8075                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
8076                           Sema &S) {
8077  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
8078                                                   CE = Current.end();
8079  if (Ctor->isInvalidDecl())
8080    return;
8081
8082  const FunctionDecl *FNTarget = 0;
8083  CXXConstructorDecl *Target;
8084
8085  // We ignore the result here since if we don't have a body, Target will be
8086  // null below.
8087  (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
8088  Target
8089= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
8090
8091  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
8092                     // Avoid dereferencing a null pointer here.
8093                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
8094
8095  if (!Current.insert(Canonical))
8096    return;
8097
8098  // We know that beyond here, we aren't chaining into a cycle.
8099  if (!Target || !Target->isDelegatingConstructor() ||
8100      Target->isInvalidDecl() || Valid.count(TCanonical)) {
8101    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
8102      Valid.insert(*CI);
8103    Current.clear();
8104  // We've hit a cycle.
8105  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
8106             Current.count(TCanonical)) {
8107    // If we haven't diagnosed this cycle yet, do so now.
8108    if (!Invalid.count(TCanonical)) {
8109      S.Diag((*Ctor->init_begin())->getSourceLocation(),
8110             diag::warn_delegating_ctor_cycle)
8111        << Ctor;
8112
8113      // Don't add a note for a function delegating directo to itself.
8114      if (TCanonical != Canonical)
8115        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
8116
8117      CXXConstructorDecl *C = Target;
8118      while (C->getCanonicalDecl() != Canonical) {
8119        (void)C->getTargetConstructor()->hasBody(FNTarget);
8120        assert(FNTarget && "Ctor cycle through bodiless function");
8121
8122        C
8123       = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
8124        S.Diag(C->getLocation(), diag::note_which_delegates_to);
8125      }
8126    }
8127
8128    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
8129      Invalid.insert(*CI);
8130    Current.clear();
8131  } else {
8132    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
8133  }
8134}
8135
8136
8137void Sema::CheckDelegatingCtorCycles() {
8138  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
8139
8140  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
8141                                                   CE = Current.end();
8142
8143  for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
8144         I = DelegatingCtorDecls.begin(),
8145         E = DelegatingCtorDecls.end();
8146       I != E; ++I) {
8147   DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
8148  }
8149
8150  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
8151    (*CI)->setInvalidDecl();
8152}
8153