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