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