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