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