SemaDeclCXX.cpp revision 7ad8390f7992ab7f19b1460c5f0b9d96f165c4e9
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  if (CXXRecordDecl *CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext))
267    return &II == CurDecl->getIdentifier();
268  else
269    return false;
270}
271
272/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
273/// one entry in the base class list of a class specifier, for
274/// example:
275///    class foo : public bar, virtual private baz {
276/// 'public bar' and 'virtual private baz' are each base-specifiers.
277Sema::BaseResult
278Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
279                         bool Virtual, AccessSpecifier Access,
280                         TypeTy *basetype, SourceLocation BaseLoc) {
281  RecordDecl *Decl = (RecordDecl*)classdecl;
282  QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
283
284  // Base specifiers must be record types.
285  if (!BaseType->isRecordType()) {
286    Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange);
287    return true;
288  }
289
290  // C++ [class.union]p1:
291  //   A union shall not be used as a base class.
292  if (BaseType->isUnionType()) {
293    Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange);
294    return true;
295  }
296
297  // C++ [class.union]p1:
298  //   A union shall not have base classes.
299  if (Decl->isUnion()) {
300    Diag(Decl->getLocation(), diag::err_base_clause_on_union,
301         SpecifierRange);
302    return true;
303  }
304
305  // C++ [class.derived]p2:
306  //   The class-name in a base-specifier shall not be an incompletely
307  //   defined class.
308  if (BaseType->isIncompleteType()) {
309    Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
310    return true;
311  }
312
313  // Create the base specifier.
314  return new CXXBaseSpecifier(SpecifierRange, Virtual,
315                              BaseType->isClassType(), Access, BaseType);
316}
317
318/// ActOnBaseSpecifiers - Attach the given base specifiers to the
319/// class, after checking whether there are any duplicate base
320/// classes.
321void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
322                               unsigned NumBases) {
323  if (NumBases == 0)
324    return;
325
326  // Used to keep track of which base types we have already seen, so
327  // that we can properly diagnose redundant direct base types. Note
328  // that the key is always the unqualified canonical type of the base
329  // class.
330  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
331
332  // Copy non-redundant base specifiers into permanent storage.
333  CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
334  unsigned NumGoodBases = 0;
335  for (unsigned idx = 0; idx < NumBases; ++idx) {
336    QualType NewBaseType
337      = Context.getCanonicalType(BaseSpecs[idx]->getType());
338    NewBaseType = NewBaseType.getUnqualifiedType();
339
340    if (KnownBaseTypes[NewBaseType]) {
341      // C++ [class.mi]p3:
342      //   A class shall not be specified as a direct base class of a
343      //   derived class more than once.
344      Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
345           diag::err_duplicate_base_class,
346           KnownBaseTypes[NewBaseType]->getType().getAsString(),
347           BaseSpecs[idx]->getSourceRange());
348
349      // Delete the duplicate base class specifier; we're going to
350      // overwrite its pointer later.
351      delete BaseSpecs[idx];
352    } else {
353      // Okay, add this new base class.
354      KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
355      BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
356    }
357  }
358
359  // Attach the remaining base class specifiers to the derived class.
360  CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
361  Decl->setBases(BaseSpecs, NumGoodBases);
362
363  // Delete the remaining (good) base class specifiers, since their
364  // data has been copied into the CXXRecordDecl.
365  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
366    delete BaseSpecs[idx];
367}
368
369//===----------------------------------------------------------------------===//
370// C++ class member Handling
371//===----------------------------------------------------------------------===//
372
373/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
374/// definition, when on C++.
375void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
376  CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
377  PushDeclContext(Dcl);
378  FieldCollector->StartClass();
379
380  if (Dcl->getIdentifier()) {
381    // C++ [class]p2:
382    //   [...] The class-name is also inserted into the scope of the
383    //   class itself; this is known as the injected-class-name. For
384    //   purposes of access checking, the injected-class-name is treated
385    //   as if it were a public member name.
386    TypedefDecl *InjectedClassName
387      = TypedefDecl::Create(Context, Dcl, LBrace, Dcl->getIdentifier(),
388                            Context.getTypeDeclType(Dcl), /*PrevDecl=*/0);
389    PushOnScopeChains(InjectedClassName, S);
390  }
391}
392
393/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
394/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
395/// bitfield width if there is one and 'InitExpr' specifies the initializer if
396/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
397/// declarators on it.
398///
399/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
400/// an instance field is declared, a new CXXFieldDecl is created but the method
401/// does *not* return it; it returns LastInGroup instead. The other C++ members
402/// (which are all ScopedDecls) are returned after appending them to
403/// LastInGroup.
404Sema::DeclTy *
405Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
406                               ExprTy *BW, ExprTy *InitExpr,
407                               DeclTy *LastInGroup) {
408  const DeclSpec &DS = D.getDeclSpec();
409  IdentifierInfo *II = D.getIdentifier();
410  Expr *BitWidth = static_cast<Expr*>(BW);
411  Expr *Init = static_cast<Expr*>(InitExpr);
412  SourceLocation Loc = D.getIdentifierLoc();
413
414  // C++ 9.2p6: A member shall not be declared to have automatic storage
415  // duration (auto, register) or with the extern storage-class-specifier.
416  switch (DS.getStorageClassSpec()) {
417    case DeclSpec::SCS_unspecified:
418    case DeclSpec::SCS_typedef:
419    case DeclSpec::SCS_static:
420      // FALL THROUGH.
421      break;
422    default:
423      if (DS.getStorageClassSpecLoc().isValid())
424        Diag(DS.getStorageClassSpecLoc(),
425             diag::err_storageclass_invalid_for_member);
426      else
427        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
428      D.getMutableDeclSpec().ClearStorageClassSpecs();
429  }
430
431  bool isFunc = D.isFunctionDeclarator();
432  if (!isFunc &&
433      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
434      D.getNumTypeObjects() == 0) {
435    // Check also for this case:
436    //
437    // typedef int f();
438    // f a;
439    //
440    Decl *TD = static_cast<Decl *>(DS.getTypeRep());
441    isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
442  }
443
444  bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
445                      !isFunc);
446
447  Decl *Member;
448  bool InvalidDecl = false;
449
450  if (isInstField)
451    Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
452  else
453    Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
454
455  if (!Member) return LastInGroup;
456
457  assert((II || isInstField) && "No identifier for non-field ?");
458
459  // set/getAccess is not part of Decl's interface to avoid bloating it with C++
460  // specific methods. Use a wrapper class that can be used with all C++ class
461  // member decls.
462  CXXClassMemberWrapper(Member).setAccess(AS);
463
464  if (BitWidth) {
465    // C++ 9.6p2: Only when declaring an unnamed bit-field may the
466    // constant-expression be a value equal to zero.
467    // FIXME: Check this.
468
469    if (D.isFunctionDeclarator()) {
470      // FIXME: Emit diagnostic about only constructors taking base initializers
471      // or something similar, when constructor support is in place.
472      Diag(Loc, diag::err_not_bitfield_type,
473           II->getName(), BitWidth->getSourceRange());
474      InvalidDecl = true;
475
476    } else if (isInstField) {
477      // C++ 9.6p3: A bit-field shall have integral or enumeration type.
478      if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
479        Diag(Loc, diag::err_not_integral_type_bitfield,
480             II->getName(), BitWidth->getSourceRange());
481        InvalidDecl = true;
482      }
483
484    } else if (isa<FunctionDecl>(Member)) {
485      // A function typedef ("typedef int f(); f a;").
486      // C++ 9.6p3: A bit-field shall have integral or enumeration type.
487      Diag(Loc, diag::err_not_integral_type_bitfield,
488           II->getName(), BitWidth->getSourceRange());
489      InvalidDecl = true;
490
491    } else if (isa<TypedefDecl>(Member)) {
492      // "cannot declare 'A' to be a bit-field type"
493      Diag(Loc, diag::err_not_bitfield_type, II->getName(),
494           BitWidth->getSourceRange());
495      InvalidDecl = true;
496
497    } else {
498      assert(isa<CXXClassVarDecl>(Member) &&
499             "Didn't we cover all member kinds?");
500      // C++ 9.6p3: A bit-field shall not be a static member.
501      // "static member 'A' cannot be a bit-field"
502      Diag(Loc, diag::err_static_not_bitfield, II->getName(),
503           BitWidth->getSourceRange());
504      InvalidDecl = true;
505    }
506  }
507
508  if (Init) {
509    // C++ 9.2p4: A member-declarator can contain a constant-initializer only
510    // if it declares a static member of const integral or const enumeration
511    // type.
512    if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
513      // ...static member of...
514      CVD->setInit(Init);
515      // ...const integral or const enumeration type.
516      if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
517          CVD->getType()->isIntegralType()) {
518        // constant-initializer
519        if (CheckForConstantInitializer(Init, CVD->getType()))
520          InvalidDecl = true;
521
522      } else {
523        // not const integral.
524        Diag(Loc, diag::err_member_initialization,
525             II->getName(), Init->getSourceRange());
526        InvalidDecl = true;
527      }
528
529    } else {
530      // not static member.
531      Diag(Loc, diag::err_member_initialization,
532           II->getName(), Init->getSourceRange());
533      InvalidDecl = true;
534    }
535  }
536
537  if (InvalidDecl)
538    Member->setInvalidDecl();
539
540  if (isInstField) {
541    FieldCollector->Add(cast<CXXFieldDecl>(Member));
542    return LastInGroup;
543  }
544  return Member;
545}
546
547/// ActOnMemInitializer - Handle a C++ member initializer.
548Sema::MemInitResult
549Sema::ActOnMemInitializer(DeclTy *ConstructorD,
550                          Scope *S,
551                          IdentifierInfo *MemberOrBase,
552                          SourceLocation IdLoc,
553                          SourceLocation LParenLoc,
554                          ExprTy **Args, unsigned NumArgs,
555                          SourceLocation *CommaLocs,
556                          SourceLocation RParenLoc) {
557  CXXConstructorDecl *Constructor
558    = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
559  if (!Constructor) {
560    // The user wrote a constructor initializer on a function that is
561    // not a C++ constructor. Ignore the error for now, because we may
562    // have more member initializers coming; we'll diagnose it just
563    // once in ActOnMemInitializers.
564    return true;
565  }
566
567  CXXRecordDecl *ClassDecl = Constructor->getParent();
568
569  // C++ [class.base.init]p2:
570  //   Names in a mem-initializer-id are looked up in the scope of the
571  //   constructor’s class and, if not found in that scope, are looked
572  //   up in the scope containing the constructor’s
573  //   definition. [Note: if the constructor’s class contains a member
574  //   with the same name as a direct or virtual base class of the
575  //   class, a mem-initializer-id naming the member or base class and
576  //   composed of a single identifier refers to the class member. A
577  //   mem-initializer-id for the hidden base class may be specified
578  //   using a qualified name. ]
579  // Look for a member, first.
580  CXXFieldDecl *Member = ClassDecl->getMember(MemberOrBase);
581
582  // FIXME: Handle members of an anonymous union.
583
584  if (Member) {
585    // FIXME: Perform direct initialization of the member.
586    return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
587  }
588
589  // It didn't name a member, so see if it names a class.
590  TypeTy *BaseTy = isTypeName(*MemberOrBase, S);
591  if (!BaseTy)
592    return Diag(IdLoc, diag::err_mem_init_not_member_or_class,
593                MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
594
595  QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
596  if (!BaseType->isRecordType())
597    return Diag(IdLoc, diag::err_base_init_does_not_name_class,
598                BaseType.getAsString(), SourceRange(IdLoc, RParenLoc));
599
600  // C++ [class.base.init]p2:
601  //   [...] Unless the mem-initializer-id names a nonstatic data
602  //   member of the constructor’s class or a direct or virtual base
603  //   of that class, the mem-initializer is ill-formed. A
604  //   mem-initializer-list can initialize a base class using any
605  //   name that denotes that base class type.
606
607  // First, check for a direct base class.
608  const CXXBaseSpecifier *DirectBaseSpec = 0;
609  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
610       Base != ClassDecl->bases_end(); ++Base) {
611    if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
612        Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
613      // We found a direct base of this type. That's what we're
614      // initializing.
615      DirectBaseSpec = &*Base;
616      break;
617    }
618  }
619
620  // Check for a virtual base class.
621  // FIXME: We might be able to short-circuit this if we know in
622  // advance that there are no virtual bases.
623  const CXXBaseSpecifier *VirtualBaseSpec = 0;
624  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
625    // We haven't found a base yet; search the class hierarchy for a
626    // virtual base class.
627    BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
628                    /*DetectVirtual=*/false);
629    if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
630      for (BasePaths::paths_iterator Path = Paths.begin();
631           Path != Paths.end(); ++Path) {
632        if (Path->back().Base->isVirtual()) {
633          VirtualBaseSpec = Path->back().Base;
634          break;
635        }
636      }
637    }
638  }
639
640  // C++ [base.class.init]p2:
641  //   If a mem-initializer-id is ambiguous because it designates both
642  //   a direct non-virtual base class and an inherited virtual base
643  //   class, the mem-initializer is ill-formed.
644  if (DirectBaseSpec && VirtualBaseSpec)
645    return Diag(IdLoc, diag::err_base_init_direct_and_virtual,
646                MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
647
648  return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
649}
650
651
652void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
653                                             DeclTy *TagDecl,
654                                             SourceLocation LBrac,
655                                             SourceLocation RBrac) {
656  ActOnFields(S, RLoc, TagDecl,
657              (DeclTy**)FieldCollector->getCurFields(),
658              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
659}
660
661/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
662/// special functions, such as the default constructor, copy
663/// constructor, or destructor, to the given C++ class (C++
664/// [special]p1).  This routine can only be executed just before the
665/// definition of the class is complete.
666void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
667  if (!ClassDecl->hasUserDeclaredConstructor()) {
668    // C++ [class.ctor]p5:
669    //   A default constructor for a class X is a constructor of class X
670    //   that can be called without an argument. If there is no
671    //   user-declared constructor for class X, a default constructor is
672    //   implicitly declared. An implicitly-declared default constructor
673    //   is an inline public member of its class.
674    CXXConstructorDecl *DefaultCon =
675      CXXConstructorDecl::Create(Context, ClassDecl,
676                                 ClassDecl->getLocation(),
677                                 ClassDecl->getIdentifier(),
678                                 Context.getFunctionType(Context.VoidTy,
679                                                         0, 0, false, 0),
680                                 /*isExplicit=*/false,
681                                 /*isInline=*/true,
682                                 /*isImplicitlyDeclared=*/true);
683    DefaultCon->setAccess(AS_public);
684    ClassDecl->addConstructor(Context, DefaultCon);
685  }
686
687  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
688    // C++ [class.copy]p4:
689    //   If the class definition does not explicitly declare a copy
690    //   constructor, one is declared implicitly.
691
692    // C++ [class.copy]p5:
693    //   The implicitly-declared copy constructor for a class X will
694    //   have the form
695    //
696    //       X::X(const X&)
697    //
698    //   if
699    bool HasConstCopyConstructor = true;
700
701    //     -- each direct or virtual base class B of X has a copy
702    //        constructor whose first parameter is of type const B& or
703    //        const volatile B&, and
704    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
705         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
706      const CXXRecordDecl *BaseClassDecl
707        = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
708      HasConstCopyConstructor
709        = BaseClassDecl->hasConstCopyConstructor(Context);
710    }
711
712    //     -- for all the nonstatic data members of X that are of a
713    //        class type M (or array thereof), each such class type
714    //        has a copy constructor whose first parameter is of type
715    //        const M& or const volatile M&.
716    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
717         HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
718      QualType FieldType = (*Field)->getType();
719      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
720        FieldType = Array->getElementType();
721      if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
722        const CXXRecordDecl *FieldClassDecl
723          = cast<CXXRecordDecl>(FieldClassType->getDecl());
724        HasConstCopyConstructor
725          = FieldClassDecl->hasConstCopyConstructor(Context);
726      }
727    }
728
729    //  Otherwise, the implicitly declared copy constructor will have
730    //  the form
731    //
732    //       X::X(X&)
733    QualType ArgType = Context.getTypeDeclType(ClassDecl);
734    if (HasConstCopyConstructor)
735      ArgType = ArgType.withConst();
736    ArgType = Context.getReferenceType(ArgType);
737
738    //  An implicitly-declared copy constructor is an inline public
739    //  member of its class.
740    CXXConstructorDecl *CopyConstructor
741      = CXXConstructorDecl::Create(Context, ClassDecl,
742                                   ClassDecl->getLocation(),
743                                   ClassDecl->getIdentifier(),
744                                   Context.getFunctionType(Context.VoidTy,
745                                                           &ArgType, 1,
746                                                           false, 0),
747                                   /*isExplicit=*/false,
748                                   /*isInline=*/true,
749                                   /*isImplicitlyDeclared=*/true);
750    CopyConstructor->setAccess(AS_public);
751
752    // Add the parameter to the constructor.
753    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
754                                                 ClassDecl->getLocation(),
755                                                 /*IdentifierInfo=*/0,
756                                                 ArgType, VarDecl::None, 0, 0);
757    CopyConstructor->setParams(&FromParam, 1);
758
759    ClassDecl->addConstructor(Context, CopyConstructor);
760  }
761
762  // FIXME: Implicit destructor
763  // FIXME: Implicit copy assignment operator
764}
765
766void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
767  CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
768  FieldCollector->FinishClass();
769  AddImplicitlyDeclaredMembersToClass(Rec);
770  PopDeclContext();
771
772  // Everything, including inline method definitions, have been parsed.
773  // Let the consumer know of the new TagDecl definition.
774  Consumer.HandleTagDeclDefinition(Rec);
775}
776
777/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete
778/// the declaration of the given C++ constructor ConDecl that was
779/// built from declarator D. This routine is responsible for checking
780/// that the newly-created constructor declaration is well-formed and
781/// for recording it in the C++ class. Example:
782///
783/// @code
784/// class X {
785///   X(); // X::X() will be the ConDecl.
786/// };
787/// @endcode
788Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) {
789  assert(ConDecl && "Expected to receive a constructor declaration");
790
791  // Check default arguments on the constructor
792  CheckCXXDefaultArguments(ConDecl);
793
794  CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
795  if (!ClassDecl) {
796    ConDecl->setInvalidDecl();
797    return ConDecl;
798  }
799
800  // Make sure this constructor is an overload of the existing
801  // constructors.
802  OverloadedFunctionDecl::function_iterator MatchedDecl;
803  if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) {
804    Diag(ConDecl->getLocation(),
805         diag::err_constructor_redeclared,
806         SourceRange(ConDecl->getLocation()));
807    Diag((*MatchedDecl)->getLocation(),
808         diag::err_previous_declaration,
809         SourceRange((*MatchedDecl)->getLocation()));
810    ConDecl->setInvalidDecl();
811    return ConDecl;
812  }
813
814
815  // C++ [class.copy]p3:
816  //   A declaration of a constructor for a class X is ill-formed if
817  //   its first parameter is of type (optionally cv-qualified) X and
818  //   either there are no other parameters or else all other
819  //   parameters have default arguments.
820  if ((ConDecl->getNumParams() == 1) ||
821      (ConDecl->getNumParams() > 1 &&
822       ConDecl->getParamDecl(1)->getDefaultArg() != 0)) {
823    QualType ParamType = ConDecl->getParamDecl(0)->getType();
824    QualType ClassTy = Context.getTagDeclType(
825                         const_cast<CXXRecordDecl*>(ConDecl->getParent()));
826    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
827      Diag(ConDecl->getLocation(),
828           diag::err_constructor_byvalue_arg,
829           SourceRange(ConDecl->getParamDecl(0)->getLocation()));
830      ConDecl->setInvalidDecl();
831      return 0;
832    }
833  }
834
835  // Add this constructor to the set of constructors of the current
836  // class.
837  ClassDecl->addConstructor(Context, ConDecl);
838
839  return (DeclTy *)ConDecl;
840}
841
842//===----------------------------------------------------------------------===//
843// Namespace Handling
844//===----------------------------------------------------------------------===//
845
846/// ActOnStartNamespaceDef - This is called at the start of a namespace
847/// definition.
848Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
849                                           SourceLocation IdentLoc,
850                                           IdentifierInfo *II,
851                                           SourceLocation LBrace) {
852  NamespaceDecl *Namespc =
853      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
854  Namespc->setLBracLoc(LBrace);
855
856  Scope *DeclRegionScope = NamespcScope->getParent();
857
858  if (II) {
859    // C++ [namespace.def]p2:
860    // The identifier in an original-namespace-definition shall not have been
861    // previously defined in the declarative region in which the
862    // original-namespace-definition appears. The identifier in an
863    // original-namespace-definition is the name of the namespace. Subsequently
864    // in that declarative region, it is treated as an original-namespace-name.
865
866    Decl *PrevDecl =
867        LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
868                   /*enableLazyBuiltinCreation=*/false);
869
870    if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
871      if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
872        // This is an extended namespace definition.
873        // Attach this namespace decl to the chain of extended namespace
874        // definitions.
875        NamespaceDecl *NextNS = OrigNS;
876        while (NextNS->getNextNamespace())
877          NextNS = NextNS->getNextNamespace();
878
879        NextNS->setNextNamespace(Namespc);
880        Namespc->setOriginalNamespace(OrigNS);
881
882        // We won't add this decl to the current scope. We want the namespace
883        // name to return the original namespace decl during a name lookup.
884      } else {
885        // This is an invalid name redefinition.
886        Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
887          Namespc->getName());
888        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
889        Namespc->setInvalidDecl();
890        // Continue on to push Namespc as current DeclContext and return it.
891      }
892    } else {
893      // This namespace name is declared for the first time.
894      PushOnScopeChains(Namespc, DeclRegionScope);
895    }
896  }
897  else {
898    // FIXME: Handle anonymous namespaces
899  }
900
901  // Although we could have an invalid decl (i.e. the namespace name is a
902  // redefinition), push it as current DeclContext and try to continue parsing.
903  PushDeclContext(Namespc->getOriginalNamespace());
904  return Namespc;
905}
906
907/// ActOnFinishNamespaceDef - This callback is called after a namespace is
908/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
909void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
910  Decl *Dcl = static_cast<Decl *>(D);
911  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
912  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
913  Namespc->setRBracLoc(RBrace);
914  PopDeclContext();
915}
916
917
918/// AddCXXDirectInitializerToDecl - This action is called immediately after
919/// ActOnDeclarator, when a C++ direct initializer is present.
920/// e.g: "int x(1);"
921void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
922                                         ExprTy **ExprTys, unsigned NumExprs,
923                                         SourceLocation *CommaLocs,
924                                         SourceLocation RParenLoc) {
925  assert(NumExprs != 0 && ExprTys && "missing expressions");
926  Decl *RealDecl = static_cast<Decl *>(Dcl);
927
928  // If there is no declaration, there was an error parsing it.  Just ignore
929  // the initializer.
930  if (RealDecl == 0) {
931    for (unsigned i = 0; i != NumExprs; ++i)
932      delete static_cast<Expr *>(ExprTys[i]);
933    return;
934  }
935
936  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
937  if (!VDecl) {
938    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
939    RealDecl->setInvalidDecl();
940    return;
941  }
942
943  // We will treat direct-initialization as a copy-initialization:
944  //    int x(1);  -as-> int x = 1;
945  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
946  //
947  // Clients that want to distinguish between the two forms, can check for
948  // direct initializer using VarDecl::hasCXXDirectInitializer().
949  // A major benefit is that clients that don't particularly care about which
950  // exactly form was it (like the CodeGen) can handle both cases without
951  // special case code.
952
953  // C++ 8.5p11:
954  // The form of initialization (using parentheses or '=') is generally
955  // insignificant, but does matter when the entity being initialized has a
956  // class type.
957  QualType DeclInitType = VDecl->getType();
958  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
959    DeclInitType = Array->getElementType();
960
961  if (VDecl->getType()->isRecordType()) {
962    CXXConstructorDecl *Constructor
963      = PerformDirectInitForClassType(DeclInitType, (Expr **)ExprTys, NumExprs,
964                                      VDecl->getLocation(),
965                                      SourceRange(VDecl->getLocation(),
966                                                  RParenLoc),
967                                      VDecl->getName(),
968                                      /*HasInitializer=*/true);
969    if (!Constructor) {
970      RealDecl->setInvalidDecl();
971    }
972    return;
973  }
974
975  if (NumExprs > 1) {
976    Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
977         SourceRange(VDecl->getLocation(), RParenLoc));
978    RealDecl->setInvalidDecl();
979    return;
980  }
981
982  // Let clients know that initialization was done with a direct initializer.
983  VDecl->setCXXDirectInitializer(true);
984
985  assert(NumExprs == 1 && "Expected 1 expression");
986  // Set the init expression, handles conversions.
987  AddInitializerToDecl(Dcl, ExprTys[0]);
988}
989
990/// PerformDirectInitForClassType - Perform direct-initialization (C++
991/// [dcl.init]) for a value of the given class type with the given set
992/// of arguments (@p Args). @p Loc is the location in the source code
993/// where the initializer occurs (e.g., a declaration, member
994/// initializer, functional cast, etc.) while @p Range covers the
995/// whole initialization. @p HasInitializer is true if the initializer
996/// was actually written in the source code. When successful, returns
997/// the constructor that will be used to perform the initialization;
998/// when the initialization fails, emits a diagnostic and returns null.
999CXXConstructorDecl *
1000Sema::PerformDirectInitForClassType(QualType ClassType,
1001                                    Expr **Args, unsigned NumArgs,
1002                                    SourceLocation Loc, SourceRange Range,
1003                                    std::string InitEntity,
1004                                    bool HasInitializer) {
1005  const RecordType *ClassRec = ClassType->getAsRecordType();
1006  assert(ClassRec && "Can only initialize a class type here");
1007
1008  // C++ [dcl.init]p14:
1009  //
1010  //   If the initialization is direct-initialization, or if it is
1011  //   copy-initialization where the cv-unqualified version of the
1012  //   source type is the same class as, or a derived class of, the
1013  //   class of the destination, constructors are considered. The
1014  //   applicable constructors are enumerated (13.3.1.3), and the
1015  //   best one is chosen through overload resolution (13.3). The
1016  //   constructor so selected is called to initialize the object,
1017  //   with the initializer expression(s) as its argument(s). If no
1018  //   constructor applies, or the overload resolution is ambiguous,
1019  //   the initialization is ill-formed.
1020  //
1021  // FIXME: We don't check cv-qualifiers on the class type, because we
1022  // don't yet keep track of whether a class type is a POD class type
1023  // (or a "trivial" class type, as is used in C++0x).
1024  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1025  OverloadCandidateSet CandidateSet;
1026  OverloadCandidateSet::iterator Best;
1027  AddOverloadCandidates(ClassDecl->getConstructors(), Args, NumArgs,
1028                        CandidateSet);
1029  switch (BestViableFunction(CandidateSet, Best)) {
1030  case OR_Success:
1031    // We found a constructor. Return it.
1032    return cast<CXXConstructorDecl>(Best->Function);
1033
1034  case OR_No_Viable_Function:
1035    if (CandidateSet.empty())
1036      Diag(Loc, diag::err_ovl_no_viable_function_in_init,
1037           InitEntity, Range);
1038    else {
1039      Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands,
1040           InitEntity, Range);
1041      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1042    }
1043    return 0;
1044
1045  case OR_Ambiguous:
1046    Diag(Loc, diag::err_ovl_ambiguous_init,
1047         InitEntity, Range);
1048    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1049    return 0;
1050  }
1051
1052  return 0;
1053}
1054
1055/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1056/// determine whether they are reference-related,
1057/// reference-compatible, reference-compatible with added
1058/// qualification, or incompatible, for use in C++ initialization by
1059/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1060/// type, and the first type (T1) is the pointee type of the reference
1061/// type being initialized.
1062Sema::ReferenceCompareResult
1063Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1064                                   bool& DerivedToBase) {
1065  assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1066  assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1067
1068  T1 = Context.getCanonicalType(T1);
1069  T2 = Context.getCanonicalType(T2);
1070  QualType UnqualT1 = T1.getUnqualifiedType();
1071  QualType UnqualT2 = T2.getUnqualifiedType();
1072
1073  // C++ [dcl.init.ref]p4:
1074  //   Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1075  //   reference-related to “cv2 T2” if T1 is the same type as T2, or
1076  //   T1 is a base class of T2.
1077  if (UnqualT1 == UnqualT2)
1078    DerivedToBase = false;
1079  else if (IsDerivedFrom(UnqualT2, UnqualT1))
1080    DerivedToBase = true;
1081  else
1082    return Ref_Incompatible;
1083
1084  // At this point, we know that T1 and T2 are reference-related (at
1085  // least).
1086
1087  // C++ [dcl.init.ref]p4:
1088  //   "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1089  //   reference-related to T2 and cv1 is the same cv-qualification
1090  //   as, or greater cv-qualification than, cv2. For purposes of
1091  //   overload resolution, cases for which cv1 is greater
1092  //   cv-qualification than cv2 are identified as
1093  //   reference-compatible with added qualification (see 13.3.3.2).
1094  if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1095    return Ref_Compatible;
1096  else if (T1.isMoreQualifiedThan(T2))
1097    return Ref_Compatible_With_Added_Qualification;
1098  else
1099    return Ref_Related;
1100}
1101
1102/// CheckReferenceInit - Check the initialization of a reference
1103/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1104/// the initializer (either a simple initializer or an initializer
1105/// list), and DeclType is the type of the declaration. When ICS is
1106/// non-null, this routine will compute the implicit conversion
1107/// sequence according to C++ [over.ics.ref] and will not produce any
1108/// diagnostics; when ICS is null, it will emit diagnostics when any
1109/// errors are found. Either way, a return value of true indicates
1110/// that there was a failure, a return value of false indicates that
1111/// the reference initialization succeeded.
1112///
1113/// When @p SuppressUserConversions, user-defined conversions are
1114/// suppressed.
1115bool
1116Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
1117                         ImplicitConversionSequence *ICS,
1118                         bool SuppressUserConversions) {
1119  assert(DeclType->isReferenceType() && "Reference init needs a reference");
1120
1121  QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1122  QualType T2 = Init->getType();
1123
1124  // Compute some basic properties of the types and the initializer.
1125  bool DerivedToBase = false;
1126  Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
1127  ReferenceCompareResult RefRelationship
1128    = CompareReferenceRelationship(T1, T2, DerivedToBase);
1129
1130  // Most paths end in a failed conversion.
1131  if (ICS)
1132    ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
1133
1134  // C++ [dcl.init.ref]p5:
1135  //   A reference to type “cv1 T1” is initialized by an expression
1136  //   of type “cv2 T2” as follows:
1137
1138  //     -- If the initializer expression
1139
1140  bool BindsDirectly = false;
1141  //       -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1142  //          reference-compatible with “cv2 T2,” or
1143  //
1144  // Note that the bit-field check is skipped if we are just computing
1145  // the implicit conversion sequence (C++ [over.best.ics]p2).
1146  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1147      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1148    BindsDirectly = true;
1149
1150    if (ICS) {
1151      // C++ [over.ics.ref]p1:
1152      //   When a parameter of reference type binds directly (8.5.3)
1153      //   to an argument expression, the implicit conversion sequence
1154      //   is the identity conversion, unless the argument expression
1155      //   has a type that is a derived class of the parameter type,
1156      //   in which case the implicit conversion sequence is a
1157      //   derived-to-base Conversion (13.3.3.1).
1158      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1159      ICS->Standard.First = ICK_Identity;
1160      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1161      ICS->Standard.Third = ICK_Identity;
1162      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1163      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
1164      ICS->Standard.ReferenceBinding = true;
1165      ICS->Standard.DirectBinding = true;
1166
1167      // Nothing more to do: the inaccessibility/ambiguity check for
1168      // derived-to-base conversions is suppressed when we're
1169      // computing the implicit conversion sequence (C++
1170      // [over.best.ics]p2).
1171      return false;
1172    } else {
1173      // Perform the conversion.
1174      // FIXME: Binding to a subobject of the lvalue is going to require
1175      // more AST annotation than this.
1176      ImpCastExprToType(Init, T1);
1177    }
1178  }
1179
1180  //       -- has a class type (i.e., T2 is a class type) and can be
1181  //          implicitly converted to an lvalue of type “cv3 T3,”
1182  //          where “cv1 T1” is reference-compatible with “cv3 T3”
1183  //          92) (this conversion is selected by enumerating the
1184  //          applicable conversion functions (13.3.1.6) and choosing
1185  //          the best one through overload resolution (13.3)),
1186  // FIXME: Implement this second bullet, once we have conversion
1187  //        functions. Also remember C++ [over.ics.ref]p1, second part.
1188
1189  if (BindsDirectly) {
1190    // C++ [dcl.init.ref]p4:
1191    //   [...] In all cases where the reference-related or
1192    //   reference-compatible relationship of two types is used to
1193    //   establish the validity of a reference binding, and T1 is a
1194    //   base class of T2, a program that necessitates such a binding
1195    //   is ill-formed if T1 is an inaccessible (clause 11) or
1196    //   ambiguous (10.2) base class of T2.
1197    //
1198    // Note that we only check this condition when we're allowed to
1199    // complain about errors, because we should not be checking for
1200    // ambiguity (or inaccessibility) unless the reference binding
1201    // actually happens.
1202    if (DerivedToBase)
1203      return CheckDerivedToBaseConversion(T2, T1,
1204                                          Init->getSourceRange().getBegin(),
1205                                          Init->getSourceRange());
1206    else
1207      return false;
1208  }
1209
1210  //     -- Otherwise, the reference shall be to a non-volatile const
1211  //        type (i.e., cv1 shall be const).
1212  if (T1.getCVRQualifiers() != QualType::Const) {
1213    if (!ICS)
1214      Diag(Init->getSourceRange().getBegin(),
1215           diag::err_not_reference_to_const_init,
1216           T1.getAsString(),
1217           InitLvalue != Expr::LV_Valid? "temporary" : "value",
1218           T2.getAsString(), Init->getSourceRange());
1219    return true;
1220  }
1221
1222  //       -- If the initializer expression is an rvalue, with T2 a
1223  //          class type, and “cv1 T1” is reference-compatible with
1224  //          “cv2 T2,” the reference is bound in one of the
1225  //          following ways (the choice is implementation-defined):
1226  //
1227  //          -- The reference is bound to the object represented by
1228  //             the rvalue (see 3.10) or to a sub-object within that
1229  //             object.
1230  //
1231  //          -- A temporary of type “cv1 T2” [sic] is created, and
1232  //             a constructor is called to copy the entire rvalue
1233  //             object into the temporary. The reference is bound to
1234  //             the temporary or to a sub-object within the
1235  //             temporary.
1236  //
1237  //
1238  //          The constructor that would be used to make the copy
1239  //          shall be callable whether or not the copy is actually
1240  //          done.
1241  //
1242  // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1243  // freedom, so we will always take the first option and never build
1244  // a temporary in this case. FIXME: We will, however, have to check
1245  // for the presence of a copy constructor in C++98/03 mode.
1246  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
1247      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1248    if (ICS) {
1249      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1250      ICS->Standard.First = ICK_Identity;
1251      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1252      ICS->Standard.Third = ICK_Identity;
1253      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1254      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
1255      ICS->Standard.ReferenceBinding = true;
1256      ICS->Standard.DirectBinding = false;
1257    } else {
1258      // FIXME: Binding to a subobject of the rvalue is going to require
1259      // more AST annotation than this.
1260      ImpCastExprToType(Init, T1);
1261    }
1262    return false;
1263  }
1264
1265  //       -- Otherwise, a temporary of type “cv1 T1” is created and
1266  //          initialized from the initializer expression using the
1267  //          rules for a non-reference copy initialization (8.5). The
1268  //          reference is then bound to the temporary. If T1 is
1269  //          reference-related to T2, cv1 must be the same
1270  //          cv-qualification as, or greater cv-qualification than,
1271  //          cv2; otherwise, the program is ill-formed.
1272  if (RefRelationship == Ref_Related) {
1273    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1274    // we would be reference-compatible or reference-compatible with
1275    // added qualification. But that wasn't the case, so the reference
1276    // initialization fails.
1277    if (!ICS)
1278      Diag(Init->getSourceRange().getBegin(),
1279           diag::err_reference_init_drops_quals,
1280           T1.getAsString(),
1281           InitLvalue != Expr::LV_Valid? "temporary" : "value",
1282           T2.getAsString(), Init->getSourceRange());
1283    return true;
1284  }
1285
1286  // Actually try to convert the initializer to T1.
1287  if (ICS) {
1288    /// C++ [over.ics.ref]p2:
1289    ///
1290    ///   When a parameter of reference type is not bound directly to
1291    ///   an argument expression, the conversion sequence is the one
1292    ///   required to convert the argument expression to the
1293    ///   underlying type of the reference according to
1294    ///   13.3.3.1. Conceptually, this conversion sequence corresponds
1295    ///   to copy-initializing a temporary of the underlying type with
1296    ///   the argument expression. Any difference in top-level
1297    ///   cv-qualification is subsumed by the initialization itself
1298    ///   and does not constitute a conversion.
1299    *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
1300    return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1301  } else {
1302    return PerformImplicitConversion(Init, T1);
1303  }
1304}
1305