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