SemaDeclCXX.cpp revision 13c8577201e4fc0ddac5f09d05fd1778832137d1
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 "Sema.h"
15#include "SemaInit.h"
16#include "Lookup.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/DeclVisitor.h"
22#include "clang/AST/RecordLayout.h"
23#include "clang/AST/StmtVisitor.h"
24#include "clang/AST/TypeLoc.h"
25#include "clang/AST/TypeOrdering.h"
26#include "clang/Parse/DeclSpec.h"
27#include "clang/Parse/Template.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Lex/Preprocessor.h"
30#include "llvm/ADT/STLExtras.h"
31#include <map>
32#include <set>
33
34using namespace clang;
35
36//===----------------------------------------------------------------------===//
37// CheckDefaultArgumentVisitor
38//===----------------------------------------------------------------------===//
39
40namespace {
41  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
42  /// the default argument of a parameter to determine whether it
43  /// contains any ill-formed subexpressions. For example, this will
44  /// diagnose the use of local variables or parameters within the
45  /// default argument expression.
46  class CheckDefaultArgumentVisitor
47    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
48    Expr *DefaultArg;
49    Sema *S;
50
51  public:
52    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
53      : DefaultArg(defarg), S(s) {}
54
55    bool VisitExpr(Expr *Node);
56    bool VisitDeclRefExpr(DeclRefExpr *DRE);
57    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
58  };
59
60  /// VisitExpr - Visit all of the children of this expression.
61  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
62    bool IsInvalid = false;
63    for (Stmt::child_iterator I = Node->child_begin(),
64         E = Node->child_end(); I != E; ++I)
65      IsInvalid |= Visit(*I);
66    return IsInvalid;
67  }
68
69  /// VisitDeclRefExpr - Visit a reference to a declaration, to
70  /// determine whether this declaration can be used in the default
71  /// argument expression.
72  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
73    NamedDecl *Decl = DRE->getDecl();
74    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
75      // C++ [dcl.fct.default]p9
76      //   Default arguments are evaluated each time the function is
77      //   called. The order of evaluation of function arguments is
78      //   unspecified. Consequently, parameters of a function shall not
79      //   be used in default argument expressions, even if they are not
80      //   evaluated. Parameters of a function declared before a default
81      //   argument expression are in scope and can hide namespace and
82      //   class member names.
83      return S->Diag(DRE->getSourceRange().getBegin(),
84                     diag::err_param_default_argument_references_param)
85         << Param->getDeclName() << DefaultArg->getSourceRange();
86    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
87      // C++ [dcl.fct.default]p7
88      //   Local variables shall not be used in default argument
89      //   expressions.
90      if (VDecl->isBlockVarDecl())
91        return S->Diag(DRE->getSourceRange().getBegin(),
92                       diag::err_param_default_argument_references_local)
93          << VDecl->getDeclName() << DefaultArg->getSourceRange();
94    }
95
96    return false;
97  }
98
99  /// VisitCXXThisExpr - Visit a C++ "this" expression.
100  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
101    // C++ [dcl.fct.default]p8:
102    //   The keyword this shall not be used in a default argument of a
103    //   member function.
104    return S->Diag(ThisE->getSourceRange().getBegin(),
105                   diag::err_param_default_argument_references_this)
106               << ThisE->getSourceRange();
107  }
108}
109
110bool
111Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
112                              SourceLocation EqualLoc) {
113  if (RequireCompleteType(Param->getLocation(), Param->getType(),
114                          diag::err_typecheck_decl_incomplete_type)) {
115    Param->setInvalidDecl();
116    return true;
117  }
118
119  Expr *Arg = (Expr *)DefaultArg.get();
120
121  // C++ [dcl.fct.default]p5
122  //   A default argument expression is implicitly converted (clause
123  //   4) to the parameter type. The default argument expression has
124  //   the same semantic constraints as the initializer expression in
125  //   a declaration of a variable of the parameter type, using the
126  //   copy-initialization semantics (8.5).
127  InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
128  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
129                                                           EqualLoc);
130  InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
131  OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
132                                          MultiExprArg(*this, (void**)&Arg, 1));
133  if (Result.isInvalid())
134    return true;
135  Arg = Result.takeAs<Expr>();
136
137  Arg = MaybeCreateCXXExprWithTemporaries(Arg);
138
139  // Okay: add the default argument to the parameter
140  Param->setDefaultArg(Arg);
141
142  DefaultArg.release();
143
144  return false;
145}
146
147/// ActOnParamDefaultArgument - Check whether the default argument
148/// provided for a function parameter is well-formed. If so, attach it
149/// to the parameter declaration.
150void
151Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
152                                ExprArg defarg) {
153  if (!param || !defarg.get())
154    return;
155
156  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
157  UnparsedDefaultArgLocs.erase(Param);
158
159  ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
160
161  // Default arguments are only permitted in C++
162  if (!getLangOptions().CPlusPlus) {
163    Diag(EqualLoc, diag::err_param_default_argument)
164      << DefaultArg->getSourceRange();
165    Param->setInvalidDecl();
166    return;
167  }
168
169  // Check that the default argument is well-formed
170  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
171  if (DefaultArgChecker.Visit(DefaultArg.get())) {
172    Param->setInvalidDecl();
173    return;
174  }
175
176  SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
177}
178
179/// ActOnParamUnparsedDefaultArgument - We've seen a default
180/// argument for a function parameter, but we can't parse it yet
181/// because we're inside a class definition. Note that this default
182/// argument will be parsed later.
183void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
184                                             SourceLocation EqualLoc,
185                                             SourceLocation ArgLoc) {
186  if (!param)
187    return;
188
189  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
190  if (Param)
191    Param->setUnparsedDefaultArg();
192
193  UnparsedDefaultArgLocs[Param] = ArgLoc;
194}
195
196/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
197/// the default argument for the parameter param failed.
198void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
199  if (!param)
200    return;
201
202  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
203
204  Param->setInvalidDecl();
205
206  UnparsedDefaultArgLocs.erase(Param);
207}
208
209/// CheckExtraCXXDefaultArguments - Check for any extra default
210/// arguments in the declarator, which is not a function declaration
211/// or definition and therefore is not permitted to have default
212/// arguments. This routine should be invoked for every declarator
213/// that is not a function declaration or definition.
214void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
215  // C++ [dcl.fct.default]p3
216  //   A default argument expression shall be specified only in the
217  //   parameter-declaration-clause of a function declaration or in a
218  //   template-parameter (14.1). It shall not be specified for a
219  //   parameter pack. If it is specified in a
220  //   parameter-declaration-clause, it shall not occur within a
221  //   declarator or abstract-declarator of a parameter-declaration.
222  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
223    DeclaratorChunk &chunk = D.getTypeObject(i);
224    if (chunk.Kind == DeclaratorChunk::Function) {
225      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
226        ParmVarDecl *Param =
227          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
228        if (Param->hasUnparsedDefaultArg()) {
229          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
230          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
231            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
232          delete Toks;
233          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
234        } else if (Param->getDefaultArg()) {
235          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
236            << Param->getDefaultArg()->getSourceRange();
237          Param->setDefaultArg(0);
238        }
239      }
240    }
241  }
242}
243
244// MergeCXXFunctionDecl - Merge two declarations of the same C++
245// function, once we already know that they have the same
246// type. Subroutine of MergeFunctionDecl. Returns true if there was an
247// error, false otherwise.
248bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
249  bool Invalid = false;
250
251  // C++ [dcl.fct.default]p4:
252  //   For non-template functions, default arguments can be added in
253  //   later declarations of a function in the same
254  //   scope. Declarations in different scopes have completely
255  //   distinct sets of default arguments. That is, declarations in
256  //   inner scopes do not acquire default arguments from
257  //   declarations in outer scopes, and vice versa. In a given
258  //   function declaration, all parameters subsequent to a
259  //   parameter with a default argument shall have default
260  //   arguments supplied in this or previous declarations. A
261  //   default argument shall not be redefined by a later
262  //   declaration (not even to the same value).
263  //
264  // C++ [dcl.fct.default]p6:
265  //   Except for member functions of class templates, the default arguments
266  //   in a member function definition that appears outside of the class
267  //   definition are added to the set of default arguments provided by the
268  //   member function declaration in the class definition.
269  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
270    ParmVarDecl *OldParam = Old->getParamDecl(p);
271    ParmVarDecl *NewParam = New->getParamDecl(p);
272
273    if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
274      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
275      // hint here. Alternatively, we could walk the type-source information
276      // for NewParam to find the last source location in the type... but it
277      // isn't worth the effort right now. This is the kind of test case that
278      // is hard to get right:
279
280      //   int f(int);
281      //   void g(int (*fp)(int) = f);
282      //   void g(int (*fp)(int) = &f);
283      Diag(NewParam->getLocation(),
284           diag::err_param_default_argument_redefinition)
285        << NewParam->getDefaultArgRange();
286
287      // Look for the function declaration where the default argument was
288      // actually written, which may be a declaration prior to Old.
289      for (FunctionDecl *Older = Old->getPreviousDeclaration();
290           Older; Older = Older->getPreviousDeclaration()) {
291        if (!Older->getParamDecl(p)->hasDefaultArg())
292          break;
293
294        OldParam = Older->getParamDecl(p);
295      }
296
297      Diag(OldParam->getLocation(), diag::note_previous_definition)
298        << OldParam->getDefaultArgRange();
299      Invalid = true;
300    } else if (OldParam->hasDefaultArg()) {
301      // Merge the old default argument into the new parameter.
302      // It's important to use getInit() here;  getDefaultArg()
303      // strips off any top-level CXXExprWithTemporaries.
304      NewParam->setHasInheritedDefaultArg();
305      if (OldParam->hasUninstantiatedDefaultArg())
306        NewParam->setUninstantiatedDefaultArg(
307                                      OldParam->getUninstantiatedDefaultArg());
308      else
309        NewParam->setDefaultArg(OldParam->getInit());
310    } else if (NewParam->hasDefaultArg()) {
311      if (New->getDescribedFunctionTemplate()) {
312        // Paragraph 4, quoted above, only applies to non-template functions.
313        Diag(NewParam->getLocation(),
314             diag::err_param_default_argument_template_redecl)
315          << NewParam->getDefaultArgRange();
316        Diag(Old->getLocation(), diag::note_template_prev_declaration)
317          << false;
318      } else if (New->getTemplateSpecializationKind()
319                   != TSK_ImplicitInstantiation &&
320                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
321        // C++ [temp.expr.spec]p21:
322        //   Default function arguments shall not be specified in a declaration
323        //   or a definition for one of the following explicit specializations:
324        //     - the explicit specialization of a function template;
325        //     - the explicit specialization of a member function template;
326        //     - the explicit specialization of a member function of a class
327        //       template where the class template specialization to which the
328        //       member function specialization belongs is implicitly
329        //       instantiated.
330        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
331          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
332          << New->getDeclName()
333          << NewParam->getDefaultArgRange();
334      } else if (New->getDeclContext()->isDependentContext()) {
335        // C++ [dcl.fct.default]p6 (DR217):
336        //   Default arguments for a member function of a class template shall
337        //   be specified on the initial declaration of the member function
338        //   within the class template.
339        //
340        // Reading the tea leaves a bit in DR217 and its reference to DR205
341        // leads me to the conclusion that one cannot add default function
342        // arguments for an out-of-line definition of a member function of a
343        // dependent type.
344        int WhichKind = 2;
345        if (CXXRecordDecl *Record
346              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
347          if (Record->getDescribedClassTemplate())
348            WhichKind = 0;
349          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
350            WhichKind = 1;
351          else
352            WhichKind = 2;
353        }
354
355        Diag(NewParam->getLocation(),
356             diag::err_param_default_argument_member_template_redecl)
357          << WhichKind
358          << NewParam->getDefaultArgRange();
359      }
360    }
361  }
362
363  if (CheckEquivalentExceptionSpec(Old, New))
364    Invalid = true;
365
366  return Invalid;
367}
368
369/// CheckCXXDefaultArguments - Verify that the default arguments for a
370/// function declaration are well-formed according to C++
371/// [dcl.fct.default].
372void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
373  unsigned NumParams = FD->getNumParams();
374  unsigned p;
375
376  // Find first parameter with a default argument
377  for (p = 0; p < NumParams; ++p) {
378    ParmVarDecl *Param = FD->getParamDecl(p);
379    if (Param->hasDefaultArg())
380      break;
381  }
382
383  // C++ [dcl.fct.default]p4:
384  //   In a given function declaration, all parameters
385  //   subsequent to a parameter with a default argument shall
386  //   have default arguments supplied in this or previous
387  //   declarations. A default argument shall not be redefined
388  //   by a later declaration (not even to the same value).
389  unsigned LastMissingDefaultArg = 0;
390  for (; p < NumParams; ++p) {
391    ParmVarDecl *Param = FD->getParamDecl(p);
392    if (!Param->hasDefaultArg()) {
393      if (Param->isInvalidDecl())
394        /* We already complained about this parameter. */;
395      else if (Param->getIdentifier())
396        Diag(Param->getLocation(),
397             diag::err_param_default_argument_missing_name)
398          << Param->getIdentifier();
399      else
400        Diag(Param->getLocation(),
401             diag::err_param_default_argument_missing);
402
403      LastMissingDefaultArg = p;
404    }
405  }
406
407  if (LastMissingDefaultArg > 0) {
408    // Some default arguments were missing. Clear out all of the
409    // default arguments up to (and including) the last missing
410    // default argument, so that we leave the function parameters
411    // in a semantically valid state.
412    for (p = 0; p <= LastMissingDefaultArg; ++p) {
413      ParmVarDecl *Param = FD->getParamDecl(p);
414      if (Param->hasDefaultArg()) {
415        if (!Param->hasUnparsedDefaultArg())
416          Param->getDefaultArg()->Destroy(Context);
417        Param->setDefaultArg(0);
418      }
419    }
420  }
421}
422
423/// isCurrentClassName - Determine whether the identifier II is the
424/// name of the class type currently being defined. In the case of
425/// nested classes, this will only return true if II is the name of
426/// the innermost class.
427bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
428                              const CXXScopeSpec *SS) {
429  assert(getLangOptions().CPlusPlus && "No class names in C!");
430
431  CXXRecordDecl *CurDecl;
432  if (SS && SS->isSet() && !SS->isInvalid()) {
433    DeclContext *DC = computeDeclContext(*SS, true);
434    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
435  } else
436    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
437
438  if (CurDecl && CurDecl->getIdentifier())
439    return &II == CurDecl->getIdentifier();
440  else
441    return false;
442}
443
444/// \brief Check the validity of a C++ base class specifier.
445///
446/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
447/// and returns NULL otherwise.
448CXXBaseSpecifier *
449Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
450                         SourceRange SpecifierRange,
451                         bool Virtual, AccessSpecifier Access,
452                         QualType BaseType,
453                         SourceLocation BaseLoc) {
454  // C++ [class.union]p1:
455  //   A union shall not have base classes.
456  if (Class->isUnion()) {
457    Diag(Class->getLocation(), diag::err_base_clause_on_union)
458      << SpecifierRange;
459    return 0;
460  }
461
462  if (BaseType->isDependentType())
463    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
464                                Class->getTagKind() == RecordDecl::TK_class,
465                                Access, BaseType);
466
467  // Base specifiers must be record types.
468  if (!BaseType->isRecordType()) {
469    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
470    return 0;
471  }
472
473  // C++ [class.union]p1:
474  //   A union shall not be used as a base class.
475  if (BaseType->isUnionType()) {
476    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
477    return 0;
478  }
479
480  // C++ [class.derived]p2:
481  //   The class-name in a base-specifier shall not be an incompletely
482  //   defined class.
483  if (RequireCompleteType(BaseLoc, BaseType,
484                          PDiag(diag::err_incomplete_base_class)
485                            << SpecifierRange))
486    return 0;
487
488  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
489  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
490  assert(BaseDecl && "Record type has no declaration");
491  BaseDecl = BaseDecl->getDefinition();
492  assert(BaseDecl && "Base type is not incomplete, but has no definition");
493  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
494  assert(CXXBaseDecl && "Base type is not a C++ type");
495
496  // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
497  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
498    Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
499    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
500      << BaseType;
501    return 0;
502  }
503
504  SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
505
506  // Create the base specifier.
507  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
508                              Class->getTagKind() == RecordDecl::TK_class,
509                              Access, BaseType);
510}
511
512void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
513                                          const CXXRecordDecl *BaseClass,
514                                          bool BaseIsVirtual) {
515  // A class with a non-empty base class is not empty.
516  // FIXME: Standard ref?
517  if (!BaseClass->isEmpty())
518    Class->setEmpty(false);
519
520  // C++ [class.virtual]p1:
521  //   A class that [...] inherits a virtual function is called a polymorphic
522  //   class.
523  if (BaseClass->isPolymorphic())
524    Class->setPolymorphic(true);
525
526  // C++ [dcl.init.aggr]p1:
527  //   An aggregate is [...] a class with [...] no base classes [...].
528  Class->setAggregate(false);
529
530  // C++ [class]p4:
531  //   A POD-struct is an aggregate class...
532  Class->setPOD(false);
533
534  if (BaseIsVirtual) {
535    // C++ [class.ctor]p5:
536    //   A constructor is trivial if its class has no virtual base classes.
537    Class->setHasTrivialConstructor(false);
538
539    // C++ [class.copy]p6:
540    //   A copy constructor is trivial if its class has no virtual base classes.
541    Class->setHasTrivialCopyConstructor(false);
542
543    // C++ [class.copy]p11:
544    //   A copy assignment operator is trivial if its class has no virtual
545    //   base classes.
546    Class->setHasTrivialCopyAssignment(false);
547
548    // C++0x [meta.unary.prop] is_empty:
549    //    T is a class type, but not a union type, with ... no virtual base
550    //    classes
551    Class->setEmpty(false);
552  } else {
553    // C++ [class.ctor]p5:
554    //   A constructor is trivial if all the direct base classes of its
555    //   class have trivial constructors.
556    if (!BaseClass->hasTrivialConstructor())
557      Class->setHasTrivialConstructor(false);
558
559    // C++ [class.copy]p6:
560    //   A copy constructor is trivial if all the direct base classes of its
561    //   class have trivial copy constructors.
562    if (!BaseClass->hasTrivialCopyConstructor())
563      Class->setHasTrivialCopyConstructor(false);
564
565    // C++ [class.copy]p11:
566    //   A copy assignment operator is trivial if all the direct base classes
567    //   of its class have trivial copy assignment operators.
568    if (!BaseClass->hasTrivialCopyAssignment())
569      Class->setHasTrivialCopyAssignment(false);
570  }
571
572  // C++ [class.ctor]p3:
573  //   A destructor is trivial if all the direct base classes of its class
574  //   have trivial destructors.
575  if (!BaseClass->hasTrivialDestructor())
576    Class->setHasTrivialDestructor(false);
577}
578
579/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
580/// one entry in the base class list of a class specifier, for
581/// example:
582///    class foo : public bar, virtual private baz {
583/// 'public bar' and 'virtual private baz' are each base-specifiers.
584Sema::BaseResult
585Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
586                         bool Virtual, AccessSpecifier Access,
587                         TypeTy *basetype, SourceLocation BaseLoc) {
588  if (!classdecl)
589    return true;
590
591  AdjustDeclIfTemplate(classdecl);
592  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
593  if (!Class)
594    return true;
595
596  QualType BaseType = GetTypeFromParser(basetype);
597  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
598                                                      Virtual, Access,
599                                                      BaseType, BaseLoc))
600    return BaseSpec;
601
602  return true;
603}
604
605/// \brief Performs the actual work of attaching the given base class
606/// specifiers to a C++ class.
607bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
608                                unsigned NumBases) {
609 if (NumBases == 0)
610    return false;
611
612  // Used to keep track of which base types we have already seen, so
613  // that we can properly diagnose redundant direct base types. Note
614  // that the key is always the unqualified canonical type of the base
615  // class.
616  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
617
618  // Copy non-redundant base specifiers into permanent storage.
619  unsigned NumGoodBases = 0;
620  bool Invalid = false;
621  for (unsigned idx = 0; idx < NumBases; ++idx) {
622    QualType NewBaseType
623      = Context.getCanonicalType(Bases[idx]->getType());
624    NewBaseType = NewBaseType.getLocalUnqualifiedType();
625
626    if (KnownBaseTypes[NewBaseType]) {
627      // C++ [class.mi]p3:
628      //   A class shall not be specified as a direct base class of a
629      //   derived class more than once.
630      Diag(Bases[idx]->getSourceRange().getBegin(),
631           diag::err_duplicate_base_class)
632        << KnownBaseTypes[NewBaseType]->getType()
633        << Bases[idx]->getSourceRange();
634
635      // Delete the duplicate base class specifier; we're going to
636      // overwrite its pointer later.
637      Context.Deallocate(Bases[idx]);
638
639      Invalid = true;
640    } else {
641      // Okay, add this new base class.
642      KnownBaseTypes[NewBaseType] = Bases[idx];
643      Bases[NumGoodBases++] = Bases[idx];
644    }
645  }
646
647  // Attach the remaining base class specifiers to the derived class.
648  Class->setBases(Bases, NumGoodBases);
649
650  // Delete the remaining (good) base class specifiers, since their
651  // data has been copied into the CXXRecordDecl.
652  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
653    Context.Deallocate(Bases[idx]);
654
655  return Invalid;
656}
657
658/// ActOnBaseSpecifiers - Attach the given base specifiers to the
659/// class, after checking whether there are any duplicate base
660/// classes.
661void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
662                               unsigned NumBases) {
663  if (!ClassDecl || !Bases || !NumBases)
664    return;
665
666  AdjustDeclIfTemplate(ClassDecl);
667  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
668                       (CXXBaseSpecifier**)(Bases), NumBases);
669}
670
671static CXXRecordDecl *GetClassForType(QualType T) {
672  if (const RecordType *RT = T->getAs<RecordType>())
673    return cast<CXXRecordDecl>(RT->getDecl());
674  else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
675    return ICT->getDecl();
676  else
677    return 0;
678}
679
680/// \brief Determine whether the type \p Derived is a C++ class that is
681/// derived from the type \p Base.
682bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
683  if (!getLangOptions().CPlusPlus)
684    return false;
685
686  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
687  if (!DerivedRD)
688    return false;
689
690  CXXRecordDecl *BaseRD = GetClassForType(Base);
691  if (!BaseRD)
692    return false;
693
694  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
695  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
696}
697
698/// \brief Determine whether the type \p Derived is a C++ class that is
699/// derived from the type \p Base.
700bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
701  if (!getLangOptions().CPlusPlus)
702    return false;
703
704  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
705  if (!DerivedRD)
706    return false;
707
708  CXXRecordDecl *BaseRD = GetClassForType(Base);
709  if (!BaseRD)
710    return false;
711
712  return DerivedRD->isDerivedFrom(BaseRD, Paths);
713}
714
715void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
716                              CXXBaseSpecifierArray &BasePathArray) {
717  assert(BasePathArray.empty() && "Base path array must be empty!");
718  assert(Paths.isRecordingPaths() && "Must record paths!");
719
720  const CXXBasePath &Path = Paths.front();
721
722  // We first go backward and check if we have a virtual base.
723  // FIXME: It would be better if CXXBasePath had the base specifier for
724  // the nearest virtual base.
725  unsigned Start = 0;
726  for (unsigned I = Path.size(); I != 0; --I) {
727    if (Path[I - 1].Base->isVirtual()) {
728      Start = I - 1;
729      break;
730    }
731  }
732
733  // Now add all bases.
734  for (unsigned I = Start, E = Path.size(); I != E; ++I)
735    BasePathArray.push_back(Path[I].Base);
736}
737
738/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
739/// conversion (where Derived and Base are class types) is
740/// well-formed, meaning that the conversion is unambiguous (and
741/// that all of the base classes are accessible). Returns true
742/// and emits a diagnostic if the code is ill-formed, returns false
743/// otherwise. Loc is the location where this routine should point to
744/// if there is an error, and Range is the source range to highlight
745/// if there is an error.
746bool
747Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
748                                   unsigned InaccessibleBaseID,
749                                   unsigned AmbigiousBaseConvID,
750                                   SourceLocation Loc, SourceRange Range,
751                                   DeclarationName Name,
752                                   CXXBaseSpecifierArray *BasePath) {
753  // First, determine whether the path from Derived to Base is
754  // ambiguous. This is slightly more expensive than checking whether
755  // the Derived to Base conversion exists, because here we need to
756  // explore multiple paths to determine if there is an ambiguity.
757  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
758                     /*DetectVirtual=*/false);
759  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
760  assert(DerivationOkay &&
761         "Can only be used with a derived-to-base conversion");
762  (void)DerivationOkay;
763
764  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
765    if (InaccessibleBaseID) {
766      // Check that the base class can be accessed.
767      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
768                                   InaccessibleBaseID)) {
769        case AR_inaccessible:
770          return true;
771        case AR_accessible:
772        case AR_dependent:
773        case AR_delayed:
774          break;
775      }
776    }
777
778    // Build a base path if necessary.
779    if (BasePath)
780      BuildBasePathArray(Paths, *BasePath);
781    return false;
782  }
783
784  // We know that the derived-to-base conversion is ambiguous, and
785  // we're going to produce a diagnostic. Perform the derived-to-base
786  // search just one more time to compute all of the possible paths so
787  // that we can print them out. This is more expensive than any of
788  // the previous derived-to-base checks we've done, but at this point
789  // performance isn't as much of an issue.
790  Paths.clear();
791  Paths.setRecordingPaths(true);
792  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
793  assert(StillOkay && "Can only be used with a derived-to-base conversion");
794  (void)StillOkay;
795
796  // Build up a textual representation of the ambiguous paths, e.g.,
797  // D -> B -> A, that will be used to illustrate the ambiguous
798  // conversions in the diagnostic. We only print one of the paths
799  // to each base class subobject.
800  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
801
802  Diag(Loc, AmbigiousBaseConvID)
803  << Derived << Base << PathDisplayStr << Range << Name;
804  return true;
805}
806
807bool
808Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
809                                   SourceLocation Loc, SourceRange Range,
810                                   CXXBaseSpecifierArray *BasePath,
811                                   bool IgnoreAccess) {
812  return CheckDerivedToBaseConversion(Derived, Base,
813                                      IgnoreAccess ? 0
814                                       : diag::err_upcast_to_inaccessible_base,
815                                      diag::err_ambiguous_derived_to_base_conv,
816                                      Loc, Range, DeclarationName(),
817                                      BasePath);
818}
819
820
821/// @brief Builds a string representing ambiguous paths from a
822/// specific derived class to different subobjects of the same base
823/// class.
824///
825/// This function builds a string that can be used in error messages
826/// to show the different paths that one can take through the
827/// inheritance hierarchy to go from the derived class to different
828/// subobjects of a base class. The result looks something like this:
829/// @code
830/// struct D -> struct B -> struct A
831/// struct D -> struct C -> struct A
832/// @endcode
833std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
834  std::string PathDisplayStr;
835  std::set<unsigned> DisplayedPaths;
836  for (CXXBasePaths::paths_iterator Path = Paths.begin();
837       Path != Paths.end(); ++Path) {
838    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
839      // We haven't displayed a path to this particular base
840      // class subobject yet.
841      PathDisplayStr += "\n    ";
842      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
843      for (CXXBasePath::const_iterator Element = Path->begin();
844           Element != Path->end(); ++Element)
845        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
846    }
847  }
848
849  return PathDisplayStr;
850}
851
852//===----------------------------------------------------------------------===//
853// C++ class member Handling
854//===----------------------------------------------------------------------===//
855
856/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
857/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
858/// bitfield width if there is one and 'InitExpr' specifies the initializer if
859/// any.
860Sema::DeclPtrTy
861Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
862                               MultiTemplateParamsArg TemplateParameterLists,
863                               ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
864                               bool Deleted) {
865  const DeclSpec &DS = D.getDeclSpec();
866  DeclarationName Name = GetNameForDeclarator(D);
867  Expr *BitWidth = static_cast<Expr*>(BW);
868  Expr *Init = static_cast<Expr*>(InitExpr);
869  SourceLocation Loc = D.getIdentifierLoc();
870
871  bool isFunc = D.isFunctionDeclarator();
872
873  assert(!DS.isFriendSpecified());
874
875  // C++ 9.2p6: A member shall not be declared to have automatic storage
876  // duration (auto, register) or with the extern storage-class-specifier.
877  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
878  // data members and cannot be applied to names declared const or static,
879  // and cannot be applied to reference members.
880  switch (DS.getStorageClassSpec()) {
881    case DeclSpec::SCS_unspecified:
882    case DeclSpec::SCS_typedef:
883    case DeclSpec::SCS_static:
884      // FALL THROUGH.
885      break;
886    case DeclSpec::SCS_mutable:
887      if (isFunc) {
888        if (DS.getStorageClassSpecLoc().isValid())
889          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
890        else
891          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
892
893        // FIXME: It would be nicer if the keyword was ignored only for this
894        // declarator. Otherwise we could get follow-up errors.
895        D.getMutableDeclSpec().ClearStorageClassSpecs();
896      } else {
897        QualType T = GetTypeForDeclarator(D, S);
898        diag::kind err = static_cast<diag::kind>(0);
899        if (T->isReferenceType())
900          err = diag::err_mutable_reference;
901        else if (T.isConstQualified())
902          err = diag::err_mutable_const;
903        if (err != 0) {
904          if (DS.getStorageClassSpecLoc().isValid())
905            Diag(DS.getStorageClassSpecLoc(), err);
906          else
907            Diag(DS.getThreadSpecLoc(), err);
908          // FIXME: It would be nicer if the keyword was ignored only for this
909          // declarator. Otherwise we could get follow-up errors.
910          D.getMutableDeclSpec().ClearStorageClassSpecs();
911        }
912      }
913      break;
914    default:
915      if (DS.getStorageClassSpecLoc().isValid())
916        Diag(DS.getStorageClassSpecLoc(),
917             diag::err_storageclass_invalid_for_member);
918      else
919        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
920      D.getMutableDeclSpec().ClearStorageClassSpecs();
921  }
922
923  if (!isFunc &&
924      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
925      D.getNumTypeObjects() == 0) {
926    // Check also for this case:
927    //
928    // typedef int f();
929    // f a;
930    //
931    QualType TDType = GetTypeFromParser(DS.getTypeRep());
932    isFunc = TDType->isFunctionType();
933  }
934
935  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
936                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
937                      !isFunc);
938
939  Decl *Member;
940  if (isInstField) {
941    // FIXME: Check for template parameters!
942    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
943                         AS);
944    assert(Member && "HandleField never returns null");
945  } else {
946    Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
947               .getAs<Decl>();
948    if (!Member) {
949      if (BitWidth) DeleteExpr(BitWidth);
950      return DeclPtrTy();
951    }
952
953    // Non-instance-fields can't have a bitfield.
954    if (BitWidth) {
955      if (Member->isInvalidDecl()) {
956        // don't emit another diagnostic.
957      } else if (isa<VarDecl>(Member)) {
958        // C++ 9.6p3: A bit-field shall not be a static member.
959        // "static member 'A' cannot be a bit-field"
960        Diag(Loc, diag::err_static_not_bitfield)
961          << Name << BitWidth->getSourceRange();
962      } else if (isa<TypedefDecl>(Member)) {
963        // "typedef member 'x' cannot be a bit-field"
964        Diag(Loc, diag::err_typedef_not_bitfield)
965          << Name << BitWidth->getSourceRange();
966      } else {
967        // A function typedef ("typedef int f(); f a;").
968        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
969        Diag(Loc, diag::err_not_integral_type_bitfield)
970          << Name << cast<ValueDecl>(Member)->getType()
971          << BitWidth->getSourceRange();
972      }
973
974      DeleteExpr(BitWidth);
975      BitWidth = 0;
976      Member->setInvalidDecl();
977    }
978
979    Member->setAccess(AS);
980
981    // If we have declared a member function template, set the access of the
982    // templated declaration as well.
983    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
984      FunTmpl->getTemplatedDecl()->setAccess(AS);
985  }
986
987  assert((Name || isInstField) && "No identifier for non-field ?");
988
989  if (Init)
990    AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
991  if (Deleted) // FIXME: Source location is not very good.
992    SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
993
994  if (isInstField) {
995    FieldCollector->Add(cast<FieldDecl>(Member));
996    return DeclPtrTy();
997  }
998  return DeclPtrTy::make(Member);
999}
1000
1001/// \brief Find the direct and/or virtual base specifiers that
1002/// correspond to the given base type, for use in base initialization
1003/// within a constructor.
1004static bool FindBaseInitializer(Sema &SemaRef,
1005                                CXXRecordDecl *ClassDecl,
1006                                QualType BaseType,
1007                                const CXXBaseSpecifier *&DirectBaseSpec,
1008                                const CXXBaseSpecifier *&VirtualBaseSpec) {
1009  // First, check for a direct base class.
1010  DirectBaseSpec = 0;
1011  for (CXXRecordDecl::base_class_const_iterator Base
1012         = ClassDecl->bases_begin();
1013       Base != ClassDecl->bases_end(); ++Base) {
1014    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1015      // We found a direct base of this type. That's what we're
1016      // initializing.
1017      DirectBaseSpec = &*Base;
1018      break;
1019    }
1020  }
1021
1022  // Check for a virtual base class.
1023  // FIXME: We might be able to short-circuit this if we know in advance that
1024  // there are no virtual bases.
1025  VirtualBaseSpec = 0;
1026  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1027    // We haven't found a base yet; search the class hierarchy for a
1028    // virtual base class.
1029    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1030                       /*DetectVirtual=*/false);
1031    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1032                              BaseType, Paths)) {
1033      for (CXXBasePaths::paths_iterator Path = Paths.begin();
1034           Path != Paths.end(); ++Path) {
1035        if (Path->back().Base->isVirtual()) {
1036          VirtualBaseSpec = Path->back().Base;
1037          break;
1038        }
1039      }
1040    }
1041  }
1042
1043  return DirectBaseSpec || VirtualBaseSpec;
1044}
1045
1046/// ActOnMemInitializer - Handle a C++ member initializer.
1047Sema::MemInitResult
1048Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
1049                          Scope *S,
1050                          CXXScopeSpec &SS,
1051                          IdentifierInfo *MemberOrBase,
1052                          TypeTy *TemplateTypeTy,
1053                          SourceLocation IdLoc,
1054                          SourceLocation LParenLoc,
1055                          ExprTy **Args, unsigned NumArgs,
1056                          SourceLocation *CommaLocs,
1057                          SourceLocation RParenLoc) {
1058  if (!ConstructorD)
1059    return true;
1060
1061  AdjustDeclIfTemplate(ConstructorD);
1062
1063  CXXConstructorDecl *Constructor
1064    = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
1065  if (!Constructor) {
1066    // The user wrote a constructor initializer on a function that is
1067    // not a C++ constructor. Ignore the error for now, because we may
1068    // have more member initializers coming; we'll diagnose it just
1069    // once in ActOnMemInitializers.
1070    return true;
1071  }
1072
1073  CXXRecordDecl *ClassDecl = Constructor->getParent();
1074
1075  // C++ [class.base.init]p2:
1076  //   Names in a mem-initializer-id are looked up in the scope of the
1077  //   constructor’s class and, if not found in that scope, are looked
1078  //   up in the scope containing the constructor’s
1079  //   definition. [Note: if the constructor’s class contains a member
1080  //   with the same name as a direct or virtual base class of the
1081  //   class, a mem-initializer-id naming the member or base class and
1082  //   composed of a single identifier refers to the class member. A
1083  //   mem-initializer-id for the hidden base class may be specified
1084  //   using a qualified name. ]
1085  if (!SS.getScopeRep() && !TemplateTypeTy) {
1086    // Look for a member, first.
1087    FieldDecl *Member = 0;
1088    DeclContext::lookup_result Result
1089      = ClassDecl->lookup(MemberOrBase);
1090    if (Result.first != Result.second)
1091      Member = dyn_cast<FieldDecl>(*Result.first);
1092
1093    // FIXME: Handle members of an anonymous union.
1094
1095    if (Member)
1096      return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1097                                    LParenLoc, RParenLoc);
1098  }
1099  // It didn't name a member, so see if it names a class.
1100  QualType BaseType;
1101  TypeSourceInfo *TInfo = 0;
1102
1103  if (TemplateTypeTy) {
1104    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1105  } else {
1106    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1107    LookupParsedName(R, S, &SS);
1108
1109    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1110    if (!TyD) {
1111      if (R.isAmbiguous()) return true;
1112
1113      // We don't want access-control diagnostics here.
1114      R.suppressDiagnostics();
1115
1116      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1117        bool NotUnknownSpecialization = false;
1118        DeclContext *DC = computeDeclContext(SS, false);
1119        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1120          NotUnknownSpecialization = !Record->hasAnyDependentBases();
1121
1122        if (!NotUnknownSpecialization) {
1123          // When the scope specifier can refer to a member of an unknown
1124          // specialization, we take it as a type name.
1125          BaseType = CheckTypenameType(ETK_None,
1126                                       (NestedNameSpecifier *)SS.getScopeRep(),
1127                                       *MemberOrBase, SS.getRange());
1128          if (BaseType.isNull())
1129            return true;
1130
1131          R.clear();
1132        }
1133      }
1134
1135      // If no results were found, try to correct typos.
1136      if (R.empty() && BaseType.isNull() &&
1137          CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1138          R.isSingleResult()) {
1139        if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1140          if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1141            // We have found a non-static data member with a similar
1142            // name to what was typed; complain and initialize that
1143            // member.
1144            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1145              << MemberOrBase << true << R.getLookupName()
1146              << FixItHint::CreateReplacement(R.getNameLoc(),
1147                                              R.getLookupName().getAsString());
1148            Diag(Member->getLocation(), diag::note_previous_decl)
1149              << Member->getDeclName();
1150
1151            return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1152                                          LParenLoc, RParenLoc);
1153          }
1154        } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1155          const CXXBaseSpecifier *DirectBaseSpec;
1156          const CXXBaseSpecifier *VirtualBaseSpec;
1157          if (FindBaseInitializer(*this, ClassDecl,
1158                                  Context.getTypeDeclType(Type),
1159                                  DirectBaseSpec, VirtualBaseSpec)) {
1160            // We have found a direct or virtual base class with a
1161            // similar name to what was typed; complain and initialize
1162            // that base class.
1163            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1164              << MemberOrBase << false << R.getLookupName()
1165              << FixItHint::CreateReplacement(R.getNameLoc(),
1166                                              R.getLookupName().getAsString());
1167
1168            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1169                                                             : VirtualBaseSpec;
1170            Diag(BaseSpec->getSourceRange().getBegin(),
1171                 diag::note_base_class_specified_here)
1172              << BaseSpec->getType()
1173              << BaseSpec->getSourceRange();
1174
1175            TyD = Type;
1176          }
1177        }
1178      }
1179
1180      if (!TyD && BaseType.isNull()) {
1181        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1182          << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1183        return true;
1184      }
1185    }
1186
1187    if (BaseType.isNull()) {
1188      BaseType = Context.getTypeDeclType(TyD);
1189      if (SS.isSet()) {
1190        NestedNameSpecifier *Qualifier =
1191          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1192
1193        // FIXME: preserve source range information
1194        BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1195      }
1196    }
1197  }
1198
1199  if (!TInfo)
1200    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1201
1202  return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
1203                              LParenLoc, RParenLoc, ClassDecl);
1204}
1205
1206/// Checks an initializer expression for use of uninitialized fields, such as
1207/// containing the field that is being initialized. Returns true if there is an
1208/// uninitialized field was used an updates the SourceLocation parameter; false
1209/// otherwise.
1210static bool InitExprContainsUninitializedFields(const Stmt* S,
1211                                                const FieldDecl* LhsField,
1212                                                SourceLocation* L) {
1213  const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1214  if (ME) {
1215    const NamedDecl* RhsField = ME->getMemberDecl();
1216    if (RhsField == LhsField) {
1217      // Initializing a field with itself. Throw a warning.
1218      // But wait; there are exceptions!
1219      // Exception #1:  The field may not belong to this record.
1220      // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1221      const Expr* base = ME->getBase();
1222      if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1223        // Even though the field matches, it does not belong to this record.
1224        return false;
1225      }
1226      // None of the exceptions triggered; return true to indicate an
1227      // uninitialized field was used.
1228      *L = ME->getMemberLoc();
1229      return true;
1230    }
1231  }
1232  bool found = false;
1233  for (Stmt::const_child_iterator it = S->child_begin();
1234       it != S->child_end() && found == false;
1235       ++it) {
1236    if (isa<CallExpr>(S)) {
1237      // Do not descend into function calls or constructors, as the use
1238      // of an uninitialized field may be valid. One would have to inspect
1239      // the contents of the function/ctor to determine if it is safe or not.
1240      // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1241      // may be safe, depending on what the function/ctor does.
1242      continue;
1243    }
1244    found = InitExprContainsUninitializedFields(*it, LhsField, L);
1245  }
1246  return found;
1247}
1248
1249Sema::MemInitResult
1250Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1251                             unsigned NumArgs, SourceLocation IdLoc,
1252                             SourceLocation LParenLoc,
1253                             SourceLocation RParenLoc) {
1254  // Diagnose value-uses of fields to initialize themselves, e.g.
1255  //   foo(foo)
1256  // where foo is not also a parameter to the constructor.
1257  // TODO: implement -Wuninitialized and fold this into that framework.
1258  for (unsigned i = 0; i < NumArgs; ++i) {
1259    SourceLocation L;
1260    if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1261      // FIXME: Return true in the case when other fields are used before being
1262      // uninitialized. For example, let this field be the i'th field. When
1263      // initializing the i'th field, throw a warning if any of the >= i'th
1264      // fields are used, as they are not yet initialized.
1265      // Right now we are only handling the case where the i'th field uses
1266      // itself in its initializer.
1267      Diag(L, diag::warn_field_is_uninit);
1268    }
1269  }
1270
1271  bool HasDependentArg = false;
1272  for (unsigned i = 0; i < NumArgs; i++)
1273    HasDependentArg |= Args[i]->isTypeDependent();
1274
1275  QualType FieldType = Member->getType();
1276  if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1277    FieldType = Array->getElementType();
1278  if (FieldType->isDependentType() || HasDependentArg) {
1279    // Can't check initialization for a member of dependent type or when
1280    // any of the arguments are type-dependent expressions.
1281    OwningExprResult Init
1282      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1283                                          RParenLoc));
1284
1285    // Erase any temporaries within this evaluation context; we're not
1286    // going to track them in the AST, since we'll be rebuilding the
1287    // ASTs during template instantiation.
1288    ExprTemporaries.erase(
1289              ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1290                          ExprTemporaries.end());
1291
1292    return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1293                                                    LParenLoc,
1294                                                    Init.takeAs<Expr>(),
1295                                                    RParenLoc);
1296
1297  }
1298
1299  if (Member->isInvalidDecl())
1300    return true;
1301
1302  // Initialize the member.
1303  InitializedEntity MemberEntity =
1304    InitializedEntity::InitializeMember(Member, 0);
1305  InitializationKind Kind =
1306    InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1307
1308  InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1309
1310  OwningExprResult MemberInit =
1311    InitSeq.Perform(*this, MemberEntity, Kind,
1312                    MultiExprArg(*this, (void**)Args, NumArgs), 0);
1313  if (MemberInit.isInvalid())
1314    return true;
1315
1316  // C++0x [class.base.init]p7:
1317  //   The initialization of each base and member constitutes a
1318  //   full-expression.
1319  MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1320  if (MemberInit.isInvalid())
1321    return true;
1322
1323  // If we are in a dependent context, template instantiation will
1324  // perform this type-checking again. Just save the arguments that we
1325  // received in a ParenListExpr.
1326  // FIXME: This isn't quite ideal, since our ASTs don't capture all
1327  // of the information that we have about the member
1328  // initializer. However, deconstructing the ASTs is a dicey process,
1329  // and this approach is far more likely to get the corner cases right.
1330  if (CurContext->isDependentContext()) {
1331    // Bump the reference count of all of the arguments.
1332    for (unsigned I = 0; I != NumArgs; ++I)
1333      Args[I]->Retain();
1334
1335    OwningExprResult Init
1336      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1337                                          RParenLoc));
1338    return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1339                                                    LParenLoc,
1340                                                    Init.takeAs<Expr>(),
1341                                                    RParenLoc);
1342  }
1343
1344  return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1345                                                  LParenLoc,
1346                                                  MemberInit.takeAs<Expr>(),
1347                                                  RParenLoc);
1348}
1349
1350Sema::MemInitResult
1351Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
1352                           Expr **Args, unsigned NumArgs,
1353                           SourceLocation LParenLoc, SourceLocation RParenLoc,
1354                           CXXRecordDecl *ClassDecl) {
1355  bool HasDependentArg = false;
1356  for (unsigned i = 0; i < NumArgs; i++)
1357    HasDependentArg |= Args[i]->isTypeDependent();
1358
1359  SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
1360  if (BaseType->isDependentType() || HasDependentArg) {
1361    // Can't check initialization for a base of dependent type or when
1362    // any of the arguments are type-dependent expressions.
1363    OwningExprResult BaseInit
1364      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1365                                          RParenLoc));
1366
1367    // Erase any temporaries within this evaluation context; we're not
1368    // going to track them in the AST, since we'll be rebuilding the
1369    // ASTs during template instantiation.
1370    ExprTemporaries.erase(
1371              ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1372                          ExprTemporaries.end());
1373
1374    return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1375                                                    /*IsVirtual=*/false,
1376                                                    LParenLoc,
1377                                                    BaseInit.takeAs<Expr>(),
1378                                                    RParenLoc);
1379  }
1380
1381  if (!BaseType->isRecordType())
1382    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1383             << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1384
1385  // C++ [class.base.init]p2:
1386  //   [...] Unless the mem-initializer-id names a nonstatic data
1387  //   member of the constructor’s class or a direct or virtual base
1388  //   of that class, the mem-initializer is ill-formed. A
1389  //   mem-initializer-list can initialize a base class using any
1390  //   name that denotes that base class type.
1391
1392  // Check for direct and virtual base classes.
1393  const CXXBaseSpecifier *DirectBaseSpec = 0;
1394  const CXXBaseSpecifier *VirtualBaseSpec = 0;
1395  FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1396                      VirtualBaseSpec);
1397
1398  // C++ [base.class.init]p2:
1399  //   If a mem-initializer-id is ambiguous because it designates both
1400  //   a direct non-virtual base class and an inherited virtual base
1401  //   class, the mem-initializer is ill-formed.
1402  if (DirectBaseSpec && VirtualBaseSpec)
1403    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1404      << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1405  // C++ [base.class.init]p2:
1406  // Unless the mem-initializer-id names a nonstatic data membeer of the
1407  // constructor's class ot a direst or virtual base of that class, the
1408  // mem-initializer is ill-formed.
1409  if (!DirectBaseSpec && !VirtualBaseSpec)
1410    return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1411      << BaseType << Context.getTypeDeclType(ClassDecl)
1412      << BaseTInfo->getTypeLoc().getSourceRange();
1413
1414  CXXBaseSpecifier *BaseSpec
1415    = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1416  if (!BaseSpec)
1417    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1418
1419  // Initialize the base.
1420  InitializedEntity BaseEntity =
1421    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
1422  InitializationKind Kind =
1423    InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1424
1425  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1426
1427  OwningExprResult BaseInit =
1428    InitSeq.Perform(*this, BaseEntity, Kind,
1429                    MultiExprArg(*this, (void**)Args, NumArgs), 0);
1430  if (BaseInit.isInvalid())
1431    return true;
1432
1433  // C++0x [class.base.init]p7:
1434  //   The initialization of each base and member constitutes a
1435  //   full-expression.
1436  BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1437  if (BaseInit.isInvalid())
1438    return true;
1439
1440  // If we are in a dependent context, template instantiation will
1441  // perform this type-checking again. Just save the arguments that we
1442  // received in a ParenListExpr.
1443  // FIXME: This isn't quite ideal, since our ASTs don't capture all
1444  // of the information that we have about the base
1445  // initializer. However, deconstructing the ASTs is a dicey process,
1446  // and this approach is far more likely to get the corner cases right.
1447  if (CurContext->isDependentContext()) {
1448    // Bump the reference count of all of the arguments.
1449    for (unsigned I = 0; I != NumArgs; ++I)
1450      Args[I]->Retain();
1451
1452    OwningExprResult Init
1453      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1454                                          RParenLoc));
1455    return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1456                                                    BaseSpec->isVirtual(),
1457                                                    LParenLoc,
1458                                                    Init.takeAs<Expr>(),
1459                                                    RParenLoc);
1460  }
1461
1462  return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1463                                                  BaseSpec->isVirtual(),
1464                                                  LParenLoc,
1465                                                  BaseInit.takeAs<Expr>(),
1466                                                  RParenLoc);
1467}
1468
1469/// ImplicitInitializerKind - How an implicit base or member initializer should
1470/// initialize its base or member.
1471enum ImplicitInitializerKind {
1472  IIK_Default,
1473  IIK_Copy,
1474  IIK_Move
1475};
1476
1477static bool
1478BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1479                             ImplicitInitializerKind ImplicitInitKind,
1480                             CXXBaseSpecifier *BaseSpec,
1481                             bool IsInheritedVirtualBase,
1482                             CXXBaseOrMemberInitializer *&CXXBaseInit) {
1483  InitializedEntity InitEntity
1484    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1485                                        IsInheritedVirtualBase);
1486
1487  Sema::OwningExprResult BaseInit(SemaRef);
1488
1489  switch (ImplicitInitKind) {
1490  case IIK_Default: {
1491    InitializationKind InitKind
1492      = InitializationKind::CreateDefault(Constructor->getLocation());
1493    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1494    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1495                               Sema::MultiExprArg(SemaRef, 0, 0));
1496    break;
1497  }
1498
1499  case IIK_Copy: {
1500    ParmVarDecl *Param = Constructor->getParamDecl(0);
1501    QualType ParamType = Param->getType().getNonReferenceType();
1502
1503    Expr *CopyCtorArg =
1504      DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
1505                          Constructor->getLocation(), ParamType, 0);
1506
1507    // Cast to the base class to avoid ambiguities.
1508    QualType ArgTy =
1509      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1510                                       ParamType.getQualifiers());
1511    SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1512                              CastExpr::CK_UncheckedDerivedToBase,
1513                              /*isLvalue=*/true,
1514                              CXXBaseSpecifierArray(BaseSpec));
1515
1516    InitializationKind InitKind
1517      = InitializationKind::CreateDirect(Constructor->getLocation(),
1518                                         SourceLocation(), SourceLocation());
1519    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1520                                   &CopyCtorArg, 1);
1521    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1522                               Sema::MultiExprArg(SemaRef,
1523                                                  (void**)&CopyCtorArg, 1));
1524    break;
1525  }
1526
1527  case IIK_Move:
1528    assert(false && "Unhandled initializer kind!");
1529  }
1530
1531  BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1532  if (BaseInit.isInvalid())
1533    return true;
1534
1535  CXXBaseInit =
1536    new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1537               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1538                                                        SourceLocation()),
1539                                             BaseSpec->isVirtual(),
1540                                             SourceLocation(),
1541                                             BaseInit.takeAs<Expr>(),
1542                                             SourceLocation());
1543
1544  return false;
1545}
1546
1547static bool
1548BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1549                               ImplicitInitializerKind ImplicitInitKind,
1550                               FieldDecl *Field,
1551                               CXXBaseOrMemberInitializer *&CXXMemberInit) {
1552  if (ImplicitInitKind == IIK_Copy) {
1553    SourceLocation Loc = Constructor->getLocation();
1554    ParmVarDecl *Param = Constructor->getParamDecl(0);
1555    QualType ParamType = Param->getType().getNonReferenceType();
1556
1557    Expr *MemberExprBase =
1558      DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
1559                          Loc, ParamType, 0);
1560
1561    // Build a reference to this field within the parameter.
1562    CXXScopeSpec SS;
1563    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1564                              Sema::LookupMemberName);
1565    MemberLookup.addDecl(Field, AS_public);
1566    MemberLookup.resolveKind();
1567    Sema::OwningExprResult CopyCtorArg
1568      = SemaRef.BuildMemberReferenceExpr(SemaRef.Owned(MemberExprBase),
1569                                         ParamType, Loc,
1570                                         /*IsArrow=*/false,
1571                                         SS,
1572                                         /*FirstQualifierInScope=*/0,
1573                                         MemberLookup,
1574                                         /*TemplateArgs=*/0);
1575    if (CopyCtorArg.isInvalid())
1576      return true;
1577
1578    // When the field we are copying is an array, create index variables for
1579    // each dimension of the array. We use these index variables to subscript
1580    // the source array, and other clients (e.g., CodeGen) will perform the
1581    // necessary iteration with these index variables.
1582    llvm::SmallVector<VarDecl *, 4> IndexVariables;
1583    QualType BaseType = Field->getType();
1584    QualType SizeType = SemaRef.Context.getSizeType();
1585    while (const ConstantArrayType *Array
1586                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1587      // Create the iteration variable for this array index.
1588      IdentifierInfo *IterationVarName = 0;
1589      {
1590        llvm::SmallString<8> Str;
1591        llvm::raw_svector_ostream OS(Str);
1592        OS << "__i" << IndexVariables.size();
1593        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1594      }
1595      VarDecl *IterationVar
1596        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1597                          IterationVarName, SizeType,
1598                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
1599                          VarDecl::None, VarDecl::None);
1600      IndexVariables.push_back(IterationVar);
1601
1602      // Create a reference to the iteration variable.
1603      Sema::OwningExprResult IterationVarRef
1604        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1605      assert(!IterationVarRef.isInvalid() &&
1606             "Reference to invented variable cannot fail!");
1607
1608      // Subscript the array with this iteration variable.
1609      CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(move(CopyCtorArg),
1610                                                            Loc,
1611                                                          move(IterationVarRef),
1612                                                            Loc);
1613      if (CopyCtorArg.isInvalid())
1614        return true;
1615
1616      BaseType = Array->getElementType();
1617    }
1618
1619    // Construct the entity that we will be initializing. For an array, this
1620    // will be first element in the array, which may require several levels
1621    // of array-subscript entities.
1622    llvm::SmallVector<InitializedEntity, 4> Entities;
1623    Entities.reserve(1 + IndexVariables.size());
1624    Entities.push_back(InitializedEntity::InitializeMember(Field));
1625    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1626      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1627                                                              0,
1628                                                              Entities.back()));
1629
1630    // Direct-initialize to use the copy constructor.
1631    InitializationKind InitKind =
1632      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1633
1634    Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1635    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1636                                   &CopyCtorArgE, 1);
1637
1638    Sema::OwningExprResult MemberInit
1639      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
1640                        Sema::MultiExprArg(SemaRef, (void**)&CopyCtorArgE, 1));
1641    MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1642    if (MemberInit.isInvalid())
1643      return true;
1644
1645    CXXMemberInit
1646      = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1647                                           MemberInit.takeAs<Expr>(), Loc,
1648                                           IndexVariables.data(),
1649                                           IndexVariables.size());
1650    return false;
1651  }
1652
1653  assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1654
1655  QualType FieldBaseElementType =
1656    SemaRef.Context.getBaseElementType(Field->getType());
1657
1658  if (FieldBaseElementType->isRecordType()) {
1659    InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
1660    InitializationKind InitKind =
1661      InitializationKind::CreateDefault(Constructor->getLocation());
1662
1663    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1664    Sema::OwningExprResult MemberInit =
1665      InitSeq.Perform(SemaRef, InitEntity, InitKind,
1666                      Sema::MultiExprArg(SemaRef, 0, 0));
1667    MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1668    if (MemberInit.isInvalid())
1669      return true;
1670
1671    CXXMemberInit =
1672      new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1673                                                       Field, SourceLocation(),
1674                                                       SourceLocation(),
1675                                                      MemberInit.takeAs<Expr>(),
1676                                                       SourceLocation());
1677    return false;
1678  }
1679
1680  if (FieldBaseElementType->isReferenceType()) {
1681    SemaRef.Diag(Constructor->getLocation(),
1682                 diag::err_uninitialized_member_in_ctor)
1683    << (int)Constructor->isImplicit()
1684    << SemaRef.Context.getTagDeclType(Constructor->getParent())
1685    << 0 << Field->getDeclName();
1686    SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1687    return true;
1688  }
1689
1690  if (FieldBaseElementType.isConstQualified()) {
1691    SemaRef.Diag(Constructor->getLocation(),
1692                 diag::err_uninitialized_member_in_ctor)
1693    << (int)Constructor->isImplicit()
1694    << SemaRef.Context.getTagDeclType(Constructor->getParent())
1695    << 1 << Field->getDeclName();
1696    SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1697    return true;
1698  }
1699
1700  // Nothing to initialize.
1701  CXXMemberInit = 0;
1702  return false;
1703}
1704
1705bool
1706Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
1707                                  CXXBaseOrMemberInitializer **Initializers,
1708                                  unsigned NumInitializers,
1709                                  bool AnyErrors) {
1710  if (Constructor->getDeclContext()->isDependentContext()) {
1711    // Just store the initializers as written, they will be checked during
1712    // instantiation.
1713    if (NumInitializers > 0) {
1714      Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1715      CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1716        new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1717      memcpy(baseOrMemberInitializers, Initializers,
1718             NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1719      Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1720    }
1721
1722    return false;
1723  }
1724
1725  ImplicitInitializerKind ImplicitInitKind = IIK_Default;
1726
1727  // FIXME: Handle implicit move constructors.
1728  if (Constructor->isImplicit() && Constructor->isCopyConstructor())
1729    ImplicitInitKind = IIK_Copy;
1730
1731  // We need to build the initializer AST according to order of construction
1732  // and not what user specified in the Initializers list.
1733  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
1734  if (!ClassDecl)
1735    return true;
1736
1737  llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1738  llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1739  bool HadError = false;
1740
1741  for (unsigned i = 0; i < NumInitializers; i++) {
1742    CXXBaseOrMemberInitializer *Member = Initializers[i];
1743
1744    if (Member->isBaseInitializer())
1745      AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1746    else
1747      AllBaseFields[Member->getMember()] = Member;
1748  }
1749
1750  // Keep track of the direct virtual bases.
1751  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1752  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1753       E = ClassDecl->bases_end(); I != E; ++I) {
1754    if (I->isVirtual())
1755      DirectVBases.insert(I);
1756  }
1757
1758  // Push virtual bases before others.
1759  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1760       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1761
1762    if (CXXBaseOrMemberInitializer *Value
1763        = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1764      AllToInit.push_back(Value);
1765    } else if (!AnyErrors) {
1766      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
1767      CXXBaseOrMemberInitializer *CXXBaseInit;
1768      if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1769                                       VBase, IsInheritedVirtualBase,
1770                                       CXXBaseInit)) {
1771        HadError = true;
1772        continue;
1773      }
1774
1775      AllToInit.push_back(CXXBaseInit);
1776    }
1777  }
1778
1779  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1780       E = ClassDecl->bases_end(); Base != E; ++Base) {
1781    // Virtuals are in the virtual base list and already constructed.
1782    if (Base->isVirtual())
1783      continue;
1784
1785    if (CXXBaseOrMemberInitializer *Value
1786          = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1787      AllToInit.push_back(Value);
1788    } else if (!AnyErrors) {
1789      CXXBaseOrMemberInitializer *CXXBaseInit;
1790      if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1791                                       Base, /*IsInheritedVirtualBase=*/false,
1792                                       CXXBaseInit)) {
1793        HadError = true;
1794        continue;
1795      }
1796
1797      AllToInit.push_back(CXXBaseInit);
1798    }
1799  }
1800
1801  // non-static data members.
1802  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1803       E = ClassDecl->field_end(); Field != E; ++Field) {
1804    if ((*Field)->isAnonymousStructOrUnion()) {
1805      if (const RecordType *FieldClassType =
1806          Field->getType()->getAs<RecordType>()) {
1807        CXXRecordDecl *FieldClassDecl
1808          = cast<CXXRecordDecl>(FieldClassType->getDecl());
1809        for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1810            EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1811          if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1812            // 'Member' is the anonymous union field and 'AnonUnionMember' is
1813            // set to the anonymous union data member used in the initializer
1814            // list.
1815            Value->setMember(*Field);
1816            Value->setAnonUnionMember(*FA);
1817            AllToInit.push_back(Value);
1818            break;
1819          }
1820        }
1821      }
1822
1823      if (ImplicitInitKind == IIK_Default)
1824        continue;
1825    }
1826    if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1827      AllToInit.push_back(Value);
1828      continue;
1829    }
1830
1831    if (AnyErrors)
1832      continue;
1833
1834    CXXBaseOrMemberInitializer *Member;
1835    if (BuildImplicitMemberInitializer(*this, Constructor, ImplicitInitKind,
1836                                       *Field, Member)) {
1837      HadError = true;
1838      continue;
1839    }
1840
1841    // If the member doesn't need to be initialized, it will be null.
1842    if (Member)
1843      AllToInit.push_back(Member);
1844  }
1845
1846  NumInitializers = AllToInit.size();
1847  if (NumInitializers > 0) {
1848    Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1849    CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1850      new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1851    memcpy(baseOrMemberInitializers, AllToInit.data(),
1852           NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1853    Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1854
1855    // Constructors implicitly reference the base and member
1856    // destructors.
1857    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1858                                           Constructor->getParent());
1859  }
1860
1861  return HadError;
1862}
1863
1864static void *GetKeyForTopLevelField(FieldDecl *Field) {
1865  // For anonymous unions, use the class declaration as the key.
1866  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
1867    if (RT->getDecl()->isAnonymousStructOrUnion())
1868      return static_cast<void *>(RT->getDecl());
1869  }
1870  return static_cast<void *>(Field);
1871}
1872
1873static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1874  return Context.getCanonicalType(BaseType).getTypePtr();
1875}
1876
1877static void *GetKeyForMember(ASTContext &Context,
1878                             CXXBaseOrMemberInitializer *Member,
1879                             bool MemberMaybeAnon = false) {
1880  if (!Member->isMemberInitializer())
1881    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
1882
1883  // For fields injected into the class via declaration of an anonymous union,
1884  // use its anonymous union class declaration as the unique key.
1885  FieldDecl *Field = Member->getMember();
1886
1887  // After SetBaseOrMemberInitializers call, Field is the anonymous union
1888  // data member of the class. Data member used in the initializer list is
1889  // in AnonUnionMember field.
1890  if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1891    Field = Member->getAnonUnionMember();
1892
1893  // If the field is a member of an anonymous struct or union, our key
1894  // is the anonymous record decl that's a direct child of the class.
1895  RecordDecl *RD = Field->getParent();
1896  if (RD->isAnonymousStructOrUnion()) {
1897    while (true) {
1898      RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1899      if (Parent->isAnonymousStructOrUnion())
1900        RD = Parent;
1901      else
1902        break;
1903    }
1904
1905    return static_cast<void *>(RD);
1906  }
1907
1908  return static_cast<void *>(Field);
1909}
1910
1911static void
1912DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
1913                                  const CXXConstructorDecl *Constructor,
1914                                  CXXBaseOrMemberInitializer **Inits,
1915                                  unsigned NumInits) {
1916  if (Constructor->getDeclContext()->isDependentContext())
1917    return;
1918
1919  if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
1920        == Diagnostic::Ignored)
1921    return;
1922
1923  // Build the list of bases and members in the order that they'll
1924  // actually be initialized.  The explicit initializers should be in
1925  // this same order but may be missing things.
1926  llvm::SmallVector<const void*, 32> IdealInitKeys;
1927
1928  const CXXRecordDecl *ClassDecl = Constructor->getParent();
1929
1930  // 1. Virtual bases.
1931  for (CXXRecordDecl::base_class_const_iterator VBase =
1932       ClassDecl->vbases_begin(),
1933       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
1934    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
1935
1936  // 2. Non-virtual bases.
1937  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
1938       E = ClassDecl->bases_end(); Base != E; ++Base) {
1939    if (Base->isVirtual())
1940      continue;
1941    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
1942  }
1943
1944  // 3. Direct fields.
1945  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1946       E = ClassDecl->field_end(); Field != E; ++Field)
1947    IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
1948
1949  unsigned NumIdealInits = IdealInitKeys.size();
1950  unsigned IdealIndex = 0;
1951
1952  CXXBaseOrMemberInitializer *PrevInit = 0;
1953  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
1954    CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
1955    void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
1956
1957    // Scan forward to try to find this initializer in the idealized
1958    // initializers list.
1959    for (; IdealIndex != NumIdealInits; ++IdealIndex)
1960      if (InitKey == IdealInitKeys[IdealIndex])
1961        break;
1962
1963    // If we didn't find this initializer, it must be because we
1964    // scanned past it on a previous iteration.  That can only
1965    // happen if we're out of order;  emit a warning.
1966    if (IdealIndex == NumIdealInits) {
1967      assert(PrevInit && "initializer not found in initializer list");
1968
1969      Sema::SemaDiagnosticBuilder D =
1970        SemaRef.Diag(PrevInit->getSourceLocation(),
1971                     diag::warn_initializer_out_of_order);
1972
1973      if (PrevInit->isMemberInitializer())
1974        D << 0 << PrevInit->getMember()->getDeclName();
1975      else
1976        D << 1 << PrevInit->getBaseClassInfo()->getType();
1977
1978      if (Init->isMemberInitializer())
1979        D << 0 << Init->getMember()->getDeclName();
1980      else
1981        D << 1 << Init->getBaseClassInfo()->getType();
1982
1983      // Move back to the initializer's location in the ideal list.
1984      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
1985        if (InitKey == IdealInitKeys[IdealIndex])
1986          break;
1987
1988      assert(IdealIndex != NumIdealInits &&
1989             "initializer not found in initializer list");
1990    }
1991
1992    PrevInit = Init;
1993  }
1994}
1995
1996namespace {
1997bool CheckRedundantInit(Sema &S,
1998                        CXXBaseOrMemberInitializer *Init,
1999                        CXXBaseOrMemberInitializer *&PrevInit) {
2000  if (!PrevInit) {
2001    PrevInit = Init;
2002    return false;
2003  }
2004
2005  if (FieldDecl *Field = Init->getMember())
2006    S.Diag(Init->getSourceLocation(),
2007           diag::err_multiple_mem_initialization)
2008      << Field->getDeclName()
2009      << Init->getSourceRange();
2010  else {
2011    Type *BaseClass = Init->getBaseClass();
2012    assert(BaseClass && "neither field nor base");
2013    S.Diag(Init->getSourceLocation(),
2014           diag::err_multiple_base_initialization)
2015      << QualType(BaseClass, 0)
2016      << Init->getSourceRange();
2017  }
2018  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2019    << 0 << PrevInit->getSourceRange();
2020
2021  return true;
2022}
2023
2024typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2025typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2026
2027bool CheckRedundantUnionInit(Sema &S,
2028                             CXXBaseOrMemberInitializer *Init,
2029                             RedundantUnionMap &Unions) {
2030  FieldDecl *Field = Init->getMember();
2031  RecordDecl *Parent = Field->getParent();
2032  if (!Parent->isAnonymousStructOrUnion())
2033    return false;
2034
2035  NamedDecl *Child = Field;
2036  do {
2037    if (Parent->isUnion()) {
2038      UnionEntry &En = Unions[Parent];
2039      if (En.first && En.first != Child) {
2040        S.Diag(Init->getSourceLocation(),
2041               diag::err_multiple_mem_union_initialization)
2042          << Field->getDeclName()
2043          << Init->getSourceRange();
2044        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2045          << 0 << En.second->getSourceRange();
2046        return true;
2047      } else if (!En.first) {
2048        En.first = Child;
2049        En.second = Init;
2050      }
2051    }
2052
2053    Child = Parent;
2054    Parent = cast<RecordDecl>(Parent->getDeclContext());
2055  } while (Parent->isAnonymousStructOrUnion());
2056
2057  return false;
2058}
2059}
2060
2061/// ActOnMemInitializers - Handle the member initializers for a constructor.
2062void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
2063                                SourceLocation ColonLoc,
2064                                MemInitTy **meminits, unsigned NumMemInits,
2065                                bool AnyErrors) {
2066  if (!ConstructorDecl)
2067    return;
2068
2069  AdjustDeclIfTemplate(ConstructorDecl);
2070
2071  CXXConstructorDecl *Constructor
2072    = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
2073
2074  if (!Constructor) {
2075    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2076    return;
2077  }
2078
2079  CXXBaseOrMemberInitializer **MemInits =
2080    reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
2081
2082  // Mapping for the duplicate initializers check.
2083  // For member initializers, this is keyed with a FieldDecl*.
2084  // For base initializers, this is keyed with a Type*.
2085  llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
2086
2087  // Mapping for the inconsistent anonymous-union initializers check.
2088  RedundantUnionMap MemberUnions;
2089
2090  bool HadError = false;
2091  for (unsigned i = 0; i < NumMemInits; i++) {
2092    CXXBaseOrMemberInitializer *Init = MemInits[i];
2093
2094    if (Init->isMemberInitializer()) {
2095      FieldDecl *Field = Init->getMember();
2096      if (CheckRedundantInit(*this, Init, Members[Field]) ||
2097          CheckRedundantUnionInit(*this, Init, MemberUnions))
2098        HadError = true;
2099    } else {
2100      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2101      if (CheckRedundantInit(*this, Init, Members[Key]))
2102        HadError = true;
2103    }
2104  }
2105
2106  if (HadError)
2107    return;
2108
2109  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
2110
2111  SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
2112}
2113
2114void
2115Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2116                                             CXXRecordDecl *ClassDecl) {
2117  // Ignore dependent contexts.
2118  if (ClassDecl->isDependentContext())
2119    return;
2120
2121  // FIXME: all the access-control diagnostics are positioned on the
2122  // field/base declaration.  That's probably good; that said, the
2123  // user might reasonably want to know why the destructor is being
2124  // emitted, and we currently don't say.
2125
2126  // Non-static data members.
2127  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2128       E = ClassDecl->field_end(); I != E; ++I) {
2129    FieldDecl *Field = *I;
2130
2131    QualType FieldType = Context.getBaseElementType(Field->getType());
2132
2133    const RecordType* RT = FieldType->getAs<RecordType>();
2134    if (!RT)
2135      continue;
2136
2137    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2138    if (FieldClassDecl->hasTrivialDestructor())
2139      continue;
2140
2141    CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
2142    CheckDestructorAccess(Field->getLocation(), Dtor,
2143                          PDiag(diag::err_access_dtor_field)
2144                            << Field->getDeclName()
2145                            << FieldType);
2146
2147    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2148  }
2149
2150  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2151
2152  // Bases.
2153  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2154       E = ClassDecl->bases_end(); Base != E; ++Base) {
2155    // Bases are always records in a well-formed non-dependent class.
2156    const RecordType *RT = Base->getType()->getAs<RecordType>();
2157
2158    // Remember direct virtual bases.
2159    if (Base->isVirtual())
2160      DirectVirtualBases.insert(RT);
2161
2162    // Ignore trivial destructors.
2163    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2164    if (BaseClassDecl->hasTrivialDestructor())
2165      continue;
2166
2167    CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2168
2169    // FIXME: caret should be on the start of the class name
2170    CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
2171                          PDiag(diag::err_access_dtor_base)
2172                            << Base->getType()
2173                            << Base->getSourceRange());
2174
2175    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2176  }
2177
2178  // Virtual bases.
2179  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2180       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2181
2182    // Bases are always records in a well-formed non-dependent class.
2183    const RecordType *RT = VBase->getType()->getAs<RecordType>();
2184
2185    // Ignore direct virtual bases.
2186    if (DirectVirtualBases.count(RT))
2187      continue;
2188
2189    // Ignore trivial destructors.
2190    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2191    if (BaseClassDecl->hasTrivialDestructor())
2192      continue;
2193
2194    CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2195    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
2196                          PDiag(diag::err_access_dtor_vbase)
2197                            << VBase->getType());
2198
2199    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2200  }
2201}
2202
2203void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
2204  if (!CDtorDecl)
2205    return;
2206
2207  if (CXXConstructorDecl *Constructor
2208      = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
2209    SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
2210}
2211
2212bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2213                                  unsigned DiagID, AbstractDiagSelID SelID,
2214                                  const CXXRecordDecl *CurrentRD) {
2215  if (SelID == -1)
2216    return RequireNonAbstractType(Loc, T,
2217                                  PDiag(DiagID), CurrentRD);
2218  else
2219    return RequireNonAbstractType(Loc, T,
2220                                  PDiag(DiagID) << SelID, CurrentRD);
2221}
2222
2223bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2224                                  const PartialDiagnostic &PD,
2225                                  const CXXRecordDecl *CurrentRD) {
2226  if (!getLangOptions().CPlusPlus)
2227    return false;
2228
2229  if (const ArrayType *AT = Context.getAsArrayType(T))
2230    return RequireNonAbstractType(Loc, AT->getElementType(), PD,
2231                                  CurrentRD);
2232
2233  if (const PointerType *PT = T->getAs<PointerType>()) {
2234    // Find the innermost pointer type.
2235    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
2236      PT = T;
2237
2238    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
2239      return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
2240  }
2241
2242  const RecordType *RT = T->getAs<RecordType>();
2243  if (!RT)
2244    return false;
2245
2246  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2247
2248  if (CurrentRD && CurrentRD != RD)
2249    return false;
2250
2251  // FIXME: is this reasonable?  It matches current behavior, but....
2252  if (!RD->getDefinition())
2253    return false;
2254
2255  if (!RD->isAbstract())
2256    return false;
2257
2258  Diag(Loc, PD) << RD->getDeclName();
2259
2260  // Check if we've already emitted the list of pure virtual functions for this
2261  // class.
2262  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2263    return true;
2264
2265  CXXFinalOverriderMap FinalOverriders;
2266  RD->getFinalOverriders(FinalOverriders);
2267
2268  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2269                                   MEnd = FinalOverriders.end();
2270       M != MEnd;
2271       ++M) {
2272    for (OverridingMethods::iterator SO = M->second.begin(),
2273                                  SOEnd = M->second.end();
2274         SO != SOEnd; ++SO) {
2275      // C++ [class.abstract]p4:
2276      //   A class is abstract if it contains or inherits at least one
2277      //   pure virtual function for which the final overrider is pure
2278      //   virtual.
2279
2280      //
2281      if (SO->second.size() != 1)
2282        continue;
2283
2284      if (!SO->second.front().Method->isPure())
2285        continue;
2286
2287      Diag(SO->second.front().Method->getLocation(),
2288           diag::note_pure_virtual_function)
2289        << SO->second.front().Method->getDeclName();
2290    }
2291  }
2292
2293  if (!PureVirtualClassDiagSet)
2294    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2295  PureVirtualClassDiagSet->insert(RD);
2296
2297  return true;
2298}
2299
2300namespace {
2301  class AbstractClassUsageDiagnoser
2302    : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2303    Sema &SemaRef;
2304    CXXRecordDecl *AbstractClass;
2305
2306    bool VisitDeclContext(const DeclContext *DC) {
2307      bool Invalid = false;
2308
2309      for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2310           E = DC->decls_end(); I != E; ++I)
2311        Invalid |= Visit(*I);
2312
2313      return Invalid;
2314    }
2315
2316  public:
2317    AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2318      : SemaRef(SemaRef), AbstractClass(ac) {
2319        Visit(SemaRef.Context.getTranslationUnitDecl());
2320    }
2321
2322    bool VisitFunctionDecl(const FunctionDecl *FD) {
2323      if (FD->isThisDeclarationADefinition()) {
2324        // No need to do the check if we're in a definition, because it requires
2325        // that the return/param types are complete.
2326        // because that requires
2327        return VisitDeclContext(FD);
2328      }
2329
2330      // Check the return type.
2331      QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
2332      bool Invalid =
2333        SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2334                                       diag::err_abstract_type_in_decl,
2335                                       Sema::AbstractReturnType,
2336                                       AbstractClass);
2337
2338      for (FunctionDecl::param_const_iterator I = FD->param_begin(),
2339           E = FD->param_end(); I != E; ++I) {
2340        const ParmVarDecl *VD = *I;
2341        Invalid |=
2342          SemaRef.RequireNonAbstractType(VD->getLocation(),
2343                                         VD->getOriginalType(),
2344                                         diag::err_abstract_type_in_decl,
2345                                         Sema::AbstractParamType,
2346                                         AbstractClass);
2347      }
2348
2349      return Invalid;
2350    }
2351
2352    bool VisitDecl(const Decl* D) {
2353      if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2354        return VisitDeclContext(DC);
2355
2356      return false;
2357    }
2358  };
2359}
2360
2361/// \brief Perform semantic checks on a class definition that has been
2362/// completing, introducing implicitly-declared members, checking for
2363/// abstract types, etc.
2364void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
2365  if (!Record || Record->isInvalidDecl())
2366    return;
2367
2368  if (!Record->isDependentType())
2369    AddImplicitlyDeclaredMembersToClass(S, Record);
2370
2371  if (Record->isInvalidDecl())
2372    return;
2373
2374  // Set access bits correctly on the directly-declared conversions.
2375  UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2376  for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2377    Convs->setAccess(I, (*I)->getAccess());
2378
2379  // Determine whether we need to check for final overriders. We do
2380  // this either when there are virtual base classes (in which case we
2381  // may end up finding multiple final overriders for a given virtual
2382  // function) or any of the base classes is abstract (in which case
2383  // we might detect that this class is abstract).
2384  bool CheckFinalOverriders = false;
2385  if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2386      !Record->isDependentType()) {
2387    if (Record->getNumVBases())
2388      CheckFinalOverriders = true;
2389    else if (!Record->isAbstract()) {
2390      for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2391                                                 BEnd = Record->bases_end();
2392           B != BEnd; ++B) {
2393        CXXRecordDecl *BaseDecl
2394          = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2395        if (BaseDecl->isAbstract()) {
2396          CheckFinalOverriders = true;
2397          break;
2398        }
2399      }
2400    }
2401  }
2402
2403  if (CheckFinalOverriders) {
2404    CXXFinalOverriderMap FinalOverriders;
2405    Record->getFinalOverriders(FinalOverriders);
2406
2407    for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2408                                     MEnd = FinalOverriders.end();
2409         M != MEnd; ++M) {
2410      for (OverridingMethods::iterator SO = M->second.begin(),
2411                                    SOEnd = M->second.end();
2412           SO != SOEnd; ++SO) {
2413        assert(SO->second.size() > 0 &&
2414               "All virtual functions have overridding virtual functions");
2415        if (SO->second.size() == 1) {
2416          // C++ [class.abstract]p4:
2417          //   A class is abstract if it contains or inherits at least one
2418          //   pure virtual function for which the final overrider is pure
2419          //   virtual.
2420          if (SO->second.front().Method->isPure())
2421            Record->setAbstract(true);
2422          continue;
2423        }
2424
2425        // C++ [class.virtual]p2:
2426        //   In a derived class, if a virtual member function of a base
2427        //   class subobject has more than one final overrider the
2428        //   program is ill-formed.
2429        Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2430          << (NamedDecl *)M->first << Record;
2431        Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2432        for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2433                                                 OMEnd = SO->second.end();
2434             OM != OMEnd; ++OM)
2435          Diag(OM->Method->getLocation(), diag::note_final_overrider)
2436            << (NamedDecl *)M->first << OM->Method->getParent();
2437
2438        Record->setInvalidDecl();
2439      }
2440    }
2441  }
2442
2443  if (Record->isAbstract() && !Record->isInvalidDecl())
2444    (void)AbstractClassUsageDiagnoser(*this, Record);
2445
2446  // If this is not an aggregate type and has no user-declared constructor,
2447  // complain about any non-static data members of reference or const scalar
2448  // type, since they will never get initializers.
2449  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2450      !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2451    bool Complained = false;
2452    for (RecordDecl::field_iterator F = Record->field_begin(),
2453                                 FEnd = Record->field_end();
2454         F != FEnd; ++F) {
2455      if (F->getType()->isReferenceType() ||
2456          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
2457        if (!Complained) {
2458          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2459            << Record->getTagKind() << Record;
2460          Complained = true;
2461        }
2462
2463        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2464          << F->getType()->isReferenceType()
2465          << F->getDeclName();
2466      }
2467    }
2468  }
2469}
2470
2471void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
2472                                             DeclPtrTy TagDecl,
2473                                             SourceLocation LBrac,
2474                                             SourceLocation RBrac,
2475                                             AttributeList *AttrList) {
2476  if (!TagDecl)
2477    return;
2478
2479  AdjustDeclIfTemplate(TagDecl);
2480
2481  ActOnFields(S, RLoc, TagDecl,
2482              (DeclPtrTy*)FieldCollector->getCurFields(),
2483              FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
2484
2485  CheckCompletedCXXClass(S,
2486                      dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
2487}
2488
2489/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2490/// special functions, such as the default constructor, copy
2491/// constructor, or destructor, to the given C++ class (C++
2492/// [special]p1).  This routine can only be executed just before the
2493/// definition of the class is complete.
2494///
2495/// The scope, if provided, is the class scope.
2496void Sema::AddImplicitlyDeclaredMembersToClass(Scope *S,
2497                                               CXXRecordDecl *ClassDecl) {
2498  CanQualType ClassType
2499    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
2500
2501  // FIXME: Implicit declarations have exception specifications, which are
2502  // the union of the specifications of the implicitly called functions.
2503
2504  if (!ClassDecl->hasUserDeclaredConstructor()) {
2505    // C++ [class.ctor]p5:
2506    //   A default constructor for a class X is a constructor of class X
2507    //   that can be called without an argument. If there is no
2508    //   user-declared constructor for class X, a default constructor is
2509    //   implicitly declared. An implicitly-declared default constructor
2510    //   is an inline public member of its class.
2511    DeclarationName Name
2512      = Context.DeclarationNames.getCXXConstructorName(ClassType);
2513    CXXConstructorDecl *DefaultCon =
2514      CXXConstructorDecl::Create(Context, ClassDecl,
2515                                 ClassDecl->getLocation(), Name,
2516                                 Context.getFunctionType(Context.VoidTy,
2517                                                         0, 0, false, 0,
2518                                                         /*FIXME*/false, false,
2519                                                         0, 0,
2520                                                       FunctionType::ExtInfo()),
2521                                 /*TInfo=*/0,
2522                                 /*isExplicit=*/false,
2523                                 /*isInline=*/true,
2524                                 /*isImplicitlyDeclared=*/true);
2525    DefaultCon->setAccess(AS_public);
2526    DefaultCon->setImplicit();
2527    DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
2528    if (S)
2529      PushOnScopeChains(DefaultCon, S, true);
2530    else
2531      ClassDecl->addDecl(DefaultCon);
2532  }
2533
2534  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2535    // C++ [class.copy]p4:
2536    //   If the class definition does not explicitly declare a copy
2537    //   constructor, one is declared implicitly.
2538
2539    // C++ [class.copy]p5:
2540    //   The implicitly-declared copy constructor for a class X will
2541    //   have the form
2542    //
2543    //       X::X(const X&)
2544    //
2545    //   if
2546    bool HasConstCopyConstructor = true;
2547
2548    //     -- each direct or virtual base class B of X has a copy
2549    //        constructor whose first parameter is of type const B& or
2550    //        const volatile B&, and
2551    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2552         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2553      const CXXRecordDecl *BaseClassDecl
2554        = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2555      HasConstCopyConstructor
2556        = BaseClassDecl->hasConstCopyConstructor(Context);
2557    }
2558
2559    //     -- for all the nonstatic data members of X that are of a
2560    //        class type M (or array thereof), each such class type
2561    //        has a copy constructor whose first parameter is of type
2562    //        const M& or const volatile M&.
2563    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2564         HasConstCopyConstructor && Field != ClassDecl->field_end();
2565         ++Field) {
2566      QualType FieldType = (*Field)->getType();
2567      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2568        FieldType = Array->getElementType();
2569      if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2570        const CXXRecordDecl *FieldClassDecl
2571          = cast<CXXRecordDecl>(FieldClassType->getDecl());
2572        HasConstCopyConstructor
2573          = FieldClassDecl->hasConstCopyConstructor(Context);
2574      }
2575    }
2576
2577    //   Otherwise, the implicitly declared copy constructor will have
2578    //   the form
2579    //
2580    //       X::X(X&)
2581    QualType ArgType = ClassType;
2582    if (HasConstCopyConstructor)
2583      ArgType = ArgType.withConst();
2584    ArgType = Context.getLValueReferenceType(ArgType);
2585
2586    //   An implicitly-declared copy constructor is an inline public
2587    //   member of its class.
2588    DeclarationName Name
2589      = Context.DeclarationNames.getCXXConstructorName(ClassType);
2590    CXXConstructorDecl *CopyConstructor
2591      = CXXConstructorDecl::Create(Context, ClassDecl,
2592                                   ClassDecl->getLocation(), Name,
2593                                   Context.getFunctionType(Context.VoidTy,
2594                                                           &ArgType, 1,
2595                                                           false, 0,
2596                                                           /*FIXME:*/false,
2597                                                           false, 0, 0,
2598                                                       FunctionType::ExtInfo()),
2599                                   /*TInfo=*/0,
2600                                   /*isExplicit=*/false,
2601                                   /*isInline=*/true,
2602                                   /*isImplicitlyDeclared=*/true);
2603    CopyConstructor->setAccess(AS_public);
2604    CopyConstructor->setImplicit();
2605    CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
2606
2607    // Add the parameter to the constructor.
2608    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2609                                                 ClassDecl->getLocation(),
2610                                                 /*IdentifierInfo=*/0,
2611                                                 ArgType, /*TInfo=*/0,
2612                                                 VarDecl::None,
2613                                                 VarDecl::None, 0);
2614    CopyConstructor->setParams(&FromParam, 1);
2615    if (S)
2616      PushOnScopeChains(CopyConstructor, S, true);
2617    else
2618      ClassDecl->addDecl(CopyConstructor);
2619  }
2620
2621  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2622    // Note: The following rules are largely analoguous to the copy
2623    // constructor rules. Note that virtual bases are not taken into account
2624    // for determining the argument type of the operator. Note also that
2625    // operators taking an object instead of a reference are allowed.
2626    //
2627    // C++ [class.copy]p10:
2628    //   If the class definition does not explicitly declare a copy
2629    //   assignment operator, one is declared implicitly.
2630    //   The implicitly-defined copy assignment operator for a class X
2631    //   will have the form
2632    //
2633    //       X& X::operator=(const X&)
2634    //
2635    //   if
2636    bool HasConstCopyAssignment = true;
2637
2638    //       -- each direct base class B of X has a copy assignment operator
2639    //          whose parameter is of type const B&, const volatile B& or B,
2640    //          and
2641    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2642         HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
2643      assert(!Base->getType()->isDependentType() &&
2644            "Cannot generate implicit members for class with dependent bases.");
2645      const CXXRecordDecl *BaseClassDecl
2646        = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2647      const CXXMethodDecl *MD = 0;
2648      HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
2649                                                                     MD);
2650    }
2651
2652    //       -- for all the nonstatic data members of X that are of a class
2653    //          type M (or array thereof), each such class type has a copy
2654    //          assignment operator whose parameter is of type const M&,
2655    //          const volatile M& or M.
2656    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2657         HasConstCopyAssignment && Field != ClassDecl->field_end();
2658         ++Field) {
2659      QualType FieldType = (*Field)->getType();
2660      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2661        FieldType = Array->getElementType();
2662      if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2663        const CXXRecordDecl *FieldClassDecl
2664          = cast<CXXRecordDecl>(FieldClassType->getDecl());
2665        const CXXMethodDecl *MD = 0;
2666        HasConstCopyAssignment
2667          = FieldClassDecl->hasConstCopyAssignment(Context, MD);
2668      }
2669    }
2670
2671    //   Otherwise, the implicitly declared copy assignment operator will
2672    //   have the form
2673    //
2674    //       X& X::operator=(X&)
2675    QualType ArgType = ClassType;
2676    QualType RetType = Context.getLValueReferenceType(ArgType);
2677    if (HasConstCopyAssignment)
2678      ArgType = ArgType.withConst();
2679    ArgType = Context.getLValueReferenceType(ArgType);
2680
2681    //   An implicitly-declared copy assignment operator is an inline public
2682    //   member of its class.
2683    DeclarationName Name =
2684      Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2685    CXXMethodDecl *CopyAssignment =
2686      CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2687                            Context.getFunctionType(RetType, &ArgType, 1,
2688                                                    false, 0,
2689                                                    /*FIXME:*/false,
2690                                                    false, 0, 0,
2691                                                    FunctionType::ExtInfo()),
2692                            /*TInfo=*/0, /*isStatic=*/false,
2693                            /*StorageClassAsWritten=*/FunctionDecl::None,
2694                            /*isInline=*/true);
2695    CopyAssignment->setAccess(AS_public);
2696    CopyAssignment->setImplicit();
2697    CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
2698    CopyAssignment->setCopyAssignment(true);
2699
2700    // Add the parameter to the operator.
2701    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2702                                                 ClassDecl->getLocation(),
2703                                                 /*Id=*/0,
2704                                                 ArgType, /*TInfo=*/0,
2705                                                 VarDecl::None,
2706                                                 VarDecl::None, 0);
2707    CopyAssignment->setParams(&FromParam, 1);
2708
2709    // Don't call addedAssignmentOperator. There is no way to distinguish an
2710    // implicit from an explicit assignment operator.
2711    if (S)
2712      PushOnScopeChains(CopyAssignment, S, true);
2713    else
2714      ClassDecl->addDecl(CopyAssignment);
2715    AddOverriddenMethods(ClassDecl, CopyAssignment);
2716  }
2717
2718  if (!ClassDecl->hasUserDeclaredDestructor()) {
2719    // C++ [class.dtor]p2:
2720    //   If a class has no user-declared destructor, a destructor is
2721    //   declared implicitly. An implicitly-declared destructor is an
2722    //   inline public member of its class.
2723    QualType Ty = Context.getFunctionType(Context.VoidTy,
2724                                          0, 0, false, 0,
2725                                          /*FIXME:*/false,
2726                                          false, 0, 0, FunctionType::ExtInfo());
2727
2728    DeclarationName Name
2729      = Context.DeclarationNames.getCXXDestructorName(ClassType);
2730    CXXDestructorDecl *Destructor
2731      = CXXDestructorDecl::Create(Context, ClassDecl,
2732                                  ClassDecl->getLocation(), Name, Ty,
2733                                  /*isInline=*/true,
2734                                  /*isImplicitlyDeclared=*/true);
2735    Destructor->setAccess(AS_public);
2736    Destructor->setImplicit();
2737    Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
2738    if (S)
2739      PushOnScopeChains(Destructor, S, true);
2740    else
2741      ClassDecl->addDecl(Destructor);
2742
2743    // This could be uniqued if it ever proves significant.
2744    Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
2745
2746    AddOverriddenMethods(ClassDecl, Destructor);
2747  }
2748}
2749
2750void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
2751  Decl *D = TemplateD.getAs<Decl>();
2752  if (!D)
2753    return;
2754
2755  TemplateParameterList *Params = 0;
2756  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2757    Params = Template->getTemplateParameters();
2758  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2759           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2760    Params = PartialSpec->getTemplateParameters();
2761  else
2762    return;
2763
2764  for (TemplateParameterList::iterator Param = Params->begin(),
2765                                    ParamEnd = Params->end();
2766       Param != ParamEnd; ++Param) {
2767    NamedDecl *Named = cast<NamedDecl>(*Param);
2768    if (Named->getDeclName()) {
2769      S->AddDecl(DeclPtrTy::make(Named));
2770      IdResolver.AddDecl(Named);
2771    }
2772  }
2773}
2774
2775void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2776  if (!RecordD) return;
2777  AdjustDeclIfTemplate(RecordD);
2778  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2779  PushDeclContext(S, Record);
2780}
2781
2782void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2783  if (!RecordD) return;
2784  PopDeclContext();
2785}
2786
2787/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2788/// parsing a top-level (non-nested) C++ class, and we are now
2789/// parsing those parts of the given Method declaration that could
2790/// not be parsed earlier (C++ [class.mem]p2), such as default
2791/// arguments. This action should enter the scope of the given
2792/// Method declaration as if we had just parsed the qualified method
2793/// name. However, it should not bring the parameters into scope;
2794/// that will be performed by ActOnDelayedCXXMethodParameter.
2795void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2796}
2797
2798/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2799/// C++ method declaration. We're (re-)introducing the given
2800/// function parameter into scope for use in parsing later parts of
2801/// the method declaration. For example, we could see an
2802/// ActOnParamDefaultArgument event for this parameter.
2803void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
2804  if (!ParamD)
2805    return;
2806
2807  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
2808
2809  // If this parameter has an unparsed default argument, clear it out
2810  // to make way for the parsed default argument.
2811  if (Param->hasUnparsedDefaultArg())
2812    Param->setDefaultArg(0);
2813
2814  S->AddDecl(DeclPtrTy::make(Param));
2815  if (Param->getDeclName())
2816    IdResolver.AddDecl(Param);
2817}
2818
2819/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2820/// processing the delayed method declaration for Method. The method
2821/// declaration is now considered finished. There may be a separate
2822/// ActOnStartOfFunctionDef action later (not necessarily
2823/// immediately!) for this method, if it was also defined inside the
2824/// class body.
2825void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2826  if (!MethodD)
2827    return;
2828
2829  AdjustDeclIfTemplate(MethodD);
2830
2831  FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
2832
2833  // Now that we have our default arguments, check the constructor
2834  // again. It could produce additional diagnostics or affect whether
2835  // the class has implicitly-declared destructors, among other
2836  // things.
2837  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2838    CheckConstructor(Constructor);
2839
2840  // Check the default arguments, which we may have added.
2841  if (!Method->isInvalidDecl())
2842    CheckCXXDefaultArguments(Method);
2843}
2844
2845/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
2846/// the well-formedness of the constructor declarator @p D with type @p
2847/// R. If there are any errors in the declarator, this routine will
2848/// emit diagnostics and set the invalid bit to true.  In any case, the type
2849/// will be updated to reflect a well-formed type for the constructor and
2850/// returned.
2851QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2852                                          FunctionDecl::StorageClass &SC) {
2853  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2854
2855  // C++ [class.ctor]p3:
2856  //   A constructor shall not be virtual (10.3) or static (9.4). A
2857  //   constructor can be invoked for a const, volatile or const
2858  //   volatile object. A constructor shall not be declared const,
2859  //   volatile, or const volatile (9.3.2).
2860  if (isVirtual) {
2861    if (!D.isInvalidType())
2862      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2863        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2864        << SourceRange(D.getIdentifierLoc());
2865    D.setInvalidType();
2866  }
2867  if (SC == FunctionDecl::Static) {
2868    if (!D.isInvalidType())
2869      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2870        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2871        << SourceRange(D.getIdentifierLoc());
2872    D.setInvalidType();
2873    SC = FunctionDecl::None;
2874  }
2875
2876  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2877  if (FTI.TypeQuals != 0) {
2878    if (FTI.TypeQuals & Qualifiers::Const)
2879      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2880        << "const" << SourceRange(D.getIdentifierLoc());
2881    if (FTI.TypeQuals & Qualifiers::Volatile)
2882      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2883        << "volatile" << SourceRange(D.getIdentifierLoc());
2884    if (FTI.TypeQuals & Qualifiers::Restrict)
2885      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2886        << "restrict" << SourceRange(D.getIdentifierLoc());
2887  }
2888
2889  // Rebuild the function type "R" without any type qualifiers (in
2890  // case any of the errors above fired) and with "void" as the
2891  // return type, since constructors don't have return types. We
2892  // *always* have to do this, because GetTypeForDeclarator will
2893  // put in a result type of "int" when none was specified.
2894  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
2895  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2896                                 Proto->getNumArgs(),
2897                                 Proto->isVariadic(), 0,
2898                                 Proto->hasExceptionSpec(),
2899                                 Proto->hasAnyExceptionSpec(),
2900                                 Proto->getNumExceptions(),
2901                                 Proto->exception_begin(),
2902                                 Proto->getExtInfo());
2903}
2904
2905/// CheckConstructor - Checks a fully-formed constructor for
2906/// well-formedness, issuing any diagnostics required. Returns true if
2907/// the constructor declarator is invalid.
2908void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
2909  CXXRecordDecl *ClassDecl
2910    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2911  if (!ClassDecl)
2912    return Constructor->setInvalidDecl();
2913
2914  // C++ [class.copy]p3:
2915  //   A declaration of a constructor for a class X is ill-formed if
2916  //   its first parameter is of type (optionally cv-qualified) X and
2917  //   either there are no other parameters or else all other
2918  //   parameters have default arguments.
2919  if (!Constructor->isInvalidDecl() &&
2920      ((Constructor->getNumParams() == 1) ||
2921       (Constructor->getNumParams() > 1 &&
2922        Constructor->getParamDecl(1)->hasDefaultArg())) &&
2923      Constructor->getTemplateSpecializationKind()
2924                                              != TSK_ImplicitInstantiation) {
2925    QualType ParamType = Constructor->getParamDecl(0)->getType();
2926    QualType ClassTy = Context.getTagDeclType(ClassDecl);
2927    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
2928      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2929      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
2930        << FixItHint::CreateInsertion(ParamLoc, " const &");
2931
2932      // FIXME: Rather that making the constructor invalid, we should endeavor
2933      // to fix the type.
2934      Constructor->setInvalidDecl();
2935    }
2936  }
2937
2938  // Notify the class that we've added a constructor.  In principle we
2939  // don't need to do this for out-of-line declarations; in practice
2940  // we only instantiate the most recent declaration of a method, so
2941  // we have to call this for everything but friends.
2942  if (!Constructor->getFriendObjectKind())
2943    ClassDecl->addedConstructor(Context, Constructor);
2944}
2945
2946/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2947/// issuing any diagnostics required. Returns true on error.
2948bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
2949  CXXRecordDecl *RD = Destructor->getParent();
2950
2951  if (Destructor->isVirtual()) {
2952    SourceLocation Loc;
2953
2954    if (!Destructor->isImplicit())
2955      Loc = Destructor->getLocation();
2956    else
2957      Loc = RD->getLocation();
2958
2959    // If we have a virtual destructor, look up the deallocation function
2960    FunctionDecl *OperatorDelete = 0;
2961    DeclarationName Name =
2962    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2963    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2964      return true;
2965
2966    Destructor->setOperatorDelete(OperatorDelete);
2967  }
2968
2969  return false;
2970}
2971
2972static inline bool
2973FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2974  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2975          FTI.ArgInfo[0].Param &&
2976          FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2977}
2978
2979/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2980/// the well-formednes of the destructor declarator @p D with type @p
2981/// R. If there are any errors in the declarator, this routine will
2982/// emit diagnostics and set the declarator to invalid.  Even if this happens,
2983/// will be updated to reflect a well-formed type for the destructor and
2984/// returned.
2985QualType Sema::CheckDestructorDeclarator(Declarator &D,
2986                                         FunctionDecl::StorageClass& SC) {
2987  // C++ [class.dtor]p1:
2988  //   [...] A typedef-name that names a class is a class-name
2989  //   (7.1.3); however, a typedef-name that names a class shall not
2990  //   be used as the identifier in the declarator for a destructor
2991  //   declaration.
2992  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
2993  if (isa<TypedefType>(DeclaratorType)) {
2994    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
2995      << DeclaratorType;
2996    D.setInvalidType();
2997  }
2998
2999  // C++ [class.dtor]p2:
3000  //   A destructor is used to destroy objects of its class type. A
3001  //   destructor takes no parameters, and no return type can be
3002  //   specified for it (not even void). The address of a destructor
3003  //   shall not be taken. A destructor shall not be static. A
3004  //   destructor can be invoked for a const, volatile or const
3005  //   volatile object. A destructor shall not be declared const,
3006  //   volatile or const volatile (9.3.2).
3007  if (SC == FunctionDecl::Static) {
3008    if (!D.isInvalidType())
3009      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3010        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3011        << SourceRange(D.getIdentifierLoc());
3012    SC = FunctionDecl::None;
3013    D.setInvalidType();
3014  }
3015  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
3016    // Destructors don't have return types, but the parser will
3017    // happily parse something like:
3018    //
3019    //   class X {
3020    //     float ~X();
3021    //   };
3022    //
3023    // The return type will be eliminated later.
3024    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3025      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3026      << SourceRange(D.getIdentifierLoc());
3027  }
3028
3029  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3030  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
3031    if (FTI.TypeQuals & Qualifiers::Const)
3032      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3033        << "const" << SourceRange(D.getIdentifierLoc());
3034    if (FTI.TypeQuals & Qualifiers::Volatile)
3035      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3036        << "volatile" << SourceRange(D.getIdentifierLoc());
3037    if (FTI.TypeQuals & Qualifiers::Restrict)
3038      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3039        << "restrict" << SourceRange(D.getIdentifierLoc());
3040    D.setInvalidType();
3041  }
3042
3043  // Make sure we don't have any parameters.
3044  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
3045    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3046
3047    // Delete the parameters.
3048    FTI.freeArgs();
3049    D.setInvalidType();
3050  }
3051
3052  // Make sure the destructor isn't variadic.
3053  if (FTI.isVariadic) {
3054    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
3055    D.setInvalidType();
3056  }
3057
3058  // Rebuild the function type "R" without any type qualifiers or
3059  // parameters (in case any of the errors above fired) and with
3060  // "void" as the return type, since destructors don't have return
3061  // types. We *always* have to do this, because GetTypeForDeclarator
3062  // will put in a result type of "int" when none was specified.
3063  // FIXME: Exceptions!
3064  return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
3065                                 false, false, 0, 0, FunctionType::ExtInfo());
3066}
3067
3068/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3069/// well-formednes of the conversion function declarator @p D with
3070/// type @p R. If there are any errors in the declarator, this routine
3071/// will emit diagnostics and return true. Otherwise, it will return
3072/// false. Either way, the type @p R will be updated to reflect a
3073/// well-formed type for the conversion operator.
3074void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
3075                                     FunctionDecl::StorageClass& SC) {
3076  // C++ [class.conv.fct]p1:
3077  //   Neither parameter types nor return type can be specified. The
3078  //   type of a conversion function (8.3.5) is "function taking no
3079  //   parameter returning conversion-type-id."
3080  if (SC == FunctionDecl::Static) {
3081    if (!D.isInvalidType())
3082      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3083        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3084        << SourceRange(D.getIdentifierLoc());
3085    D.setInvalidType();
3086    SC = FunctionDecl::None;
3087  }
3088
3089  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3090
3091  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
3092    // Conversion functions don't have return types, but the parser will
3093    // happily parse something like:
3094    //
3095    //   class X {
3096    //     float operator bool();
3097    //   };
3098    //
3099    // The return type will be changed later anyway.
3100    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3101      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3102      << SourceRange(D.getIdentifierLoc());
3103    D.setInvalidType();
3104  }
3105
3106  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3107
3108  // Make sure we don't have any parameters.
3109  if (Proto->getNumArgs() > 0) {
3110    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3111
3112    // Delete the parameters.
3113    D.getTypeObject(0).Fun.freeArgs();
3114    D.setInvalidType();
3115  } else if (Proto->isVariadic()) {
3116    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
3117    D.setInvalidType();
3118  }
3119
3120  // Diagnose "&operator bool()" and other such nonsense.  This
3121  // is actually a gcc extension which we don't support.
3122  if (Proto->getResultType() != ConvType) {
3123    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3124      << Proto->getResultType();
3125    D.setInvalidType();
3126    ConvType = Proto->getResultType();
3127  }
3128
3129  // C++ [class.conv.fct]p4:
3130  //   The conversion-type-id shall not represent a function type nor
3131  //   an array type.
3132  if (ConvType->isArrayType()) {
3133    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3134    ConvType = Context.getPointerType(ConvType);
3135    D.setInvalidType();
3136  } else if (ConvType->isFunctionType()) {
3137    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3138    ConvType = Context.getPointerType(ConvType);
3139    D.setInvalidType();
3140  }
3141
3142  // Rebuild the function type "R" without any parameters (in case any
3143  // of the errors above fired) and with the conversion type as the
3144  // return type.
3145  if (D.isInvalidType()) {
3146    R = Context.getFunctionType(ConvType, 0, 0, false,
3147                                Proto->getTypeQuals(),
3148                                Proto->hasExceptionSpec(),
3149                                Proto->hasAnyExceptionSpec(),
3150                                Proto->getNumExceptions(),
3151                                Proto->exception_begin(),
3152                                Proto->getExtInfo());
3153  }
3154
3155  // C++0x explicit conversion operators.
3156  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
3157    Diag(D.getDeclSpec().getExplicitSpecLoc(),
3158         diag::warn_explicit_conversion_functions)
3159      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
3160}
3161
3162/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3163/// the declaration of the given C++ conversion function. This routine
3164/// is responsible for recording the conversion function in the C++
3165/// class, if possible.
3166Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
3167  assert(Conversion && "Expected to receive a conversion function declaration");
3168
3169  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
3170
3171  // Make sure we aren't redeclaring the conversion function.
3172  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
3173
3174  // C++ [class.conv.fct]p1:
3175  //   [...] A conversion function is never used to convert a
3176  //   (possibly cv-qualified) object to the (possibly cv-qualified)
3177  //   same object type (or a reference to it), to a (possibly
3178  //   cv-qualified) base class of that type (or a reference to it),
3179  //   or to (possibly cv-qualified) void.
3180  // FIXME: Suppress this warning if the conversion function ends up being a
3181  // virtual function that overrides a virtual function in a base class.
3182  QualType ClassType
3183    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
3184  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
3185    ConvType = ConvTypeRef->getPointeeType();
3186  if (ConvType->isRecordType()) {
3187    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3188    if (ConvType == ClassType)
3189      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
3190        << ClassType;
3191    else if (IsDerivedFrom(ClassType, ConvType))
3192      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
3193        <<  ClassType << ConvType;
3194  } else if (ConvType->isVoidType()) {
3195    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
3196      << ClassType << ConvType;
3197  }
3198
3199  if (Conversion->getPrimaryTemplate()) {
3200    // ignore specializations
3201  } else if (Conversion->getPreviousDeclaration()) {
3202    if (FunctionTemplateDecl *ConversionTemplate
3203                                  = Conversion->getDescribedFunctionTemplate()) {
3204      if (ClassDecl->replaceConversion(
3205                                   ConversionTemplate->getPreviousDeclaration(),
3206                                       ConversionTemplate))
3207        return DeclPtrTy::make(ConversionTemplate);
3208    } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3209                                            Conversion))
3210      return DeclPtrTy::make(Conversion);
3211    assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
3212  } else if (FunctionTemplateDecl *ConversionTemplate
3213               = Conversion->getDescribedFunctionTemplate())
3214    ClassDecl->addConversionFunction(ConversionTemplate);
3215  else
3216    ClassDecl->addConversionFunction(Conversion);
3217
3218  return DeclPtrTy::make(Conversion);
3219}
3220
3221//===----------------------------------------------------------------------===//
3222// Namespace Handling
3223//===----------------------------------------------------------------------===//
3224
3225/// ActOnStartNamespaceDef - This is called at the start of a namespace
3226/// definition.
3227Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
3228                                             SourceLocation IdentLoc,
3229                                             IdentifierInfo *II,
3230                                             SourceLocation LBrace,
3231                                             AttributeList *AttrList) {
3232  NamespaceDecl *Namespc =
3233      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
3234  Namespc->setLBracLoc(LBrace);
3235
3236  Scope *DeclRegionScope = NamespcScope->getParent();
3237
3238  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3239
3240  if (II) {
3241    // C++ [namespace.def]p2:
3242    // The identifier in an original-namespace-definition shall not have been
3243    // previously defined in the declarative region in which the
3244    // original-namespace-definition appears. The identifier in an
3245    // original-namespace-definition is the name of the namespace. Subsequently
3246    // in that declarative region, it is treated as an original-namespace-name.
3247
3248    NamedDecl *PrevDecl
3249      = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
3250                         ForRedeclaration);
3251
3252    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3253      // This is an extended namespace definition.
3254      // Attach this namespace decl to the chain of extended namespace
3255      // definitions.
3256      OrigNS->setNextNamespace(Namespc);
3257      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
3258
3259      // Remove the previous declaration from the scope.
3260      if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
3261        IdResolver.RemoveDecl(OrigNS);
3262        DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
3263      }
3264    } else if (PrevDecl) {
3265      // This is an invalid name redefinition.
3266      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3267       << Namespc->getDeclName();
3268      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3269      Namespc->setInvalidDecl();
3270      // Continue on to push Namespc as current DeclContext and return it.
3271    } else if (II->isStr("std") &&
3272               CurContext->getLookupContext()->isTranslationUnit()) {
3273      // This is the first "real" definition of the namespace "std", so update
3274      // our cache of the "std" namespace to point at this definition.
3275      if (StdNamespace) {
3276        // We had already defined a dummy namespace "std". Link this new
3277        // namespace definition to the dummy namespace "std".
3278        StdNamespace->setNextNamespace(Namespc);
3279        StdNamespace->setLocation(IdentLoc);
3280        Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
3281      }
3282
3283      // Make our StdNamespace cache point at the first real definition of the
3284      // "std" namespace.
3285      StdNamespace = Namespc;
3286    }
3287
3288    PushOnScopeChains(Namespc, DeclRegionScope);
3289  } else {
3290    // Anonymous namespaces.
3291    assert(Namespc->isAnonymousNamespace());
3292
3293    // Link the anonymous namespace into its parent.
3294    NamespaceDecl *PrevDecl;
3295    DeclContext *Parent = CurContext->getLookupContext();
3296    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3297      PrevDecl = TU->getAnonymousNamespace();
3298      TU->setAnonymousNamespace(Namespc);
3299    } else {
3300      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3301      PrevDecl = ND->getAnonymousNamespace();
3302      ND->setAnonymousNamespace(Namespc);
3303    }
3304
3305    // Link the anonymous namespace with its previous declaration.
3306    if (PrevDecl) {
3307      assert(PrevDecl->isAnonymousNamespace());
3308      assert(!PrevDecl->getNextNamespace());
3309      Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3310      PrevDecl->setNextNamespace(Namespc);
3311    }
3312
3313    CurContext->addDecl(Namespc);
3314
3315    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
3316    //   behaves as if it were replaced by
3317    //     namespace unique { /* empty body */ }
3318    //     using namespace unique;
3319    //     namespace unique { namespace-body }
3320    //   where all occurrences of 'unique' in a translation unit are
3321    //   replaced by the same identifier and this identifier differs
3322    //   from all other identifiers in the entire program.
3323
3324    // We just create the namespace with an empty name and then add an
3325    // implicit using declaration, just like the standard suggests.
3326    //
3327    // CodeGen enforces the "universally unique" aspect by giving all
3328    // declarations semantically contained within an anonymous
3329    // namespace internal linkage.
3330
3331    if (!PrevDecl) {
3332      UsingDirectiveDecl* UD
3333        = UsingDirectiveDecl::Create(Context, CurContext,
3334                                     /* 'using' */ LBrace,
3335                                     /* 'namespace' */ SourceLocation(),
3336                                     /* qualifier */ SourceRange(),
3337                                     /* NNS */ NULL,
3338                                     /* identifier */ SourceLocation(),
3339                                     Namespc,
3340                                     /* Ancestor */ CurContext);
3341      UD->setImplicit();
3342      CurContext->addDecl(UD);
3343    }
3344  }
3345
3346  // Although we could have an invalid decl (i.e. the namespace name is a
3347  // redefinition), push it as current DeclContext and try to continue parsing.
3348  // FIXME: We should be able to push Namespc here, so that the each DeclContext
3349  // for the namespace has the declarations that showed up in that particular
3350  // namespace definition.
3351  PushDeclContext(NamespcScope, Namespc);
3352  return DeclPtrTy::make(Namespc);
3353}
3354
3355/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3356/// is a namespace alias, returns the namespace it points to.
3357static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3358  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3359    return AD->getNamespace();
3360  return dyn_cast_or_null<NamespaceDecl>(D);
3361}
3362
3363/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3364/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
3365void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3366  Decl *Dcl = D.getAs<Decl>();
3367  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3368  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3369  Namespc->setRBracLoc(RBrace);
3370  PopDeclContext();
3371}
3372
3373Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3374                                          SourceLocation UsingLoc,
3375                                          SourceLocation NamespcLoc,
3376                                          CXXScopeSpec &SS,
3377                                          SourceLocation IdentLoc,
3378                                          IdentifierInfo *NamespcName,
3379                                          AttributeList *AttrList) {
3380  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3381  assert(NamespcName && "Invalid NamespcName.");
3382  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
3383  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
3384
3385  UsingDirectiveDecl *UDir = 0;
3386
3387  // Lookup namespace name.
3388  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3389  LookupParsedName(R, S, &SS);
3390  if (R.isAmbiguous())
3391    return DeclPtrTy();
3392
3393  if (!R.empty()) {
3394    NamedDecl *Named = R.getFoundDecl();
3395    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3396        && "expected namespace decl");
3397    // C++ [namespace.udir]p1:
3398    //   A using-directive specifies that the names in the nominated
3399    //   namespace can be used in the scope in which the
3400    //   using-directive appears after the using-directive. During
3401    //   unqualified name lookup (3.4.1), the names appear as if they
3402    //   were declared in the nearest enclosing namespace which
3403    //   contains both the using-directive and the nominated
3404    //   namespace. [Note: in this context, "contains" means "contains
3405    //   directly or indirectly". ]
3406
3407    // Find enclosing context containing both using-directive and
3408    // nominated namespace.
3409    NamespaceDecl *NS = getNamespaceDecl(Named);
3410    DeclContext *CommonAncestor = cast<DeclContext>(NS);
3411    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3412      CommonAncestor = CommonAncestor->getParent();
3413
3414    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
3415                                      SS.getRange(),
3416                                      (NestedNameSpecifier *)SS.getScopeRep(),
3417                                      IdentLoc, Named, CommonAncestor);
3418    PushUsingDirective(S, UDir);
3419  } else {
3420    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
3421  }
3422
3423  // FIXME: We ignore attributes for now.
3424  delete AttrList;
3425  return DeclPtrTy::make(UDir);
3426}
3427
3428void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3429  // If scope has associated entity, then using directive is at namespace
3430  // or translation unit scope. We add UsingDirectiveDecls, into
3431  // it's lookup structure.
3432  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
3433    Ctx->addDecl(UDir);
3434  else
3435    // Otherwise it is block-sope. using-directives will affect lookup
3436    // only to the end of scope.
3437    S->PushUsingDirective(DeclPtrTy::make(UDir));
3438}
3439
3440
3441Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
3442                                            AccessSpecifier AS,
3443                                            bool HasUsingKeyword,
3444                                            SourceLocation UsingLoc,
3445                                            CXXScopeSpec &SS,
3446                                            UnqualifiedId &Name,
3447                                            AttributeList *AttrList,
3448                                            bool IsTypeName,
3449                                            SourceLocation TypenameLoc) {
3450  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
3451
3452  switch (Name.getKind()) {
3453  case UnqualifiedId::IK_Identifier:
3454  case UnqualifiedId::IK_OperatorFunctionId:
3455  case UnqualifiedId::IK_LiteralOperatorId:
3456  case UnqualifiedId::IK_ConversionFunctionId:
3457    break;
3458
3459  case UnqualifiedId::IK_ConstructorName:
3460  case UnqualifiedId::IK_ConstructorTemplateId:
3461    // C++0x inherited constructors.
3462    if (getLangOptions().CPlusPlus0x) break;
3463
3464    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3465      << SS.getRange();
3466    return DeclPtrTy();
3467
3468  case UnqualifiedId::IK_DestructorName:
3469    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3470      << SS.getRange();
3471    return DeclPtrTy();
3472
3473  case UnqualifiedId::IK_TemplateId:
3474    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3475      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3476    return DeclPtrTy();
3477  }
3478
3479  DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
3480  if (!TargetName)
3481    return DeclPtrTy();
3482
3483  // Warn about using declarations.
3484  // TODO: store that the declaration was written without 'using' and
3485  // talk about access decls instead of using decls in the
3486  // diagnostics.
3487  if (!HasUsingKeyword) {
3488    UsingLoc = Name.getSourceRange().getBegin();
3489
3490    Diag(UsingLoc, diag::warn_access_decl_deprecated)
3491      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
3492  }
3493
3494  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
3495                                        Name.getSourceRange().getBegin(),
3496                                        TargetName, AttrList,
3497                                        /* IsInstantiation */ false,
3498                                        IsTypeName, TypenameLoc);
3499  if (UD)
3500    PushOnScopeChains(UD, S, /*AddToContext*/ false);
3501
3502  return DeclPtrTy::make(UD);
3503}
3504
3505/// Determines whether to create a using shadow decl for a particular
3506/// decl, given the set of decls existing prior to this using lookup.
3507bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3508                                const LookupResult &Previous) {
3509  // Diagnose finding a decl which is not from a base class of the
3510  // current class.  We do this now because there are cases where this
3511  // function will silently decide not to build a shadow decl, which
3512  // will pre-empt further diagnostics.
3513  //
3514  // We don't need to do this in C++0x because we do the check once on
3515  // the qualifier.
3516  //
3517  // FIXME: diagnose the following if we care enough:
3518  //   struct A { int foo; };
3519  //   struct B : A { using A::foo; };
3520  //   template <class T> struct C : A {};
3521  //   template <class T> struct D : C<T> { using B::foo; } // <---
3522  // This is invalid (during instantiation) in C++03 because B::foo
3523  // resolves to the using decl in B, which is not a base class of D<T>.
3524  // We can't diagnose it immediately because C<T> is an unknown
3525  // specialization.  The UsingShadowDecl in D<T> then points directly
3526  // to A::foo, which will look well-formed when we instantiate.
3527  // The right solution is to not collapse the shadow-decl chain.
3528  if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3529    DeclContext *OrigDC = Orig->getDeclContext();
3530
3531    // Handle enums and anonymous structs.
3532    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3533    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3534    while (OrigRec->isAnonymousStructOrUnion())
3535      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3536
3537    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3538      if (OrigDC == CurContext) {
3539        Diag(Using->getLocation(),
3540             diag::err_using_decl_nested_name_specifier_is_current_class)
3541          << Using->getNestedNameRange();
3542        Diag(Orig->getLocation(), diag::note_using_decl_target);
3543        return true;
3544      }
3545
3546      Diag(Using->getNestedNameRange().getBegin(),
3547           diag::err_using_decl_nested_name_specifier_is_not_base_class)
3548        << Using->getTargetNestedNameDecl()
3549        << cast<CXXRecordDecl>(CurContext)
3550        << Using->getNestedNameRange();
3551      Diag(Orig->getLocation(), diag::note_using_decl_target);
3552      return true;
3553    }
3554  }
3555
3556  if (Previous.empty()) return false;
3557
3558  NamedDecl *Target = Orig;
3559  if (isa<UsingShadowDecl>(Target))
3560    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3561
3562  // If the target happens to be one of the previous declarations, we
3563  // don't have a conflict.
3564  //
3565  // FIXME: but we might be increasing its access, in which case we
3566  // should redeclare it.
3567  NamedDecl *NonTag = 0, *Tag = 0;
3568  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3569         I != E; ++I) {
3570    NamedDecl *D = (*I)->getUnderlyingDecl();
3571    if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3572      return false;
3573
3574    (isa<TagDecl>(D) ? Tag : NonTag) = D;
3575  }
3576
3577  if (Target->isFunctionOrFunctionTemplate()) {
3578    FunctionDecl *FD;
3579    if (isa<FunctionTemplateDecl>(Target))
3580      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3581    else
3582      FD = cast<FunctionDecl>(Target);
3583
3584    NamedDecl *OldDecl = 0;
3585    switch (CheckOverload(FD, Previous, OldDecl)) {
3586    case Ovl_Overload:
3587      return false;
3588
3589    case Ovl_NonFunction:
3590      Diag(Using->getLocation(), diag::err_using_decl_conflict);
3591      break;
3592
3593    // We found a decl with the exact signature.
3594    case Ovl_Match:
3595      if (isa<UsingShadowDecl>(OldDecl)) {
3596        // Silently ignore the possible conflict.
3597        return false;
3598      }
3599
3600      // If we're in a record, we want to hide the target, so we
3601      // return true (without a diagnostic) to tell the caller not to
3602      // build a shadow decl.
3603      if (CurContext->isRecord())
3604        return true;
3605
3606      // If we're not in a record, this is an error.
3607      Diag(Using->getLocation(), diag::err_using_decl_conflict);
3608      break;
3609    }
3610
3611    Diag(Target->getLocation(), diag::note_using_decl_target);
3612    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3613    return true;
3614  }
3615
3616  // Target is not a function.
3617
3618  if (isa<TagDecl>(Target)) {
3619    // No conflict between a tag and a non-tag.
3620    if (!Tag) return false;
3621
3622    Diag(Using->getLocation(), diag::err_using_decl_conflict);
3623    Diag(Target->getLocation(), diag::note_using_decl_target);
3624    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3625    return true;
3626  }
3627
3628  // No conflict between a tag and a non-tag.
3629  if (!NonTag) return false;
3630
3631  Diag(Using->getLocation(), diag::err_using_decl_conflict);
3632  Diag(Target->getLocation(), diag::note_using_decl_target);
3633  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3634  return true;
3635}
3636
3637/// Builds a shadow declaration corresponding to a 'using' declaration.
3638UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
3639                                            UsingDecl *UD,
3640                                            NamedDecl *Orig) {
3641
3642  // If we resolved to another shadow declaration, just coalesce them.
3643  NamedDecl *Target = Orig;
3644  if (isa<UsingShadowDecl>(Target)) {
3645    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3646    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
3647  }
3648
3649  UsingShadowDecl *Shadow
3650    = UsingShadowDecl::Create(Context, CurContext,
3651                              UD->getLocation(), UD, Target);
3652  UD->addShadowDecl(Shadow);
3653
3654  if (S)
3655    PushOnScopeChains(Shadow, S);
3656  else
3657    CurContext->addDecl(Shadow);
3658  Shadow->setAccess(UD->getAccess());
3659
3660  // Register it as a conversion if appropriate.
3661  if (Shadow->getDeclName().getNameKind()
3662        == DeclarationName::CXXConversionFunctionName)
3663    cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3664
3665  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3666    Shadow->setInvalidDecl();
3667
3668  return Shadow;
3669}
3670
3671/// Hides a using shadow declaration.  This is required by the current
3672/// using-decl implementation when a resolvable using declaration in a
3673/// class is followed by a declaration which would hide or override
3674/// one or more of the using decl's targets; for example:
3675///
3676///   struct Base { void foo(int); };
3677///   struct Derived : Base {
3678///     using Base::foo;
3679///     void foo(int);
3680///   };
3681///
3682/// The governing language is C++03 [namespace.udecl]p12:
3683///
3684///   When a using-declaration brings names from a base class into a
3685///   derived class scope, member functions in the derived class
3686///   override and/or hide member functions with the same name and
3687///   parameter types in a base class (rather than conflicting).
3688///
3689/// There are two ways to implement this:
3690///   (1) optimistically create shadow decls when they're not hidden
3691///       by existing declarations, or
3692///   (2) don't create any shadow decls (or at least don't make them
3693///       visible) until we've fully parsed/instantiated the class.
3694/// The problem with (1) is that we might have to retroactively remove
3695/// a shadow decl, which requires several O(n) operations because the
3696/// decl structures are (very reasonably) not designed for removal.
3697/// (2) avoids this but is very fiddly and phase-dependent.
3698void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3699  if (Shadow->getDeclName().getNameKind() ==
3700        DeclarationName::CXXConversionFunctionName)
3701    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3702
3703  // Remove it from the DeclContext...
3704  Shadow->getDeclContext()->removeDecl(Shadow);
3705
3706  // ...and the scope, if applicable...
3707  if (S) {
3708    S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3709    IdResolver.RemoveDecl(Shadow);
3710  }
3711
3712  // ...and the using decl.
3713  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3714
3715  // TODO: complain somehow if Shadow was used.  It shouldn't
3716  // be possible for this to happen, because...?
3717}
3718
3719/// Builds a using declaration.
3720///
3721/// \param IsInstantiation - Whether this call arises from an
3722///   instantiation of an unresolved using declaration.  We treat
3723///   the lookup differently for these declarations.
3724NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3725                                       SourceLocation UsingLoc,
3726                                       CXXScopeSpec &SS,
3727                                       SourceLocation IdentLoc,
3728                                       DeclarationName Name,
3729                                       AttributeList *AttrList,
3730                                       bool IsInstantiation,
3731                                       bool IsTypeName,
3732                                       SourceLocation TypenameLoc) {
3733  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3734  assert(IdentLoc.isValid() && "Invalid TargetName location.");
3735
3736  // FIXME: We ignore attributes for now.
3737  delete AttrList;
3738
3739  if (SS.isEmpty()) {
3740    Diag(IdentLoc, diag::err_using_requires_qualname);
3741    return 0;
3742  }
3743
3744  // Do the redeclaration lookup in the current scope.
3745  LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3746                        ForRedeclaration);
3747  Previous.setHideTags(false);
3748  if (S) {
3749    LookupName(Previous, S);
3750
3751    // It is really dumb that we have to do this.
3752    LookupResult::Filter F = Previous.makeFilter();
3753    while (F.hasNext()) {
3754      NamedDecl *D = F.next();
3755      if (!isDeclInScope(D, CurContext, S))
3756        F.erase();
3757    }
3758    F.done();
3759  } else {
3760    assert(IsInstantiation && "no scope in non-instantiation");
3761    assert(CurContext->isRecord() && "scope not record in instantiation");
3762    LookupQualifiedName(Previous, CurContext);
3763  }
3764
3765  NestedNameSpecifier *NNS =
3766    static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3767
3768  // Check for invalid redeclarations.
3769  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3770    return 0;
3771
3772  // Check for bad qualifiers.
3773  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3774    return 0;
3775
3776  DeclContext *LookupContext = computeDeclContext(SS);
3777  NamedDecl *D;
3778  if (!LookupContext) {
3779    if (IsTypeName) {
3780      // FIXME: not all declaration name kinds are legal here
3781      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3782                                              UsingLoc, TypenameLoc,
3783                                              SS.getRange(), NNS,
3784                                              IdentLoc, Name);
3785    } else {
3786      D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3787                                           UsingLoc, SS.getRange(), NNS,
3788                                           IdentLoc, Name);
3789    }
3790  } else {
3791    D = UsingDecl::Create(Context, CurContext, IdentLoc,
3792                          SS.getRange(), UsingLoc, NNS, Name,
3793                          IsTypeName);
3794  }
3795  D->setAccess(AS);
3796  CurContext->addDecl(D);
3797
3798  if (!LookupContext) return D;
3799  UsingDecl *UD = cast<UsingDecl>(D);
3800
3801  if (RequireCompleteDeclContext(SS, LookupContext)) {
3802    UD->setInvalidDecl();
3803    return UD;
3804  }
3805
3806  // Look up the target name.
3807
3808  LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
3809
3810  // Unlike most lookups, we don't always want to hide tag
3811  // declarations: tag names are visible through the using declaration
3812  // even if hidden by ordinary names, *except* in a dependent context
3813  // where it's important for the sanity of two-phase lookup.
3814  if (!IsInstantiation)
3815    R.setHideTags(false);
3816
3817  LookupQualifiedName(R, LookupContext);
3818
3819  if (R.empty()) {
3820    Diag(IdentLoc, diag::err_no_member)
3821      << Name << LookupContext << SS.getRange();
3822    UD->setInvalidDecl();
3823    return UD;
3824  }
3825
3826  if (R.isAmbiguous()) {
3827    UD->setInvalidDecl();
3828    return UD;
3829  }
3830
3831  if (IsTypeName) {
3832    // If we asked for a typename and got a non-type decl, error out.
3833    if (!R.getAsSingle<TypeDecl>()) {
3834      Diag(IdentLoc, diag::err_using_typename_non_type);
3835      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3836        Diag((*I)->getUnderlyingDecl()->getLocation(),
3837             diag::note_using_decl_target);
3838      UD->setInvalidDecl();
3839      return UD;
3840    }
3841  } else {
3842    // If we asked for a non-typename and we got a type, error out,
3843    // but only if this is an instantiation of an unresolved using
3844    // decl.  Otherwise just silently find the type name.
3845    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
3846      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3847      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
3848      UD->setInvalidDecl();
3849      return UD;
3850    }
3851  }
3852
3853  // C++0x N2914 [namespace.udecl]p6:
3854  // A using-declaration shall not name a namespace.
3855  if (R.getAsSingle<NamespaceDecl>()) {
3856    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3857      << SS.getRange();
3858    UD->setInvalidDecl();
3859    return UD;
3860  }
3861
3862  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3863    if (!CheckUsingShadowDecl(UD, *I, Previous))
3864      BuildUsingShadowDecl(S, UD, *I);
3865  }
3866
3867  return UD;
3868}
3869
3870/// Checks that the given using declaration is not an invalid
3871/// redeclaration.  Note that this is checking only for the using decl
3872/// itself, not for any ill-formedness among the UsingShadowDecls.
3873bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3874                                       bool isTypeName,
3875                                       const CXXScopeSpec &SS,
3876                                       SourceLocation NameLoc,
3877                                       const LookupResult &Prev) {
3878  // C++03 [namespace.udecl]p8:
3879  // C++0x [namespace.udecl]p10:
3880  //   A using-declaration is a declaration and can therefore be used
3881  //   repeatedly where (and only where) multiple declarations are
3882  //   allowed.
3883  // That's only in file contexts.
3884  if (CurContext->getLookupContext()->isFileContext())
3885    return false;
3886
3887  NestedNameSpecifier *Qual
3888    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3889
3890  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3891    NamedDecl *D = *I;
3892
3893    bool DTypename;
3894    NestedNameSpecifier *DQual;
3895    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3896      DTypename = UD->isTypeName();
3897      DQual = UD->getTargetNestedNameDecl();
3898    } else if (UnresolvedUsingValueDecl *UD
3899                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3900      DTypename = false;
3901      DQual = UD->getTargetNestedNameSpecifier();
3902    } else if (UnresolvedUsingTypenameDecl *UD
3903                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3904      DTypename = true;
3905      DQual = UD->getTargetNestedNameSpecifier();
3906    } else continue;
3907
3908    // using decls differ if one says 'typename' and the other doesn't.
3909    // FIXME: non-dependent using decls?
3910    if (isTypeName != DTypename) continue;
3911
3912    // using decls differ if they name different scopes (but note that
3913    // template instantiation can cause this check to trigger when it
3914    // didn't before instantiation).
3915    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3916        Context.getCanonicalNestedNameSpecifier(DQual))
3917      continue;
3918
3919    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
3920    Diag(D->getLocation(), diag::note_using_decl) << 1;
3921    return true;
3922  }
3923
3924  return false;
3925}
3926
3927
3928/// Checks that the given nested-name qualifier used in a using decl
3929/// in the current context is appropriately related to the current
3930/// scope.  If an error is found, diagnoses it and returns true.
3931bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3932                                   const CXXScopeSpec &SS,
3933                                   SourceLocation NameLoc) {
3934  DeclContext *NamedContext = computeDeclContext(SS);
3935
3936  if (!CurContext->isRecord()) {
3937    // C++03 [namespace.udecl]p3:
3938    // C++0x [namespace.udecl]p8:
3939    //   A using-declaration for a class member shall be a member-declaration.
3940
3941    // If we weren't able to compute a valid scope, it must be a
3942    // dependent class scope.
3943    if (!NamedContext || NamedContext->isRecord()) {
3944      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3945        << SS.getRange();
3946      return true;
3947    }
3948
3949    // Otherwise, everything is known to be fine.
3950    return false;
3951  }
3952
3953  // The current scope is a record.
3954
3955  // If the named context is dependent, we can't decide much.
3956  if (!NamedContext) {
3957    // FIXME: in C++0x, we can diagnose if we can prove that the
3958    // nested-name-specifier does not refer to a base class, which is
3959    // still possible in some cases.
3960
3961    // Otherwise we have to conservatively report that things might be
3962    // okay.
3963    return false;
3964  }
3965
3966  if (!NamedContext->isRecord()) {
3967    // Ideally this would point at the last name in the specifier,
3968    // but we don't have that level of source info.
3969    Diag(SS.getRange().getBegin(),
3970         diag::err_using_decl_nested_name_specifier_is_not_class)
3971      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3972    return true;
3973  }
3974
3975  if (getLangOptions().CPlusPlus0x) {
3976    // C++0x [namespace.udecl]p3:
3977    //   In a using-declaration used as a member-declaration, the
3978    //   nested-name-specifier shall name a base class of the class
3979    //   being defined.
3980
3981    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3982                                 cast<CXXRecordDecl>(NamedContext))) {
3983      if (CurContext == NamedContext) {
3984        Diag(NameLoc,
3985             diag::err_using_decl_nested_name_specifier_is_current_class)
3986          << SS.getRange();
3987        return true;
3988      }
3989
3990      Diag(SS.getRange().getBegin(),
3991           diag::err_using_decl_nested_name_specifier_is_not_base_class)
3992        << (NestedNameSpecifier*) SS.getScopeRep()
3993        << cast<CXXRecordDecl>(CurContext)
3994        << SS.getRange();
3995      return true;
3996    }
3997
3998    return false;
3999  }
4000
4001  // C++03 [namespace.udecl]p4:
4002  //   A using-declaration used as a member-declaration shall refer
4003  //   to a member of a base class of the class being defined [etc.].
4004
4005  // Salient point: SS doesn't have to name a base class as long as
4006  // lookup only finds members from base classes.  Therefore we can
4007  // diagnose here only if we can prove that that can't happen,
4008  // i.e. if the class hierarchies provably don't intersect.
4009
4010  // TODO: it would be nice if "definitely valid" results were cached
4011  // in the UsingDecl and UsingShadowDecl so that these checks didn't
4012  // need to be repeated.
4013
4014  struct UserData {
4015    llvm::DenseSet<const CXXRecordDecl*> Bases;
4016
4017    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4018      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4019      Data->Bases.insert(Base);
4020      return true;
4021    }
4022
4023    bool hasDependentBases(const CXXRecordDecl *Class) {
4024      return !Class->forallBases(collect, this);
4025    }
4026
4027    /// Returns true if the base is dependent or is one of the
4028    /// accumulated base classes.
4029    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4030      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4031      return !Data->Bases.count(Base);
4032    }
4033
4034    bool mightShareBases(const CXXRecordDecl *Class) {
4035      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4036    }
4037  };
4038
4039  UserData Data;
4040
4041  // Returns false if we find a dependent base.
4042  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4043    return false;
4044
4045  // Returns false if the class has a dependent base or if it or one
4046  // of its bases is present in the base set of the current context.
4047  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4048    return false;
4049
4050  Diag(SS.getRange().getBegin(),
4051       diag::err_using_decl_nested_name_specifier_is_not_base_class)
4052    << (NestedNameSpecifier*) SS.getScopeRep()
4053    << cast<CXXRecordDecl>(CurContext)
4054    << SS.getRange();
4055
4056  return true;
4057}
4058
4059Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
4060                                             SourceLocation NamespaceLoc,
4061                                             SourceLocation AliasLoc,
4062                                             IdentifierInfo *Alias,
4063                                             CXXScopeSpec &SS,
4064                                             SourceLocation IdentLoc,
4065                                             IdentifierInfo *Ident) {
4066
4067  // Lookup the namespace name.
4068  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4069  LookupParsedName(R, S, &SS);
4070
4071  // Check if we have a previous declaration with the same name.
4072  NamedDecl *PrevDecl
4073    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4074                       ForRedeclaration);
4075  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4076    PrevDecl = 0;
4077
4078  if (PrevDecl) {
4079    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
4080      // We already have an alias with the same name that points to the same
4081      // namespace, so don't create a new one.
4082      // FIXME: At some point, we'll want to create the (redundant)
4083      // declaration to maintain better source information.
4084      if (!R.isAmbiguous() && !R.empty() &&
4085          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
4086        return DeclPtrTy();
4087    }
4088
4089    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4090      diag::err_redefinition_different_kind;
4091    Diag(AliasLoc, DiagID) << Alias;
4092    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4093    return DeclPtrTy();
4094  }
4095
4096  if (R.isAmbiguous())
4097    return DeclPtrTy();
4098
4099  if (R.empty()) {
4100    Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
4101    return DeclPtrTy();
4102  }
4103
4104  NamespaceAliasDecl *AliasDecl =
4105    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4106                               Alias, SS.getRange(),
4107                               (NestedNameSpecifier *)SS.getScopeRep(),
4108                               IdentLoc, R.getFoundDecl());
4109
4110  PushOnScopeChains(AliasDecl, S);
4111  return DeclPtrTy::make(AliasDecl);
4112}
4113
4114namespace {
4115  /// \brief Scoped object used to handle the state changes required in Sema
4116  /// to implicitly define the body of a C++ member function;
4117  class ImplicitlyDefinedFunctionScope {
4118    Sema &S;
4119    DeclContext *PreviousContext;
4120
4121  public:
4122    ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4123      : S(S), PreviousContext(S.CurContext)
4124    {
4125      S.CurContext = Method;
4126      S.PushFunctionScope();
4127      S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4128    }
4129
4130    ~ImplicitlyDefinedFunctionScope() {
4131      S.PopExpressionEvaluationContext();
4132      S.PopFunctionOrBlockScope();
4133      S.CurContext = PreviousContext;
4134    }
4135  };
4136}
4137
4138void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4139                                            CXXConstructorDecl *Constructor) {
4140  assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
4141          !Constructor->isUsed()) &&
4142    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
4143
4144  CXXRecordDecl *ClassDecl = Constructor->getParent();
4145  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
4146
4147  ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
4148  if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false)) {
4149    Diag(CurrentLocation, diag::note_member_synthesized_at)
4150      << CXXConstructor << Context.getTagDeclType(ClassDecl);
4151    Constructor->setInvalidDecl();
4152  } else {
4153    Constructor->setUsed();
4154  }
4155}
4156
4157void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
4158                                    CXXDestructorDecl *Destructor) {
4159  assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
4160         "DefineImplicitDestructor - call it for implicit default dtor");
4161  CXXRecordDecl *ClassDecl = Destructor->getParent();
4162  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
4163
4164  ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
4165
4166  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4167                                         Destructor->getParent());
4168
4169  // FIXME: If CheckDestructor fails, we should emit a note about where the
4170  // implicit destructor was needed.
4171  if (CheckDestructor(Destructor)) {
4172    Diag(CurrentLocation, diag::note_member_synthesized_at)
4173      << CXXDestructor << Context.getTagDeclType(ClassDecl);
4174
4175    Destructor->setInvalidDecl();
4176    return;
4177  }
4178
4179  Destructor->setUsed();
4180}
4181
4182/// \brief Builds a statement that copies the given entity from \p From to
4183/// \c To.
4184///
4185/// This routine is used to copy the members of a class with an
4186/// implicitly-declared copy assignment operator. When the entities being
4187/// copied are arrays, this routine builds for loops to copy them.
4188///
4189/// \param S The Sema object used for type-checking.
4190///
4191/// \param Loc The location where the implicit copy is being generated.
4192///
4193/// \param T The type of the expressions being copied. Both expressions must
4194/// have this type.
4195///
4196/// \param To The expression we are copying to.
4197///
4198/// \param From The expression we are copying from.
4199///
4200/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4201/// Otherwise, it's a non-static member subobject.
4202///
4203/// \param Depth Internal parameter recording the depth of the recursion.
4204///
4205/// \returns A statement or a loop that copies the expressions.
4206static Sema::OwningStmtResult
4207BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
4208                      Sema::OwningExprResult To, Sema::OwningExprResult From,
4209                      bool CopyingBaseSubobject, unsigned Depth = 0) {
4210  typedef Sema::OwningStmtResult OwningStmtResult;
4211  typedef Sema::OwningExprResult OwningExprResult;
4212
4213  // C++0x [class.copy]p30:
4214  //   Each subobject is assigned in the manner appropriate to its type:
4215  //
4216  //     - if the subobject is of class type, the copy assignment operator
4217  //       for the class is used (as if by explicit qualification; that is,
4218  //       ignoring any possible virtual overriding functions in more derived
4219  //       classes);
4220  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4221    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4222
4223    // Look for operator=.
4224    DeclarationName Name
4225      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4226    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4227    S.LookupQualifiedName(OpLookup, ClassDecl, false);
4228
4229    // Filter out any result that isn't a copy-assignment operator.
4230    LookupResult::Filter F = OpLookup.makeFilter();
4231    while (F.hasNext()) {
4232      NamedDecl *D = F.next();
4233      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4234        if (Method->isCopyAssignmentOperator())
4235          continue;
4236
4237      F.erase();
4238    }
4239    F.done();
4240
4241    // Suppress the protected check (C++ [class.protected]) for each of the
4242    // assignment operators we found. This strange dance is required when
4243    // we're assigning via a base classes's copy-assignment operator. To
4244    // ensure that we're getting the right base class subobject (without
4245    // ambiguities), we need to cast "this" to that subobject type; to
4246    // ensure that we don't go through the virtual call mechanism, we need
4247    // to qualify the operator= name with the base class (see below). However,
4248    // this means that if the base class has a protected copy assignment
4249    // operator, the protected member access check will fail. So, we
4250    // rewrite "protected" access to "public" access in this case, since we
4251    // know by construction that we're calling from a derived class.
4252    if (CopyingBaseSubobject) {
4253      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4254           L != LEnd; ++L) {
4255        if (L.getAccess() == AS_protected)
4256          L.setAccess(AS_public);
4257      }
4258    }
4259
4260    // Create the nested-name-specifier that will be used to qualify the
4261    // reference to operator=; this is required to suppress the virtual
4262    // call mechanism.
4263    CXXScopeSpec SS;
4264    SS.setRange(Loc);
4265    SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4266                                               T.getTypePtr()));
4267
4268    // Create the reference to operator=.
4269    OwningExprResult OpEqualRef
4270      = S.BuildMemberReferenceExpr(move(To), T, Loc, /*isArrow=*/false, SS,
4271                                   /*FirstQualifierInScope=*/0, OpLookup,
4272                                   /*TemplateArgs=*/0,
4273                                   /*SuppressQualifierCheck=*/true);
4274    if (OpEqualRef.isInvalid())
4275      return S.StmtError();
4276
4277    // Build the call to the assignment operator.
4278    Expr *FromE = From.takeAs<Expr>();
4279    OwningExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
4280                                                      OpEqualRef.takeAs<Expr>(),
4281                                                        Loc, &FromE, 1, 0, Loc);
4282    if (Call.isInvalid())
4283      return S.StmtError();
4284
4285    return S.Owned(Call.takeAs<Stmt>());
4286  }
4287
4288  //     - if the subobject is of scalar type, the built-in assignment
4289  //       operator is used.
4290  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4291  if (!ArrayTy) {
4292    OwningExprResult Assignment = S.CreateBuiltinBinOp(Loc,
4293                                                       BinaryOperator::Assign,
4294                                                       To.takeAs<Expr>(),
4295                                                       From.takeAs<Expr>());
4296    if (Assignment.isInvalid())
4297      return S.StmtError();
4298
4299    return S.Owned(Assignment.takeAs<Stmt>());
4300  }
4301
4302  //     - if the subobject is an array, each element is assigned, in the
4303  //       manner appropriate to the element type;
4304
4305  // Construct a loop over the array bounds, e.g.,
4306  //
4307  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4308  //
4309  // that will copy each of the array elements.
4310  QualType SizeType = S.Context.getSizeType();
4311
4312  // Create the iteration variable.
4313  IdentifierInfo *IterationVarName = 0;
4314  {
4315    llvm::SmallString<8> Str;
4316    llvm::raw_svector_ostream OS(Str);
4317    OS << "__i" << Depth;
4318    IterationVarName = &S.Context.Idents.get(OS.str());
4319  }
4320  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4321                                          IterationVarName, SizeType,
4322                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
4323                                          VarDecl::None, VarDecl::None);
4324
4325  // Initialize the iteration variable to zero.
4326  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
4327  IterationVar->setInit(new (S.Context) IntegerLiteral(Zero, SizeType, Loc));
4328
4329  // Create a reference to the iteration variable; we'll use this several
4330  // times throughout.
4331  Expr *IterationVarRef
4332    = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4333  assert(IterationVarRef && "Reference to invented variable cannot fail!");
4334
4335  // Create the DeclStmt that holds the iteration variable.
4336  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4337
4338  // Create the comparison against the array bound.
4339  llvm::APInt Upper = ArrayTy->getSize();
4340  Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
4341  OwningExprResult Comparison
4342    = S.Owned(new (S.Context) BinaryOperator(IterationVarRef->Retain(),
4343                           new (S.Context) IntegerLiteral(Upper, SizeType, Loc),
4344                                    BinaryOperator::NE, S.Context.BoolTy, Loc));
4345
4346  // Create the pre-increment of the iteration variable.
4347  OwningExprResult Increment
4348    = S.Owned(new (S.Context) UnaryOperator(IterationVarRef->Retain(),
4349                                            UnaryOperator::PreInc,
4350                                            SizeType, Loc));
4351
4352  // Subscript the "from" and "to" expressions with the iteration variable.
4353  From = S.CreateBuiltinArraySubscriptExpr(move(From), Loc,
4354                                           S.Owned(IterationVarRef->Retain()),
4355                                           Loc);
4356  To = S.CreateBuiltinArraySubscriptExpr(move(To), Loc,
4357                                         S.Owned(IterationVarRef->Retain()),
4358                                         Loc);
4359  assert(!From.isInvalid() && "Builtin subscripting can't fail!");
4360  assert(!To.isInvalid() && "Builtin subscripting can't fail!");
4361
4362  // Build the copy for an individual element of the array.
4363  OwningStmtResult Copy = BuildSingleCopyAssign(S, Loc,
4364                                                ArrayTy->getElementType(),
4365                                                move(To), move(From),
4366                                                CopyingBaseSubobject, Depth+1);
4367  if (Copy.isInvalid()) {
4368    InitStmt->Destroy(S.Context);
4369    return S.StmtError();
4370  }
4371
4372  // Construct the loop that copies all elements of this array.
4373  return S.ActOnForStmt(Loc, Loc, S.Owned(InitStmt),
4374                        S.MakeFullExpr(Comparison),
4375                        Sema::DeclPtrTy(),
4376                        S.MakeFullExpr(Increment),
4377                        Loc, move(Copy));
4378}
4379
4380void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4381                                        CXXMethodDecl *CopyAssignOperator) {
4382  assert((CopyAssignOperator->isImplicit() &&
4383          CopyAssignOperator->isOverloadedOperator() &&
4384          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
4385          !CopyAssignOperator->isUsed()) &&
4386         "DefineImplicitCopyAssignment called for wrong function");
4387
4388  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4389
4390  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4391    CopyAssignOperator->setInvalidDecl();
4392    return;
4393  }
4394
4395  CopyAssignOperator->setUsed();
4396
4397  ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
4398
4399  // C++0x [class.copy]p30:
4400  //   The implicitly-defined or explicitly-defaulted copy assignment operator
4401  //   for a non-union class X performs memberwise copy assignment of its
4402  //   subobjects. The direct base classes of X are assigned first, in the
4403  //   order of their declaration in the base-specifier-list, and then the
4404  //   immediate non-static data members of X are assigned, in the order in
4405  //   which they were declared in the class definition.
4406
4407  // The statements that form the synthesized function body.
4408  ASTOwningVector<&ActionBase::DeleteStmt> Statements(*this);
4409
4410  // The parameter for the "other" object, which we are copying from.
4411  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4412  Qualifiers OtherQuals = Other->getType().getQualifiers();
4413  QualType OtherRefType = Other->getType();
4414  if (const LValueReferenceType *OtherRef
4415                                = OtherRefType->getAs<LValueReferenceType>()) {
4416    OtherRefType = OtherRef->getPointeeType();
4417    OtherQuals = OtherRefType.getQualifiers();
4418  }
4419
4420  // Our location for everything implicitly-generated.
4421  SourceLocation Loc = CopyAssignOperator->getLocation();
4422
4423  // Construct a reference to the "other" object. We'll be using this
4424  // throughout the generated ASTs.
4425  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4426  assert(OtherRef && "Reference to parameter cannot fail!");
4427
4428  // Construct the "this" pointer. We'll be using this throughout the generated
4429  // ASTs.
4430  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4431  assert(This && "Reference to this cannot fail!");
4432
4433  // Assign base classes.
4434  bool Invalid = false;
4435  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4436       E = ClassDecl->bases_end(); Base != E; ++Base) {
4437    // Form the assignment:
4438    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4439    QualType BaseType = Base->getType().getUnqualifiedType();
4440    CXXRecordDecl *BaseClassDecl = 0;
4441    if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4442      BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4443    else {
4444      Invalid = true;
4445      continue;
4446    }
4447
4448    // Construct the "from" expression, which is an implicit cast to the
4449    // appropriately-qualified base type.
4450    Expr *From = OtherRef->Retain();
4451    ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
4452                      CastExpr::CK_UncheckedDerivedToBase, /*isLvalue=*/true,
4453                      CXXBaseSpecifierArray(Base));
4454
4455    // Dereference "this".
4456    OwningExprResult To = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4457                                               Owned(This->Retain()));
4458
4459    // Implicitly cast "this" to the appropriately-qualified base type.
4460    Expr *ToE = To.takeAs<Expr>();
4461    ImpCastExprToType(ToE,
4462                      Context.getCVRQualifiedType(BaseType,
4463                                      CopyAssignOperator->getTypeQualifiers()),
4464                      CastExpr::CK_UncheckedDerivedToBase,
4465                      /*isLvalue=*/true, CXXBaseSpecifierArray(Base));
4466    To = Owned(ToE);
4467
4468    // Build the copy.
4469    OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
4470                                                  move(To), Owned(From),
4471                                                /*CopyingBaseSubobject=*/true);
4472    if (Copy.isInvalid()) {
4473      Diag(CurrentLocation, diag::note_member_synthesized_at)
4474        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4475      CopyAssignOperator->setInvalidDecl();
4476      return;
4477    }
4478
4479    // Success! Record the copy.
4480    Statements.push_back(Copy.takeAs<Expr>());
4481  }
4482
4483  // \brief Reference to the __builtin_memcpy function.
4484  Expr *BuiltinMemCpyRef = 0;
4485
4486  // Assign non-static members.
4487  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4488                                  FieldEnd = ClassDecl->field_end();
4489       Field != FieldEnd; ++Field) {
4490    // Check for members of reference type; we can't copy those.
4491    if (Field->getType()->isReferenceType()) {
4492      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4493        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4494      Diag(Field->getLocation(), diag::note_declared_at);
4495      Diag(CurrentLocation, diag::note_member_synthesized_at)
4496        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4497      Invalid = true;
4498      continue;
4499    }
4500
4501    // Check for members of const-qualified, non-class type.
4502    QualType BaseType = Context.getBaseElementType(Field->getType());
4503    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4504      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4505        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4506      Diag(Field->getLocation(), diag::note_declared_at);
4507      Diag(CurrentLocation, diag::note_member_synthesized_at)
4508        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4509      Invalid = true;
4510      continue;
4511    }
4512
4513    QualType FieldType = Field->getType().getNonReferenceType();
4514
4515    // Build references to the field in the object we're copying from and to.
4516    CXXScopeSpec SS; // Intentionally empty
4517    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
4518                              LookupMemberName);
4519    MemberLookup.addDecl(*Field);
4520    MemberLookup.resolveKind();
4521    OwningExprResult From = BuildMemberReferenceExpr(Owned(OtherRef->Retain()),
4522                                                     OtherRefType,
4523                                                     Loc, /*IsArrow=*/false,
4524                                                     SS, 0, MemberLookup, 0);
4525    OwningExprResult To = BuildMemberReferenceExpr(Owned(This->Retain()),
4526                                                   This->getType(),
4527                                                   Loc, /*IsArrow=*/true,
4528                                                   SS, 0, MemberLookup, 0);
4529    assert(!From.isInvalid() && "Implicit field reference cannot fail");
4530    assert(!To.isInvalid() && "Implicit field reference cannot fail");
4531
4532    // If the field should be copied with __builtin_memcpy rather than via
4533    // explicit assignments, do so. This optimization only applies for arrays
4534    // of scalars and arrays of class type with trivial copy-assignment
4535    // operators.
4536    if (FieldType->isArrayType() &&
4537        (!BaseType->isRecordType() ||
4538         cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
4539           ->hasTrivialCopyAssignment())) {
4540      // Compute the size of the memory buffer to be copied.
4541      QualType SizeType = Context.getSizeType();
4542      llvm::APInt Size(Context.getTypeSize(SizeType),
4543                       Context.getTypeSizeInChars(BaseType).getQuantity());
4544      for (const ConstantArrayType *Array
4545              = Context.getAsConstantArrayType(FieldType);
4546           Array;
4547           Array = Context.getAsConstantArrayType(Array->getElementType())) {
4548        llvm::APInt ArraySize = Array->getSize();
4549        ArraySize.zextOrTrunc(Size.getBitWidth());
4550        Size *= ArraySize;
4551      }
4552
4553      // Take the address of the field references for "from" and "to".
4554      From = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(From));
4555      To = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(To));
4556
4557      // Create a reference to the __builtin_memcpy builtin function.
4558      if (!BuiltinMemCpyRef) {
4559        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
4560                       LookupOrdinaryName);
4561        LookupName(R, TUScope, true);
4562
4563        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
4564        if (!BuiltinMemCpy) {
4565          // Something went horribly wrong earlier, and we will have complained
4566          // about it.
4567          Invalid = true;
4568          continue;
4569        }
4570
4571        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
4572                                            BuiltinMemCpy->getType(),
4573                                            Loc, 0).takeAs<Expr>();
4574        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
4575      }
4576
4577      ASTOwningVector<&ActionBase::DeleteExpr> CallArgs(*this);
4578      CallArgs.push_back(To.takeAs<Expr>());
4579      CallArgs.push_back(From.takeAs<Expr>());
4580      CallArgs.push_back(new (Context) IntegerLiteral(Size, SizeType, Loc));
4581      llvm::SmallVector<SourceLocation, 4> Commas; // FIXME: Silly
4582      Commas.push_back(Loc);
4583      Commas.push_back(Loc);
4584      OwningExprResult Call = ActOnCallExpr(/*Scope=*/0,
4585                                            Owned(BuiltinMemCpyRef->Retain()),
4586                                            Loc, move_arg(CallArgs),
4587                                            Commas.data(), Loc);
4588      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
4589      Statements.push_back(Call.takeAs<Expr>());
4590      continue;
4591    }
4592
4593    // Build the copy of this field.
4594    OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
4595                                                  move(To), move(From),
4596                                              /*CopyingBaseSubobject=*/false);
4597    if (Copy.isInvalid()) {
4598      Diag(CurrentLocation, diag::note_member_synthesized_at)
4599        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4600      CopyAssignOperator->setInvalidDecl();
4601      return;
4602    }
4603
4604    // Success! Record the copy.
4605    Statements.push_back(Copy.takeAs<Stmt>());
4606  }
4607
4608  if (!Invalid) {
4609    // Add a "return *this;"
4610    OwningExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4611                                                    Owned(This->Retain()));
4612
4613    OwningStmtResult Return = ActOnReturnStmt(Loc, move(ThisObj));
4614    if (Return.isInvalid())
4615      Invalid = true;
4616    else {
4617      Statements.push_back(Return.takeAs<Stmt>());
4618    }
4619  }
4620
4621  if (Invalid) {
4622    CopyAssignOperator->setInvalidDecl();
4623    return;
4624  }
4625
4626  OwningStmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
4627                                            /*isStmtExpr=*/false);
4628  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
4629  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
4630}
4631
4632void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4633                                   CXXConstructorDecl *CopyConstructor,
4634                                   unsigned TypeQuals) {
4635  assert((CopyConstructor->isImplicit() &&
4636          CopyConstructor->isCopyConstructor(TypeQuals) &&
4637          !CopyConstructor->isUsed()) &&
4638         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
4639
4640  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
4641  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
4642
4643  ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
4644
4645  if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false)) {
4646    Diag(CurrentLocation, diag::note_member_synthesized_at)
4647      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
4648    CopyConstructor->setInvalidDecl();
4649  }  else {
4650    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
4651                                               CopyConstructor->getLocation(),
4652                                               MultiStmtArg(*this, 0, 0),
4653                                               /*isStmtExpr=*/false)
4654                                                              .takeAs<Stmt>());
4655  }
4656
4657  CopyConstructor->setUsed();
4658}
4659
4660Sema::OwningExprResult
4661Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4662                            CXXConstructorDecl *Constructor,
4663                            MultiExprArg ExprArgs,
4664                            bool RequiresZeroInit,
4665                            CXXConstructExpr::ConstructionKind ConstructKind) {
4666  bool Elidable = false;
4667
4668  // C++0x [class.copy]p34:
4669  //   When certain criteria are met, an implementation is allowed to
4670  //   omit the copy/move construction of a class object, even if the
4671  //   copy/move constructor and/or destructor for the object have
4672  //   side effects. [...]
4673  //     - when a temporary class object that has not been bound to a
4674  //       reference (12.2) would be copied/moved to a class object
4675  //       with the same cv-unqualified type, the copy/move operation
4676  //       can be omitted by constructing the temporary object
4677  //       directly into the target of the omitted copy/move
4678  if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
4679    Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
4680    Elidable = SubExpr->isTemporaryObject() &&
4681      Context.hasSameUnqualifiedType(SubExpr->getType(),
4682                           Context.getTypeDeclType(Constructor->getParent()));
4683  }
4684
4685  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
4686                               Elidable, move(ExprArgs), RequiresZeroInit,
4687                               ConstructKind);
4688}
4689
4690/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4691/// including handling of its default argument expressions.
4692Sema::OwningExprResult
4693Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4694                            CXXConstructorDecl *Constructor, bool Elidable,
4695                            MultiExprArg ExprArgs,
4696                            bool RequiresZeroInit,
4697                            CXXConstructExpr::ConstructionKind ConstructKind) {
4698  unsigned NumExprs = ExprArgs.size();
4699  Expr **Exprs = (Expr **)ExprArgs.release();
4700
4701  MarkDeclarationReferenced(ConstructLoc, Constructor);
4702  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
4703                                        Constructor, Elidable, Exprs, NumExprs,
4704                                        RequiresZeroInit, ConstructKind));
4705}
4706
4707bool Sema::InitializeVarWithConstructor(VarDecl *VD,
4708                                        CXXConstructorDecl *Constructor,
4709                                        MultiExprArg Exprs) {
4710  OwningExprResult TempResult =
4711    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
4712                          move(Exprs));
4713  if (TempResult.isInvalid())
4714    return true;
4715
4716  Expr *Temp = TempResult.takeAs<Expr>();
4717  MarkDeclarationReferenced(VD->getLocation(), Constructor);
4718  Temp = MaybeCreateCXXExprWithTemporaries(Temp);
4719  VD->setInit(Temp);
4720
4721  return false;
4722}
4723
4724void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4725  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
4726  if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4727      !ClassDecl->hasTrivialDestructor()) {
4728    CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4729    MarkDeclarationReferenced(VD->getLocation(), Destructor);
4730    CheckDestructorAccess(VD->getLocation(), Destructor,
4731                          PDiag(diag::err_access_dtor_var)
4732                            << VD->getDeclName()
4733                            << VD->getType());
4734  }
4735}
4736
4737/// AddCXXDirectInitializerToDecl - This action is called immediately after
4738/// ActOnDeclarator, when a C++ direct initializer is present.
4739/// e.g: "int x(1);"
4740void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4741                                         SourceLocation LParenLoc,
4742                                         MultiExprArg Exprs,
4743                                         SourceLocation *CommaLocs,
4744                                         SourceLocation RParenLoc) {
4745  assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
4746  Decl *RealDecl = Dcl.getAs<Decl>();
4747
4748  // If there is no declaration, there was an error parsing it.  Just ignore
4749  // the initializer.
4750  if (RealDecl == 0)
4751    return;
4752
4753  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4754  if (!VDecl) {
4755    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4756    RealDecl->setInvalidDecl();
4757    return;
4758  }
4759
4760  // We will represent direct-initialization similarly to copy-initialization:
4761  //    int x(1);  -as-> int x = 1;
4762  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4763  //
4764  // Clients that want to distinguish between the two forms, can check for
4765  // direct initializer using VarDecl::hasCXXDirectInitializer().
4766  // A major benefit is that clients that don't particularly care about which
4767  // exactly form was it (like the CodeGen) can handle both cases without
4768  // special case code.
4769
4770  // C++ 8.5p11:
4771  // The form of initialization (using parentheses or '=') is generally
4772  // insignificant, but does matter when the entity being initialized has a
4773  // class type.
4774  QualType DeclInitType = VDecl->getType();
4775  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
4776    DeclInitType = Context.getBaseElementType(Array);
4777
4778  if (!VDecl->getType()->isDependentType() &&
4779      RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
4780                          diag::err_typecheck_decl_incomplete_type)) {
4781    VDecl->setInvalidDecl();
4782    return;
4783  }
4784
4785  // The variable can not have an abstract class type.
4786  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4787                             diag::err_abstract_type_in_decl,
4788                             AbstractVariableType))
4789    VDecl->setInvalidDecl();
4790
4791  const VarDecl *Def;
4792  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
4793    Diag(VDecl->getLocation(), diag::err_redefinition)
4794    << VDecl->getDeclName();
4795    Diag(Def->getLocation(), diag::note_previous_definition);
4796    VDecl->setInvalidDecl();
4797    return;
4798  }
4799
4800  // If either the declaration has a dependent type or if any of the
4801  // expressions is type-dependent, we represent the initialization
4802  // via a ParenListExpr for later use during template instantiation.
4803  if (VDecl->getType()->isDependentType() ||
4804      Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4805    // Let clients know that initialization was done with a direct initializer.
4806    VDecl->setCXXDirectInitializer(true);
4807
4808    // Store the initialization expressions as a ParenListExpr.
4809    unsigned NumExprs = Exprs.size();
4810    VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4811                                               (Expr **)Exprs.release(),
4812                                               NumExprs, RParenLoc));
4813    return;
4814  }
4815
4816  // Capture the variable that is being initialized and the style of
4817  // initialization.
4818  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4819
4820  // FIXME: Poor source location information.
4821  InitializationKind Kind
4822    = InitializationKind::CreateDirect(VDecl->getLocation(),
4823                                       LParenLoc, RParenLoc);
4824
4825  InitializationSequence InitSeq(*this, Entity, Kind,
4826                                 (Expr**)Exprs.get(), Exprs.size());
4827  OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4828  if (Result.isInvalid()) {
4829    VDecl->setInvalidDecl();
4830    return;
4831  }
4832
4833  Result = MaybeCreateCXXExprWithTemporaries(move(Result));
4834  VDecl->setInit(Result.takeAs<Expr>());
4835  VDecl->setCXXDirectInitializer(true);
4836
4837  if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4838    FinalizeVarWithDestructor(VDecl, Record);
4839}
4840
4841/// \brief Given a constructor and the set of arguments provided for the
4842/// constructor, convert the arguments and add any required default arguments
4843/// to form a proper call to this constructor.
4844///
4845/// \returns true if an error occurred, false otherwise.
4846bool
4847Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4848                              MultiExprArg ArgsPtr,
4849                              SourceLocation Loc,
4850                     ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4851  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4852  unsigned NumArgs = ArgsPtr.size();
4853  Expr **Args = (Expr **)ArgsPtr.get();
4854
4855  const FunctionProtoType *Proto
4856    = Constructor->getType()->getAs<FunctionProtoType>();
4857  assert(Proto && "Constructor without a prototype?");
4858  unsigned NumArgsInProto = Proto->getNumArgs();
4859
4860  // If too few arguments are available, we'll fill in the rest with defaults.
4861  if (NumArgs < NumArgsInProto)
4862    ConvertedArgs.reserve(NumArgsInProto);
4863  else
4864    ConvertedArgs.reserve(NumArgs);
4865
4866  VariadicCallType CallType =
4867    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4868  llvm::SmallVector<Expr *, 8> AllArgs;
4869  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4870                                        Proto, 0, Args, NumArgs, AllArgs,
4871                                        CallType);
4872  for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4873    ConvertedArgs.push_back(AllArgs[i]);
4874  return Invalid;
4875}
4876
4877static inline bool
4878CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4879                                       const FunctionDecl *FnDecl) {
4880  const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4881  if (isa<NamespaceDecl>(DC)) {
4882    return SemaRef.Diag(FnDecl->getLocation(),
4883                        diag::err_operator_new_delete_declared_in_namespace)
4884      << FnDecl->getDeclName();
4885  }
4886
4887  if (isa<TranslationUnitDecl>(DC) &&
4888      FnDecl->getStorageClass() == FunctionDecl::Static) {
4889    return SemaRef.Diag(FnDecl->getLocation(),
4890                        diag::err_operator_new_delete_declared_static)
4891      << FnDecl->getDeclName();
4892  }
4893
4894  return false;
4895}
4896
4897static inline bool
4898CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4899                            CanQualType ExpectedResultType,
4900                            CanQualType ExpectedFirstParamType,
4901                            unsigned DependentParamTypeDiag,
4902                            unsigned InvalidParamTypeDiag) {
4903  QualType ResultType =
4904    FnDecl->getType()->getAs<FunctionType>()->getResultType();
4905
4906  // Check that the result type is not dependent.
4907  if (ResultType->isDependentType())
4908    return SemaRef.Diag(FnDecl->getLocation(),
4909                        diag::err_operator_new_delete_dependent_result_type)
4910    << FnDecl->getDeclName() << ExpectedResultType;
4911
4912  // Check that the result type is what we expect.
4913  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4914    return SemaRef.Diag(FnDecl->getLocation(),
4915                        diag::err_operator_new_delete_invalid_result_type)
4916    << FnDecl->getDeclName() << ExpectedResultType;
4917
4918  // A function template must have at least 2 parameters.
4919  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4920    return SemaRef.Diag(FnDecl->getLocation(),
4921                      diag::err_operator_new_delete_template_too_few_parameters)
4922        << FnDecl->getDeclName();
4923
4924  // The function decl must have at least 1 parameter.
4925  if (FnDecl->getNumParams() == 0)
4926    return SemaRef.Diag(FnDecl->getLocation(),
4927                        diag::err_operator_new_delete_too_few_parameters)
4928      << FnDecl->getDeclName();
4929
4930  // Check the the first parameter type is not dependent.
4931  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4932  if (FirstParamType->isDependentType())
4933    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4934      << FnDecl->getDeclName() << ExpectedFirstParamType;
4935
4936  // Check that the first parameter type is what we expect.
4937  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
4938      ExpectedFirstParamType)
4939    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4940    << FnDecl->getDeclName() << ExpectedFirstParamType;
4941
4942  return false;
4943}
4944
4945static bool
4946CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4947  // C++ [basic.stc.dynamic.allocation]p1:
4948  //   A program is ill-formed if an allocation function is declared in a
4949  //   namespace scope other than global scope or declared static in global
4950  //   scope.
4951  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4952    return true;
4953
4954  CanQualType SizeTy =
4955    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4956
4957  // C++ [basic.stc.dynamic.allocation]p1:
4958  //  The return type shall be void*. The first parameter shall have type
4959  //  std::size_t.
4960  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4961                                  SizeTy,
4962                                  diag::err_operator_new_dependent_param_type,
4963                                  diag::err_operator_new_param_type))
4964    return true;
4965
4966  // C++ [basic.stc.dynamic.allocation]p1:
4967  //  The first parameter shall not have an associated default argument.
4968  if (FnDecl->getParamDecl(0)->hasDefaultArg())
4969    return SemaRef.Diag(FnDecl->getLocation(),
4970                        diag::err_operator_new_default_arg)
4971      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4972
4973  return false;
4974}
4975
4976static bool
4977CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4978  // C++ [basic.stc.dynamic.deallocation]p1:
4979  //   A program is ill-formed if deallocation functions are declared in a
4980  //   namespace scope other than global scope or declared static in global
4981  //   scope.
4982  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4983    return true;
4984
4985  // C++ [basic.stc.dynamic.deallocation]p2:
4986  //   Each deallocation function shall return void and its first parameter
4987  //   shall be void*.
4988  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4989                                  SemaRef.Context.VoidPtrTy,
4990                                 diag::err_operator_delete_dependent_param_type,
4991                                 diag::err_operator_delete_param_type))
4992    return true;
4993
4994  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4995  if (FirstParamType->isDependentType())
4996    return SemaRef.Diag(FnDecl->getLocation(),
4997                        diag::err_operator_delete_dependent_param_type)
4998    << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4999
5000  if (SemaRef.Context.getCanonicalType(FirstParamType) !=
5001      SemaRef.Context.VoidPtrTy)
5002    return SemaRef.Diag(FnDecl->getLocation(),
5003                        diag::err_operator_delete_param_type)
5004      << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
5005
5006  return false;
5007}
5008
5009/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5010/// of this overloaded operator is well-formed. If so, returns false;
5011/// otherwise, emits appropriate diagnostics and returns true.
5012bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
5013  assert(FnDecl && FnDecl->isOverloadedOperator() &&
5014         "Expected an overloaded operator declaration");
5015
5016  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5017
5018  // C++ [over.oper]p5:
5019  //   The allocation and deallocation functions, operator new,
5020  //   operator new[], operator delete and operator delete[], are
5021  //   described completely in 3.7.3. The attributes and restrictions
5022  //   found in the rest of this subclause do not apply to them unless
5023  //   explicitly stated in 3.7.3.
5024  if (Op == OO_Delete || Op == OO_Array_Delete)
5025    return CheckOperatorDeleteDeclaration(*this, FnDecl);
5026
5027  if (Op == OO_New || Op == OO_Array_New)
5028    return CheckOperatorNewDeclaration(*this, FnDecl);
5029
5030  // C++ [over.oper]p6:
5031  //   An operator function shall either be a non-static member
5032  //   function or be a non-member function and have at least one
5033  //   parameter whose type is a class, a reference to a class, an
5034  //   enumeration, or a reference to an enumeration.
5035  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5036    if (MethodDecl->isStatic())
5037      return Diag(FnDecl->getLocation(),
5038                  diag::err_operator_overload_static) << FnDecl->getDeclName();
5039  } else {
5040    bool ClassOrEnumParam = false;
5041    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5042                                   ParamEnd = FnDecl->param_end();
5043         Param != ParamEnd; ++Param) {
5044      QualType ParamType = (*Param)->getType().getNonReferenceType();
5045      if (ParamType->isDependentType() || ParamType->isRecordType() ||
5046          ParamType->isEnumeralType()) {
5047        ClassOrEnumParam = true;
5048        break;
5049      }
5050    }
5051
5052    if (!ClassOrEnumParam)
5053      return Diag(FnDecl->getLocation(),
5054                  diag::err_operator_overload_needs_class_or_enum)
5055        << FnDecl->getDeclName();
5056  }
5057
5058  // C++ [over.oper]p8:
5059  //   An operator function cannot have default arguments (8.3.6),
5060  //   except where explicitly stated below.
5061  //
5062  // Only the function-call operator allows default arguments
5063  // (C++ [over.call]p1).
5064  if (Op != OO_Call) {
5065    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5066         Param != FnDecl->param_end(); ++Param) {
5067      if ((*Param)->hasDefaultArg())
5068        return Diag((*Param)->getLocation(),
5069                    diag::err_operator_overload_default_arg)
5070          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
5071    }
5072  }
5073
5074  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5075    { false, false, false }
5076#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5077    , { Unary, Binary, MemberOnly }
5078#include "clang/Basic/OperatorKinds.def"
5079  };
5080
5081  bool CanBeUnaryOperator = OperatorUses[Op][0];
5082  bool CanBeBinaryOperator = OperatorUses[Op][1];
5083  bool MustBeMemberOperator = OperatorUses[Op][2];
5084
5085  // C++ [over.oper]p8:
5086  //   [...] Operator functions cannot have more or fewer parameters
5087  //   than the number required for the corresponding operator, as
5088  //   described in the rest of this subclause.
5089  unsigned NumParams = FnDecl->getNumParams()
5090                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
5091  if (Op != OO_Call &&
5092      ((NumParams == 1 && !CanBeUnaryOperator) ||
5093       (NumParams == 2 && !CanBeBinaryOperator) ||
5094       (NumParams < 1) || (NumParams > 2))) {
5095    // We have the wrong number of parameters.
5096    unsigned ErrorKind;
5097    if (CanBeUnaryOperator && CanBeBinaryOperator) {
5098      ErrorKind = 2;  // 2 -> unary or binary.
5099    } else if (CanBeUnaryOperator) {
5100      ErrorKind = 0;  // 0 -> unary
5101    } else {
5102      assert(CanBeBinaryOperator &&
5103             "All non-call overloaded operators are unary or binary!");
5104      ErrorKind = 1;  // 1 -> binary
5105    }
5106
5107    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
5108      << FnDecl->getDeclName() << NumParams << ErrorKind;
5109  }
5110
5111  // Overloaded operators other than operator() cannot be variadic.
5112  if (Op != OO_Call &&
5113      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
5114    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
5115      << FnDecl->getDeclName();
5116  }
5117
5118  // Some operators must be non-static member functions.
5119  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5120    return Diag(FnDecl->getLocation(),
5121                diag::err_operator_overload_must_be_member)
5122      << FnDecl->getDeclName();
5123  }
5124
5125  // C++ [over.inc]p1:
5126  //   The user-defined function called operator++ implements the
5127  //   prefix and postfix ++ operator. If this function is a member
5128  //   function with no parameters, or a non-member function with one
5129  //   parameter of class or enumeration type, it defines the prefix
5130  //   increment operator ++ for objects of that type. If the function
5131  //   is a member function with one parameter (which shall be of type
5132  //   int) or a non-member function with two parameters (the second
5133  //   of which shall be of type int), it defines the postfix
5134  //   increment operator ++ for objects of that type.
5135  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5136    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5137    bool ParamIsInt = false;
5138    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
5139      ParamIsInt = BT->getKind() == BuiltinType::Int;
5140
5141    if (!ParamIsInt)
5142      return Diag(LastParam->getLocation(),
5143                  diag::err_operator_overload_post_incdec_must_be_int)
5144        << LastParam->getType() << (Op == OO_MinusMinus);
5145  }
5146
5147  // Notify the class if it got an assignment operator.
5148  if (Op == OO_Equal) {
5149    // Would have returned earlier otherwise.
5150    assert(isa<CXXMethodDecl>(FnDecl) &&
5151      "Overloaded = not member, but not filtered.");
5152    CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5153    Method->getParent()->addedAssignmentOperator(Context, Method);
5154  }
5155
5156  return false;
5157}
5158
5159/// CheckLiteralOperatorDeclaration - Check whether the declaration
5160/// of this literal operator function is well-formed. If so, returns
5161/// false; otherwise, emits appropriate diagnostics and returns true.
5162bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5163  DeclContext *DC = FnDecl->getDeclContext();
5164  Decl::Kind Kind = DC->getDeclKind();
5165  if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5166      Kind != Decl::LinkageSpec) {
5167    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5168      << FnDecl->getDeclName();
5169    return true;
5170  }
5171
5172  bool Valid = false;
5173
5174  // template <char...> type operator "" name() is the only valid template
5175  // signature, and the only valid signature with no parameters.
5176  if (FnDecl->param_size() == 0) {
5177    if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5178      // Must have only one template parameter
5179      TemplateParameterList *Params = TpDecl->getTemplateParameters();
5180      if (Params->size() == 1) {
5181        NonTypeTemplateParmDecl *PmDecl =
5182          cast<NonTypeTemplateParmDecl>(Params->getParam(0));
5183
5184        // The template parameter must be a char parameter pack.
5185        // FIXME: This test will always fail because non-type parameter packs
5186        //   have not been implemented.
5187        if (PmDecl && PmDecl->isTemplateParameterPack() &&
5188            Context.hasSameType(PmDecl->getType(), Context.CharTy))
5189          Valid = true;
5190      }
5191    }
5192  } else {
5193    // Check the first parameter
5194    FunctionDecl::param_iterator Param = FnDecl->param_begin();
5195
5196    QualType T = (*Param)->getType();
5197
5198    // unsigned long long int, long double, and any character type are allowed
5199    // as the only parameters.
5200    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5201        Context.hasSameType(T, Context.LongDoubleTy) ||
5202        Context.hasSameType(T, Context.CharTy) ||
5203        Context.hasSameType(T, Context.WCharTy) ||
5204        Context.hasSameType(T, Context.Char16Ty) ||
5205        Context.hasSameType(T, Context.Char32Ty)) {
5206      if (++Param == FnDecl->param_end())
5207        Valid = true;
5208      goto FinishedParams;
5209    }
5210
5211    // Otherwise it must be a pointer to const; let's strip those qualifiers.
5212    const PointerType *PT = T->getAs<PointerType>();
5213    if (!PT)
5214      goto FinishedParams;
5215    T = PT->getPointeeType();
5216    if (!T.isConstQualified())
5217      goto FinishedParams;
5218    T = T.getUnqualifiedType();
5219
5220    // Move on to the second parameter;
5221    ++Param;
5222
5223    // If there is no second parameter, the first must be a const char *
5224    if (Param == FnDecl->param_end()) {
5225      if (Context.hasSameType(T, Context.CharTy))
5226        Valid = true;
5227      goto FinishedParams;
5228    }
5229
5230    // const char *, const wchar_t*, const char16_t*, and const char32_t*
5231    // are allowed as the first parameter to a two-parameter function
5232    if (!(Context.hasSameType(T, Context.CharTy) ||
5233          Context.hasSameType(T, Context.WCharTy) ||
5234          Context.hasSameType(T, Context.Char16Ty) ||
5235          Context.hasSameType(T, Context.Char32Ty)))
5236      goto FinishedParams;
5237
5238    // The second and final parameter must be an std::size_t
5239    T = (*Param)->getType().getUnqualifiedType();
5240    if (Context.hasSameType(T, Context.getSizeType()) &&
5241        ++Param == FnDecl->param_end())
5242      Valid = true;
5243  }
5244
5245  // FIXME: This diagnostic is absolutely terrible.
5246FinishedParams:
5247  if (!Valid) {
5248    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5249      << FnDecl->getDeclName();
5250    return true;
5251  }
5252
5253  return false;
5254}
5255
5256/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5257/// linkage specification, including the language and (if present)
5258/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5259/// the location of the language string literal, which is provided
5260/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5261/// the '{' brace. Otherwise, this linkage specification does not
5262/// have any braces.
5263Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5264                                                     SourceLocation ExternLoc,
5265                                                     SourceLocation LangLoc,
5266                                                     llvm::StringRef Lang,
5267                                                     SourceLocation LBraceLoc) {
5268  LinkageSpecDecl::LanguageIDs Language;
5269  if (Lang == "\"C\"")
5270    Language = LinkageSpecDecl::lang_c;
5271  else if (Lang == "\"C++\"")
5272    Language = LinkageSpecDecl::lang_cxx;
5273  else {
5274    Diag(LangLoc, diag::err_bad_language);
5275    return DeclPtrTy();
5276  }
5277
5278  // FIXME: Add all the various semantics of linkage specifications
5279
5280  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
5281                                               LangLoc, Language,
5282                                               LBraceLoc.isValid());
5283  CurContext->addDecl(D);
5284  PushDeclContext(S, D);
5285  return DeclPtrTy::make(D);
5286}
5287
5288/// ActOnFinishLinkageSpecification - Completely the definition of
5289/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5290/// valid, it's the position of the closing '}' brace in a linkage
5291/// specification that uses braces.
5292Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5293                                                      DeclPtrTy LinkageSpec,
5294                                                      SourceLocation RBraceLoc) {
5295  if (LinkageSpec)
5296    PopDeclContext();
5297  return LinkageSpec;
5298}
5299
5300/// \brief Perform semantic analysis for the variable declaration that
5301/// occurs within a C++ catch clause, returning the newly-created
5302/// variable.
5303VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
5304                                         TypeSourceInfo *TInfo,
5305                                         IdentifierInfo *Name,
5306                                         SourceLocation Loc,
5307                                         SourceRange Range) {
5308  bool Invalid = false;
5309
5310  // Arrays and functions decay.
5311  if (ExDeclType->isArrayType())
5312    ExDeclType = Context.getArrayDecayedType(ExDeclType);
5313  else if (ExDeclType->isFunctionType())
5314    ExDeclType = Context.getPointerType(ExDeclType);
5315
5316  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5317  // The exception-declaration shall not denote a pointer or reference to an
5318  // incomplete type, other than [cv] void*.
5319  // N2844 forbids rvalue references.
5320  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
5321    Diag(Loc, diag::err_catch_rvalue_ref) << Range;
5322    Invalid = true;
5323  }
5324
5325  // GCC allows catching pointers and references to incomplete types
5326  // as an extension; so do we, but we warn by default.
5327
5328  QualType BaseType = ExDeclType;
5329  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
5330  unsigned DK = diag::err_catch_incomplete;
5331  bool IncompleteCatchIsInvalid = true;
5332  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
5333    BaseType = Ptr->getPointeeType();
5334    Mode = 1;
5335    DK = diag::ext_catch_incomplete_ptr;
5336    IncompleteCatchIsInvalid = false;
5337  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
5338    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
5339    BaseType = Ref->getPointeeType();
5340    Mode = 2;
5341    DK = diag::ext_catch_incomplete_ref;
5342    IncompleteCatchIsInvalid = false;
5343  }
5344  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
5345      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
5346      IncompleteCatchIsInvalid)
5347    Invalid = true;
5348
5349  if (!Invalid && !ExDeclType->isDependentType() &&
5350      RequireNonAbstractType(Loc, ExDeclType,
5351                             diag::err_abstract_type_in_decl,
5352                             AbstractVariableType))
5353    Invalid = true;
5354
5355  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
5356                                    Name, ExDeclType, TInfo, VarDecl::None,
5357                                    VarDecl::None);
5358  ExDecl->setExceptionVariable(true);
5359
5360  if (!Invalid) {
5361    if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
5362      // C++ [except.handle]p16:
5363      //   The object declared in an exception-declaration or, if the
5364      //   exception-declaration does not specify a name, a temporary (12.2) is
5365      //   copy-initialized (8.5) from the exception object. [...]
5366      //   The object is destroyed when the handler exits, after the destruction
5367      //   of any automatic objects initialized within the handler.
5368      //
5369      // We just pretend to initialize the object with itself, then make sure
5370      // it can be destroyed later.
5371      InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
5372      Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
5373                                            Loc, ExDeclType, 0);
5374      InitializationKind Kind = InitializationKind::CreateCopy(Loc,
5375                                                               SourceLocation());
5376      InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
5377      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5378                                    MultiExprArg(*this, (void**)&ExDeclRef, 1));
5379      if (Result.isInvalid())
5380        Invalid = true;
5381      else
5382        FinalizeVarWithDestructor(ExDecl, RecordTy);
5383    }
5384  }
5385
5386  if (Invalid)
5387    ExDecl->setInvalidDecl();
5388
5389  return ExDecl;
5390}
5391
5392/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5393/// handler.
5394Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
5395  TypeSourceInfo *TInfo = 0;
5396  QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
5397
5398  bool Invalid = D.isInvalidType();
5399  IdentifierInfo *II = D.getIdentifier();
5400  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
5401                                             LookupOrdinaryName,
5402                                             ForRedeclaration)) {
5403    // The scope should be freshly made just for us. There is just no way
5404    // it contains any previous declaration.
5405    assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
5406    if (PrevDecl->isTemplateParameter()) {
5407      // Maybe we will complain about the shadowed template parameter.
5408      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5409    }
5410  }
5411
5412  if (D.getCXXScopeSpec().isSet() && !Invalid) {
5413    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5414      << D.getCXXScopeSpec().getRange();
5415    Invalid = true;
5416  }
5417
5418  VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
5419                                              D.getIdentifier(),
5420                                              D.getIdentifierLoc(),
5421                                            D.getDeclSpec().getSourceRange());
5422
5423  if (Invalid)
5424    ExDecl->setInvalidDecl();
5425
5426  // Add the exception declaration into this scope.
5427  if (II)
5428    PushOnScopeChains(ExDecl, S);
5429  else
5430    CurContext->addDecl(ExDecl);
5431
5432  ProcessDeclAttributes(S, ExDecl, D);
5433  return DeclPtrTy::make(ExDecl);
5434}
5435
5436Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
5437                                                   ExprArg assertexpr,
5438                                                   ExprArg assertmessageexpr) {
5439  Expr *AssertExpr = (Expr *)assertexpr.get();
5440  StringLiteral *AssertMessage =
5441    cast<StringLiteral>((Expr *)assertmessageexpr.get());
5442
5443  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5444    llvm::APSInt Value(32);
5445    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5446      Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5447        AssertExpr->getSourceRange();
5448      return DeclPtrTy();
5449    }
5450
5451    if (Value == 0) {
5452      Diag(AssertLoc, diag::err_static_assert_failed)
5453        << AssertMessage->getString() << AssertExpr->getSourceRange();
5454    }
5455  }
5456
5457  assertexpr.release();
5458  assertmessageexpr.release();
5459  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
5460                                        AssertExpr, AssertMessage);
5461
5462  CurContext->addDecl(Decl);
5463  return DeclPtrTy::make(Decl);
5464}
5465
5466/// \brief Perform semantic analysis of the given friend type declaration.
5467///
5468/// \returns A friend declaration that.
5469FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
5470                                      TypeSourceInfo *TSInfo) {
5471  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
5472
5473  QualType T = TSInfo->getType();
5474  SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
5475
5476  if (!getLangOptions().CPlusPlus0x) {
5477    // C++03 [class.friend]p2:
5478    //   An elaborated-type-specifier shall be used in a friend declaration
5479    //   for a class.*
5480    //
5481    //   * The class-key of the elaborated-type-specifier is required.
5482    if (!ActiveTemplateInstantiations.empty()) {
5483      // Do not complain about the form of friend template types during
5484      // template instantiation; we will already have complained when the
5485      // template was declared.
5486    } else if (!T->isElaboratedTypeSpecifier()) {
5487      // If we evaluated the type to a record type, suggest putting
5488      // a tag in front.
5489      if (const RecordType *RT = T->getAs<RecordType>()) {
5490        RecordDecl *RD = RT->getDecl();
5491
5492        std::string InsertionText = std::string(" ") + RD->getKindName();
5493
5494        Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
5495          << (unsigned) RD->getTagKind()
5496          << T
5497          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
5498                                        InsertionText);
5499      } else {
5500        Diag(FriendLoc, diag::ext_nonclass_type_friend)
5501          << T
5502          << SourceRange(FriendLoc, TypeRange.getEnd());
5503      }
5504    } else if (T->getAs<EnumType>()) {
5505      Diag(FriendLoc, diag::ext_enum_friend)
5506        << T
5507        << SourceRange(FriendLoc, TypeRange.getEnd());
5508    }
5509  }
5510
5511  // C++0x [class.friend]p3:
5512  //   If the type specifier in a friend declaration designates a (possibly
5513  //   cv-qualified) class type, that class is declared as a friend; otherwise,
5514  //   the friend declaration is ignored.
5515
5516  // FIXME: C++0x has some syntactic restrictions on friend type declarations
5517  // in [class.friend]p3 that we do not implement.
5518
5519  return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
5520}
5521
5522/// Handle a friend type declaration.  This works in tandem with
5523/// ActOnTag.
5524///
5525/// Notes on friend class templates:
5526///
5527/// We generally treat friend class declarations as if they were
5528/// declaring a class.  So, for example, the elaborated type specifier
5529/// in a friend declaration is required to obey the restrictions of a
5530/// class-head (i.e. no typedefs in the scope chain), template
5531/// parameters are required to match up with simple template-ids, &c.
5532/// However, unlike when declaring a template specialization, it's
5533/// okay to refer to a template specialization without an empty
5534/// template parameter declaration, e.g.
5535///   friend class A<T>::B<unsigned>;
5536/// We permit this as a special case; if there are any template
5537/// parameters present at all, require proper matching, i.e.
5538///   template <> template <class T> friend class A<int>::B;
5539Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5540                                          MultiTemplateParamsArg TempParams) {
5541  SourceLocation Loc = DS.getSourceRange().getBegin();
5542
5543  assert(DS.isFriendSpecified());
5544  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5545
5546  // Try to convert the decl specifier to a type.  This works for
5547  // friend templates because ActOnTag never produces a ClassTemplateDecl
5548  // for a TUK_Friend.
5549  Declarator TheDeclarator(DS, Declarator::MemberContext);
5550  TypeSourceInfo *TSI;
5551  QualType T = GetTypeForDeclarator(TheDeclarator, S, &TSI);
5552  if (TheDeclarator.isInvalidType())
5553    return DeclPtrTy();
5554
5555  if (!TSI)
5556    TSI = Context.getTrivialTypeSourceInfo(T, DS.getSourceRange().getBegin());
5557
5558  // This is definitely an error in C++98.  It's probably meant to
5559  // be forbidden in C++0x, too, but the specification is just
5560  // poorly written.
5561  //
5562  // The problem is with declarations like the following:
5563  //   template <T> friend A<T>::foo;
5564  // where deciding whether a class C is a friend or not now hinges
5565  // on whether there exists an instantiation of A that causes
5566  // 'foo' to equal C.  There are restrictions on class-heads
5567  // (which we declare (by fiat) elaborated friend declarations to
5568  // be) that makes this tractable.
5569  //
5570  // FIXME: handle "template <> friend class A<T>;", which
5571  // is possibly well-formed?  Who even knows?
5572  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
5573    Diag(Loc, diag::err_tagless_friend_type_template)
5574      << DS.getSourceRange();
5575    return DeclPtrTy();
5576  }
5577
5578  // C++98 [class.friend]p1: A friend of a class is a function
5579  //   or class that is not a member of the class . . .
5580  // This is fixed in DR77, which just barely didn't make the C++03
5581  // deadline.  It's also a very silly restriction that seriously
5582  // affects inner classes and which nobody else seems to implement;
5583  // thus we never diagnose it, not even in -pedantic.
5584  //
5585  // But note that we could warn about it: it's always useless to
5586  // friend one of your own members (it's not, however, worthless to
5587  // friend a member of an arbitrary specialization of your template).
5588
5589  Decl *D;
5590  if (unsigned NumTempParamLists = TempParams.size())
5591    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5592                                   NumTempParamLists,
5593                                 (TemplateParameterList**) TempParams.release(),
5594                                   TSI,
5595                                   DS.getFriendSpecLoc());
5596  else
5597    D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
5598
5599  if (!D)
5600    return DeclPtrTy();
5601
5602  D->setAccess(AS_public);
5603  CurContext->addDecl(D);
5604
5605  return DeclPtrTy::make(D);
5606}
5607
5608Sema::DeclPtrTy
5609Sema::ActOnFriendFunctionDecl(Scope *S,
5610                              Declarator &D,
5611                              bool IsDefinition,
5612                              MultiTemplateParamsArg TemplateParams) {
5613  const DeclSpec &DS = D.getDeclSpec();
5614
5615  assert(DS.isFriendSpecified());
5616  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5617
5618  SourceLocation Loc = D.getIdentifierLoc();
5619  TypeSourceInfo *TInfo = 0;
5620  QualType T = GetTypeForDeclarator(D, S, &TInfo);
5621
5622  // C++ [class.friend]p1
5623  //   A friend of a class is a function or class....
5624  // Note that this sees through typedefs, which is intended.
5625  // It *doesn't* see through dependent types, which is correct
5626  // according to [temp.arg.type]p3:
5627  //   If a declaration acquires a function type through a
5628  //   type dependent on a template-parameter and this causes
5629  //   a declaration that does not use the syntactic form of a
5630  //   function declarator to have a function type, the program
5631  //   is ill-formed.
5632  if (!T->isFunctionType()) {
5633    Diag(Loc, diag::err_unexpected_friend);
5634
5635    // It might be worthwhile to try to recover by creating an
5636    // appropriate declaration.
5637    return DeclPtrTy();
5638  }
5639
5640  // C++ [namespace.memdef]p3
5641  //  - If a friend declaration in a non-local class first declares a
5642  //    class or function, the friend class or function is a member
5643  //    of the innermost enclosing namespace.
5644  //  - The name of the friend is not found by simple name lookup
5645  //    until a matching declaration is provided in that namespace
5646  //    scope (either before or after the class declaration granting
5647  //    friendship).
5648  //  - If a friend function is called, its name may be found by the
5649  //    name lookup that considers functions from namespaces and
5650  //    classes associated with the types of the function arguments.
5651  //  - When looking for a prior declaration of a class or a function
5652  //    declared as a friend, scopes outside the innermost enclosing
5653  //    namespace scope are not considered.
5654
5655  CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5656  DeclarationName Name = GetNameForDeclarator(D);
5657  assert(Name);
5658
5659  // The context we found the declaration in, or in which we should
5660  // create the declaration.
5661  DeclContext *DC;
5662
5663  // FIXME: handle local classes
5664
5665  // Recover from invalid scope qualifiers as if they just weren't there.
5666  LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5667                        ForRedeclaration);
5668  if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
5669    DC = computeDeclContext(ScopeQual);
5670
5671    // FIXME: handle dependent contexts
5672    if (!DC) return DeclPtrTy();
5673    if (RequireCompleteDeclContext(ScopeQual, DC)) return DeclPtrTy();
5674
5675    LookupQualifiedName(Previous, DC);
5676
5677    // If searching in that context implicitly found a declaration in
5678    // a different context, treat it like it wasn't found at all.
5679    // TODO: better diagnostics for this case.  Suggesting the right
5680    // qualified scope would be nice...
5681    // FIXME: getRepresentativeDecl() is not right here at all
5682    if (Previous.empty() ||
5683        !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
5684      D.setInvalidType();
5685      Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5686      return DeclPtrTy();
5687    }
5688
5689    // C++ [class.friend]p1: A friend of a class is a function or
5690    //   class that is not a member of the class . . .
5691    if (DC->Equals(CurContext))
5692      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5693
5694  // Otherwise walk out to the nearest namespace scope looking for matches.
5695  } else {
5696    // TODO: handle local class contexts.
5697
5698    DC = CurContext;
5699    while (true) {
5700      // Skip class contexts.  If someone can cite chapter and verse
5701      // for this behavior, that would be nice --- it's what GCC and
5702      // EDG do, and it seems like a reasonable intent, but the spec
5703      // really only says that checks for unqualified existing
5704      // declarations should stop at the nearest enclosing namespace,
5705      // not that they should only consider the nearest enclosing
5706      // namespace.
5707      while (DC->isRecord())
5708        DC = DC->getParent();
5709
5710      LookupQualifiedName(Previous, DC);
5711
5712      // TODO: decide what we think about using declarations.
5713      if (!Previous.empty())
5714        break;
5715
5716      if (DC->isFileContext()) break;
5717      DC = DC->getParent();
5718    }
5719
5720    // C++ [class.friend]p1: A friend of a class is a function or
5721    //   class that is not a member of the class . . .
5722    // C++0x changes this for both friend types and functions.
5723    // Most C++ 98 compilers do seem to give an error here, so
5724    // we do, too.
5725    if (!Previous.empty() && DC->Equals(CurContext)
5726        && !getLangOptions().CPlusPlus0x)
5727      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5728  }
5729
5730  if (DC->isFileContext()) {
5731    // This implies that it has to be an operator or function.
5732    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5733        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5734        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
5735      Diag(Loc, diag::err_introducing_special_friend) <<
5736        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5737         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
5738      return DeclPtrTy();
5739    }
5740  }
5741
5742  bool Redeclaration = false;
5743  NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
5744                                          move(TemplateParams),
5745                                          IsDefinition,
5746                                          Redeclaration);
5747  if (!ND) return DeclPtrTy();
5748
5749  assert(ND->getDeclContext() == DC);
5750  assert(ND->getLexicalDeclContext() == CurContext);
5751
5752  // Add the function declaration to the appropriate lookup tables,
5753  // adjusting the redeclarations list as necessary.  We don't
5754  // want to do this yet if the friending class is dependent.
5755  //
5756  // Also update the scope-based lookup if the target context's
5757  // lookup context is in lexical scope.
5758  if (!CurContext->isDependentContext()) {
5759    DC = DC->getLookupContext();
5760    DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
5761    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
5762      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
5763  }
5764
5765  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
5766                                       D.getIdentifierLoc(), ND,
5767                                       DS.getFriendSpecLoc());
5768  FrD->setAccess(AS_public);
5769  CurContext->addDecl(FrD);
5770
5771  return DeclPtrTy::make(ND);
5772}
5773
5774void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
5775  AdjustDeclIfTemplate(dcl);
5776
5777  Decl *Dcl = dcl.getAs<Decl>();
5778  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5779  if (!Fn) {
5780    Diag(DelLoc, diag::err_deleted_non_function);
5781    return;
5782  }
5783  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5784    Diag(DelLoc, diag::err_deleted_decl_not_first);
5785    Diag(Prev->getLocation(), diag::note_previous_declaration);
5786    // If the declaration wasn't the first, we delete the function anyway for
5787    // recovery.
5788  }
5789  Fn->setDeleted();
5790}
5791
5792static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5793  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5794       ++CI) {
5795    Stmt *SubStmt = *CI;
5796    if (!SubStmt)
5797      continue;
5798    if (isa<ReturnStmt>(SubStmt))
5799      Self.Diag(SubStmt->getSourceRange().getBegin(),
5800           diag::err_return_in_constructor_handler);
5801    if (!isa<Expr>(SubStmt))
5802      SearchForReturnInStmt(Self, SubStmt);
5803  }
5804}
5805
5806void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5807  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5808    CXXCatchStmt *Handler = TryBlock->getHandler(I);
5809    SearchForReturnInStmt(*this, Handler);
5810  }
5811}
5812
5813bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5814                                             const CXXMethodDecl *Old) {
5815  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5816  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
5817
5818  if (Context.hasSameType(NewTy, OldTy) ||
5819      NewTy->isDependentType() || OldTy->isDependentType())
5820    return false;
5821
5822  // Check if the return types are covariant
5823  QualType NewClassTy, OldClassTy;
5824
5825  /// Both types must be pointers or references to classes.
5826  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5827    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
5828      NewClassTy = NewPT->getPointeeType();
5829      OldClassTy = OldPT->getPointeeType();
5830    }
5831  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5832    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5833      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5834        NewClassTy = NewRT->getPointeeType();
5835        OldClassTy = OldRT->getPointeeType();
5836      }
5837    }
5838  }
5839
5840  // The return types aren't either both pointers or references to a class type.
5841  if (NewClassTy.isNull()) {
5842    Diag(New->getLocation(),
5843         diag::err_different_return_type_for_overriding_virtual_function)
5844      << New->getDeclName() << NewTy << OldTy;
5845    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5846
5847    return true;
5848  }
5849
5850  // C++ [class.virtual]p6:
5851  //   If the return type of D::f differs from the return type of B::f, the
5852  //   class type in the return type of D::f shall be complete at the point of
5853  //   declaration of D::f or shall be the class type D.
5854  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5855    if (!RT->isBeingDefined() &&
5856        RequireCompleteType(New->getLocation(), NewClassTy,
5857                            PDiag(diag::err_covariant_return_incomplete)
5858                              << New->getDeclName()))
5859    return true;
5860  }
5861
5862  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
5863    // Check if the new class derives from the old class.
5864    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5865      Diag(New->getLocation(),
5866           diag::err_covariant_return_not_derived)
5867      << New->getDeclName() << NewTy << OldTy;
5868      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5869      return true;
5870    }
5871
5872    // Check if we the conversion from derived to base is valid.
5873    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
5874                    diag::err_covariant_return_inaccessible_base,
5875                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
5876                    // FIXME: Should this point to the return type?
5877                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
5878      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5879      return true;
5880    }
5881  }
5882
5883  // The qualifiers of the return types must be the same.
5884  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
5885    Diag(New->getLocation(),
5886         diag::err_covariant_return_type_different_qualifications)
5887    << New->getDeclName() << NewTy << OldTy;
5888    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5889    return true;
5890  };
5891
5892
5893  // The new class type must have the same or less qualifiers as the old type.
5894  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5895    Diag(New->getLocation(),
5896         diag::err_covariant_return_type_class_type_more_qualified)
5897    << New->getDeclName() << NewTy << OldTy;
5898    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5899    return true;
5900  };
5901
5902  return false;
5903}
5904
5905bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5906                                             const CXXMethodDecl *Old)
5907{
5908  if (Old->hasAttr<FinalAttr>()) {
5909    Diag(New->getLocation(), diag::err_final_function_overridden)
5910      << New->getDeclName();
5911    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5912    return true;
5913  }
5914
5915  return false;
5916}
5917
5918/// \brief Mark the given method pure.
5919///
5920/// \param Method the method to be marked pure.
5921///
5922/// \param InitRange the source range that covers the "0" initializer.
5923bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5924  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5925    Method->setPure();
5926
5927    // A class is abstract if at least one function is pure virtual.
5928    Method->getParent()->setAbstract(true);
5929    return false;
5930  }
5931
5932  if (!Method->isInvalidDecl())
5933    Diag(Method->getLocation(), diag::err_non_virtual_pure)
5934      << Method->getDeclName() << InitRange;
5935  return true;
5936}
5937
5938/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5939/// an initializer for the out-of-line declaration 'Dcl'.  The scope
5940/// is a fresh scope pushed for just this purpose.
5941///
5942/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5943/// static data member of class X, names should be looked up in the scope of
5944/// class X.
5945void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
5946  // If there is no declaration, there was an error parsing it.
5947  Decl *D = Dcl.getAs<Decl>();
5948  if (D == 0) return;
5949
5950  // We should only get called for declarations with scope specifiers, like:
5951  //   int foo::bar;
5952  assert(D->isOutOfLine());
5953  EnterDeclaratorContext(S, D->getDeclContext());
5954}
5955
5956/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5957/// initializer for the out-of-line declaration 'Dcl'.
5958void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
5959  // If there is no declaration, there was an error parsing it.
5960  Decl *D = Dcl.getAs<Decl>();
5961  if (D == 0) return;
5962
5963  assert(D->isOutOfLine());
5964  ExitDeclaratorContext(S);
5965}
5966
5967/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5968/// C++ if/switch/while/for statement.
5969/// e.g: "if (int x = f()) {...}"
5970Action::DeclResult
5971Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5972  // C++ 6.4p2:
5973  // The declarator shall not specify a function or an array.
5974  // The type-specifier-seq shall not contain typedef and shall not declare a
5975  // new class or enumeration.
5976  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5977         "Parser allowed 'typedef' as storage class of condition decl.");
5978
5979  TypeSourceInfo *TInfo = 0;
5980  TagDecl *OwnedTag = 0;
5981  QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
5982
5983  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5984                              // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5985                              // would be created and CXXConditionDeclExpr wants a VarDecl.
5986    Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5987      << D.getSourceRange();
5988    return DeclResult();
5989  } else if (OwnedTag && OwnedTag->isDefinition()) {
5990    // The type-specifier-seq shall not declare a new class or enumeration.
5991    Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5992  }
5993
5994  DeclPtrTy Dcl = ActOnDeclarator(S, D);
5995  if (!Dcl)
5996    return DeclResult();
5997
5998  VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5999  VD->setDeclaredInCondition(true);
6000  return Dcl;
6001}
6002
6003static bool needsVTable(CXXMethodDecl *MD, ASTContext &Context) {
6004  // Ignore dependent types.
6005  if (MD->isDependentContext())
6006    return false;
6007
6008  // Ignore declarations that are not definitions.
6009  if (!MD->isThisDeclarationADefinition())
6010    return false;
6011
6012  CXXRecordDecl *RD = MD->getParent();
6013
6014  // Ignore classes without a vtable.
6015  if (!RD->isDynamicClass())
6016    return false;
6017
6018  switch (MD->getParent()->getTemplateSpecializationKind()) {
6019  case TSK_Undeclared:
6020  case TSK_ExplicitSpecialization:
6021    // Classes that aren't instantiations of templates don't need their
6022    // virtual methods marked until we see the definition of the key
6023    // function.
6024    break;
6025
6026  case TSK_ImplicitInstantiation:
6027    // This is a constructor of a class template; mark all of the virtual
6028    // members as referenced to ensure that they get instantiatied.
6029    if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
6030      return true;
6031    break;
6032
6033  case TSK_ExplicitInstantiationDeclaration:
6034    return false;
6035
6036  case TSK_ExplicitInstantiationDefinition:
6037    // This is method of a explicit instantiation; mark all of the virtual
6038    // members as referenced to ensure that they get instantiatied.
6039    return true;
6040  }
6041
6042  // Consider only out-of-line definitions of member functions. When we see
6043  // an inline definition, it's too early to compute the key function.
6044  if (!MD->isOutOfLine())
6045    return false;
6046
6047  const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
6048
6049  // If there is no key function, we will need a copy of the vtable.
6050  if (!KeyFunction)
6051    return true;
6052
6053  // If this is the key function, we need to mark virtual members.
6054  if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
6055    return true;
6056
6057  return false;
6058}
6059
6060void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
6061                                             CXXMethodDecl *MD) {
6062  CXXRecordDecl *RD = MD->getParent();
6063
6064  // We will need to mark all of the virtual members as referenced to build the
6065  // vtable.
6066  if (!needsVTable(MD, Context))
6067    return;
6068
6069  TemplateSpecializationKind kind = RD->getTemplateSpecializationKind();
6070  if (kind == TSK_ImplicitInstantiation)
6071    ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
6072  else
6073    MarkVirtualMembersReferenced(Loc, RD);
6074}
6075
6076bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
6077  if (ClassesWithUnmarkedVirtualMembers.empty())
6078    return false;
6079
6080  while (!ClassesWithUnmarkedVirtualMembers.empty()) {
6081    CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
6082    SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
6083    ClassesWithUnmarkedVirtualMembers.pop_back();
6084    MarkVirtualMembersReferenced(Loc, RD);
6085  }
6086
6087  return true;
6088}
6089
6090void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6091                                        const CXXRecordDecl *RD) {
6092  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6093       e = RD->method_end(); i != e; ++i) {
6094    CXXMethodDecl *MD = *i;
6095
6096    // C++ [basic.def.odr]p2:
6097    //   [...] A virtual member function is used if it is not pure. [...]
6098    if (MD->isVirtual() && !MD->isPure())
6099      MarkDeclarationReferenced(Loc, MD);
6100  }
6101
6102  // Only classes that have virtual bases need a VTT.
6103  if (RD->getNumVBases() == 0)
6104    return;
6105
6106  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6107           e = RD->bases_end(); i != e; ++i) {
6108    const CXXRecordDecl *Base =
6109        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
6110    if (i->isVirtual())
6111      continue;
6112    if (Base->getNumVBases() == 0)
6113      continue;
6114    MarkVirtualMembersReferenced(Loc, Base);
6115  }
6116}
6117
6118/// SetIvarInitializers - This routine builds initialization ASTs for the
6119/// Objective-C implementation whose ivars need be initialized.
6120void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6121  if (!getLangOptions().CPlusPlus)
6122    return;
6123  if (const ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
6124    llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6125    CollectIvarsToConstructOrDestruct(OID, ivars);
6126    if (ivars.empty())
6127      return;
6128    llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6129    for (unsigned i = 0; i < ivars.size(); i++) {
6130      FieldDecl *Field = ivars[i];
6131      CXXBaseOrMemberInitializer *Member;
6132      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6133      InitializationKind InitKind =
6134        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6135
6136      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
6137      Sema::OwningExprResult MemberInit =
6138        InitSeq.Perform(*this, InitEntity, InitKind,
6139                        Sema::MultiExprArg(*this, 0, 0));
6140      MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
6141      // Note, MemberInit could actually come back empty if no initialization
6142      // is required (e.g., because it would call a trivial default constructor)
6143      if (!MemberInit.get() || MemberInit.isInvalid())
6144        continue;
6145
6146      Member =
6147        new (Context) CXXBaseOrMemberInitializer(Context,
6148                                                 Field, SourceLocation(),
6149                                                 SourceLocation(),
6150                                                 MemberInit.takeAs<Expr>(),
6151                                                 SourceLocation());
6152      AllToInit.push_back(Member);
6153    }
6154    ObjCImplementation->setIvarInitializers(Context,
6155                                            AllToInit.data(), AllToInit.size());
6156  }
6157}
6158