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