SemaDeclCXX.cpp revision 70d2612fd956d4d3aeac8b3abed8ef5e29c4b7a5
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 "Sema.h"
15#include "SemaInherit.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/TypeOrdering.h"
19#include "clang/AST/StmtVisitor.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Parse/DeclSpec.h"
23#include "llvm/Support/Compiler.h"
24#include <algorithm> // for std::equal
25#include <map>
26
27using namespace clang;
28
29//===----------------------------------------------------------------------===//
30// CheckDefaultArgumentVisitor
31//===----------------------------------------------------------------------===//
32
33namespace {
34  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
35  /// the default argument of a parameter to determine whether it
36  /// contains any ill-formed subexpressions. For example, this will
37  /// diagnose the use of local variables or parameters within the
38  /// default argument expression.
39  class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
40    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
41    Expr *DefaultArg;
42    Sema *S;
43
44  public:
45    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
46      : DefaultArg(defarg), S(s) {}
47
48    bool VisitExpr(Expr *Node);
49    bool VisitDeclRefExpr(DeclRefExpr *DRE);
50    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
51  };
52
53  /// VisitExpr - Visit all of the children of this expression.
54  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
55    bool IsInvalid = false;
56    for (Stmt::child_iterator I = Node->child_begin(),
57         E = Node->child_end(); I != E; ++I)
58      IsInvalid |= Visit(*I);
59    return IsInvalid;
60  }
61
62  /// VisitDeclRefExpr - Visit a reference to a declaration, to
63  /// determine whether this declaration can be used in the default
64  /// argument expression.
65  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
66    NamedDecl *Decl = DRE->getDecl();
67    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
68      // C++ [dcl.fct.default]p9
69      //   Default arguments are evaluated each time the function is
70      //   called. The order of evaluation of function arguments is
71      //   unspecified. Consequently, parameters of a function shall not
72      //   be used in default argument expressions, even if they are not
73      //   evaluated. Parameters of a function declared before a default
74      //   argument expression are in scope and can hide namespace and
75      //   class member names.
76      return S->Diag(DRE->getSourceRange().getBegin(),
77                     diag::err_param_default_argument_references_param,
78                     Param->getName(), DefaultArg->getSourceRange());
79    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
80      // C++ [dcl.fct.default]p7
81      //   Local variables shall not be used in default argument
82      //   expressions.
83      if (VDecl->isBlockVarDecl())
84        return S->Diag(DRE->getSourceRange().getBegin(),
85                       diag::err_param_default_argument_references_local,
86                       VDecl->getName(), DefaultArg->getSourceRange());
87    }
88
89    return false;
90  }
91
92  /// VisitCXXThisExpr - Visit a C++ "this" expression.
93  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
94    // C++ [dcl.fct.default]p8:
95    //   The keyword this shall not be used in a default argument of a
96    //   member function.
97    return S->Diag(ThisE->getSourceRange().getBegin(),
98                   diag::err_param_default_argument_references_this,
99                   ThisE->getSourceRange());
100  }
101}
102
103/// ActOnParamDefaultArgument - Check whether the default argument
104/// provided for a function parameter is well-formed. If so, attach it
105/// to the parameter declaration.
106void
107Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
108                                ExprTy *defarg) {
109  ParmVarDecl *Param = (ParmVarDecl *)param;
110  llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
111  QualType ParamType = Param->getType();
112
113  // Default arguments are only permitted in C++
114  if (!getLangOptions().CPlusPlus) {
115    Diag(EqualLoc, diag::err_param_default_argument,
116         DefaultArg->getSourceRange());
117    return;
118  }
119
120  // C++ [dcl.fct.default]p5
121  //   A default argument expression is implicitly converted (clause
122  //   4) to the parameter type. The default argument expression has
123  //   the same semantic constraints as the initializer expression in
124  //   a declaration of a variable of the parameter type, using the
125  //   copy-initialization semantics (8.5).
126  Expr *DefaultArgPtr = DefaultArg.get();
127  bool DefaultInitFailed = PerformCopyInitialization(DefaultArgPtr, ParamType,
128                                                     "in default argument");
129  if (DefaultArgPtr != DefaultArg.get()) {
130    DefaultArg.take();
131    DefaultArg.reset(DefaultArgPtr);
132  }
133  if (DefaultInitFailed) {
134    return;
135  }
136
137  // Check that the default argument is well-formed
138  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
139  if (DefaultArgChecker.Visit(DefaultArg.get()))
140    return;
141
142  // Okay: add the default argument to the parameter
143  Param->setDefaultArg(DefaultArg.take());
144}
145
146/// CheckExtraCXXDefaultArguments - Check for any extra default
147/// arguments in the declarator, which is not a function declaration
148/// or definition and therefore is not permitted to have default
149/// arguments. This routine should be invoked for every declarator
150/// that is not a function declaration or definition.
151void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
152  // C++ [dcl.fct.default]p3
153  //   A default argument expression shall be specified only in the
154  //   parameter-declaration-clause of a function declaration or in a
155  //   template-parameter (14.1). It shall not be specified for a
156  //   parameter pack. If it is specified in a
157  //   parameter-declaration-clause, it shall not occur within a
158  //   declarator or abstract-declarator of a parameter-declaration.
159  for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
160    DeclaratorChunk &chunk = D.getTypeObject(i);
161    if (chunk.Kind == DeclaratorChunk::Function) {
162      for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
163        ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
164        if (Param->getDefaultArg()) {
165          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc,
166               Param->getDefaultArg()->getSourceRange());
167          Param->setDefaultArg(0);
168        }
169      }
170    }
171  }
172}
173
174// MergeCXXFunctionDecl - Merge two declarations of the same C++
175// function, once we already know that they have the same
176// type. Subroutine of MergeFunctionDecl.
177FunctionDecl *
178Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
179  // C++ [dcl.fct.default]p4:
180  //
181  //   For non-template functions, default arguments can be added in
182  //   later declarations of a function in the same
183  //   scope. Declarations in different scopes have completely
184  //   distinct sets of default arguments. That is, declarations in
185  //   inner scopes do not acquire default arguments from
186  //   declarations in outer scopes, and vice versa. In a given
187  //   function declaration, all parameters subsequent to a
188  //   parameter with a default argument shall have default
189  //   arguments supplied in this or previous declarations. A
190  //   default argument shall not be redefined by a later
191  //   declaration (not even to the same value).
192  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
193    ParmVarDecl *OldParam = Old->getParamDecl(p);
194    ParmVarDecl *NewParam = New->getParamDecl(p);
195
196    if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
197      Diag(NewParam->getLocation(),
198           diag::err_param_default_argument_redefinition,
199           NewParam->getDefaultArg()->getSourceRange());
200      Diag(OldParam->getLocation(), diag::err_previous_definition);
201    } else if (OldParam->getDefaultArg()) {
202      // Merge the old default argument into the new parameter
203      NewParam->setDefaultArg(OldParam->getDefaultArg());
204    }
205  }
206
207  return New;
208}
209
210/// CheckCXXDefaultArguments - Verify that the default arguments for a
211/// function declaration are well-formed according to C++
212/// [dcl.fct.default].
213void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
214  unsigned NumParams = FD->getNumParams();
215  unsigned p;
216
217  // Find first parameter with a default argument
218  for (p = 0; p < NumParams; ++p) {
219    ParmVarDecl *Param = FD->getParamDecl(p);
220    if (Param->getDefaultArg())
221      break;
222  }
223
224  // C++ [dcl.fct.default]p4:
225  //   In a given function declaration, all parameters
226  //   subsequent to a parameter with a default argument shall
227  //   have default arguments supplied in this or previous
228  //   declarations. A default argument shall not be redefined
229  //   by a later declaration (not even to the same value).
230  unsigned LastMissingDefaultArg = 0;
231  for(; p < NumParams; ++p) {
232    ParmVarDecl *Param = FD->getParamDecl(p);
233    if (!Param->getDefaultArg()) {
234      if (Param->getIdentifier())
235        Diag(Param->getLocation(),
236             diag::err_param_default_argument_missing_name,
237             Param->getIdentifier()->getName());
238      else
239        Diag(Param->getLocation(),
240             diag::err_param_default_argument_missing);
241
242      LastMissingDefaultArg = p;
243    }
244  }
245
246  if (LastMissingDefaultArg > 0) {
247    // Some default arguments were missing. Clear out all of the
248    // default arguments up to (and including) the last missing
249    // default argument, so that we leave the function parameters
250    // in a semantically valid state.
251    for (p = 0; p <= LastMissingDefaultArg; ++p) {
252      ParmVarDecl *Param = FD->getParamDecl(p);
253      if (Param->getDefaultArg()) {
254        delete Param->getDefaultArg();
255        Param->setDefaultArg(0);
256      }
257    }
258  }
259}
260
261/// isCurrentClassName - Determine whether the identifier II is the
262/// name of the class type currently being defined. In the case of
263/// nested classes, this will only return true if II is the name of
264/// the innermost class.
265bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
266                              const CXXScopeSpec *SS) {
267  CXXRecordDecl *CurDecl;
268  if (SS) {
269    DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
270    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
271  } else
272    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
273
274  if (CurDecl)
275    return &II == CurDecl->getIdentifier();
276  else
277    return false;
278}
279
280/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
281/// one entry in the base class list of a class specifier, for
282/// example:
283///    class foo : public bar, virtual private baz {
284/// 'public bar' and 'virtual private baz' are each base-specifiers.
285Sema::BaseResult
286Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
287                         bool Virtual, AccessSpecifier Access,
288                         TypeTy *basetype, SourceLocation BaseLoc) {
289  RecordDecl *Decl = (RecordDecl*)classdecl;
290  QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
291
292  // Base specifiers must be record types.
293  if (!BaseType->isRecordType()) {
294    Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange);
295    return true;
296  }
297
298  // C++ [class.union]p1:
299  //   A union shall not be used as a base class.
300  if (BaseType->isUnionType()) {
301    Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange);
302    return true;
303  }
304
305  // C++ [class.union]p1:
306  //   A union shall not have base classes.
307  if (Decl->isUnion()) {
308    Diag(Decl->getLocation(), diag::err_base_clause_on_union,
309         SpecifierRange);
310    return true;
311  }
312
313  // C++ [class.derived]p2:
314  //   The class-name in a base-specifier shall not be an incompletely
315  //   defined class.
316  if (BaseType->isIncompleteType()) {
317    Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
318    return true;
319  }
320
321  // If the base class is polymorphic, the new one is, too.
322  RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
323  assert(BaseDecl && "Record type has no declaration");
324  BaseDecl = BaseDecl->getDefinition(Context);
325  assert(BaseDecl && "Base type is not incomplete, but has no definition");
326  if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic()) {
327    cast<CXXRecordDecl>(Decl)->setPolymorphic(true);
328  }
329
330  // Create the base specifier.
331  return new CXXBaseSpecifier(SpecifierRange, Virtual,
332                              BaseType->isClassType(), Access, BaseType);
333}
334
335/// ActOnBaseSpecifiers - Attach the given base specifiers to the
336/// class, after checking whether there are any duplicate base
337/// classes.
338void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
339                               unsigned NumBases) {
340  if (NumBases == 0)
341    return;
342
343  // Used to keep track of which base types we have already seen, so
344  // that we can properly diagnose redundant direct base types. Note
345  // that the key is always the unqualified canonical type of the base
346  // class.
347  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
348
349  // Copy non-redundant base specifiers into permanent storage.
350  CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
351  unsigned NumGoodBases = 0;
352  for (unsigned idx = 0; idx < NumBases; ++idx) {
353    QualType NewBaseType
354      = Context.getCanonicalType(BaseSpecs[idx]->getType());
355    NewBaseType = NewBaseType.getUnqualifiedType();
356
357    if (KnownBaseTypes[NewBaseType]) {
358      // C++ [class.mi]p3:
359      //   A class shall not be specified as a direct base class of a
360      //   derived class more than once.
361      Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
362           diag::err_duplicate_base_class,
363           KnownBaseTypes[NewBaseType]->getType().getAsString(),
364           BaseSpecs[idx]->getSourceRange());
365
366      // Delete the duplicate base class specifier; we're going to
367      // overwrite its pointer later.
368      delete BaseSpecs[idx];
369    } else {
370      // Okay, add this new base class.
371      KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
372      BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
373    }
374  }
375
376  // Attach the remaining base class specifiers to the derived class.
377  CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
378  Decl->setBases(BaseSpecs, NumGoodBases);
379
380  // Delete the remaining (good) base class specifiers, since their
381  // data has been copied into the CXXRecordDecl.
382  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
383    delete BaseSpecs[idx];
384}
385
386//===----------------------------------------------------------------------===//
387// C++ class member Handling
388//===----------------------------------------------------------------------===//
389
390/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
391/// definition, when on C++.
392void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
393  CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
394  PushDeclContext(Dcl);
395  FieldCollector->StartClass();
396
397  if (Dcl->getIdentifier()) {
398    // C++ [class]p2:
399    //   [...] The class-name is also inserted into the scope of the
400    //   class itself; this is known as the injected-class-name. For
401    //   purposes of access checking, the injected-class-name is treated
402    //   as if it were a public member name.
403    PushOnScopeChains(Dcl, S);
404  }
405}
406
407/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
408/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
409/// bitfield width if there is one and 'InitExpr' specifies the initializer if
410/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
411/// declarators on it.
412///
413/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
414/// an instance field is declared, a new CXXFieldDecl is created but the method
415/// does *not* return it; it returns LastInGroup instead. The other C++ members
416/// (which are all ScopedDecls) are returned after appending them to
417/// LastInGroup.
418Sema::DeclTy *
419Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
420                               ExprTy *BW, ExprTy *InitExpr,
421                               DeclTy *LastInGroup) {
422  const DeclSpec &DS = D.getDeclSpec();
423  IdentifierInfo *II = D.getIdentifier();
424  Expr *BitWidth = static_cast<Expr*>(BW);
425  Expr *Init = static_cast<Expr*>(InitExpr);
426  SourceLocation Loc = D.getIdentifierLoc();
427
428  // C++ 9.2p6: A member shall not be declared to have automatic storage
429  // duration (auto, register) or with the extern storage-class-specifier.
430  switch (DS.getStorageClassSpec()) {
431    case DeclSpec::SCS_unspecified:
432    case DeclSpec::SCS_typedef:
433    case DeclSpec::SCS_static:
434      // FALL THROUGH.
435      break;
436    default:
437      if (DS.getStorageClassSpecLoc().isValid())
438        Diag(DS.getStorageClassSpecLoc(),
439             diag::err_storageclass_invalid_for_member);
440      else
441        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
442      D.getMutableDeclSpec().ClearStorageClassSpecs();
443  }
444
445  bool isFunc = D.isFunctionDeclarator();
446  if (!isFunc &&
447      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
448      D.getNumTypeObjects() == 0) {
449    // Check also for this case:
450    //
451    // typedef int f();
452    // f a;
453    //
454    Decl *TD = static_cast<Decl *>(DS.getTypeRep());
455    isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
456  }
457
458  bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
459                      !isFunc);
460
461  Decl *Member;
462  bool InvalidDecl = false;
463
464  if (isInstField)
465    Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
466  else
467    Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
468
469  if (!Member) return LastInGroup;
470
471  assert((II || isInstField) && "No identifier for non-field ?");
472
473  // set/getAccess is not part of Decl's interface to avoid bloating it with C++
474  // specific methods. Use a wrapper class that can be used with all C++ class
475  // member decls.
476  CXXClassMemberWrapper(Member).setAccess(AS);
477
478  // C++ [dcl.init.aggr]p1:
479  //   An aggregate is an array or a class (clause 9) with [...] no
480  //   private or protected non-static data members (clause 11).
481  if (isInstField && (AS == AS_private || AS == AS_protected))
482    cast<CXXRecordDecl>(CurContext)->setAggregate(false);
483
484  if (DS.isVirtualSpecified()) {
485    if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
486      Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
487      InvalidDecl = true;
488    } else {
489      CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
490      CurClass->setAggregate(false);
491      CurClass->setPolymorphic(true);
492    }
493  }
494
495  if (BitWidth) {
496    // C++ 9.6p2: Only when declaring an unnamed bit-field may the
497    // constant-expression be a value equal to zero.
498    // FIXME: Check this.
499
500    if (D.isFunctionDeclarator()) {
501      // FIXME: Emit diagnostic about only constructors taking base initializers
502      // or something similar, when constructor support is in place.
503      Diag(Loc, diag::err_not_bitfield_type,
504           II->getName(), BitWidth->getSourceRange());
505      InvalidDecl = true;
506
507    } else if (isInstField) {
508      // C++ 9.6p3: A bit-field shall have integral or enumeration type.
509      if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
510        Diag(Loc, diag::err_not_integral_type_bitfield,
511             II->getName(), BitWidth->getSourceRange());
512        InvalidDecl = true;
513      }
514
515    } else if (isa<FunctionDecl>(Member)) {
516      // A function typedef ("typedef int f(); f a;").
517      // C++ 9.6p3: A bit-field shall have integral or enumeration type.
518      Diag(Loc, diag::err_not_integral_type_bitfield,
519           II->getName(), BitWidth->getSourceRange());
520      InvalidDecl = true;
521
522    } else if (isa<TypedefDecl>(Member)) {
523      // "cannot declare 'A' to be a bit-field type"
524      Diag(Loc, diag::err_not_bitfield_type, II->getName(),
525           BitWidth->getSourceRange());
526      InvalidDecl = true;
527
528    } else {
529      assert(isa<CXXClassVarDecl>(Member) &&
530             "Didn't we cover all member kinds?");
531      // C++ 9.6p3: A bit-field shall not be a static member.
532      // "static member 'A' cannot be a bit-field"
533      Diag(Loc, diag::err_static_not_bitfield, II->getName(),
534           BitWidth->getSourceRange());
535      InvalidDecl = true;
536    }
537  }
538
539  if (Init) {
540    // C++ 9.2p4: A member-declarator can contain a constant-initializer only
541    // if it declares a static member of const integral or const enumeration
542    // type.
543    if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
544      // ...static member of...
545      CVD->setInit(Init);
546      // ...const integral or const enumeration type.
547      if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
548          CVD->getType()->isIntegralType()) {
549        // constant-initializer
550        if (CheckForConstantInitializer(Init, CVD->getType()))
551          InvalidDecl = true;
552
553      } else {
554        // not const integral.
555        Diag(Loc, diag::err_member_initialization,
556             II->getName(), Init->getSourceRange());
557        InvalidDecl = true;
558      }
559
560    } else {
561      // not static member.
562      Diag(Loc, diag::err_member_initialization,
563           II->getName(), Init->getSourceRange());
564      InvalidDecl = true;
565    }
566  }
567
568  if (InvalidDecl)
569    Member->setInvalidDecl();
570
571  if (isInstField) {
572    FieldCollector->Add(cast<CXXFieldDecl>(Member));
573    return LastInGroup;
574  }
575  return Member;
576}
577
578/// ActOnMemInitializer - Handle a C++ member initializer.
579Sema::MemInitResult
580Sema::ActOnMemInitializer(DeclTy *ConstructorD,
581                          Scope *S,
582                          IdentifierInfo *MemberOrBase,
583                          SourceLocation IdLoc,
584                          SourceLocation LParenLoc,
585                          ExprTy **Args, unsigned NumArgs,
586                          SourceLocation *CommaLocs,
587                          SourceLocation RParenLoc) {
588  CXXConstructorDecl *Constructor
589    = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
590  if (!Constructor) {
591    // The user wrote a constructor initializer on a function that is
592    // not a C++ constructor. Ignore the error for now, because we may
593    // have more member initializers coming; we'll diagnose it just
594    // once in ActOnMemInitializers.
595    return true;
596  }
597
598  CXXRecordDecl *ClassDecl = Constructor->getParent();
599
600  // C++ [class.base.init]p2:
601  //   Names in a mem-initializer-id are looked up in the scope of the
602  //   constructor’s class and, if not found in that scope, are looked
603  //   up in the scope containing the constructor’s
604  //   definition. [Note: if the constructor’s class contains a member
605  //   with the same name as a direct or virtual base class of the
606  //   class, a mem-initializer-id naming the member or base class and
607  //   composed of a single identifier refers to the class member. A
608  //   mem-initializer-id for the hidden base class may be specified
609  //   using a qualified name. ]
610  // Look for a member, first.
611  CXXFieldDecl *Member = ClassDecl->getMember(MemberOrBase);
612
613  // FIXME: Handle members of an anonymous union.
614
615  if (Member) {
616    // FIXME: Perform direct initialization of the member.
617    return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
618  }
619
620  // It didn't name a member, so see if it names a class.
621  TypeTy *BaseTy = isTypeName(*MemberOrBase, S, 0/*SS*/);
622  if (!BaseTy)
623    return Diag(IdLoc, diag::err_mem_init_not_member_or_class,
624                MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
625
626  QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
627  if (!BaseType->isRecordType())
628    return Diag(IdLoc, diag::err_base_init_does_not_name_class,
629                BaseType.getAsString(), SourceRange(IdLoc, RParenLoc));
630
631  // C++ [class.base.init]p2:
632  //   [...] Unless the mem-initializer-id names a nonstatic data
633  //   member of the constructor’s class or a direct or virtual base
634  //   of that class, the mem-initializer is ill-formed. A
635  //   mem-initializer-list can initialize a base class using any
636  //   name that denotes that base class type.
637
638  // First, check for a direct base class.
639  const CXXBaseSpecifier *DirectBaseSpec = 0;
640  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
641       Base != ClassDecl->bases_end(); ++Base) {
642    if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
643        Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
644      // We found a direct base of this type. That's what we're
645      // initializing.
646      DirectBaseSpec = &*Base;
647      break;
648    }
649  }
650
651  // Check for a virtual base class.
652  // FIXME: We might be able to short-circuit this if we know in
653  // advance that there are no virtual bases.
654  const CXXBaseSpecifier *VirtualBaseSpec = 0;
655  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
656    // We haven't found a base yet; search the class hierarchy for a
657    // virtual base class.
658    BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
659                    /*DetectVirtual=*/false);
660    if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
661      for (BasePaths::paths_iterator Path = Paths.begin();
662           Path != Paths.end(); ++Path) {
663        if (Path->back().Base->isVirtual()) {
664          VirtualBaseSpec = Path->back().Base;
665          break;
666        }
667      }
668    }
669  }
670
671  // C++ [base.class.init]p2:
672  //   If a mem-initializer-id is ambiguous because it designates both
673  //   a direct non-virtual base class and an inherited virtual base
674  //   class, the mem-initializer is ill-formed.
675  if (DirectBaseSpec && VirtualBaseSpec)
676    return Diag(IdLoc, diag::err_base_init_direct_and_virtual,
677                MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
678
679  return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
680}
681
682
683void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
684                                             DeclTy *TagDecl,
685                                             SourceLocation LBrac,
686                                             SourceLocation RBrac) {
687  ActOnFields(S, RLoc, TagDecl,
688              (DeclTy**)FieldCollector->getCurFields(),
689              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
690}
691
692/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
693/// special functions, such as the default constructor, copy
694/// constructor, or destructor, to the given C++ class (C++
695/// [special]p1).  This routine can only be executed just before the
696/// definition of the class is complete.
697void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
698  if (!ClassDecl->hasUserDeclaredConstructor()) {
699    // C++ [class.ctor]p5:
700    //   A default constructor for a class X is a constructor of class X
701    //   that can be called without an argument. If there is no
702    //   user-declared constructor for class X, a default constructor is
703    //   implicitly declared. An implicitly-declared default constructor
704    //   is an inline public member of its class.
705    CXXConstructorDecl *DefaultCon =
706      CXXConstructorDecl::Create(Context, ClassDecl,
707                                 ClassDecl->getLocation(),
708                                 ClassDecl->getIdentifier(),
709                                 Context.getFunctionType(Context.VoidTy,
710                                                         0, 0, false, 0),
711                                 /*isExplicit=*/false,
712                                 /*isInline=*/true,
713                                 /*isImplicitlyDeclared=*/true);
714    DefaultCon->setAccess(AS_public);
715    ClassDecl->addConstructor(Context, DefaultCon);
716  }
717
718  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
719    // C++ [class.copy]p4:
720    //   If the class definition does not explicitly declare a copy
721    //   constructor, one is declared implicitly.
722
723    // C++ [class.copy]p5:
724    //   The implicitly-declared copy constructor for a class X will
725    //   have the form
726    //
727    //       X::X(const X&)
728    //
729    //   if
730    bool HasConstCopyConstructor = true;
731
732    //     -- each direct or virtual base class B of X has a copy
733    //        constructor whose first parameter is of type const B& or
734    //        const volatile B&, and
735    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
736         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
737      const CXXRecordDecl *BaseClassDecl
738        = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
739      HasConstCopyConstructor
740        = BaseClassDecl->hasConstCopyConstructor(Context);
741    }
742
743    //     -- for all the nonstatic data members of X that are of a
744    //        class type M (or array thereof), each such class type
745    //        has a copy constructor whose first parameter is of type
746    //        const M& or const volatile M&.
747    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
748         HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
749      QualType FieldType = (*Field)->getType();
750      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
751        FieldType = Array->getElementType();
752      if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
753        const CXXRecordDecl *FieldClassDecl
754          = cast<CXXRecordDecl>(FieldClassType->getDecl());
755        HasConstCopyConstructor
756          = FieldClassDecl->hasConstCopyConstructor(Context);
757      }
758    }
759
760    //  Otherwise, the implicitly declared copy constructor will have
761    //  the form
762    //
763    //       X::X(X&)
764    QualType ArgType = Context.getTypeDeclType(ClassDecl);
765    if (HasConstCopyConstructor)
766      ArgType = ArgType.withConst();
767    ArgType = Context.getReferenceType(ArgType);
768
769    //  An implicitly-declared copy constructor is an inline public
770    //  member of its class.
771    CXXConstructorDecl *CopyConstructor
772      = CXXConstructorDecl::Create(Context, ClassDecl,
773                                   ClassDecl->getLocation(),
774                                   ClassDecl->getIdentifier(),
775                                   Context.getFunctionType(Context.VoidTy,
776                                                           &ArgType, 1,
777                                                           false, 0),
778                                   /*isExplicit=*/false,
779                                   /*isInline=*/true,
780                                   /*isImplicitlyDeclared=*/true);
781    CopyConstructor->setAccess(AS_public);
782
783    // Add the parameter to the constructor.
784    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
785                                                 ClassDecl->getLocation(),
786                                                 /*IdentifierInfo=*/0,
787                                                 ArgType, VarDecl::None, 0, 0);
788    CopyConstructor->setParams(&FromParam, 1);
789
790    ClassDecl->addConstructor(Context, CopyConstructor);
791  }
792
793  if (!ClassDecl->getDestructor()) {
794    // C++ [class.dtor]p2:
795    //   If a class has no user-declared destructor, a destructor is
796    //   declared implicitly. An implicitly-declared destructor is an
797    //   inline public member of its class.
798    std::string DestructorName = "~";
799    DestructorName += ClassDecl->getName();
800    CXXDestructorDecl *Destructor
801      = CXXDestructorDecl::Create(Context, ClassDecl,
802                                  ClassDecl->getLocation(),
803                                  &PP.getIdentifierTable().get(DestructorName),
804                                  Context.getFunctionType(Context.VoidTy,
805                                                          0, 0, false, 0),
806                                  /*isInline=*/true,
807                                  /*isImplicitlyDeclared=*/true);
808    Destructor->setAccess(AS_public);
809    ClassDecl->setDestructor(Destructor);
810  }
811
812  // FIXME: Implicit copy assignment operator
813}
814
815void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
816  CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
817  FieldCollector->FinishClass();
818  AddImplicitlyDeclaredMembersToClass(Rec);
819  PopDeclContext();
820
821  // Everything, including inline method definitions, have been parsed.
822  // Let the consumer know of the new TagDecl definition.
823  Consumer.HandleTagDeclDefinition(Rec);
824}
825
826/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
827/// the well-formednes of the constructor declarator @p D with type @p
828/// R. If there are any errors in the declarator, this routine will
829/// emit diagnostics and return true. Otherwise, it will return
830/// false. Either way, the type @p R will be updated to reflect a
831/// well-formed type for the constructor.
832bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
833                                      FunctionDecl::StorageClass& SC) {
834  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
835  bool isInvalid = false;
836
837  // C++ [class.ctor]p3:
838  //   A constructor shall not be virtual (10.3) or static (9.4). A
839  //   constructor can be invoked for a const, volatile or const
840  //   volatile object. A constructor shall not be declared const,
841  //   volatile, or const volatile (9.3.2).
842  if (isVirtual) {
843    Diag(D.getIdentifierLoc(),
844         diag::err_constructor_cannot_be,
845         "virtual",
846         SourceRange(D.getDeclSpec().getVirtualSpecLoc()),
847         SourceRange(D.getIdentifierLoc()));
848    isInvalid = true;
849  }
850  if (SC == FunctionDecl::Static) {
851    Diag(D.getIdentifierLoc(),
852         diag::err_constructor_cannot_be,
853         "static",
854         SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
855         SourceRange(D.getIdentifierLoc()));
856    isInvalid = true;
857    SC = FunctionDecl::None;
858  }
859  if (D.getDeclSpec().hasTypeSpecifier()) {
860    // Constructors don't have return types, but the parser will
861    // happily parse something like:
862    //
863    //   class X {
864    //     float X(float);
865    //   };
866    //
867    // The return type will be eliminated later.
868    Diag(D.getIdentifierLoc(),
869         diag::err_constructor_return_type,
870         SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
871         SourceRange(D.getIdentifierLoc()));
872  }
873  if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
874    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
875    if (FTI.TypeQuals & QualType::Const)
876      Diag(D.getIdentifierLoc(),
877           diag::err_invalid_qualified_constructor,
878           "const",
879           SourceRange(D.getIdentifierLoc()));
880    if (FTI.TypeQuals & QualType::Volatile)
881      Diag(D.getIdentifierLoc(),
882           diag::err_invalid_qualified_constructor,
883           "volatile",
884           SourceRange(D.getIdentifierLoc()));
885    if (FTI.TypeQuals & QualType::Restrict)
886      Diag(D.getIdentifierLoc(),
887           diag::err_invalid_qualified_constructor,
888           "restrict",
889           SourceRange(D.getIdentifierLoc()));
890  }
891
892  // Rebuild the function type "R" without any type qualifiers (in
893  // case any of the errors above fired) and with "void" as the
894  // return type, since constructors don't have return types. We
895  // *always* have to do this, because GetTypeForDeclarator will
896  // put in a result type of "int" when none was specified.
897  const FunctionTypeProto *Proto = R->getAsFunctionTypeProto();
898  R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
899                              Proto->getNumArgs(),
900                              Proto->isVariadic(),
901                              0);
902
903  return isInvalid;
904}
905
906/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
907/// the well-formednes of the destructor declarator @p D with type @p
908/// R. If there are any errors in the declarator, this routine will
909/// emit diagnostics and return true. Otherwise, it will return
910/// false. Either way, the type @p R will be updated to reflect a
911/// well-formed type for the destructor.
912bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
913                                     FunctionDecl::StorageClass& SC) {
914  bool isInvalid = false;
915
916  // C++ [class.dtor]p1:
917  //   [...] A typedef-name that names a class is a class-name
918  //   (7.1.3); however, a typedef-name that names a class shall not
919  //   be used as the identifier in the declarator for a destructor
920  //   declaration.
921  TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType();
922  if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) {
923    Diag(D.getIdentifierLoc(),
924         diag::err_destructor_typedef_name,
925         TypedefD->getName());
926    isInvalid = true;
927  }
928
929  // C++ [class.dtor]p2:
930  //   A destructor is used to destroy objects of its class type. A
931  //   destructor takes no parameters, and no return type can be
932  //   specified for it (not even void). The address of a destructor
933  //   shall not be taken. A destructor shall not be static. A
934  //   destructor can be invoked for a const, volatile or const
935  //   volatile object. A destructor shall not be declared const,
936  //   volatile or const volatile (9.3.2).
937  if (SC == FunctionDecl::Static) {
938    Diag(D.getIdentifierLoc(),
939         diag::err_destructor_cannot_be,
940         "static",
941         SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
942         SourceRange(D.getIdentifierLoc()));
943    isInvalid = true;
944    SC = FunctionDecl::None;
945  }
946  if (D.getDeclSpec().hasTypeSpecifier()) {
947    // Destructors don't have return types, but the parser will
948    // happily parse something like:
949    //
950    //   class X {
951    //     float ~X();
952    //   };
953    //
954    // The return type will be eliminated later.
955    Diag(D.getIdentifierLoc(),
956         diag::err_destructor_return_type,
957         SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
958         SourceRange(D.getIdentifierLoc()));
959  }
960  if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
961    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
962    if (FTI.TypeQuals & QualType::Const)
963      Diag(D.getIdentifierLoc(),
964           diag::err_invalid_qualified_destructor,
965           "const",
966           SourceRange(D.getIdentifierLoc()));
967    if (FTI.TypeQuals & QualType::Volatile)
968      Diag(D.getIdentifierLoc(),
969           diag::err_invalid_qualified_destructor,
970           "volatile",
971           SourceRange(D.getIdentifierLoc()));
972    if (FTI.TypeQuals & QualType::Restrict)
973      Diag(D.getIdentifierLoc(),
974           diag::err_invalid_qualified_destructor,
975           "restrict",
976           SourceRange(D.getIdentifierLoc()));
977  }
978
979  // Make sure we don't have any parameters.
980  if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
981    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
982
983    // Delete the parameters.
984    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
985    if (FTI.NumArgs) {
986      delete [] FTI.ArgInfo;
987      FTI.NumArgs = 0;
988      FTI.ArgInfo = 0;
989    }
990  }
991
992  // Make sure the destructor isn't variadic.
993  if (R->getAsFunctionTypeProto()->isVariadic())
994    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
995
996  // Rebuild the function type "R" without any type qualifiers or
997  // parameters (in case any of the errors above fired) and with
998  // "void" as the return type, since destructors don't have return
999  // types. We *always* have to do this, because GetTypeForDeclarator
1000  // will put in a result type of "int" when none was specified.
1001  R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1002
1003  return isInvalid;
1004}
1005
1006/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1007/// well-formednes of the conversion function declarator @p D with
1008/// type @p R. If there are any errors in the declarator, this routine
1009/// will emit diagnostics and return true. Otherwise, it will return
1010/// false. Either way, the type @p R will be updated to reflect a
1011/// well-formed type for the conversion operator.
1012bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1013                                     FunctionDecl::StorageClass& SC) {
1014  bool isInvalid = false;
1015
1016  // C++ [class.conv.fct]p1:
1017  //   Neither parameter types nor return type can be specified. The
1018  //   type of a conversion function (8.3.5) is “function taking no
1019  //   parameter returning conversion-type-id.”
1020  if (SC == FunctionDecl::Static) {
1021    Diag(D.getIdentifierLoc(),
1022         diag::err_conv_function_not_member,
1023         "static",
1024         SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
1025         SourceRange(D.getIdentifierLoc()));
1026    isInvalid = true;
1027    SC = FunctionDecl::None;
1028  }
1029  if (D.getDeclSpec().hasTypeSpecifier()) {
1030    // Conversion functions don't have return types, but the parser will
1031    // happily parse something like:
1032    //
1033    //   class X {
1034    //     float operator bool();
1035    //   };
1036    //
1037    // The return type will be changed later anyway.
1038    Diag(D.getIdentifierLoc(),
1039         diag::err_conv_function_return_type,
1040         SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
1041         SourceRange(D.getIdentifierLoc()));
1042  }
1043
1044  // Make sure we don't have any parameters.
1045  if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1046    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1047
1048    // Delete the parameters.
1049    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1050    if (FTI.NumArgs) {
1051      delete [] FTI.ArgInfo;
1052      FTI.NumArgs = 0;
1053      FTI.ArgInfo = 0;
1054    }
1055  }
1056
1057  // Make sure the conversion function isn't variadic.
1058  if (R->getAsFunctionTypeProto()->isVariadic())
1059    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1060
1061  // C++ [class.conv.fct]p4:
1062  //   The conversion-type-id shall not represent a function type nor
1063  //   an array type.
1064  QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1065  if (ConvType->isArrayType()) {
1066    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1067    ConvType = Context.getPointerType(ConvType);
1068  } else if (ConvType->isFunctionType()) {
1069    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1070    ConvType = Context.getPointerType(ConvType);
1071  }
1072
1073  // Rebuild the function type "R" without any parameters (in case any
1074  // of the errors above fired) and with the conversion type as the
1075  // return type.
1076  R = Context.getFunctionType(ConvType, 0, 0, false,
1077                              R->getAsFunctionTypeProto()->getTypeQuals());
1078
1079  return isInvalid;
1080}
1081
1082/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete
1083/// the declaration of the given C++ constructor ConDecl that was
1084/// built from declarator D. This routine is responsible for checking
1085/// that the newly-created constructor declaration is well-formed and
1086/// for recording it in the C++ class. Example:
1087///
1088/// @code
1089/// class X {
1090///   X(); // X::X() will be the ConDecl.
1091/// };
1092/// @endcode
1093Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) {
1094  assert(ConDecl && "Expected to receive a constructor declaration");
1095
1096  // Check default arguments on the constructor
1097  CheckCXXDefaultArguments(ConDecl);
1098
1099  CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1100  if (!ClassDecl) {
1101    ConDecl->setInvalidDecl();
1102    return ConDecl;
1103  }
1104
1105  // Make sure this constructor is an overload of the existing
1106  // constructors.
1107  OverloadedFunctionDecl::function_iterator MatchedDecl;
1108  if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) {
1109    Diag(ConDecl->getLocation(),
1110         diag::err_constructor_redeclared,
1111         SourceRange(ConDecl->getLocation()));
1112    Diag((*MatchedDecl)->getLocation(),
1113         diag::err_previous_declaration,
1114         SourceRange((*MatchedDecl)->getLocation()));
1115    ConDecl->setInvalidDecl();
1116    return ConDecl;
1117  }
1118
1119
1120  // C++ [class.copy]p3:
1121  //   A declaration of a constructor for a class X is ill-formed if
1122  //   its first parameter is of type (optionally cv-qualified) X and
1123  //   either there are no other parameters or else all other
1124  //   parameters have default arguments.
1125  if ((ConDecl->getNumParams() == 1) ||
1126      (ConDecl->getNumParams() > 1 &&
1127       ConDecl->getParamDecl(1)->getDefaultArg() != 0)) {
1128    QualType ParamType = ConDecl->getParamDecl(0)->getType();
1129    QualType ClassTy = Context.getTagDeclType(
1130                         const_cast<CXXRecordDecl*>(ConDecl->getParent()));
1131    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1132      Diag(ConDecl->getLocation(),
1133           diag::err_constructor_byvalue_arg,
1134           SourceRange(ConDecl->getParamDecl(0)->getLocation()));
1135      ConDecl->setInvalidDecl();
1136      return ConDecl;
1137    }
1138  }
1139
1140  // Add this constructor to the set of constructors of the current
1141  // class.
1142  ClassDecl->addConstructor(Context, ConDecl);
1143  return (DeclTy *)ConDecl;
1144}
1145
1146/// ActOnDestructorDeclarator - Called by ActOnDeclarator to complete
1147/// the declaration of the given C++ @p Destructor. This routine is
1148/// responsible for recording the destructor in the C++ class, if
1149/// possible.
1150Sema::DeclTy *Sema::ActOnDestructorDeclarator(CXXDestructorDecl *Destructor) {
1151  assert(Destructor && "Expected to receive a destructor declaration");
1152
1153  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext);
1154
1155  // Make sure we aren't redeclaring the destructor.
1156  if (CXXDestructorDecl *PrevDestructor = ClassDecl->getDestructor()) {
1157    Diag(Destructor->getLocation(), diag::err_destructor_redeclared);
1158    Diag(PrevDestructor->getLocation(),
1159         PrevDestructor->isThisDeclarationADefinition()?
1160             diag::err_previous_definition
1161           : diag::err_previous_declaration);
1162    Destructor->setInvalidDecl();
1163    return Destructor;
1164  }
1165
1166  ClassDecl->setDestructor(Destructor);
1167  return (DeclTy *)Destructor;
1168}
1169
1170/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1171/// the declaration of the given C++ conversion function. This routine
1172/// is responsible for recording the conversion function in the C++
1173/// class, if possible.
1174Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1175  assert(Conversion && "Expected to receive a conversion function declaration");
1176
1177  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext);
1178
1179  // Make sure we aren't redeclaring the conversion function.
1180  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
1181  OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1182  for (OverloadedFunctionDecl::function_iterator Func
1183         = Conversions->function_begin();
1184       Func != Conversions->function_end(); ++Func) {
1185    CXXConversionDecl *OtherConv = cast<CXXConversionDecl>(*Func);
1186    if (ConvType == Context.getCanonicalType(OtherConv->getConversionType())) {
1187      Diag(Conversion->getLocation(), diag::err_conv_function_redeclared);
1188      Diag(OtherConv->getLocation(),
1189           OtherConv->isThisDeclarationADefinition()?
1190              diag::err_previous_definition
1191            : diag::err_previous_declaration);
1192      Conversion->setInvalidDecl();
1193      return (DeclTy *)Conversion;
1194    }
1195  }
1196
1197  // C++ [class.conv.fct]p1:
1198  //   [...] A conversion function is never used to convert a
1199  //   (possibly cv-qualified) object to the (possibly cv-qualified)
1200  //   same object type (or a reference to it), to a (possibly
1201  //   cv-qualified) base class of that type (or a reference to it),
1202  //   or to (possibly cv-qualified) void.
1203  // FIXME: Suppress this warning if the conversion function ends up
1204  // being a virtual function that overrides a virtual function in a
1205  // base class.
1206  QualType ClassType
1207    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1208  if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1209    ConvType = ConvTypeRef->getPointeeType();
1210  if (ConvType->isRecordType()) {
1211    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1212    if (ConvType == ClassType)
1213      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used,
1214           ClassType.getAsString());
1215    else if (IsDerivedFrom(ClassType, ConvType))
1216      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used,
1217           ClassType.getAsString(),
1218           ConvType.getAsString());
1219  } else if (ConvType->isVoidType()) {
1220    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used,
1221         ClassType.getAsString(), ConvType.getAsString());
1222  }
1223
1224  ClassDecl->addConversionFunction(Context, Conversion);
1225
1226  return (DeclTy *)Conversion;
1227}
1228
1229//===----------------------------------------------------------------------===//
1230// Namespace Handling
1231//===----------------------------------------------------------------------===//
1232
1233/// ActOnStartNamespaceDef - This is called at the start of a namespace
1234/// definition.
1235Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1236                                           SourceLocation IdentLoc,
1237                                           IdentifierInfo *II,
1238                                           SourceLocation LBrace) {
1239  NamespaceDecl *Namespc =
1240      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1241  Namespc->setLBracLoc(LBrace);
1242
1243  Scope *DeclRegionScope = NamespcScope->getParent();
1244
1245  if (II) {
1246    // C++ [namespace.def]p2:
1247    // The identifier in an original-namespace-definition shall not have been
1248    // previously defined in the declarative region in which the
1249    // original-namespace-definition appears. The identifier in an
1250    // original-namespace-definition is the name of the namespace. Subsequently
1251    // in that declarative region, it is treated as an original-namespace-name.
1252
1253    Decl *PrevDecl =
1254        LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 0,
1255                   /*enableLazyBuiltinCreation=*/false);
1256
1257    if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
1258      if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
1259        // This is an extended namespace definition.
1260        // Attach this namespace decl to the chain of extended namespace
1261        // definitions.
1262        NamespaceDecl *NextNS = OrigNS;
1263        while (NextNS->getNextNamespace())
1264          NextNS = NextNS->getNextNamespace();
1265
1266        NextNS->setNextNamespace(Namespc);
1267        Namespc->setOriginalNamespace(OrigNS);
1268
1269        // We won't add this decl to the current scope. We want the namespace
1270        // name to return the original namespace decl during a name lookup.
1271      } else {
1272        // This is an invalid name redefinition.
1273        Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
1274          Namespc->getName());
1275        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1276        Namespc->setInvalidDecl();
1277        // Continue on to push Namespc as current DeclContext and return it.
1278      }
1279    } else {
1280      // This namespace name is declared for the first time.
1281      PushOnScopeChains(Namespc, DeclRegionScope);
1282    }
1283  }
1284  else {
1285    // FIXME: Handle anonymous namespaces
1286  }
1287
1288  // Although we could have an invalid decl (i.e. the namespace name is a
1289  // redefinition), push it as current DeclContext and try to continue parsing.
1290  PushDeclContext(Namespc->getOriginalNamespace());
1291  return Namespc;
1292}
1293
1294/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1295/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1296void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1297  Decl *Dcl = static_cast<Decl *>(D);
1298  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1299  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1300  Namespc->setRBracLoc(RBrace);
1301  PopDeclContext();
1302}
1303
1304
1305/// AddCXXDirectInitializerToDecl - This action is called immediately after
1306/// ActOnDeclarator, when a C++ direct initializer is present.
1307/// e.g: "int x(1);"
1308void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1309                                         ExprTy **ExprTys, unsigned NumExprs,
1310                                         SourceLocation *CommaLocs,
1311                                         SourceLocation RParenLoc) {
1312  assert(NumExprs != 0 && ExprTys && "missing expressions");
1313  Decl *RealDecl = static_cast<Decl *>(Dcl);
1314
1315  // If there is no declaration, there was an error parsing it.  Just ignore
1316  // the initializer.
1317  if (RealDecl == 0) {
1318    for (unsigned i = 0; i != NumExprs; ++i)
1319      delete static_cast<Expr *>(ExprTys[i]);
1320    return;
1321  }
1322
1323  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1324  if (!VDecl) {
1325    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1326    RealDecl->setInvalidDecl();
1327    return;
1328  }
1329
1330  // We will treat direct-initialization as a copy-initialization:
1331  //    int x(1);  -as-> int x = 1;
1332  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1333  //
1334  // Clients that want to distinguish between the two forms, can check for
1335  // direct initializer using VarDecl::hasCXXDirectInitializer().
1336  // A major benefit is that clients that don't particularly care about which
1337  // exactly form was it (like the CodeGen) can handle both cases without
1338  // special case code.
1339
1340  // C++ 8.5p11:
1341  // The form of initialization (using parentheses or '=') is generally
1342  // insignificant, but does matter when the entity being initialized has a
1343  // class type.
1344  QualType DeclInitType = VDecl->getType();
1345  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1346    DeclInitType = Array->getElementType();
1347
1348  if (VDecl->getType()->isRecordType()) {
1349    CXXConstructorDecl *Constructor
1350      = PerformInitializationByConstructor(DeclInitType,
1351                                           (Expr **)ExprTys, NumExprs,
1352                                           VDecl->getLocation(),
1353                                           SourceRange(VDecl->getLocation(),
1354                                                       RParenLoc),
1355                                           VDecl->getName(),
1356                                           IK_Direct);
1357    if (!Constructor) {
1358      RealDecl->setInvalidDecl();
1359    }
1360
1361    // Let clients know that initialization was done with a direct
1362    // initializer.
1363    VDecl->setCXXDirectInitializer(true);
1364
1365    // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1366    // the initializer.
1367    return;
1368  }
1369
1370  if (NumExprs > 1) {
1371    Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
1372         SourceRange(VDecl->getLocation(), RParenLoc));
1373    RealDecl->setInvalidDecl();
1374    return;
1375  }
1376
1377  // Let clients know that initialization was done with a direct initializer.
1378  VDecl->setCXXDirectInitializer(true);
1379
1380  assert(NumExprs == 1 && "Expected 1 expression");
1381  // Set the init expression, handles conversions.
1382  AddInitializerToDecl(Dcl, ExprTys[0]);
1383}
1384
1385/// PerformInitializationByConstructor - Perform initialization by
1386/// constructor (C++ [dcl.init]p14), which may occur as part of
1387/// direct-initialization or copy-initialization. We are initializing
1388/// an object of type @p ClassType with the given arguments @p
1389/// Args. @p Loc is the location in the source code where the
1390/// initializer occurs (e.g., a declaration, member initializer,
1391/// functional cast, etc.) while @p Range covers the whole
1392/// initialization. @p InitEntity is the entity being initialized,
1393/// which may by the name of a declaration or a type. @p Kind is the
1394/// kind of initialization we're performing, which affects whether
1395/// explicit constructors will be considered. When successful, returns
1396/// the constructor that will be used to perform the initialization;
1397/// when the initialization fails, emits a diagnostic and returns
1398/// null.
1399CXXConstructorDecl *
1400Sema::PerformInitializationByConstructor(QualType ClassType,
1401                                         Expr **Args, unsigned NumArgs,
1402                                         SourceLocation Loc, SourceRange Range,
1403                                         std::string InitEntity,
1404                                         InitializationKind Kind) {
1405  const RecordType *ClassRec = ClassType->getAsRecordType();
1406  assert(ClassRec && "Can only initialize a class type here");
1407
1408  // C++ [dcl.init]p14:
1409  //
1410  //   If the initialization is direct-initialization, or if it is
1411  //   copy-initialization where the cv-unqualified version of the
1412  //   source type is the same class as, or a derived class of, the
1413  //   class of the destination, constructors are considered. The
1414  //   applicable constructors are enumerated (13.3.1.3), and the
1415  //   best one is chosen through overload resolution (13.3). The
1416  //   constructor so selected is called to initialize the object,
1417  //   with the initializer expression(s) as its argument(s). If no
1418  //   constructor applies, or the overload resolution is ambiguous,
1419  //   the initialization is ill-formed.
1420  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1421  OverloadCandidateSet CandidateSet;
1422
1423  // Add constructors to the overload set.
1424  OverloadedFunctionDecl *Constructors
1425    = const_cast<OverloadedFunctionDecl *>(ClassDecl->getConstructors());
1426  for (OverloadedFunctionDecl::function_iterator Con
1427         = Constructors->function_begin();
1428       Con != Constructors->function_end(); ++Con) {
1429    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1430    if ((Kind == IK_Direct) ||
1431        (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1432        (Kind == IK_Default && Constructor->isDefaultConstructor()))
1433      AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1434  }
1435
1436  OverloadCandidateSet::iterator Best;
1437  switch (BestViableFunction(CandidateSet, Best)) {
1438  case OR_Success:
1439    // We found a constructor. Return it.
1440    return cast<CXXConstructorDecl>(Best->Function);
1441
1442  case OR_No_Viable_Function:
1443    if (CandidateSet.empty())
1444      Diag(Loc, diag::err_ovl_no_viable_function_in_init,
1445           InitEntity, Range);
1446    else {
1447      Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands,
1448           InitEntity, Range);
1449      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1450    }
1451    return 0;
1452
1453  case OR_Ambiguous:
1454    Diag(Loc, diag::err_ovl_ambiguous_init,
1455         InitEntity, Range);
1456    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1457    return 0;
1458  }
1459
1460  return 0;
1461}
1462
1463/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1464/// determine whether they are reference-related,
1465/// reference-compatible, reference-compatible with added
1466/// qualification, or incompatible, for use in C++ initialization by
1467/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1468/// type, and the first type (T1) is the pointee type of the reference
1469/// type being initialized.
1470Sema::ReferenceCompareResult
1471Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1472                                   bool& DerivedToBase) {
1473  assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1474  assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1475
1476  T1 = Context.getCanonicalType(T1);
1477  T2 = Context.getCanonicalType(T2);
1478  QualType UnqualT1 = T1.getUnqualifiedType();
1479  QualType UnqualT2 = T2.getUnqualifiedType();
1480
1481  // C++ [dcl.init.ref]p4:
1482  //   Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1483  //   reference-related to “cv2 T2” if T1 is the same type as T2, or
1484  //   T1 is a base class of T2.
1485  if (UnqualT1 == UnqualT2)
1486    DerivedToBase = false;
1487  else if (IsDerivedFrom(UnqualT2, UnqualT1))
1488    DerivedToBase = true;
1489  else
1490    return Ref_Incompatible;
1491
1492  // At this point, we know that T1 and T2 are reference-related (at
1493  // least).
1494
1495  // C++ [dcl.init.ref]p4:
1496  //   "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1497  //   reference-related to T2 and cv1 is the same cv-qualification
1498  //   as, or greater cv-qualification than, cv2. For purposes of
1499  //   overload resolution, cases for which cv1 is greater
1500  //   cv-qualification than cv2 are identified as
1501  //   reference-compatible with added qualification (see 13.3.3.2).
1502  if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1503    return Ref_Compatible;
1504  else if (T1.isMoreQualifiedThan(T2))
1505    return Ref_Compatible_With_Added_Qualification;
1506  else
1507    return Ref_Related;
1508}
1509
1510/// CheckReferenceInit - Check the initialization of a reference
1511/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1512/// the initializer (either a simple initializer or an initializer
1513/// list), and DeclType is the type of the declaration. When ICS is
1514/// non-null, this routine will compute the implicit conversion
1515/// sequence according to C++ [over.ics.ref] and will not produce any
1516/// diagnostics; when ICS is null, it will emit diagnostics when any
1517/// errors are found. Either way, a return value of true indicates
1518/// that there was a failure, a return value of false indicates that
1519/// the reference initialization succeeded.
1520///
1521/// When @p SuppressUserConversions, user-defined conversions are
1522/// suppressed.
1523bool
1524Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
1525                         ImplicitConversionSequence *ICS,
1526                         bool SuppressUserConversions) {
1527  assert(DeclType->isReferenceType() && "Reference init needs a reference");
1528
1529  QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1530  QualType T2 = Init->getType();
1531
1532  // If the initializer is the address of an overloaded function, try
1533  // to resolve the overloaded function. If all goes well, T2 is the
1534  // type of the resulting function.
1535  if (T2->isOverloadType()) {
1536    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1537                                                          ICS != 0);
1538    if (Fn) {
1539      // Since we're performing this reference-initialization for
1540      // real, update the initializer with the resulting function.
1541      if (!ICS)
1542        FixOverloadedFunctionReference(Init, Fn);
1543
1544      T2 = Fn->getType();
1545    }
1546  }
1547
1548  // Compute some basic properties of the types and the initializer.
1549  bool DerivedToBase = false;
1550  Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
1551  ReferenceCompareResult RefRelationship
1552    = CompareReferenceRelationship(T1, T2, DerivedToBase);
1553
1554  // Most paths end in a failed conversion.
1555  if (ICS)
1556    ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
1557
1558  // C++ [dcl.init.ref]p5:
1559  //   A reference to type “cv1 T1” is initialized by an expression
1560  //   of type “cv2 T2” as follows:
1561
1562  //     -- If the initializer expression
1563
1564  bool BindsDirectly = false;
1565  //       -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1566  //          reference-compatible with “cv2 T2,” or
1567  //
1568  // Note that the bit-field check is skipped if we are just computing
1569  // the implicit conversion sequence (C++ [over.best.ics]p2).
1570  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1571      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1572    BindsDirectly = true;
1573
1574    if (ICS) {
1575      // C++ [over.ics.ref]p1:
1576      //   When a parameter of reference type binds directly (8.5.3)
1577      //   to an argument expression, the implicit conversion sequence
1578      //   is the identity conversion, unless the argument expression
1579      //   has a type that is a derived class of the parameter type,
1580      //   in which case the implicit conversion sequence is a
1581      //   derived-to-base Conversion (13.3.3.1).
1582      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1583      ICS->Standard.First = ICK_Identity;
1584      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1585      ICS->Standard.Third = ICK_Identity;
1586      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1587      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
1588      ICS->Standard.ReferenceBinding = true;
1589      ICS->Standard.DirectBinding = true;
1590
1591      // Nothing more to do: the inaccessibility/ambiguity check for
1592      // derived-to-base conversions is suppressed when we're
1593      // computing the implicit conversion sequence (C++
1594      // [over.best.ics]p2).
1595      return false;
1596    } else {
1597      // Perform the conversion.
1598      // FIXME: Binding to a subobject of the lvalue is going to require
1599      // more AST annotation than this.
1600      ImpCastExprToType(Init, T1, /*isLvalue=*/true);
1601    }
1602  }
1603
1604  //       -- has a class type (i.e., T2 is a class type) and can be
1605  //          implicitly converted to an lvalue of type “cv3 T3,”
1606  //          where “cv1 T1” is reference-compatible with “cv3 T3”
1607  //          92) (this conversion is selected by enumerating the
1608  //          applicable conversion functions (13.3.1.6) and choosing
1609  //          the best one through overload resolution (13.3)),
1610  if (!SuppressUserConversions && T2->isRecordType()) {
1611    // FIXME: Look for conversions in base classes!
1612    CXXRecordDecl *T2RecordDecl
1613      = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
1614
1615    OverloadCandidateSet CandidateSet;
1616    OverloadedFunctionDecl *Conversions
1617      = T2RecordDecl->getConversionFunctions();
1618    for (OverloadedFunctionDecl::function_iterator Func
1619           = Conversions->function_begin();
1620         Func != Conversions->function_end(); ++Func) {
1621      CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1622
1623      // If the conversion function doesn't return a reference type,
1624      // it can't be considered for this conversion.
1625      // FIXME: This will change when we support rvalue references.
1626      if (Conv->getConversionType()->isReferenceType())
1627        AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1628    }
1629
1630    OverloadCandidateSet::iterator Best;
1631    switch (BestViableFunction(CandidateSet, Best)) {
1632    case OR_Success:
1633      // This is a direct binding.
1634      BindsDirectly = true;
1635
1636      if (ICS) {
1637        // C++ [over.ics.ref]p1:
1638        //
1639        //   [...] If the parameter binds directly to the result of
1640        //   applying a conversion function to the argument
1641        //   expression, the implicit conversion sequence is a
1642        //   user-defined conversion sequence (13.3.3.1.2), with the
1643        //   second standard conversion sequence either an identity
1644        //   conversion or, if the conversion function returns an
1645        //   entity of a type that is a derived class of the parameter
1646        //   type, a derived-to-base Conversion.
1647        ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1648        ICS->UserDefined.Before = Best->Conversions[0].Standard;
1649        ICS->UserDefined.After = Best->FinalConversion;
1650        ICS->UserDefined.ConversionFunction = Best->Function;
1651        assert(ICS->UserDefined.After.ReferenceBinding &&
1652               ICS->UserDefined.After.DirectBinding &&
1653               "Expected a direct reference binding!");
1654        return false;
1655      } else {
1656        // Perform the conversion.
1657        // FIXME: Binding to a subobject of the lvalue is going to require
1658        // more AST annotation than this.
1659        ImpCastExprToType(Init, T1, /*isLvalue=*/true);
1660      }
1661      break;
1662
1663    case OR_Ambiguous:
1664      assert(false && "Ambiguous reference binding conversions not implemented.");
1665      return true;
1666
1667    case OR_No_Viable_Function:
1668      // There was no suitable conversion; continue with other checks.
1669      break;
1670    }
1671  }
1672
1673  if (BindsDirectly) {
1674    // C++ [dcl.init.ref]p4:
1675    //   [...] In all cases where the reference-related or
1676    //   reference-compatible relationship of two types is used to
1677    //   establish the validity of a reference binding, and T1 is a
1678    //   base class of T2, a program that necessitates such a binding
1679    //   is ill-formed if T1 is an inaccessible (clause 11) or
1680    //   ambiguous (10.2) base class of T2.
1681    //
1682    // Note that we only check this condition when we're allowed to
1683    // complain about errors, because we should not be checking for
1684    // ambiguity (or inaccessibility) unless the reference binding
1685    // actually happens.
1686    if (DerivedToBase)
1687      return CheckDerivedToBaseConversion(T2, T1,
1688                                          Init->getSourceRange().getBegin(),
1689                                          Init->getSourceRange());
1690    else
1691      return false;
1692  }
1693
1694  //     -- Otherwise, the reference shall be to a non-volatile const
1695  //        type (i.e., cv1 shall be const).
1696  if (T1.getCVRQualifiers() != QualType::Const) {
1697    if (!ICS)
1698      Diag(Init->getSourceRange().getBegin(),
1699           diag::err_not_reference_to_const_init,
1700           T1.getAsString(),
1701           InitLvalue != Expr::LV_Valid? "temporary" : "value",
1702           T2.getAsString(), Init->getSourceRange());
1703    return true;
1704  }
1705
1706  //       -- If the initializer expression is an rvalue, with T2 a
1707  //          class type, and “cv1 T1” is reference-compatible with
1708  //          “cv2 T2,” the reference is bound in one of the
1709  //          following ways (the choice is implementation-defined):
1710  //
1711  //          -- The reference is bound to the object represented by
1712  //             the rvalue (see 3.10) or to a sub-object within that
1713  //             object.
1714  //
1715  //          -- A temporary of type “cv1 T2” [sic] is created, and
1716  //             a constructor is called to copy the entire rvalue
1717  //             object into the temporary. The reference is bound to
1718  //             the temporary or to a sub-object within the
1719  //             temporary.
1720  //
1721  //
1722  //          The constructor that would be used to make the copy
1723  //          shall be callable whether or not the copy is actually
1724  //          done.
1725  //
1726  // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1727  // freedom, so we will always take the first option and never build
1728  // a temporary in this case. FIXME: We will, however, have to check
1729  // for the presence of a copy constructor in C++98/03 mode.
1730  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
1731      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1732    if (ICS) {
1733      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1734      ICS->Standard.First = ICK_Identity;
1735      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1736      ICS->Standard.Third = ICK_Identity;
1737      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1738      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
1739      ICS->Standard.ReferenceBinding = true;
1740      ICS->Standard.DirectBinding = false;
1741    } else {
1742      // FIXME: Binding to a subobject of the rvalue is going to require
1743      // more AST annotation than this.
1744      ImpCastExprToType(Init, T1, /*isLvalue=*/true);
1745    }
1746    return false;
1747  }
1748
1749  //       -- Otherwise, a temporary of type “cv1 T1” is created and
1750  //          initialized from the initializer expression using the
1751  //          rules for a non-reference copy initialization (8.5). The
1752  //          reference is then bound to the temporary. If T1 is
1753  //          reference-related to T2, cv1 must be the same
1754  //          cv-qualification as, or greater cv-qualification than,
1755  //          cv2; otherwise, the program is ill-formed.
1756  if (RefRelationship == Ref_Related) {
1757    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1758    // we would be reference-compatible or reference-compatible with
1759    // added qualification. But that wasn't the case, so the reference
1760    // initialization fails.
1761    if (!ICS)
1762      Diag(Init->getSourceRange().getBegin(),
1763           diag::err_reference_init_drops_quals,
1764           T1.getAsString(),
1765           InitLvalue != Expr::LV_Valid? "temporary" : "value",
1766           T2.getAsString(), Init->getSourceRange());
1767    return true;
1768  }
1769
1770  // Actually try to convert the initializer to T1.
1771  if (ICS) {
1772    /// C++ [over.ics.ref]p2:
1773    ///
1774    ///   When a parameter of reference type is not bound directly to
1775    ///   an argument expression, the conversion sequence is the one
1776    ///   required to convert the argument expression to the
1777    ///   underlying type of the reference according to
1778    ///   13.3.3.1. Conceptually, this conversion sequence corresponds
1779    ///   to copy-initializing a temporary of the underlying type with
1780    ///   the argument expression. Any difference in top-level
1781    ///   cv-qualification is subsumed by the initialization itself
1782    ///   and does not constitute a conversion.
1783    *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
1784    return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1785  } else {
1786    return PerformImplicitConversion(Init, T1);
1787  }
1788}
1789
1790/// CheckOverloadedOperatorDeclaration - Check whether the declaration
1791/// of this overloaded operator is well-formed. If so, returns false;
1792/// otherwise, emits appropriate diagnostics and returns true.
1793bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
1794  assert(FnDecl && FnDecl->getOverloadedOperator() != OO_None &&
1795         "Expected an overloaded operator declaration");
1796
1797  bool IsInvalid = false;
1798
1799  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
1800
1801  // C++ [over.oper]p5:
1802  //   The allocation and deallocation functions, operator new,
1803  //   operator new[], operator delete and operator delete[], are
1804  //   described completely in 3.7.3. The attributes and restrictions
1805  //   found in the rest of this subclause do not apply to them unless
1806  //   explicitly stated in 3.7.3.
1807  // FIXME: Write a separate routine for checking this. For now, just
1808  // allow it.
1809  if (Op == OO_New || Op == OO_Array_New ||
1810      Op == OO_Delete || Op == OO_Array_Delete)
1811    return false;
1812
1813  // C++ [over.oper]p6:
1814  //   An operator function shall either be a non-static member
1815  //   function or be a non-member function and have at least one
1816  //   parameter whose type is a class, a reference to a class, an
1817  //   enumeration, or a reference to an enumeration.
1818  CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl);
1819  if (MethodDecl) {
1820    if (MethodDecl->isStatic()) {
1821      Diag(FnDecl->getLocation(),
1822           diag::err_operator_overload_static,
1823           FnDecl->getName(),
1824           SourceRange(FnDecl->getLocation()));
1825      IsInvalid = true;
1826
1827      // Pretend this isn't a member function; it'll supress
1828      // additional, unnecessary error messages.
1829      MethodDecl = 0;
1830    }
1831  } else {
1832    bool ClassOrEnumParam = false;
1833    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
1834         Param != FnDecl->param_end(); ++Param) {
1835      QualType ParamType = (*Param)->getType();
1836      if (const ReferenceType *RefType = ParamType->getAsReferenceType())
1837        ParamType = RefType->getPointeeType();
1838      if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
1839        ClassOrEnumParam = true;
1840        break;
1841      }
1842    }
1843
1844    if (!ClassOrEnumParam) {
1845      Diag(FnDecl->getLocation(),
1846           diag::err_operator_overload_needs_class_or_enum,
1847           FnDecl->getName(),
1848           SourceRange(FnDecl->getLocation()));
1849      IsInvalid = true;
1850    }
1851  }
1852
1853  // C++ [over.oper]p8:
1854  //   An operator function cannot have default arguments (8.3.6),
1855  //   except where explicitly stated below.
1856  //
1857  // Only the function-call operator allows default arguments
1858  // (C++ [over.call]p1).
1859  if (Op != OO_Call) {
1860    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
1861         Param != FnDecl->param_end(); ++Param) {
1862      if (Expr *DefArg = (*Param)->getDefaultArg()) {
1863        Diag((*Param)->getLocation(),
1864             diag::err_operator_overload_default_arg,
1865             DefArg->getSourceRange());
1866        IsInvalid = true;
1867      }
1868    }
1869  }
1870
1871  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
1872    { false, false, false }
1873#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1874    , { Unary, Binary, MemberOnly }
1875#include "clang/Basic/OperatorKinds.def"
1876  };
1877
1878  bool CanBeUnaryOperator = OperatorUses[Op][0];
1879  bool CanBeBinaryOperator = OperatorUses[Op][1];
1880  bool MustBeMemberOperator = OperatorUses[Op][2];
1881
1882  // C++ [over.oper]p8:
1883  //   [...] Operator functions cannot have more or fewer parameters
1884  //   than the number required for the corresponding operator, as
1885  //   described in the rest of this subclause.
1886  unsigned NumParams = FnDecl->getNumParams() + (MethodDecl? 1 : 0);
1887  if (Op != OO_Call &&
1888      ((NumParams == 1 && !CanBeUnaryOperator) ||
1889       (NumParams == 2 && !CanBeBinaryOperator) ||
1890       (NumParams < 1) || (NumParams > 2))) {
1891    // We have the wrong number of parameters.
1892    std::string NumParamsStr = (llvm::APSInt(32) = NumParams).toString(10);
1893
1894    diag::kind DK;
1895
1896    if (CanBeUnaryOperator && CanBeBinaryOperator) {
1897      if (NumParams == 1)
1898        DK = diag::err_operator_overload_must_be_unary_or_binary;
1899      else
1900        DK = diag::err_operator_overload_must_be_unary_or_binary;
1901    } else if (CanBeUnaryOperator) {
1902      if (NumParams == 1)
1903        DK = diag::err_operator_overload_must_be_unary;
1904      else
1905        DK = diag::err_operator_overload_must_be_unary_plural;
1906    } else if (CanBeBinaryOperator) {
1907      if (NumParams == 1)
1908        DK = diag::err_operator_overload_must_be_binary;
1909      else
1910        DK = diag::err_operator_overload_must_be_binary_plural;
1911    } else {
1912      assert(false && "All non-call overloaded operators are unary or binary!");
1913    }
1914
1915    Diag(FnDecl->getLocation(), DK,
1916         FnDecl->getName(), NumParamsStr,
1917         SourceRange(FnDecl->getLocation()));
1918    IsInvalid = true;
1919  }
1920
1921  // Overloaded operators cannot be variadic.
1922  if (FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) {
1923    Diag(FnDecl->getLocation(),
1924         diag::err_operator_overload_variadic,
1925         SourceRange(FnDecl->getLocation()));
1926    IsInvalid = true;
1927  }
1928
1929  // Some operators must be non-static member functions.
1930  if (MustBeMemberOperator && !MethodDecl) {
1931    Diag(FnDecl->getLocation(),
1932         diag::err_operator_overload_must_be_member,
1933         FnDecl->getName(),
1934         SourceRange(FnDecl->getLocation()));
1935    IsInvalid = true;
1936  }
1937
1938  // C++ [over.inc]p1:
1939  //   The user-defined function called operator++ implements the
1940  //   prefix and postfix ++ operator. If this function is a member
1941  //   function with no parameters, or a non-member function with one
1942  //   parameter of class or enumeration type, it defines the prefix
1943  //   increment operator ++ for objects of that type. If the function
1944  //   is a member function with one parameter (which shall be of type
1945  //   int) or a non-member function with two parameters (the second
1946  //   of which shall be of type int), it defines the postfix
1947  //   increment operator ++ for objects of that type.
1948  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
1949    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
1950    bool ParamIsInt = false;
1951    if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
1952      ParamIsInt = BT->getKind() == BuiltinType::Int;
1953
1954    if (!ParamIsInt) {
1955      diag::kind DK;
1956      if (Op == OO_PlusPlus) {
1957        if (MethodDecl)
1958          DK = diag::err_operator_overload_post_inc_must_be_int_member;
1959        else
1960          DK = diag::err_operator_overload_post_inc_must_be_int;
1961      } else {
1962        if (MethodDecl)
1963          DK = diag::err_operator_overload_post_dec_must_be_int_member;
1964        else
1965          DK = diag::err_operator_overload_post_dec_must_be_int;
1966      }
1967      Diag(LastParam->getLocation(), DK,
1968           Context.getCanonicalType(LastParam->getType()).getAsString(),
1969           SourceRange(FnDecl->getLocation()));
1970      IsInvalid = true;
1971    }
1972  }
1973
1974  return IsInvalid;
1975}
1976