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