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