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