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