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