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