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