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