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