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