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