SemaDeclCXX.cpp revision a3b34bbd1f4066a423e890727c7898fc726df2d0
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 "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/TypeOrdering.h"
18#include "clang/AST/StmtVisitor.h"
19#include "clang/Lex/Preprocessor.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Parse/DeclSpec.h"
22#include "llvm/Support/Compiler.h"
23#include <algorithm> // for std::equal
24#include <map>
25
26using namespace clang;
27
28//===----------------------------------------------------------------------===//
29// CheckDefaultArgumentVisitor
30//===----------------------------------------------------------------------===//
31
32namespace {
33  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
34  /// the default argument of a parameter to determine whether it
35  /// contains any ill-formed subexpressions. For example, this will
36  /// diagnose the use of local variables or parameters within the
37  /// default argument expression.
38  class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
39    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
40    Expr *DefaultArg;
41    Sema *S;
42
43  public:
44    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
45      : DefaultArg(defarg), S(s) {}
46
47    bool VisitExpr(Expr *Node);
48    bool VisitDeclRefExpr(DeclRefExpr *DRE);
49  };
50
51  /// VisitExpr - Visit all of the children of this expression.
52  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
53    bool IsInvalid = false;
54    for (Stmt::child_iterator I = Node->child_begin(),
55         E = Node->child_end(); I != E; ++I)
56      IsInvalid |= Visit(*I);
57    return IsInvalid;
58  }
59
60  /// VisitDeclRefExpr - Visit a reference to a declaration, to
61  /// determine whether this declaration can be used in the default
62  /// argument expression.
63  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
64    NamedDecl *Decl = DRE->getDecl();
65    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
66      // C++ [dcl.fct.default]p9
67      //   Default arguments are evaluated each time the function is
68      //   called. The order of evaluation of function arguments is
69      //   unspecified. Consequently, parameters of a function shall not
70      //   be used in default argument expressions, even if they are not
71      //   evaluated. Parameters of a function declared before a default
72      //   argument expression are in scope and can hide namespace and
73      //   class member names.
74      return S->Diag(DRE->getSourceRange().getBegin(),
75                     diag::err_param_default_argument_references_param,
76                     Param->getName(), DefaultArg->getSourceRange());
77    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
78      // C++ [dcl.fct.default]p7
79      //   Local variables shall not be used in default argument
80      //   expressions.
81      if (VDecl->isBlockVarDecl())
82        return S->Diag(DRE->getSourceRange().getBegin(),
83                       diag::err_param_default_argument_references_local,
84                       VDecl->getName(), DefaultArg->getSourceRange());
85    }
86
87    // FIXME: when Clang has support for member functions, "this"
88    // will also need to be diagnosed.
89
90    return false;
91  }
92}
93
94/// ActOnParamDefaultArgument - Check whether the default argument
95/// provided for a function parameter is well-formed. If so, attach it
96/// to the parameter declaration.
97void
98Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
99                                ExprTy *defarg) {
100  ParmVarDecl *Param = (ParmVarDecl *)param;
101  llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
102  QualType ParamType = Param->getType();
103
104  // Default arguments are only permitted in C++
105  if (!getLangOptions().CPlusPlus) {
106    Diag(EqualLoc, diag::err_param_default_argument,
107         DefaultArg->getSourceRange());
108    return;
109  }
110
111  // C++ [dcl.fct.default]p5
112  //   A default argument expression is implicitly converted (clause
113  //   4) to the parameter type. The default argument expression has
114  //   the same semantic constraints as the initializer expression in
115  //   a declaration of a variable of the parameter type, using the
116  //   copy-initialization semantics (8.5).
117  //
118  // FIXME: CheckSingleAssignmentConstraints has the wrong semantics
119  // for C++ (since we want copy-initialization, not copy-assignment),
120  // but we don't have the right semantics implemented yet. Because of
121  // this, our error message is also very poor.
122  QualType DefaultArgType = DefaultArg->getType();
123  Expr *DefaultArgPtr = DefaultArg.get();
124  AssignConvertType ConvTy = CheckSingleAssignmentConstraints(ParamType,
125                                                              DefaultArgPtr);
126  if (DefaultArgPtr != DefaultArg.get()) {
127    DefaultArg.take();
128    DefaultArg.reset(DefaultArgPtr);
129  }
130  if (DiagnoseAssignmentResult(ConvTy, DefaultArg->getLocStart(),
131                               ParamType, DefaultArgType, DefaultArg.get(),
132                               "in default argument")) {
133    return;
134  }
135
136  // Check that the default argument is well-formed
137  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
138  if (DefaultArgChecker.Visit(DefaultArg.get()))
139    return;
140
141  // Okay: add the default argument to the parameter
142  Param->setDefaultArg(DefaultArg.take());
143}
144
145/// CheckExtraCXXDefaultArguments - Check for any extra default
146/// arguments in the declarator, which is not a function declaration
147/// or definition and therefore is not permitted to have default
148/// arguments. This routine should be invoked for every declarator
149/// that is not a function declaration or definition.
150void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
151  // C++ [dcl.fct.default]p3
152  //   A default argument expression shall be specified only in the
153  //   parameter-declaration-clause of a function declaration or in a
154  //   template-parameter (14.1). It shall not be specified for a
155  //   parameter pack. If it is specified in a
156  //   parameter-declaration-clause, it shall not occur within a
157  //   declarator or abstract-declarator of a parameter-declaration.
158  for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
159    DeclaratorChunk &chunk = D.getTypeObject(i);
160    if (chunk.Kind == DeclaratorChunk::Function) {
161      for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
162        ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
163        if (Param->getDefaultArg()) {
164          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc,
165               Param->getDefaultArg()->getSourceRange());
166          Param->setDefaultArg(0);
167        }
168      }
169    }
170  }
171}
172
173// MergeCXXFunctionDecl - Merge two declarations of the same C++
174// function, once we already know that they have the same
175// type. Subroutine of MergeFunctionDecl.
176FunctionDecl *
177Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
178  // C++ [dcl.fct.default]p4:
179  //
180  //   For non-template functions, default arguments can be added in
181  //   later declarations of a function in the same
182  //   scope. Declarations in different scopes have completely
183  //   distinct sets of default arguments. That is, declarations in
184  //   inner scopes do not acquire default arguments from
185  //   declarations in outer scopes, and vice versa. In a given
186  //   function declaration, all parameters subsequent to a
187  //   parameter with a default argument shall have default
188  //   arguments supplied in this or previous declarations. A
189  //   default argument shall not be redefined by a later
190  //   declaration (not even to the same value).
191  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
192    ParmVarDecl *OldParam = Old->getParamDecl(p);
193    ParmVarDecl *NewParam = New->getParamDecl(p);
194
195    if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
196      Diag(NewParam->getLocation(),
197           diag::err_param_default_argument_redefinition,
198           NewParam->getDefaultArg()->getSourceRange());
199      Diag(OldParam->getLocation(), diag::err_previous_definition);
200    } else if (OldParam->getDefaultArg()) {
201      // Merge the old default argument into the new parameter
202      NewParam->setDefaultArg(OldParam->getDefaultArg());
203    }
204  }
205
206  return New;
207}
208
209/// CheckCXXDefaultArguments - Verify that the default arguments for a
210/// function declaration are well-formed according to C++
211/// [dcl.fct.default].
212void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
213  unsigned NumParams = FD->getNumParams();
214  unsigned p;
215
216  // Find first parameter with a default argument
217  for (p = 0; p < NumParams; ++p) {
218    ParmVarDecl *Param = FD->getParamDecl(p);
219    if (Param->getDefaultArg())
220      break;
221  }
222
223  // C++ [dcl.fct.default]p4:
224  //   In a given function declaration, all parameters
225  //   subsequent to a parameter with a default argument shall
226  //   have default arguments supplied in this or previous
227  //   declarations. A default argument shall not be redefined
228  //   by a later declaration (not even to the same value).
229  unsigned LastMissingDefaultArg = 0;
230  for(; p < NumParams; ++p) {
231    ParmVarDecl *Param = FD->getParamDecl(p);
232    if (!Param->getDefaultArg()) {
233      if (Param->getIdentifier())
234        Diag(Param->getLocation(),
235             diag::err_param_default_argument_missing_name,
236             Param->getIdentifier()->getName());
237      else
238        Diag(Param->getLocation(),
239             diag::err_param_default_argument_missing);
240
241      LastMissingDefaultArg = p;
242    }
243  }
244
245  if (LastMissingDefaultArg > 0) {
246    // Some default arguments were missing. Clear out all of the
247    // default arguments up to (and including) the last missing
248    // default argument, so that we leave the function parameters
249    // in a semantically valid state.
250    for (p = 0; p <= LastMissingDefaultArg; ++p) {
251      ParmVarDecl *Param = FD->getParamDecl(p);
252      if (Param->getDefaultArg()) {
253        delete Param->getDefaultArg();
254        Param->setDefaultArg(0);
255      }
256    }
257  }
258}
259
260/// isCurrentClassName - Determine whether the identifier II is the
261/// name of the class type currently being defined. In the case of
262/// nested classes, this will only return true if II is the name of
263/// the innermost class.
264bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *) {
265  if (CXXRecordDecl *CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext))
266    return &II == CurDecl->getIdentifier();
267  else
268    return false;
269}
270
271/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
272/// one entry in the base class list of a class specifier, for
273/// example:
274///    class foo : public bar, virtual private baz {
275/// 'public bar' and 'virtual private baz' are each base-specifiers.
276Sema::BaseResult
277Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
278                         bool Virtual, AccessSpecifier Access,
279                         TypeTy *basetype, SourceLocation BaseLoc) {
280  RecordDecl *Decl = (RecordDecl*)classdecl;
281  QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
282
283  // Base specifiers must be record types.
284  if (!BaseType->isRecordType()) {
285    Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange);
286    return true;
287  }
288
289  // C++ [class.union]p1:
290  //   A union shall not be used as a base class.
291  if (BaseType->isUnionType()) {
292    Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange);
293    return true;
294  }
295
296  // C++ [class.union]p1:
297  //   A union shall not have base classes.
298  if (Decl->isUnion()) {
299    Diag(Decl->getLocation(), diag::err_base_clause_on_union,
300         SpecifierRange);
301    return true;
302  }
303
304  // C++ [class.derived]p2:
305  //   The class-name in a base-specifier shall not be an incompletely
306  //   defined class.
307  if (BaseType->isIncompleteType()) {
308    Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
309    return true;
310  }
311
312  // Create the base specifier.
313  return new CXXBaseSpecifier(SpecifierRange, Virtual,
314                              BaseType->isClassType(), Access, BaseType);
315}
316
317/// ActOnBaseSpecifiers - Attach the given base specifiers to the
318/// class, after checking whether there are any duplicate base
319/// classes.
320void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
321                               unsigned NumBases) {
322  if (NumBases == 0)
323    return;
324
325  // Used to keep track of which base types we have already seen, so
326  // that we can properly diagnose redundant direct base types. Note
327  // that the key is always the unqualified canonical type of the base
328  // class.
329  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
330
331  // Copy non-redundant base specifiers into permanent storage.
332  CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
333  unsigned NumGoodBases = 0;
334  for (unsigned idx = 0; idx < NumBases; ++idx) {
335    QualType NewBaseType
336      = Context.getCanonicalType(BaseSpecs[idx]->getType());
337    NewBaseType = NewBaseType.getUnqualifiedType();
338
339    if (KnownBaseTypes[NewBaseType]) {
340      // C++ [class.mi]p3:
341      //   A class shall not be specified as a direct base class of a
342      //   derived class more than once.
343      Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
344           diag::err_duplicate_base_class,
345           KnownBaseTypes[NewBaseType]->getType().getAsString(),
346           BaseSpecs[idx]->getSourceRange());
347
348      // Delete the duplicate base class specifier; we're going to
349      // overwrite its pointer later.
350      delete BaseSpecs[idx];
351    } else {
352      // Okay, add this new base class.
353      KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
354      BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
355    }
356  }
357
358  // Attach the remaining base class specifiers to the derived class.
359  CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
360  Decl->setBases(BaseSpecs, NumGoodBases);
361
362  // Delete the remaining (good) base class specifiers, since their
363  // data has been copied into the CXXRecordDecl.
364  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
365    delete BaseSpecs[idx];
366}
367
368//===----------------------------------------------------------------------===//
369// C++ class member Handling
370//===----------------------------------------------------------------------===//
371
372/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
373/// definition, when on C++.
374void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
375  CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
376  PushDeclContext(Dcl);
377  FieldCollector->StartClass();
378
379  if (Dcl->getIdentifier()) {
380    // C++ [class]p2:
381    //   [...] The class-name is also inserted into the scope of the
382    //   class itself; this is known as the injected-class-name. For
383    //   purposes of access checking, the injected-class-name is treated
384    //   as if it were a public member name.
385    TypedefDecl *InjectedClassName
386      = TypedefDecl::Create(Context, Dcl, LBrace, Dcl->getIdentifier(),
387                            Context.getTypeDeclType(Dcl), /*PrevDecl=*/0);
388    PushOnScopeChains(InjectedClassName, S);
389  }
390}
391
392/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
393/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
394/// bitfield width if there is one and 'InitExpr' specifies the initializer if
395/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
396/// declarators on it.
397///
398/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
399/// an instance field is declared, a new CXXFieldDecl is created but the method
400/// does *not* return it; it returns LastInGroup instead. The other C++ members
401/// (which are all ScopedDecls) are returned after appending them to
402/// LastInGroup.
403Sema::DeclTy *
404Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
405                               ExprTy *BW, ExprTy *InitExpr,
406                               DeclTy *LastInGroup) {
407  const DeclSpec &DS = D.getDeclSpec();
408  IdentifierInfo *II = D.getIdentifier();
409  Expr *BitWidth = static_cast<Expr*>(BW);
410  Expr *Init = static_cast<Expr*>(InitExpr);
411  SourceLocation Loc = D.getIdentifierLoc();
412
413  // C++ 9.2p6: A member shall not be declared to have automatic storage
414  // duration (auto, register) or with the extern storage-class-specifier.
415  switch (DS.getStorageClassSpec()) {
416    case DeclSpec::SCS_unspecified:
417    case DeclSpec::SCS_typedef:
418    case DeclSpec::SCS_static:
419      // FALL THROUGH.
420      break;
421    default:
422      if (DS.getStorageClassSpecLoc().isValid())
423        Diag(DS.getStorageClassSpecLoc(),
424             diag::err_storageclass_invalid_for_member);
425      else
426        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
427      D.getMutableDeclSpec().ClearStorageClassSpecs();
428  }
429
430  bool isFunc = D.isFunctionDeclarator();
431  if (!isFunc &&
432      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
433      D.getNumTypeObjects() == 0) {
434    // Check also for this case:
435    //
436    // typedef int f();
437    // f a;
438    //
439    Decl *TD = static_cast<Decl *>(DS.getTypeRep());
440    isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
441  }
442
443  bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
444                      !isFunc);
445
446  Decl *Member;
447  bool InvalidDecl = false;
448
449  if (isInstField)
450    Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
451  else
452    Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
453
454  if (!Member) return LastInGroup;
455
456  assert((II || isInstField) && "No identifier for non-field ?");
457
458  // set/getAccess is not part of Decl's interface to avoid bloating it with C++
459  // specific methods. Use a wrapper class that can be used with all C++ class
460  // member decls.
461  CXXClassMemberWrapper(Member).setAccess(AS);
462
463  if (BitWidth) {
464    // C++ 9.6p2: Only when declaring an unnamed bit-field may the
465    // constant-expression be a value equal to zero.
466    // FIXME: Check this.
467
468    if (D.isFunctionDeclarator()) {
469      // FIXME: Emit diagnostic about only constructors taking base initializers
470      // or something similar, when constructor support is in place.
471      Diag(Loc, diag::err_not_bitfield_type,
472           II->getName(), BitWidth->getSourceRange());
473      InvalidDecl = true;
474
475    } else if (isInstField) {
476      // C++ 9.6p3: A bit-field shall have integral or enumeration type.
477      if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
478        Diag(Loc, diag::err_not_integral_type_bitfield,
479             II->getName(), BitWidth->getSourceRange());
480        InvalidDecl = true;
481      }
482
483    } else if (isa<FunctionDecl>(Member)) {
484      // A function typedef ("typedef int f(); f a;").
485      // C++ 9.6p3: A bit-field shall have integral or enumeration type.
486      Diag(Loc, diag::err_not_integral_type_bitfield,
487           II->getName(), BitWidth->getSourceRange());
488      InvalidDecl = true;
489
490    } else if (isa<TypedefDecl>(Member)) {
491      // "cannot declare 'A' to be a bit-field type"
492      Diag(Loc, diag::err_not_bitfield_type, II->getName(),
493           BitWidth->getSourceRange());
494      InvalidDecl = true;
495
496    } else {
497      assert(isa<CXXClassVarDecl>(Member) &&
498             "Didn't we cover all member kinds?");
499      // C++ 9.6p3: A bit-field shall not be a static member.
500      // "static member 'A' cannot be a bit-field"
501      Diag(Loc, diag::err_static_not_bitfield, II->getName(),
502           BitWidth->getSourceRange());
503      InvalidDecl = true;
504    }
505  }
506
507  if (Init) {
508    // C++ 9.2p4: A member-declarator can contain a constant-initializer only
509    // if it declares a static member of const integral or const enumeration
510    // type.
511    if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
512      // ...static member of...
513      CVD->setInit(Init);
514      // ...const integral or const enumeration type.
515      if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
516          CVD->getType()->isIntegralType()) {
517        // constant-initializer
518        if (CheckForConstantInitializer(Init, CVD->getType()))
519          InvalidDecl = true;
520
521      } else {
522        // not const integral.
523        Diag(Loc, diag::err_member_initialization,
524             II->getName(), Init->getSourceRange());
525        InvalidDecl = true;
526      }
527
528    } else {
529      // not static member.
530      Diag(Loc, diag::err_member_initialization,
531           II->getName(), Init->getSourceRange());
532      InvalidDecl = true;
533    }
534  }
535
536  if (InvalidDecl)
537    Member->setInvalidDecl();
538
539  if (isInstField) {
540    FieldCollector->Add(cast<CXXFieldDecl>(Member));
541    return LastInGroup;
542  }
543  return Member;
544}
545
546void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
547                                             DeclTy *TagDecl,
548                                             SourceLocation LBrac,
549                                             SourceLocation RBrac) {
550  ActOnFields(S, RLoc, TagDecl,
551              (DeclTy**)FieldCollector->getCurFields(),
552              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
553}
554
555/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
556/// special functions, such as the default constructor, copy
557/// constructor, or destructor, to the given C++ class (C++
558/// [special]p1).  This routine can only be executed just before the
559/// definition of the class is complete.
560void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
561  if (!ClassDecl->hasUserDeclaredConstructor()) {
562    // C++ [class.ctor]p5:
563    //   A default constructor for a class X is a constructor of class X
564    //   that can be called without an argument. If there is no
565    //   user-declared constructor for class X, a default constructor is
566    //   implicitly declared. An implicitly-declared default constructor
567    //   is an inline public member of its class.
568    CXXConstructorDecl *DefaultCon =
569      CXXConstructorDecl::Create(Context, ClassDecl,
570                                 ClassDecl->getLocation(),
571                                 ClassDecl->getIdentifier(),
572                                 Context.getFunctionType(Context.VoidTy,
573                                                         0, 0, false, 0),
574                                 /*isExplicit=*/false,
575                                 /*isInline=*/true,
576                                 /*isImplicitlyDeclared=*/true);
577    DefaultCon->setAccess(AS_public);
578    ClassDecl->addConstructor(Context, DefaultCon);
579  }
580
581  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
582    // C++ [class.copy]p4:
583    //   If the class definition does not explicitly declare a copy
584    //   constructor, one is declared implicitly.
585
586    // C++ [class.copy]p5:
587    //   The implicitly-declared copy constructor for a class X will
588    //   have the form
589    //
590    //       X::X(const X&)
591    //
592    //   if
593    bool HasConstCopyConstructor = true;
594
595    //     -- each direct or virtual base class B of X has a copy
596    //        constructor whose first parameter is of type const B& or
597    //        const volatile B&, and
598    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
599         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
600      const CXXRecordDecl *BaseClassDecl
601        = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
602      HasConstCopyConstructor
603        = BaseClassDecl->hasConstCopyConstructor(Context);
604    }
605
606    //     -- for all the nonstatic data members of X that are of a
607    //        class type M (or array thereof), each such class type
608    //        has a copy constructor whose first parameter is of type
609    //        const M& or const volatile M&.
610    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
611         HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
612      QualType FieldType = (*Field)->getType();
613      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
614        FieldType = Array->getElementType();
615      if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
616        const CXXRecordDecl *FieldClassDecl
617          = cast<CXXRecordDecl>(FieldClassType->getDecl());
618        HasConstCopyConstructor
619          = FieldClassDecl->hasConstCopyConstructor(Context);
620      }
621    }
622
623    //  Otherwise, the implicitly declared copy constructor will have
624    //  the form
625    //
626    //       X::X(X&)
627    QualType ArgType = Context.getTypeDeclType(ClassDecl);
628    if (HasConstCopyConstructor)
629      ArgType = ArgType.withConst();
630    ArgType = Context.getReferenceType(ArgType);
631
632    //  An implicitly-declared copy constructor is an inline public
633    //  member of its class.
634    CXXConstructorDecl *CopyConstructor
635      = CXXConstructorDecl::Create(Context, ClassDecl,
636                                   ClassDecl->getLocation(),
637                                   ClassDecl->getIdentifier(),
638                                   Context.getFunctionType(Context.VoidTy,
639                                                           &ArgType, 1,
640                                                           false, 0),
641                                   /*isExplicit=*/false,
642                                   /*isInline=*/true,
643                                   /*isImplicitlyDeclared=*/true);
644    CopyConstructor->setAccess(AS_public);
645
646    // Add the parameter to the constructor.
647    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
648                                                 ClassDecl->getLocation(),
649                                                 /*IdentifierInfo=*/0,
650                                                 ArgType, VarDecl::None, 0, 0);
651    CopyConstructor->setParams(&FromParam, 1);
652
653    ClassDecl->addConstructor(Context, CopyConstructor);
654  }
655
656  // FIXME: Implicit destructor
657  // FIXME: Implicit copy assignment operator
658}
659
660void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
661  CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
662  FieldCollector->FinishClass();
663  AddImplicitlyDeclaredMembersToClass(Rec);
664  PopDeclContext();
665
666  // Everything, including inline method definitions, have been parsed.
667  // Let the consumer know of the new TagDecl definition.
668  Consumer.HandleTagDeclDefinition(Rec);
669}
670
671/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete
672/// the declaration of the given C++ constructor ConDecl that was
673/// built from declarator D. This routine is responsible for checking
674/// that the newly-created constructor declaration is well-formed and
675/// for recording it in the C++ class. Example:
676///
677/// @code
678/// class X {
679///   X(); // X::X() will be the ConDecl.
680/// };
681/// @endcode
682Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) {
683  assert(ConDecl && "Expected to receive a constructor declaration");
684
685  // Check default arguments on the constructor
686  CheckCXXDefaultArguments(ConDecl);
687
688  CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
689  if (!ClassDecl) {
690    ConDecl->setInvalidDecl();
691    return ConDecl;
692  }
693
694  // Make sure this constructor is an overload of the existing
695  // constructors.
696  OverloadedFunctionDecl::function_iterator MatchedDecl;
697  if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) {
698    Diag(ConDecl->getLocation(),
699         diag::err_constructor_redeclared,
700         SourceRange(ConDecl->getLocation()));
701    Diag((*MatchedDecl)->getLocation(),
702         diag::err_previous_declaration,
703         SourceRange((*MatchedDecl)->getLocation()));
704    ConDecl->setInvalidDecl();
705    return ConDecl;
706  }
707
708
709  // C++ [class.copy]p3:
710  //   A declaration of a constructor for a class X is ill-formed if
711  //   its first parameter is of type (optionally cv-qualified) X and
712  //   either there are no other parameters or else all other
713  //   parameters have default arguments.
714  if ((ConDecl->getNumParams() == 1) ||
715      (ConDecl->getNumParams() > 1 &&
716       ConDecl->getParamDecl(1)->getDefaultArg() != 0)) {
717    QualType ParamType = ConDecl->getParamDecl(0)->getType();
718    QualType ClassTy = Context.getTagDeclType(
719                         const_cast<CXXRecordDecl*>(ConDecl->getParent()));
720    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
721      Diag(ConDecl->getLocation(),
722           diag::err_constructor_byvalue_arg,
723           SourceRange(ConDecl->getParamDecl(0)->getLocation()));
724      ConDecl->setInvalidDecl();
725      return 0;
726    }
727  }
728
729  // Add this constructor to the set of constructors of the current
730  // class.
731  ClassDecl->addConstructor(Context, ConDecl);
732
733  return (DeclTy *)ConDecl;
734}
735
736//===----------------------------------------------------------------------===//
737// Namespace Handling
738//===----------------------------------------------------------------------===//
739
740/// ActOnStartNamespaceDef - This is called at the start of a namespace
741/// definition.
742Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
743                                           SourceLocation IdentLoc,
744                                           IdentifierInfo *II,
745                                           SourceLocation LBrace) {
746  NamespaceDecl *Namespc =
747      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
748  Namespc->setLBracLoc(LBrace);
749
750  Scope *DeclRegionScope = NamespcScope->getParent();
751
752  if (II) {
753    // C++ [namespace.def]p2:
754    // The identifier in an original-namespace-definition shall not have been
755    // previously defined in the declarative region in which the
756    // original-namespace-definition appears. The identifier in an
757    // original-namespace-definition is the name of the namespace. Subsequently
758    // in that declarative region, it is treated as an original-namespace-name.
759
760    Decl *PrevDecl =
761        LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
762                   /*enableLazyBuiltinCreation=*/false);
763
764    if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
765      if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
766        // This is an extended namespace definition.
767        // Attach this namespace decl to the chain of extended namespace
768        // definitions.
769        NamespaceDecl *NextNS = OrigNS;
770        while (NextNS->getNextNamespace())
771          NextNS = NextNS->getNextNamespace();
772
773        NextNS->setNextNamespace(Namespc);
774        Namespc->setOriginalNamespace(OrigNS);
775
776        // We won't add this decl to the current scope. We want the namespace
777        // name to return the original namespace decl during a name lookup.
778      } else {
779        // This is an invalid name redefinition.
780        Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
781          Namespc->getName());
782        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
783        Namespc->setInvalidDecl();
784        // Continue on to push Namespc as current DeclContext and return it.
785      }
786    } else {
787      // This namespace name is declared for the first time.
788      PushOnScopeChains(Namespc, DeclRegionScope);
789    }
790  }
791  else {
792    // FIXME: Handle anonymous namespaces
793  }
794
795  // Although we could have an invalid decl (i.e. the namespace name is a
796  // redefinition), push it as current DeclContext and try to continue parsing.
797  PushDeclContext(Namespc->getOriginalNamespace());
798  return Namespc;
799}
800
801/// ActOnFinishNamespaceDef - This callback is called after a namespace is
802/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
803void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
804  Decl *Dcl = static_cast<Decl *>(D);
805  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
806  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
807  Namespc->setRBracLoc(RBrace);
808  PopDeclContext();
809}
810
811
812/// AddCXXDirectInitializerToDecl - This action is called immediately after
813/// ActOnDeclarator, when a C++ direct initializer is present.
814/// e.g: "int x(1);"
815void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
816                                         ExprTy **ExprTys, unsigned NumExprs,
817                                         SourceLocation *CommaLocs,
818                                         SourceLocation RParenLoc) {
819  assert(NumExprs != 0 && ExprTys && "missing expressions");
820  Decl *RealDecl = static_cast<Decl *>(Dcl);
821
822  // If there is no declaration, there was an error parsing it.  Just ignore
823  // the initializer.
824  if (RealDecl == 0) {
825    for (unsigned i = 0; i != NumExprs; ++i)
826      delete static_cast<Expr *>(ExprTys[i]);
827    return;
828  }
829
830  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
831  if (!VDecl) {
832    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
833    RealDecl->setInvalidDecl();
834    return;
835  }
836
837  // We will treat direct-initialization as a copy-initialization:
838  //    int x(1);  -as-> int x = 1;
839  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
840  //
841  // Clients that want to distinguish between the two forms, can check for
842  // direct initializer using VarDecl::hasCXXDirectInitializer().
843  // A major benefit is that clients that don't particularly care about which
844  // exactly form was it (like the CodeGen) can handle both cases without
845  // special case code.
846
847  // C++ 8.5p11:
848  // The form of initialization (using parentheses or '=') is generally
849  // insignificant, but does matter when the entity being initialized has a
850  // class type.
851
852  if (VDecl->getType()->isRecordType()) {
853    // FIXME: When constructors for class types are supported, determine how
854    // exactly semantic checking will be done for direct initializers.
855    unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
856                           "initialization for class types is not handled yet");
857    Diag(VDecl->getLocation(), DiagID);
858    RealDecl->setInvalidDecl();
859    return;
860  }
861
862  if (NumExprs > 1) {
863    Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
864         SourceRange(VDecl->getLocation(), RParenLoc));
865    RealDecl->setInvalidDecl();
866    return;
867  }
868
869  // Let clients know that initialization was done with a direct initializer.
870  VDecl->setCXXDirectInitializer(true);
871
872  assert(NumExprs == 1 && "Expected 1 expression");
873  // Set the init expression, handles conversions.
874  AddInitializerToDecl(Dcl, ExprTys[0]);
875}
876
877/// CompareReferenceRelationship - Compare the two types T1 and T2 to
878/// determine whether they are reference-related,
879/// reference-compatible, reference-compatible with added
880/// qualification, or incompatible, for use in C++ initialization by
881/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
882/// type, and the first type (T1) is the pointee type of the reference
883/// type being initialized.
884Sema::ReferenceCompareResult
885Sema::CompareReferenceRelationship(QualType T1, QualType T2,
886                                   bool& DerivedToBase) {
887  assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
888  assert(!T2->isReferenceType() && "T2 cannot be a reference type");
889
890  T1 = Context.getCanonicalType(T1);
891  T2 = Context.getCanonicalType(T2);
892  QualType UnqualT1 = T1.getUnqualifiedType();
893  QualType UnqualT2 = T2.getUnqualifiedType();
894
895  // C++ [dcl.init.ref]p4:
896  //   Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
897  //   reference-related to “cv2 T2” if T1 is the same type as T2, or
898  //   T1 is a base class of T2.
899  if (UnqualT1 == UnqualT2)
900    DerivedToBase = false;
901  else if (IsDerivedFrom(UnqualT2, UnqualT1))
902    DerivedToBase = true;
903  else
904    return Ref_Incompatible;
905
906  // At this point, we know that T1 and T2 are reference-related (at
907  // least).
908
909  // C++ [dcl.init.ref]p4:
910  //   "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
911  //   reference-related to T2 and cv1 is the same cv-qualification
912  //   as, or greater cv-qualification than, cv2. For purposes of
913  //   overload resolution, cases for which cv1 is greater
914  //   cv-qualification than cv2 are identified as
915  //   reference-compatible with added qualification (see 13.3.3.2).
916  if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
917    return Ref_Compatible;
918  else if (T1.isMoreQualifiedThan(T2))
919    return Ref_Compatible_With_Added_Qualification;
920  else
921    return Ref_Related;
922}
923
924/// CheckReferenceInit - Check the initialization of a reference
925/// variable with the given initializer (C++ [dcl.init.ref]). Init is
926/// the initializer (either a simple initializer or an initializer
927/// list), and DeclType is the type of the declaration. When ICS is
928/// non-null, this routine will compute the implicit conversion
929/// sequence according to C++ [over.ics.ref] and will not produce any
930/// diagnostics; when ICS is null, it will emit diagnostics when any
931/// errors are found. Either way, a return value of true indicates
932/// that there was a failure, a return value of false indicates that
933/// the reference initialization succeeded.
934///
935/// When @p SuppressUserConversions, user-defined conversions are
936/// suppressed.
937bool
938Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
939                         ImplicitConversionSequence *ICS,
940                         bool SuppressUserConversions) {
941  assert(DeclType->isReferenceType() && "Reference init needs a reference");
942
943  QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
944  QualType T2 = Init->getType();
945
946  // Compute some basic properties of the types and the initializer.
947  bool DerivedToBase = false;
948  Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
949  ReferenceCompareResult RefRelationship
950    = CompareReferenceRelationship(T1, T2, DerivedToBase);
951
952  // Most paths end in a failed conversion.
953  if (ICS)
954    ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
955
956  // C++ [dcl.init.ref]p5:
957  //   A reference to type “cv1 T1” is initialized by an expression
958  //   of type “cv2 T2” as follows:
959
960  //     -- If the initializer expression
961
962  bool BindsDirectly = false;
963  //       -- is an lvalue (but is not a bit-field), and “cv1 T1” is
964  //          reference-compatible with “cv2 T2,” or
965  //
966  // Note that the bit-field check is skipped if we are just computing
967  // the implicit conversion sequence (C++ [over.best.ics]p2).
968  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
969      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
970    BindsDirectly = true;
971
972    if (ICS) {
973      // C++ [over.ics.ref]p1:
974      //   When a parameter of reference type binds directly (8.5.3)
975      //   to an argument expression, the implicit conversion sequence
976      //   is the identity conversion, unless the argument expression
977      //   has a type that is a derived class of the parameter type,
978      //   in which case the implicit conversion sequence is a
979      //   derived-to-base Conversion (13.3.3.1).
980      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
981      ICS->Standard.First = ICK_Identity;
982      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
983      ICS->Standard.Third = ICK_Identity;
984      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
985      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
986      ICS->Standard.ReferenceBinding = true;
987      ICS->Standard.DirectBinding = true;
988
989      // Nothing more to do: the inaccessibility/ambiguity check for
990      // derived-to-base conversions is suppressed when we're
991      // computing the implicit conversion sequence (C++
992      // [over.best.ics]p2).
993      return false;
994    } else {
995      // Perform the conversion.
996      // FIXME: Binding to a subobject of the lvalue is going to require
997      // more AST annotation than this.
998      ImpCastExprToType(Init, T1);
999    }
1000  }
1001
1002  //       -- has a class type (i.e., T2 is a class type) and can be
1003  //          implicitly converted to an lvalue of type “cv3 T3,”
1004  //          where “cv1 T1” is reference-compatible with “cv3 T3”
1005  //          92) (this conversion is selected by enumerating the
1006  //          applicable conversion functions (13.3.1.6) and choosing
1007  //          the best one through overload resolution (13.3)),
1008  // FIXME: Implement this second bullet, once we have conversion
1009  //        functions. Also remember C++ [over.ics.ref]p1, second part.
1010
1011  if (BindsDirectly) {
1012    // C++ [dcl.init.ref]p4:
1013    //   [...] In all cases where the reference-related or
1014    //   reference-compatible relationship of two types is used to
1015    //   establish the validity of a reference binding, and T1 is a
1016    //   base class of T2, a program that necessitates such a binding
1017    //   is ill-formed if T1 is an inaccessible (clause 11) or
1018    //   ambiguous (10.2) base class of T2.
1019    //
1020    // Note that we only check this condition when we're allowed to
1021    // complain about errors, because we should not be checking for
1022    // ambiguity (or inaccessibility) unless the reference binding
1023    // actually happens.
1024    if (DerivedToBase)
1025      return CheckDerivedToBaseConversion(T2, T1,
1026                                          Init->getSourceRange().getBegin(),
1027                                          Init->getSourceRange());
1028    else
1029      return false;
1030  }
1031
1032  //     -- Otherwise, the reference shall be to a non-volatile const
1033  //        type (i.e., cv1 shall be const).
1034  if (T1.getCVRQualifiers() != QualType::Const) {
1035    if (!ICS)
1036      Diag(Init->getSourceRange().getBegin(),
1037           diag::err_not_reference_to_const_init,
1038           T1.getAsString(),
1039           InitLvalue != Expr::LV_Valid? "temporary" : "value",
1040           T2.getAsString(), Init->getSourceRange());
1041    return true;
1042  }
1043
1044  //       -- If the initializer expression is an rvalue, with T2 a
1045  //          class type, and “cv1 T1” is reference-compatible with
1046  //          “cv2 T2,” the reference is bound in one of the
1047  //          following ways (the choice is implementation-defined):
1048  //
1049  //          -- The reference is bound to the object represented by
1050  //             the rvalue (see 3.10) or to a sub-object within that
1051  //             object.
1052  //
1053  //          -- A temporary of type “cv1 T2” [sic] is created, and
1054  //             a constructor is called to copy the entire rvalue
1055  //             object into the temporary. The reference is bound to
1056  //             the temporary or to a sub-object within the
1057  //             temporary.
1058  //
1059  //
1060  //          The constructor that would be used to make the copy
1061  //          shall be callable whether or not the copy is actually
1062  //          done.
1063  //
1064  // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1065  // freedom, so we will always take the first option and never build
1066  // a temporary in this case. FIXME: We will, however, have to check
1067  // for the presence of a copy constructor in C++98/03 mode.
1068  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
1069      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1070    if (ICS) {
1071      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1072      ICS->Standard.First = ICK_Identity;
1073      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1074      ICS->Standard.Third = ICK_Identity;
1075      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1076      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
1077      ICS->Standard.ReferenceBinding = true;
1078      ICS->Standard.DirectBinding = false;
1079    } else {
1080      // FIXME: Binding to a subobject of the rvalue is going to require
1081      // more AST annotation than this.
1082      ImpCastExprToType(Init, T1);
1083    }
1084    return false;
1085  }
1086
1087  //       -- Otherwise, a temporary of type “cv1 T1” is created and
1088  //          initialized from the initializer expression using the
1089  //          rules for a non-reference copy initialization (8.5). The
1090  //          reference is then bound to the temporary. If T1 is
1091  //          reference-related to T2, cv1 must be the same
1092  //          cv-qualification as, or greater cv-qualification than,
1093  //          cv2; otherwise, the program is ill-formed.
1094  if (RefRelationship == Ref_Related) {
1095    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1096    // we would be reference-compatible or reference-compatible with
1097    // added qualification. But that wasn't the case, so the reference
1098    // initialization fails.
1099    if (!ICS)
1100      Diag(Init->getSourceRange().getBegin(),
1101           diag::err_reference_init_drops_quals,
1102           T1.getAsString(),
1103           InitLvalue != Expr::LV_Valid? "temporary" : "value",
1104           T2.getAsString(), Init->getSourceRange());
1105    return true;
1106  }
1107
1108  // Actually try to convert the initializer to T1.
1109  if (ICS) {
1110    /// C++ [over.ics.ref]p2:
1111    ///
1112    ///   When a parameter of reference type is not bound directly to
1113    ///   an argument expression, the conversion sequence is the one
1114    ///   required to convert the argument expression to the
1115    ///   underlying type of the reference according to
1116    ///   13.3.3.1. Conceptually, this conversion sequence corresponds
1117    ///   to copy-initializing a temporary of the underlying type with
1118    ///   the argument expression. Any difference in top-level
1119    ///   cv-qualification is subsumed by the initialization itself
1120    ///   and does not constitute a conversion.
1121    *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
1122    return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1123  } else {
1124    return PerformImplicitConversion(Init, T1);
1125  }
1126}
1127