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