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