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