SemaOverload.cpp revision 52ae30c90106ce7086e0787e95dd6536079202e4
1//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
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 provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "SemaInherit.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/TypeOrdering.h"
22#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/Support/Compiler.h"
25#include <algorithm>
26
27namespace clang {
28
29/// GetConversionCategory - Retrieve the implicit conversion
30/// category corresponding to the given implicit conversion kind.
31ImplicitConversionCategory
32GetConversionCategory(ImplicitConversionKind Kind) {
33  static const ImplicitConversionCategory
34    Category[(int)ICK_Num_Conversion_Kinds] = {
35    ICC_Identity,
36    ICC_Lvalue_Transformation,
37    ICC_Lvalue_Transformation,
38    ICC_Lvalue_Transformation,
39    ICC_Qualification_Adjustment,
40    ICC_Promotion,
41    ICC_Promotion,
42    ICC_Conversion,
43    ICC_Conversion,
44    ICC_Conversion,
45    ICC_Conversion,
46    ICC_Conversion,
47    ICC_Conversion,
48    ICC_Conversion
49  };
50  return Category[(int)Kind];
51}
52
53/// GetConversionRank - Retrieve the implicit conversion rank
54/// corresponding to the given implicit conversion kind.
55ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
56  static const ImplicitConversionRank
57    Rank[(int)ICK_Num_Conversion_Kinds] = {
58    ICR_Exact_Match,
59    ICR_Exact_Match,
60    ICR_Exact_Match,
61    ICR_Exact_Match,
62    ICR_Exact_Match,
63    ICR_Promotion,
64    ICR_Promotion,
65    ICR_Conversion,
66    ICR_Conversion,
67    ICR_Conversion,
68    ICR_Conversion,
69    ICR_Conversion,
70    ICR_Conversion,
71    ICR_Conversion
72  };
73  return Rank[(int)Kind];
74}
75
76/// GetImplicitConversionName - Return the name of this kind of
77/// implicit conversion.
78const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
79  static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
80    "No conversion",
81    "Lvalue-to-rvalue",
82    "Array-to-pointer",
83    "Function-to-pointer",
84    "Qualification",
85    "Integral promotion",
86    "Floating point promotion",
87    "Integral conversion",
88    "Floating conversion",
89    "Floating-integral conversion",
90    "Pointer conversion",
91    "Pointer-to-member conversion",
92    "Boolean conversion",
93    "Derived-to-base conversion"
94  };
95  return Name[Kind];
96}
97
98/// StandardConversionSequence - Set the standard conversion
99/// sequence to the identity conversion.
100void StandardConversionSequence::setAsIdentityConversion() {
101  First = ICK_Identity;
102  Second = ICK_Identity;
103  Third = ICK_Identity;
104  Deprecated = false;
105  ReferenceBinding = false;
106  DirectBinding = false;
107  CopyConstructor = 0;
108}
109
110/// getRank - Retrieve the rank of this standard conversion sequence
111/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
112/// implicit conversions.
113ImplicitConversionRank StandardConversionSequence::getRank() const {
114  ImplicitConversionRank Rank = ICR_Exact_Match;
115  if  (GetConversionRank(First) > Rank)
116    Rank = GetConversionRank(First);
117  if  (GetConversionRank(Second) > Rank)
118    Rank = GetConversionRank(Second);
119  if  (GetConversionRank(Third) > Rank)
120    Rank = GetConversionRank(Third);
121  return Rank;
122}
123
124/// isPointerConversionToBool - Determines whether this conversion is
125/// a conversion of a pointer or pointer-to-member to bool. This is
126/// used as part of the ranking of standard conversion sequences
127/// (C++ 13.3.3.2p4).
128bool StandardConversionSequence::isPointerConversionToBool() const
129{
130  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
131  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
132
133  // Note that FromType has not necessarily been transformed by the
134  // array-to-pointer or function-to-pointer implicit conversions, so
135  // check for their presence as well as checking whether FromType is
136  // a pointer.
137  if (ToType->isBooleanType() &&
138      (FromType->isPointerType() || FromType->isBlockPointerType() ||
139       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
140    return true;
141
142  return false;
143}
144
145/// isPointerConversionToVoidPointer - Determines whether this
146/// conversion is a conversion of a pointer to a void pointer. This is
147/// used as part of the ranking of standard conversion sequences (C++
148/// 13.3.3.2p4).
149bool
150StandardConversionSequence::
151isPointerConversionToVoidPointer(ASTContext& Context) const
152{
153  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
154  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
155
156  // Note that FromType has not necessarily been transformed by the
157  // array-to-pointer implicit conversion, so check for its presence
158  // and redo the conversion to get a pointer.
159  if (First == ICK_Array_To_Pointer)
160    FromType = Context.getArrayDecayedType(FromType);
161
162  if (Second == ICK_Pointer_Conversion)
163    if (const PointerType* ToPtrType = ToType->getAsPointerType())
164      return ToPtrType->getPointeeType()->isVoidType();
165
166  return false;
167}
168
169/// DebugPrint - Print this standard conversion sequence to standard
170/// error. Useful for debugging overloading issues.
171void StandardConversionSequence::DebugPrint() const {
172  bool PrintedSomething = false;
173  if (First != ICK_Identity) {
174    fprintf(stderr, "%s", GetImplicitConversionName(First));
175    PrintedSomething = true;
176  }
177
178  if (Second != ICK_Identity) {
179    if (PrintedSomething) {
180      fprintf(stderr, " -> ");
181    }
182    fprintf(stderr, "%s", GetImplicitConversionName(Second));
183
184    if (CopyConstructor) {
185      fprintf(stderr, " (by copy constructor)");
186    } else if (DirectBinding) {
187      fprintf(stderr, " (direct reference binding)");
188    } else if (ReferenceBinding) {
189      fprintf(stderr, " (reference binding)");
190    }
191    PrintedSomething = true;
192  }
193
194  if (Third != ICK_Identity) {
195    if (PrintedSomething) {
196      fprintf(stderr, " -> ");
197    }
198    fprintf(stderr, "%s", GetImplicitConversionName(Third));
199    PrintedSomething = true;
200  }
201
202  if (!PrintedSomething) {
203    fprintf(stderr, "No conversions required");
204  }
205}
206
207/// DebugPrint - Print this user-defined conversion sequence to standard
208/// error. Useful for debugging overloading issues.
209void UserDefinedConversionSequence::DebugPrint() const {
210  if (Before.First || Before.Second || Before.Third) {
211    Before.DebugPrint();
212    fprintf(stderr, " -> ");
213  }
214  fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
215  if (After.First || After.Second || After.Third) {
216    fprintf(stderr, " -> ");
217    After.DebugPrint();
218  }
219}
220
221/// DebugPrint - Print this implicit conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void ImplicitConversionSequence::DebugPrint() const {
224  switch (ConversionKind) {
225  case StandardConversion:
226    fprintf(stderr, "Standard conversion: ");
227    Standard.DebugPrint();
228    break;
229  case UserDefinedConversion:
230    fprintf(stderr, "User-defined conversion: ");
231    UserDefined.DebugPrint();
232    break;
233  case EllipsisConversion:
234    fprintf(stderr, "Ellipsis conversion");
235    break;
236  case BadConversion:
237    fprintf(stderr, "Bad conversion");
238    break;
239  }
240
241  fprintf(stderr, "\n");
242}
243
244// IsOverload - Determine whether the given New declaration is an
245// overload of the Old declaration. This routine returns false if New
246// and Old cannot be overloaded, e.g., if they are functions with the
247// same signature (C++ 1.3.10) or if the Old declaration isn't a
248// function (or overload set). When it does return false and Old is an
249// OverloadedFunctionDecl, MatchedDecl will be set to point to the
250// FunctionDecl that New cannot be overloaded with.
251//
252// Example: Given the following input:
253//
254//   void f(int, float); // #1
255//   void f(int, int); // #2
256//   int f(int, int); // #3
257//
258// When we process #1, there is no previous declaration of "f",
259// so IsOverload will not be used.
260//
261// When we process #2, Old is a FunctionDecl for #1.  By comparing the
262// parameter types, we see that #1 and #2 are overloaded (since they
263// have different signatures), so this routine returns false;
264// MatchedDecl is unchanged.
265//
266// When we process #3, Old is an OverloadedFunctionDecl containing #1
267// and #2. We compare the signatures of #3 to #1 (they're overloaded,
268// so we do nothing) and then #3 to #2. Since the signatures of #3 and
269// #2 are identical (return types of functions are not part of the
270// signature), IsOverload returns false and MatchedDecl will be set to
271// point to the FunctionDecl for #2.
272bool
273Sema::IsOverload(FunctionDecl *New, Decl* OldD,
274                 OverloadedFunctionDecl::function_iterator& MatchedDecl)
275{
276  if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
277    // Is this new function an overload of every function in the
278    // overload set?
279    OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
280                                           FuncEnd = Ovl->function_end();
281    for (; Func != FuncEnd; ++Func) {
282      if (!IsOverload(New, *Func, MatchedDecl)) {
283        MatchedDecl = Func;
284        return false;
285      }
286    }
287
288    // This function overloads every function in the overload set.
289    return true;
290  } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
291    // Is the function New an overload of the function Old?
292    QualType OldQType = Context.getCanonicalType(Old->getType());
293    QualType NewQType = Context.getCanonicalType(New->getType());
294
295    // Compare the signatures (C++ 1.3.10) of the two functions to
296    // determine whether they are overloads. If we find any mismatch
297    // in the signature, they are overloads.
298
299    // If either of these functions is a K&R-style function (no
300    // prototype), then we consider them to have matching signatures.
301    if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
302        isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
303      return false;
304
305    FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
306    FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
307
308    // The signature of a function includes the types of its
309    // parameters (C++ 1.3.10), which includes the presence or absence
310    // of the ellipsis; see C++ DR 357).
311    if (OldQType != NewQType &&
312        (OldType->getNumArgs() != NewType->getNumArgs() ||
313         OldType->isVariadic() != NewType->isVariadic() ||
314         !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
315                     NewType->arg_type_begin())))
316      return true;
317
318    // If the function is a class member, its signature includes the
319    // cv-qualifiers (if any) on the function itself.
320    //
321    // As part of this, also check whether one of the member functions
322    // is static, in which case they are not overloads (C++
323    // 13.1p2). While not part of the definition of the signature,
324    // this check is important to determine whether these functions
325    // can be overloaded.
326    CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
327    CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
328    if (OldMethod && NewMethod &&
329        !OldMethod->isStatic() && !NewMethod->isStatic() &&
330        OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
331      return true;
332
333    // The signatures match; this is not an overload.
334    return false;
335  } else {
336    // (C++ 13p1):
337    //   Only function declarations can be overloaded; object and type
338    //   declarations cannot be overloaded.
339    return false;
340  }
341}
342
343/// TryImplicitConversion - Attempt to perform an implicit conversion
344/// from the given expression (Expr) to the given type (ToType). This
345/// function returns an implicit conversion sequence that can be used
346/// to perform the initialization. Given
347///
348///   void f(float f);
349///   void g(int i) { f(i); }
350///
351/// this routine would produce an implicit conversion sequence to
352/// describe the initialization of f from i, which will be a standard
353/// conversion sequence containing an lvalue-to-rvalue conversion (C++
354/// 4.1) followed by a floating-integral conversion (C++ 4.9).
355//
356/// Note that this routine only determines how the conversion can be
357/// performed; it does not actually perform the conversion. As such,
358/// it will not produce any diagnostics if no conversion is available,
359/// but will instead return an implicit conversion sequence of kind
360/// "BadConversion".
361///
362/// If @p SuppressUserConversions, then user-defined conversions are
363/// not permitted.
364/// If @p AllowExplicit, then explicit user-defined conversions are
365/// permitted.
366ImplicitConversionSequence
367Sema::TryImplicitConversion(Expr* From, QualType ToType,
368                            bool SuppressUserConversions,
369                            bool AllowExplict)
370{
371  ImplicitConversionSequence ICS;
372  if (IsStandardConversion(From, ToType, ICS.Standard))
373    ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
374  else if (!SuppressUserConversions &&
375           IsUserDefinedConversion(From, ToType, ICS.UserDefined, AllowExplict)) {
376    ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
377    // C++ [over.ics.user]p4:
378    //   A conversion of an expression of class type to the same class
379    //   type is given Exact Match rank, and a conversion of an
380    //   expression of class type to a base class of that type is
381    //   given Conversion rank, in spite of the fact that a copy
382    //   constructor (i.e., a user-defined conversion function) is
383    //   called for those cases.
384    if (CXXConstructorDecl *Constructor
385          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
386      if (Constructor->isCopyConstructor(Context)) {
387        // Turn this into a "standard" conversion sequence, so that it
388        // gets ranked with standard conversion sequences.
389        ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
390        ICS.Standard.setAsIdentityConversion();
391        ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
392        ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
393        ICS.Standard.CopyConstructor = Constructor;
394        if (IsDerivedFrom(From->getType().getUnqualifiedType(),
395                          ToType.getUnqualifiedType()))
396          ICS.Standard.Second = ICK_Derived_To_Base;
397      }
398    }
399  } else
400    ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
401
402  return ICS;
403}
404
405/// IsStandardConversion - Determines whether there is a standard
406/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
407/// expression From to the type ToType. Standard conversion sequences
408/// only consider non-class types; for conversions that involve class
409/// types, use TryImplicitConversion. If a conversion exists, SCS will
410/// contain the standard conversion sequence required to perform this
411/// conversion and this routine will return true. Otherwise, this
412/// routine will return false and the value of SCS is unspecified.
413bool
414Sema::IsStandardConversion(Expr* From, QualType ToType,
415                           StandardConversionSequence &SCS)
416{
417  QualType FromType = From->getType();
418
419  // There are no standard conversions for class types, so abort early.
420  if (FromType->isRecordType() || ToType->isRecordType())
421    return false;
422
423  // Standard conversions (C++ [conv])
424  SCS.setAsIdentityConversion();
425  SCS.Deprecated = false;
426  SCS.IncompatibleObjC = false;
427  SCS.FromTypePtr = FromType.getAsOpaquePtr();
428  SCS.CopyConstructor = 0;
429
430  // The first conversion can be an lvalue-to-rvalue conversion,
431  // array-to-pointer conversion, or function-to-pointer conversion
432  // (C++ 4p1).
433
434  // Lvalue-to-rvalue conversion (C++ 4.1):
435  //   An lvalue (3.10) of a non-function, non-array type T can be
436  //   converted to an rvalue.
437  Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
438  if (argIsLvalue == Expr::LV_Valid &&
439      !FromType->isFunctionType() && !FromType->isArrayType() &&
440      !FromType->isOverloadType()) {
441    SCS.First = ICK_Lvalue_To_Rvalue;
442
443    // If T is a non-class type, the type of the rvalue is the
444    // cv-unqualified version of T. Otherwise, the type of the rvalue
445    // is T (C++ 4.1p1).
446    FromType = FromType.getUnqualifiedType();
447  }
448  // Array-to-pointer conversion (C++ 4.2)
449  else if (FromType->isArrayType()) {
450    SCS.First = ICK_Array_To_Pointer;
451
452    // An lvalue or rvalue of type "array of N T" or "array of unknown
453    // bound of T" can be converted to an rvalue of type "pointer to
454    // T" (C++ 4.2p1).
455    FromType = Context.getArrayDecayedType(FromType);
456
457    if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
458      // This conversion is deprecated. (C++ D.4).
459      SCS.Deprecated = true;
460
461      // For the purpose of ranking in overload resolution
462      // (13.3.3.1.1), this conversion is considered an
463      // array-to-pointer conversion followed by a qualification
464      // conversion (4.4). (C++ 4.2p2)
465      SCS.Second = ICK_Identity;
466      SCS.Third = ICK_Qualification;
467      SCS.ToTypePtr = ToType.getAsOpaquePtr();
468      return true;
469    }
470  }
471  // Function-to-pointer conversion (C++ 4.3).
472  else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
473    SCS.First = ICK_Function_To_Pointer;
474
475    // An lvalue of function type T can be converted to an rvalue of
476    // type "pointer to T." The result is a pointer to the
477    // function. (C++ 4.3p1).
478    FromType = Context.getPointerType(FromType);
479  }
480  // Address of overloaded function (C++ [over.over]).
481  else if (FunctionDecl *Fn
482             = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
483    SCS.First = ICK_Function_To_Pointer;
484
485    // We were able to resolve the address of the overloaded function,
486    // so we can convert to the type of that function.
487    FromType = Fn->getType();
488    if (ToType->isReferenceType())
489      FromType = Context.getReferenceType(FromType);
490    else
491      FromType = Context.getPointerType(FromType);
492  }
493  // We don't require any conversions for the first step.
494  else {
495    SCS.First = ICK_Identity;
496  }
497
498  // The second conversion can be an integral promotion, floating
499  // point promotion, integral conversion, floating point conversion,
500  // floating-integral conversion, pointer conversion,
501  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
502  bool IncompatibleObjC = false;
503  if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
504      Context.getCanonicalType(ToType).getUnqualifiedType()) {
505    // The unqualified versions of the types are the same: there's no
506    // conversion to do.
507    SCS.Second = ICK_Identity;
508  }
509  // Integral promotion (C++ 4.5).
510  else if (IsIntegralPromotion(From, FromType, ToType)) {
511    SCS.Second = ICK_Integral_Promotion;
512    FromType = ToType.getUnqualifiedType();
513  }
514  // Floating point promotion (C++ 4.6).
515  else if (IsFloatingPointPromotion(FromType, ToType)) {
516    SCS.Second = ICK_Floating_Promotion;
517    FromType = ToType.getUnqualifiedType();
518  }
519  // Integral conversions (C++ 4.7).
520  // FIXME: isIntegralType shouldn't be true for enums in C++.
521  else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
522           (ToType->isIntegralType() && !ToType->isEnumeralType())) {
523    SCS.Second = ICK_Integral_Conversion;
524    FromType = ToType.getUnqualifiedType();
525  }
526  // Floating point conversions (C++ 4.8).
527  else if (FromType->isFloatingType() && ToType->isFloatingType()) {
528    SCS.Second = ICK_Floating_Conversion;
529    FromType = ToType.getUnqualifiedType();
530  }
531  // Floating-integral conversions (C++ 4.9).
532  // FIXME: isIntegralType shouldn't be true for enums in C++.
533  else if ((FromType->isFloatingType() &&
534            ToType->isIntegralType() && !ToType->isBooleanType() &&
535                                        !ToType->isEnumeralType()) ||
536           ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
537            ToType->isFloatingType())) {
538    SCS.Second = ICK_Floating_Integral;
539    FromType = ToType.getUnqualifiedType();
540  }
541  // Pointer conversions (C++ 4.10).
542  else if (IsPointerConversion(From, FromType, ToType, FromType,
543                               IncompatibleObjC)) {
544    SCS.Second = ICK_Pointer_Conversion;
545    SCS.IncompatibleObjC = IncompatibleObjC;
546  }
547  // Pointer to member conversions (4.11).
548  else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
549    SCS.Second = ICK_Pointer_Member;
550  }
551  // Boolean conversions (C++ 4.12).
552  else if (ToType->isBooleanType() &&
553           (FromType->isArithmeticType() ||
554            FromType->isEnumeralType() ||
555            FromType->isPointerType() ||
556            FromType->isBlockPointerType() ||
557            FromType->isMemberPointerType())) {
558    SCS.Second = ICK_Boolean_Conversion;
559    FromType = Context.BoolTy;
560  } else {
561    // No second conversion required.
562    SCS.Second = ICK_Identity;
563  }
564
565  QualType CanonFrom;
566  QualType CanonTo;
567  // The third conversion can be a qualification conversion (C++ 4p1).
568  if (IsQualificationConversion(FromType, ToType)) {
569    SCS.Third = ICK_Qualification;
570    FromType = ToType;
571    CanonFrom = Context.getCanonicalType(FromType);
572    CanonTo = Context.getCanonicalType(ToType);
573  } else {
574    // No conversion required
575    SCS.Third = ICK_Identity;
576
577    // C++ [over.best.ics]p6:
578    //   [...] Any difference in top-level cv-qualification is
579    //   subsumed by the initialization itself and does not constitute
580    //   a conversion. [...]
581    CanonFrom = Context.getCanonicalType(FromType);
582    CanonTo = Context.getCanonicalType(ToType);
583    if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
584        CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
585      FromType = ToType;
586      CanonFrom = CanonTo;
587    }
588  }
589
590  // If we have not converted the argument type to the parameter type,
591  // this is a bad conversion sequence.
592  if (CanonFrom != CanonTo)
593    return false;
594
595  SCS.ToTypePtr = FromType.getAsOpaquePtr();
596  return true;
597}
598
599/// IsIntegralPromotion - Determines whether the conversion from the
600/// expression From (whose potentially-adjusted type is FromType) to
601/// ToType is an integral promotion (C++ 4.5). If so, returns true and
602/// sets PromotedType to the promoted type.
603bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
604{
605  const BuiltinType *To = ToType->getAsBuiltinType();
606  // All integers are built-in.
607  if (!To) {
608    return false;
609  }
610
611  // An rvalue of type char, signed char, unsigned char, short int, or
612  // unsigned short int can be converted to an rvalue of type int if
613  // int can represent all the values of the source type; otherwise,
614  // the source rvalue can be converted to an rvalue of type unsigned
615  // int (C++ 4.5p1).
616  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
617    if (// We can promote any signed, promotable integer type to an int
618        (FromType->isSignedIntegerType() ||
619         // We can promote any unsigned integer type whose size is
620         // less than int to an int.
621         (!FromType->isSignedIntegerType() &&
622          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
623      return To->getKind() == BuiltinType::Int;
624    }
625
626    return To->getKind() == BuiltinType::UInt;
627  }
628
629  // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
630  // can be converted to an rvalue of the first of the following types
631  // that can represent all the values of its underlying type: int,
632  // unsigned int, long, or unsigned long (C++ 4.5p2).
633  if ((FromType->isEnumeralType() || FromType->isWideCharType())
634      && ToType->isIntegerType()) {
635    // Determine whether the type we're converting from is signed or
636    // unsigned.
637    bool FromIsSigned;
638    uint64_t FromSize = Context.getTypeSize(FromType);
639    if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
640      QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
641      FromIsSigned = UnderlyingType->isSignedIntegerType();
642    } else {
643      // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
644      FromIsSigned = true;
645    }
646
647    // The types we'll try to promote to, in the appropriate
648    // order. Try each of these types.
649    QualType PromoteTypes[6] = {
650      Context.IntTy, Context.UnsignedIntTy,
651      Context.LongTy, Context.UnsignedLongTy ,
652      Context.LongLongTy, Context.UnsignedLongLongTy
653    };
654    for (int Idx = 0; Idx < 6; ++Idx) {
655      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
656      if (FromSize < ToSize ||
657          (FromSize == ToSize &&
658           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
659        // We found the type that we can promote to. If this is the
660        // type we wanted, we have a promotion. Otherwise, no
661        // promotion.
662        return Context.getCanonicalType(ToType).getUnqualifiedType()
663          == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
664      }
665    }
666  }
667
668  // An rvalue for an integral bit-field (9.6) can be converted to an
669  // rvalue of type int if int can represent all the values of the
670  // bit-field; otherwise, it can be converted to unsigned int if
671  // unsigned int can represent all the values of the bit-field. If
672  // the bit-field is larger yet, no integral promotion applies to
673  // it. If the bit-field has an enumerated type, it is treated as any
674  // other value of that type for promotion purposes (C++ 4.5p3).
675  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
676    using llvm::APSInt;
677    if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) {
678      APSInt BitWidth;
679      if (MemberDecl->isBitField() &&
680          FromType->isIntegralType() && !FromType->isEnumeralType() &&
681          From->isIntegerConstantExpr(BitWidth, Context)) {
682        APSInt ToSize(Context.getTypeSize(ToType));
683
684        // Are we promoting to an int from a bitfield that fits in an int?
685        if (BitWidth < ToSize ||
686            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
687          return To->getKind() == BuiltinType::Int;
688        }
689
690        // Are we promoting to an unsigned int from an unsigned bitfield
691        // that fits into an unsigned int?
692        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
693          return To->getKind() == BuiltinType::UInt;
694        }
695
696        return false;
697      }
698    }
699  }
700
701  // An rvalue of type bool can be converted to an rvalue of type int,
702  // with false becoming zero and true becoming one (C++ 4.5p4).
703  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
704    return true;
705  }
706
707  return false;
708}
709
710/// IsFloatingPointPromotion - Determines whether the conversion from
711/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
712/// returns true and sets PromotedType to the promoted type.
713bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
714{
715  /// An rvalue of type float can be converted to an rvalue of type
716  /// double. (C++ 4.6p1).
717  if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
718    if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
719      if (FromBuiltin->getKind() == BuiltinType::Float &&
720          ToBuiltin->getKind() == BuiltinType::Double)
721        return true;
722
723  return false;
724}
725
726/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
727/// the pointer type FromPtr to a pointer to type ToPointee, with the
728/// same type qualifiers as FromPtr has on its pointee type. ToType,
729/// if non-empty, will be a pointer to ToType that may or may not have
730/// the right set of qualifiers on its pointee.
731static QualType
732BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
733                                   QualType ToPointee, QualType ToType,
734                                   ASTContext &Context) {
735  QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
736  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
737  unsigned Quals = CanonFromPointee.getCVRQualifiers();
738
739  // Exact qualifier match -> return the pointer type we're converting to.
740  if (CanonToPointee.getCVRQualifiers() == Quals) {
741    // ToType is exactly what we need. Return it.
742    if (ToType.getTypePtr())
743      return ToType;
744
745    // Build a pointer to ToPointee. It has the right qualifiers
746    // already.
747    return Context.getPointerType(ToPointee);
748  }
749
750  // Just build a canonical type that has the right qualifiers.
751  return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
752}
753
754/// IsPointerConversion - Determines whether the conversion of the
755/// expression From, which has the (possibly adjusted) type FromType,
756/// can be converted to the type ToType via a pointer conversion (C++
757/// 4.10). If so, returns true and places the converted type (that
758/// might differ from ToType in its cv-qualifiers at some level) into
759/// ConvertedType.
760///
761/// This routine also supports conversions to and from block pointers
762/// and conversions with Objective-C's 'id', 'id<protocols...>', and
763/// pointers to interfaces. FIXME: Once we've determined the
764/// appropriate overloading rules for Objective-C, we may want to
765/// split the Objective-C checks into a different routine; however,
766/// GCC seems to consider all of these conversions to be pointer
767/// conversions, so for now they live here. IncompatibleObjC will be
768/// set if the conversion is an allowed Objective-C conversion that
769/// should result in a warning.
770bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
771                               QualType& ConvertedType,
772                               bool &IncompatibleObjC)
773{
774  IncompatibleObjC = false;
775  if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
776    return true;
777
778  // Conversion from a null pointer constant to any Objective-C pointer type.
779  if (Context.isObjCObjectPointerType(ToType) &&
780      From->isNullPointerConstant(Context)) {
781    ConvertedType = ToType;
782    return true;
783  }
784
785  // Blocks: Block pointers can be converted to void*.
786  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
787      ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
788    ConvertedType = ToType;
789    return true;
790  }
791  // Blocks: A null pointer constant can be converted to a block
792  // pointer type.
793  if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
794    ConvertedType = ToType;
795    return true;
796  }
797
798  const PointerType* ToTypePtr = ToType->getAsPointerType();
799  if (!ToTypePtr)
800    return false;
801
802  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
803  if (From->isNullPointerConstant(Context)) {
804    ConvertedType = ToType;
805    return true;
806  }
807
808  // Beyond this point, both types need to be pointers.
809  const PointerType *FromTypePtr = FromType->getAsPointerType();
810  if (!FromTypePtr)
811    return false;
812
813  QualType FromPointeeType = FromTypePtr->getPointeeType();
814  QualType ToPointeeType = ToTypePtr->getPointeeType();
815
816  // An rvalue of type "pointer to cv T," where T is an object type,
817  // can be converted to an rvalue of type "pointer to cv void" (C++
818  // 4.10p2).
819  if (FromPointeeType->isIncompleteOrObjectType() &&
820      ToPointeeType->isVoidType()) {
821    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
822                                                       ToPointeeType,
823                                                       ToType, Context);
824    return true;
825  }
826
827  // C++ [conv.ptr]p3:
828  //
829  //   An rvalue of type "pointer to cv D," where D is a class type,
830  //   can be converted to an rvalue of type "pointer to cv B," where
831  //   B is a base class (clause 10) of D. If B is an inaccessible
832  //   (clause 11) or ambiguous (10.2) base class of D, a program that
833  //   necessitates this conversion is ill-formed. The result of the
834  //   conversion is a pointer to the base class sub-object of the
835  //   derived class object. The null pointer value is converted to
836  //   the null pointer value of the destination type.
837  //
838  // Note that we do not check for ambiguity or inaccessibility
839  // here. That is handled by CheckPointerConversion.
840  if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
841      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
842    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
843                                                       ToPointeeType,
844                                                       ToType, Context);
845    return true;
846  }
847
848  return false;
849}
850
851/// isObjCPointerConversion - Determines whether this is an
852/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
853/// with the same arguments and return values.
854bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
855                                   QualType& ConvertedType,
856                                   bool &IncompatibleObjC) {
857  if (!getLangOptions().ObjC1)
858    return false;
859
860  // Conversions with Objective-C's id<...>.
861  if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
862      ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
863    ConvertedType = ToType;
864    return true;
865  }
866
867  // Beyond this point, both types need to be pointers or block pointers.
868  QualType ToPointeeType;
869  const PointerType* ToTypePtr = ToType->getAsPointerType();
870  if (ToTypePtr)
871    ToPointeeType = ToTypePtr->getPointeeType();
872  else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
873    ToPointeeType = ToBlockPtr->getPointeeType();
874  else
875    return false;
876
877  QualType FromPointeeType;
878  const PointerType *FromTypePtr = FromType->getAsPointerType();
879  if (FromTypePtr)
880    FromPointeeType = FromTypePtr->getPointeeType();
881  else if (const BlockPointerType *FromBlockPtr
882             = FromType->getAsBlockPointerType())
883    FromPointeeType = FromBlockPtr->getPointeeType();
884  else
885    return false;
886
887  // Objective C++: We're able to convert from a pointer to an
888  // interface to a pointer to a different interface.
889  const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
890  const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
891  if (FromIface && ToIface &&
892      Context.canAssignObjCInterfaces(ToIface, FromIface)) {
893    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
894                                                       ToPointeeType,
895                                                       ToType, Context);
896    return true;
897  }
898
899  if (FromIface && ToIface &&
900      Context.canAssignObjCInterfaces(FromIface, ToIface)) {
901    // Okay: this is some kind of implicit downcast of Objective-C
902    // interfaces, which is permitted. However, we're going to
903    // complain about it.
904    IncompatibleObjC = true;
905    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
906                                                       ToPointeeType,
907                                                       ToType, Context);
908    return true;
909  }
910
911  // Objective C++: We're able to convert between "id" and a pointer
912  // to any interface (in both directions).
913  if ((FromIface && Context.isObjCIdType(ToPointeeType))
914      || (ToIface && Context.isObjCIdType(FromPointeeType))) {
915    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
916                                                       ToPointeeType,
917                                                       ToType, Context);
918    return true;
919  }
920
921  // Objective C++: Allow conversions between the Objective-C "id" and
922  // "Class", in either direction.
923  if ((Context.isObjCIdType(FromPointeeType) &&
924       Context.isObjCClassType(ToPointeeType)) ||
925      (Context.isObjCClassType(FromPointeeType) &&
926       Context.isObjCIdType(ToPointeeType))) {
927    ConvertedType = ToType;
928    return true;
929  }
930
931  // If we have pointers to pointers, recursively check whether this
932  // is an Objective-C conversion.
933  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
934      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
935                              IncompatibleObjC)) {
936    // We always complain about this conversion.
937    IncompatibleObjC = true;
938    ConvertedType = ToType;
939    return true;
940  }
941
942  // If we have pointers to functions or blocks, check whether the only
943  // differences in the argument and result types are in Objective-C
944  // pointer conversions. If so, we permit the conversion (but
945  // complain about it).
946  const FunctionTypeProto *FromFunctionType
947    = FromPointeeType->getAsFunctionTypeProto();
948  const FunctionTypeProto *ToFunctionType
949    = ToPointeeType->getAsFunctionTypeProto();
950  if (FromFunctionType && ToFunctionType) {
951    // If the function types are exactly the same, this isn't an
952    // Objective-C pointer conversion.
953    if (Context.getCanonicalType(FromPointeeType)
954          == Context.getCanonicalType(ToPointeeType))
955      return false;
956
957    // Perform the quick checks that will tell us whether these
958    // function types are obviously different.
959    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
960        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
961        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
962      return false;
963
964    bool HasObjCConversion = false;
965    if (Context.getCanonicalType(FromFunctionType->getResultType())
966          == Context.getCanonicalType(ToFunctionType->getResultType())) {
967      // Okay, the types match exactly. Nothing to do.
968    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
969                                       ToFunctionType->getResultType(),
970                                       ConvertedType, IncompatibleObjC)) {
971      // Okay, we have an Objective-C pointer conversion.
972      HasObjCConversion = true;
973    } else {
974      // Function types are too different. Abort.
975      return false;
976    }
977
978    // Check argument types.
979    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
980         ArgIdx != NumArgs; ++ArgIdx) {
981      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
982      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
983      if (Context.getCanonicalType(FromArgType)
984            == Context.getCanonicalType(ToArgType)) {
985        // Okay, the types match exactly. Nothing to do.
986      } else if (isObjCPointerConversion(FromArgType, ToArgType,
987                                         ConvertedType, IncompatibleObjC)) {
988        // Okay, we have an Objective-C pointer conversion.
989        HasObjCConversion = true;
990      } else {
991        // Argument types are too different. Abort.
992        return false;
993      }
994    }
995
996    if (HasObjCConversion) {
997      // We had an Objective-C conversion. Allow this pointer
998      // conversion, but complain about it.
999      ConvertedType = ToType;
1000      IncompatibleObjC = true;
1001      return true;
1002    }
1003  }
1004
1005  return false;
1006}
1007
1008/// CheckPointerConversion - Check the pointer conversion from the
1009/// expression From to the type ToType. This routine checks for
1010/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1011/// conversions for which IsPointerConversion has already returned
1012/// true. It returns true and produces a diagnostic if there was an
1013/// error, or returns false otherwise.
1014bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1015  QualType FromType = From->getType();
1016
1017  if (const PointerType *FromPtrType = FromType->getAsPointerType())
1018    if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
1019      QualType FromPointeeType = FromPtrType->getPointeeType(),
1020               ToPointeeType   = ToPtrType->getPointeeType();
1021
1022      // Objective-C++ conversions are always okay.
1023      // FIXME: We should have a different class of conversions for
1024      // the Objective-C++ implicit conversions.
1025      if (Context.isObjCIdType(FromPointeeType) ||
1026          Context.isObjCIdType(ToPointeeType) ||
1027          Context.isObjCClassType(FromPointeeType) ||
1028          Context.isObjCClassType(ToPointeeType))
1029        return false;
1030
1031      if (FromPointeeType->isRecordType() &&
1032          ToPointeeType->isRecordType()) {
1033        // We must have a derived-to-base conversion. Check an
1034        // ambiguous or inaccessible conversion.
1035        return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1036                                            From->getExprLoc(),
1037                                            From->getSourceRange());
1038      }
1039    }
1040
1041  return false;
1042}
1043
1044/// IsMemberPointerConversion - Determines whether the conversion of the
1045/// expression From, which has the (possibly adjusted) type FromType, can be
1046/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1047/// If so, returns true and places the converted type (that might differ from
1048/// ToType in its cv-qualifiers at some level) into ConvertedType.
1049bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1050                                     QualType ToType, QualType &ConvertedType)
1051{
1052  const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1053  if (!ToTypePtr)
1054    return false;
1055
1056  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1057  if (From->isNullPointerConstant(Context)) {
1058    ConvertedType = ToType;
1059    return true;
1060  }
1061
1062  // Otherwise, both types have to be member pointers.
1063  const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1064  if (!FromTypePtr)
1065    return false;
1066
1067  // A pointer to member of B can be converted to a pointer to member of D,
1068  // where D is derived from B (C++ 4.11p2).
1069  QualType FromClass(FromTypePtr->getClass(), 0);
1070  QualType ToClass(ToTypePtr->getClass(), 0);
1071  // FIXME: What happens when these are dependent? Is this function even called?
1072
1073  if (IsDerivedFrom(ToClass, FromClass)) {
1074    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1075                                                 ToClass.getTypePtr());
1076    return true;
1077  }
1078
1079  return false;
1080}
1081
1082/// CheckMemberPointerConversion - Check the member pointer conversion from the
1083/// expression From to the type ToType. This routine checks for ambiguous or
1084/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1085/// for which IsMemberPointerConversion has already returned true. It returns
1086/// true and produces a diagnostic if there was an error, or returns false
1087/// otherwise.
1088bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1089  QualType FromType = From->getType();
1090  const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1091  if (!FromPtrType)
1092    return false;
1093
1094  const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1095  assert(ToPtrType && "No member pointer cast has a target type "
1096                      "that is not a member pointer.");
1097
1098  QualType FromClass = QualType(FromPtrType->getClass(), 0);
1099  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
1100
1101  // FIXME: What about dependent types?
1102  assert(FromClass->isRecordType() && "Pointer into non-class.");
1103  assert(ToClass->isRecordType() && "Pointer into non-class.");
1104
1105  BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1106                  /*DetectVirtual=*/true);
1107  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1108  assert(DerivationOkay &&
1109         "Should not have been called if derivation isn't OK.");
1110  (void)DerivationOkay;
1111
1112  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1113                                  getUnqualifiedType())) {
1114    // Derivation is ambiguous. Redo the check to find the exact paths.
1115    Paths.clear();
1116    Paths.setRecordingPaths(true);
1117    bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1118    assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1119    (void)StillOkay;
1120
1121    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1122    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1123      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1124    return true;
1125  }
1126
1127  if (const CXXRecordType *VBase = Paths.getDetectedVirtual()) {
1128    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1129      << FromClass << ToClass << QualType(VBase, 0)
1130      << From->getSourceRange();
1131    return true;
1132  }
1133
1134  return false;
1135}
1136
1137/// IsQualificationConversion - Determines whether the conversion from
1138/// an rvalue of type FromType to ToType is a qualification conversion
1139/// (C++ 4.4).
1140bool
1141Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1142{
1143  FromType = Context.getCanonicalType(FromType);
1144  ToType = Context.getCanonicalType(ToType);
1145
1146  // If FromType and ToType are the same type, this is not a
1147  // qualification conversion.
1148  if (FromType == ToType)
1149    return false;
1150
1151  // (C++ 4.4p4):
1152  //   A conversion can add cv-qualifiers at levels other than the first
1153  //   in multi-level pointers, subject to the following rules: [...]
1154  bool PreviousToQualsIncludeConst = true;
1155  bool UnwrappedAnyPointer = false;
1156  while (UnwrapSimilarPointerTypes(FromType, ToType)) {
1157    // Within each iteration of the loop, we check the qualifiers to
1158    // determine if this still looks like a qualification
1159    // conversion. Then, if all is well, we unwrap one more level of
1160    // pointers or pointers-to-members and do it all again
1161    // until there are no more pointers or pointers-to-members left to
1162    // unwrap.
1163    UnwrappedAnyPointer = true;
1164
1165    //   -- for every j > 0, if const is in cv 1,j then const is in cv
1166    //      2,j, and similarly for volatile.
1167    if (!ToType.isAtLeastAsQualifiedAs(FromType))
1168      return false;
1169
1170    //   -- if the cv 1,j and cv 2,j are different, then const is in
1171    //      every cv for 0 < k < j.
1172    if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
1173        && !PreviousToQualsIncludeConst)
1174      return false;
1175
1176    // Keep track of whether all prior cv-qualifiers in the "to" type
1177    // include const.
1178    PreviousToQualsIncludeConst
1179      = PreviousToQualsIncludeConst && ToType.isConstQualified();
1180  }
1181
1182  // We are left with FromType and ToType being the pointee types
1183  // after unwrapping the original FromType and ToType the same number
1184  // of types. If we unwrapped any pointers, and if FromType and
1185  // ToType have the same unqualified type (since we checked
1186  // qualifiers above), then this is a qualification conversion.
1187  return UnwrappedAnyPointer &&
1188    FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1189}
1190
1191/// IsUserDefinedConversion - Determines whether there is a
1192/// user-defined conversion sequence (C++ [over.ics.user]) that
1193/// converts expression From to the type ToType. If such a conversion
1194/// exists, User will contain the user-defined conversion sequence
1195/// that performs such a conversion and this routine will return
1196/// true. Otherwise, this routine returns false and User is
1197/// unspecified. AllowExplicit is true if the conversion should
1198/// consider C++0x "explicit" conversion functions as well as
1199/// non-explicit conversion functions (C++0x [class.conv.fct]p2).
1200bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1201                                   UserDefinedConversionSequence& User,
1202                                   bool AllowExplicit)
1203{
1204  OverloadCandidateSet CandidateSet;
1205  if (const CXXRecordType *ToRecordType
1206        = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
1207    // C++ [over.match.ctor]p1:
1208    //   When objects of class type are direct-initialized (8.5), or
1209    //   copy-initialized from an expression of the same or a
1210    //   derived class type (8.5), overload resolution selects the
1211    //   constructor. [...] For copy-initialization, the candidate
1212    //   functions are all the converting constructors (12.3.1) of
1213    //   that class. The argument list is the expression-list within
1214    //   the parentheses of the initializer.
1215    CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
1216    DeclarationName ConstructorName
1217      = Context.DeclarationNames.getCXXConstructorName(
1218                        Context.getCanonicalType(ToType).getUnqualifiedType());
1219    DeclContext::lookup_iterator Con, ConEnd;
1220    for (llvm::tie(Con, ConEnd) = ToRecordDecl->lookup(ConstructorName);
1221         Con != ConEnd; ++Con) {
1222      CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1223      if (Constructor->isConvertingConstructor())
1224        AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1225                             /*SuppressUserConversions=*/true);
1226    }
1227  }
1228
1229  if (const CXXRecordType *FromRecordType
1230        = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) {
1231    // Add all of the conversion functions as candidates.
1232    // FIXME: Look for conversions in base classes!
1233    CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
1234    OverloadedFunctionDecl *Conversions
1235      = FromRecordDecl->getConversionFunctions();
1236    for (OverloadedFunctionDecl::function_iterator Func
1237           = Conversions->function_begin();
1238         Func != Conversions->function_end(); ++Func) {
1239      CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1240      if (AllowExplicit || !Conv->isExplicit())
1241        AddConversionCandidate(Conv, From, ToType, CandidateSet);
1242    }
1243  }
1244
1245  OverloadCandidateSet::iterator Best;
1246  switch (BestViableFunction(CandidateSet, Best)) {
1247    case OR_Success:
1248      // Record the standard conversion we used and the conversion function.
1249      if (CXXConstructorDecl *Constructor
1250            = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1251        // C++ [over.ics.user]p1:
1252        //   If the user-defined conversion is specified by a
1253        //   constructor (12.3.1), the initial standard conversion
1254        //   sequence converts the source type to the type required by
1255        //   the argument of the constructor.
1256        //
1257        // FIXME: What about ellipsis conversions?
1258        QualType ThisType = Constructor->getThisType(Context);
1259        User.Before = Best->Conversions[0].Standard;
1260        User.ConversionFunction = Constructor;
1261        User.After.setAsIdentityConversion();
1262        User.After.FromTypePtr
1263          = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1264        User.After.ToTypePtr = ToType.getAsOpaquePtr();
1265        return true;
1266      } else if (CXXConversionDecl *Conversion
1267                   = dyn_cast<CXXConversionDecl>(Best->Function)) {
1268        // C++ [over.ics.user]p1:
1269        //
1270        //   [...] If the user-defined conversion is specified by a
1271        //   conversion function (12.3.2), the initial standard
1272        //   conversion sequence converts the source type to the
1273        //   implicit object parameter of the conversion function.
1274        User.Before = Best->Conversions[0].Standard;
1275        User.ConversionFunction = Conversion;
1276
1277        // C++ [over.ics.user]p2:
1278        //   The second standard conversion sequence converts the
1279        //   result of the user-defined conversion to the target type
1280        //   for the sequence. Since an implicit conversion sequence
1281        //   is an initialization, the special rules for
1282        //   initialization by user-defined conversion apply when
1283        //   selecting the best user-defined conversion for a
1284        //   user-defined conversion sequence (see 13.3.3 and
1285        //   13.3.3.1).
1286        User.After = Best->FinalConversion;
1287        return true;
1288      } else {
1289        assert(false && "Not a constructor or conversion function?");
1290        return false;
1291      }
1292
1293    case OR_No_Viable_Function:
1294      // No conversion here! We're done.
1295      return false;
1296
1297    case OR_Ambiguous:
1298      // FIXME: See C++ [over.best.ics]p10 for the handling of
1299      // ambiguous conversion sequences.
1300      return false;
1301    }
1302
1303  return false;
1304}
1305
1306/// CompareImplicitConversionSequences - Compare two implicit
1307/// conversion sequences to determine whether one is better than the
1308/// other or if they are indistinguishable (C++ 13.3.3.2).
1309ImplicitConversionSequence::CompareKind
1310Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1311                                         const ImplicitConversionSequence& ICS2)
1312{
1313  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1314  // conversion sequences (as defined in 13.3.3.1)
1315  //   -- a standard conversion sequence (13.3.3.1.1) is a better
1316  //      conversion sequence than a user-defined conversion sequence or
1317  //      an ellipsis conversion sequence, and
1318  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
1319  //      conversion sequence than an ellipsis conversion sequence
1320  //      (13.3.3.1.3).
1321  //
1322  if (ICS1.ConversionKind < ICS2.ConversionKind)
1323    return ImplicitConversionSequence::Better;
1324  else if (ICS2.ConversionKind < ICS1.ConversionKind)
1325    return ImplicitConversionSequence::Worse;
1326
1327  // Two implicit conversion sequences of the same form are
1328  // indistinguishable conversion sequences unless one of the
1329  // following rules apply: (C++ 13.3.3.2p3):
1330  if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1331    return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1332  else if (ICS1.ConversionKind ==
1333             ImplicitConversionSequence::UserDefinedConversion) {
1334    // User-defined conversion sequence U1 is a better conversion
1335    // sequence than another user-defined conversion sequence U2 if
1336    // they contain the same user-defined conversion function or
1337    // constructor and if the second standard conversion sequence of
1338    // U1 is better than the second standard conversion sequence of
1339    // U2 (C++ 13.3.3.2p3).
1340    if (ICS1.UserDefined.ConversionFunction ==
1341          ICS2.UserDefined.ConversionFunction)
1342      return CompareStandardConversionSequences(ICS1.UserDefined.After,
1343                                                ICS2.UserDefined.After);
1344  }
1345
1346  return ImplicitConversionSequence::Indistinguishable;
1347}
1348
1349/// CompareStandardConversionSequences - Compare two standard
1350/// conversion sequences to determine whether one is better than the
1351/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1352ImplicitConversionSequence::CompareKind
1353Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1354                                         const StandardConversionSequence& SCS2)
1355{
1356  // Standard conversion sequence S1 is a better conversion sequence
1357  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1358
1359  //  -- S1 is a proper subsequence of S2 (comparing the conversion
1360  //     sequences in the canonical form defined by 13.3.3.1.1,
1361  //     excluding any Lvalue Transformation; the identity conversion
1362  //     sequence is considered to be a subsequence of any
1363  //     non-identity conversion sequence) or, if not that,
1364  if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1365    // Neither is a proper subsequence of the other. Do nothing.
1366    ;
1367  else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1368           (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1369           (SCS1.Second == ICK_Identity &&
1370            SCS1.Third == ICK_Identity))
1371    // SCS1 is a proper subsequence of SCS2.
1372    return ImplicitConversionSequence::Better;
1373  else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1374           (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1375           (SCS2.Second == ICK_Identity &&
1376            SCS2.Third == ICK_Identity))
1377    // SCS2 is a proper subsequence of SCS1.
1378    return ImplicitConversionSequence::Worse;
1379
1380  //  -- the rank of S1 is better than the rank of S2 (by the rules
1381  //     defined below), or, if not that,
1382  ImplicitConversionRank Rank1 = SCS1.getRank();
1383  ImplicitConversionRank Rank2 = SCS2.getRank();
1384  if (Rank1 < Rank2)
1385    return ImplicitConversionSequence::Better;
1386  else if (Rank2 < Rank1)
1387    return ImplicitConversionSequence::Worse;
1388
1389  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1390  // are indistinguishable unless one of the following rules
1391  // applies:
1392
1393  //   A conversion that is not a conversion of a pointer, or
1394  //   pointer to member, to bool is better than another conversion
1395  //   that is such a conversion.
1396  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1397    return SCS2.isPointerConversionToBool()
1398             ? ImplicitConversionSequence::Better
1399             : ImplicitConversionSequence::Worse;
1400
1401  // C++ [over.ics.rank]p4b2:
1402  //
1403  //   If class B is derived directly or indirectly from class A,
1404  //   conversion of B* to A* is better than conversion of B* to
1405  //   void*, and conversion of A* to void* is better than conversion
1406  //   of B* to void*.
1407  bool SCS1ConvertsToVoid
1408    = SCS1.isPointerConversionToVoidPointer(Context);
1409  bool SCS2ConvertsToVoid
1410    = SCS2.isPointerConversionToVoidPointer(Context);
1411  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1412    // Exactly one of the conversion sequences is a conversion to
1413    // a void pointer; it's the worse conversion.
1414    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1415                              : ImplicitConversionSequence::Worse;
1416  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1417    // Neither conversion sequence converts to a void pointer; compare
1418    // their derived-to-base conversions.
1419    if (ImplicitConversionSequence::CompareKind DerivedCK
1420          = CompareDerivedToBaseConversions(SCS1, SCS2))
1421      return DerivedCK;
1422  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1423    // Both conversion sequences are conversions to void
1424    // pointers. Compare the source types to determine if there's an
1425    // inheritance relationship in their sources.
1426    QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1427    QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1428
1429    // Adjust the types we're converting from via the array-to-pointer
1430    // conversion, if we need to.
1431    if (SCS1.First == ICK_Array_To_Pointer)
1432      FromType1 = Context.getArrayDecayedType(FromType1);
1433    if (SCS2.First == ICK_Array_To_Pointer)
1434      FromType2 = Context.getArrayDecayedType(FromType2);
1435
1436    QualType FromPointee1
1437      = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1438    QualType FromPointee2
1439      = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1440
1441    if (IsDerivedFrom(FromPointee2, FromPointee1))
1442      return ImplicitConversionSequence::Better;
1443    else if (IsDerivedFrom(FromPointee1, FromPointee2))
1444      return ImplicitConversionSequence::Worse;
1445
1446    // Objective-C++: If one interface is more specific than the
1447    // other, it is the better one.
1448    const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1449    const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1450    if (FromIface1 && FromIface1) {
1451      if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1452        return ImplicitConversionSequence::Better;
1453      else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1454        return ImplicitConversionSequence::Worse;
1455    }
1456  }
1457
1458  // Compare based on qualification conversions (C++ 13.3.3.2p3,
1459  // bullet 3).
1460  if (ImplicitConversionSequence::CompareKind QualCK
1461        = CompareQualificationConversions(SCS1, SCS2))
1462    return QualCK;
1463
1464  // C++ [over.ics.rank]p3b4:
1465  //   -- S1 and S2 are reference bindings (8.5.3), and the types to
1466  //      which the references refer are the same type except for
1467  //      top-level cv-qualifiers, and the type to which the reference
1468  //      initialized by S2 refers is more cv-qualified than the type
1469  //      to which the reference initialized by S1 refers.
1470  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1471    QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1472    QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1473    T1 = Context.getCanonicalType(T1);
1474    T2 = Context.getCanonicalType(T2);
1475    if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1476      if (T2.isMoreQualifiedThan(T1))
1477        return ImplicitConversionSequence::Better;
1478      else if (T1.isMoreQualifiedThan(T2))
1479        return ImplicitConversionSequence::Worse;
1480    }
1481  }
1482
1483  return ImplicitConversionSequence::Indistinguishable;
1484}
1485
1486/// CompareQualificationConversions - Compares two standard conversion
1487/// sequences to determine whether they can be ranked based on their
1488/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1489ImplicitConversionSequence::CompareKind
1490Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1491                                      const StandardConversionSequence& SCS2)
1492{
1493  // C++ 13.3.3.2p3:
1494  //  -- S1 and S2 differ only in their qualification conversion and
1495  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
1496  //     cv-qualification signature of type T1 is a proper subset of
1497  //     the cv-qualification signature of type T2, and S1 is not the
1498  //     deprecated string literal array-to-pointer conversion (4.2).
1499  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1500      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1501    return ImplicitConversionSequence::Indistinguishable;
1502
1503  // FIXME: the example in the standard doesn't use a qualification
1504  // conversion (!)
1505  QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1506  QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1507  T1 = Context.getCanonicalType(T1);
1508  T2 = Context.getCanonicalType(T2);
1509
1510  // If the types are the same, we won't learn anything by unwrapped
1511  // them.
1512  if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1513    return ImplicitConversionSequence::Indistinguishable;
1514
1515  ImplicitConversionSequence::CompareKind Result
1516    = ImplicitConversionSequence::Indistinguishable;
1517  while (UnwrapSimilarPointerTypes(T1, T2)) {
1518    // Within each iteration of the loop, we check the qualifiers to
1519    // determine if this still looks like a qualification
1520    // conversion. Then, if all is well, we unwrap one more level of
1521    // pointers or pointers-to-members and do it all again
1522    // until there are no more pointers or pointers-to-members left
1523    // to unwrap. This essentially mimics what
1524    // IsQualificationConversion does, but here we're checking for a
1525    // strict subset of qualifiers.
1526    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1527      // The qualifiers are the same, so this doesn't tell us anything
1528      // about how the sequences rank.
1529      ;
1530    else if (T2.isMoreQualifiedThan(T1)) {
1531      // T1 has fewer qualifiers, so it could be the better sequence.
1532      if (Result == ImplicitConversionSequence::Worse)
1533        // Neither has qualifiers that are a subset of the other's
1534        // qualifiers.
1535        return ImplicitConversionSequence::Indistinguishable;
1536
1537      Result = ImplicitConversionSequence::Better;
1538    } else if (T1.isMoreQualifiedThan(T2)) {
1539      // T2 has fewer qualifiers, so it could be the better sequence.
1540      if (Result == ImplicitConversionSequence::Better)
1541        // Neither has qualifiers that are a subset of the other's
1542        // qualifiers.
1543        return ImplicitConversionSequence::Indistinguishable;
1544
1545      Result = ImplicitConversionSequence::Worse;
1546    } else {
1547      // Qualifiers are disjoint.
1548      return ImplicitConversionSequence::Indistinguishable;
1549    }
1550
1551    // If the types after this point are equivalent, we're done.
1552    if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1553      break;
1554  }
1555
1556  // Check that the winning standard conversion sequence isn't using
1557  // the deprecated string literal array to pointer conversion.
1558  switch (Result) {
1559  case ImplicitConversionSequence::Better:
1560    if (SCS1.Deprecated)
1561      Result = ImplicitConversionSequence::Indistinguishable;
1562    break;
1563
1564  case ImplicitConversionSequence::Indistinguishable:
1565    break;
1566
1567  case ImplicitConversionSequence::Worse:
1568    if (SCS2.Deprecated)
1569      Result = ImplicitConversionSequence::Indistinguishable;
1570    break;
1571  }
1572
1573  return Result;
1574}
1575
1576/// CompareDerivedToBaseConversions - Compares two standard conversion
1577/// sequences to determine whether they can be ranked based on their
1578/// various kinds of derived-to-base conversions (C++
1579/// [over.ics.rank]p4b3).  As part of these checks, we also look at
1580/// conversions between Objective-C interface types.
1581ImplicitConversionSequence::CompareKind
1582Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1583                                      const StandardConversionSequence& SCS2) {
1584  QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1585  QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1586  QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1587  QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1588
1589  // Adjust the types we're converting from via the array-to-pointer
1590  // conversion, if we need to.
1591  if (SCS1.First == ICK_Array_To_Pointer)
1592    FromType1 = Context.getArrayDecayedType(FromType1);
1593  if (SCS2.First == ICK_Array_To_Pointer)
1594    FromType2 = Context.getArrayDecayedType(FromType2);
1595
1596  // Canonicalize all of the types.
1597  FromType1 = Context.getCanonicalType(FromType1);
1598  ToType1 = Context.getCanonicalType(ToType1);
1599  FromType2 = Context.getCanonicalType(FromType2);
1600  ToType2 = Context.getCanonicalType(ToType2);
1601
1602  // C++ [over.ics.rank]p4b3:
1603  //
1604  //   If class B is derived directly or indirectly from class A and
1605  //   class C is derived directly or indirectly from B,
1606  //
1607  // For Objective-C, we let A, B, and C also be Objective-C
1608  // interfaces.
1609
1610  // Compare based on pointer conversions.
1611  if (SCS1.Second == ICK_Pointer_Conversion &&
1612      SCS2.Second == ICK_Pointer_Conversion &&
1613      /*FIXME: Remove if Objective-C id conversions get their own rank*/
1614      FromType1->isPointerType() && FromType2->isPointerType() &&
1615      ToType1->isPointerType() && ToType2->isPointerType()) {
1616    QualType FromPointee1
1617      = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1618    QualType ToPointee1
1619      = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1620    QualType FromPointee2
1621      = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1622    QualType ToPointee2
1623      = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1624
1625    const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1626    const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1627    const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1628    const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1629
1630    //   -- conversion of C* to B* is better than conversion of C* to A*,
1631    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1632      if (IsDerivedFrom(ToPointee1, ToPointee2))
1633        return ImplicitConversionSequence::Better;
1634      else if (IsDerivedFrom(ToPointee2, ToPointee1))
1635        return ImplicitConversionSequence::Worse;
1636
1637      if (ToIface1 && ToIface2) {
1638        if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1639          return ImplicitConversionSequence::Better;
1640        else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1641          return ImplicitConversionSequence::Worse;
1642      }
1643    }
1644
1645    //   -- conversion of B* to A* is better than conversion of C* to A*,
1646    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1647      if (IsDerivedFrom(FromPointee2, FromPointee1))
1648        return ImplicitConversionSequence::Better;
1649      else if (IsDerivedFrom(FromPointee1, FromPointee2))
1650        return ImplicitConversionSequence::Worse;
1651
1652      if (FromIface1 && FromIface2) {
1653        if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1654          return ImplicitConversionSequence::Better;
1655        else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1656          return ImplicitConversionSequence::Worse;
1657      }
1658    }
1659  }
1660
1661  // Compare based on reference bindings.
1662  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1663      SCS1.Second == ICK_Derived_To_Base) {
1664    //   -- binding of an expression of type C to a reference of type
1665    //      B& is better than binding an expression of type C to a
1666    //      reference of type A&,
1667    if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1668        ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1669      if (IsDerivedFrom(ToType1, ToType2))
1670        return ImplicitConversionSequence::Better;
1671      else if (IsDerivedFrom(ToType2, ToType1))
1672        return ImplicitConversionSequence::Worse;
1673    }
1674
1675    //   -- binding of an expression of type B to a reference of type
1676    //      A& is better than binding an expression of type C to a
1677    //      reference of type A&,
1678    if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1679        ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1680      if (IsDerivedFrom(FromType2, FromType1))
1681        return ImplicitConversionSequence::Better;
1682      else if (IsDerivedFrom(FromType1, FromType2))
1683        return ImplicitConversionSequence::Worse;
1684    }
1685  }
1686
1687
1688  // FIXME: conversion of A::* to B::* is better than conversion of
1689  // A::* to C::*,
1690
1691  // FIXME: conversion of B::* to C::* is better than conversion of
1692  // A::* to C::*, and
1693
1694  if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1695      SCS1.Second == ICK_Derived_To_Base) {
1696    //   -- conversion of C to B is better than conversion of C to A,
1697    if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1698        ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1699      if (IsDerivedFrom(ToType1, ToType2))
1700        return ImplicitConversionSequence::Better;
1701      else if (IsDerivedFrom(ToType2, ToType1))
1702        return ImplicitConversionSequence::Worse;
1703    }
1704
1705    //   -- conversion of B to A is better than conversion of C to A.
1706    if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1707        ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1708      if (IsDerivedFrom(FromType2, FromType1))
1709        return ImplicitConversionSequence::Better;
1710      else if (IsDerivedFrom(FromType1, FromType2))
1711        return ImplicitConversionSequence::Worse;
1712    }
1713  }
1714
1715  return ImplicitConversionSequence::Indistinguishable;
1716}
1717
1718/// TryCopyInitialization - Try to copy-initialize a value of type
1719/// ToType from the expression From. Return the implicit conversion
1720/// sequence required to pass this argument, which may be a bad
1721/// conversion sequence (meaning that the argument cannot be passed to
1722/// a parameter of this type). If @p SuppressUserConversions, then we
1723/// do not permit any user-defined conversion sequences.
1724ImplicitConversionSequence
1725Sema::TryCopyInitialization(Expr *From, QualType ToType,
1726                            bool SuppressUserConversions) {
1727  if (!getLangOptions().CPlusPlus) {
1728    // In C, copy initialization is the same as performing an assignment.
1729    AssignConvertType ConvTy =
1730      CheckSingleAssignmentConstraints(ToType, From);
1731    ImplicitConversionSequence ICS;
1732    if (getLangOptions().NoExtensions? ConvTy != Compatible
1733                                     : ConvTy == Incompatible)
1734      ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1735    else
1736      ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1737    return ICS;
1738  } else if (ToType->isReferenceType()) {
1739    ImplicitConversionSequence ICS;
1740    CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
1741    return ICS;
1742  } else {
1743    return TryImplicitConversion(From, ToType, SuppressUserConversions);
1744  }
1745}
1746
1747/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1748/// type ToType. Returns true (and emits a diagnostic) if there was
1749/// an error, returns false if the initialization succeeded.
1750bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1751                                     const char* Flavor) {
1752  if (!getLangOptions().CPlusPlus) {
1753    // In C, argument passing is the same as performing an assignment.
1754    QualType FromType = From->getType();
1755    AssignConvertType ConvTy =
1756      CheckSingleAssignmentConstraints(ToType, From);
1757
1758    return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1759                                    FromType, From, Flavor);
1760  }
1761
1762  if (ToType->isReferenceType())
1763    return CheckReferenceInit(From, ToType);
1764
1765  if (!PerformImplicitConversion(From, ToType, Flavor))
1766    return false;
1767
1768  return Diag(From->getSourceRange().getBegin(),
1769              diag::err_typecheck_convert_incompatible)
1770    << ToType << From->getType() << Flavor << From->getSourceRange();
1771}
1772
1773/// TryObjectArgumentInitialization - Try to initialize the object
1774/// parameter of the given member function (@c Method) from the
1775/// expression @p From.
1776ImplicitConversionSequence
1777Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1778  QualType ClassType = Context.getTypeDeclType(Method->getParent());
1779  unsigned MethodQuals = Method->getTypeQualifiers();
1780  QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1781
1782  // Set up the conversion sequence as a "bad" conversion, to allow us
1783  // to exit early.
1784  ImplicitConversionSequence ICS;
1785  ICS.Standard.setAsIdentityConversion();
1786  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1787
1788  // We need to have an object of class type.
1789  QualType FromType = From->getType();
1790  if (!FromType->isRecordType())
1791    return ICS;
1792
1793  // The implicit object parmeter is has the type "reference to cv X",
1794  // where X is the class of which the function is a member
1795  // (C++ [over.match.funcs]p4). However, when finding an implicit
1796  // conversion sequence for the argument, we are not allowed to
1797  // create temporaries or perform user-defined conversions
1798  // (C++ [over.match.funcs]p5). We perform a simplified version of
1799  // reference binding here, that allows class rvalues to bind to
1800  // non-constant references.
1801
1802  // First check the qualifiers. We don't care about lvalue-vs-rvalue
1803  // with the implicit object parameter (C++ [over.match.funcs]p5).
1804  QualType FromTypeCanon = Context.getCanonicalType(FromType);
1805  if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1806      !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1807    return ICS;
1808
1809  // Check that we have either the same type or a derived type. It
1810  // affects the conversion rank.
1811  QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1812  if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1813    ICS.Standard.Second = ICK_Identity;
1814  else if (IsDerivedFrom(FromType, ClassType))
1815    ICS.Standard.Second = ICK_Derived_To_Base;
1816  else
1817    return ICS;
1818
1819  // Success. Mark this as a reference binding.
1820  ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1821  ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1822  ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1823  ICS.Standard.ReferenceBinding = true;
1824  ICS.Standard.DirectBinding = true;
1825  return ICS;
1826}
1827
1828/// PerformObjectArgumentInitialization - Perform initialization of
1829/// the implicit object parameter for the given Method with the given
1830/// expression.
1831bool
1832Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1833  QualType ImplicitParamType
1834    = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1835  ImplicitConversionSequence ICS
1836    = TryObjectArgumentInitialization(From, Method);
1837  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1838    return Diag(From->getSourceRange().getBegin(),
1839                diag::err_implicit_object_parameter_init)
1840       << ImplicitParamType << From->getType() << From->getSourceRange();
1841
1842  if (ICS.Standard.Second == ICK_Derived_To_Base &&
1843      CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1844                                   From->getSourceRange().getBegin(),
1845                                   From->getSourceRange()))
1846    return true;
1847
1848  ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1849  return false;
1850}
1851
1852/// TryContextuallyConvertToBool - Attempt to contextually convert the
1853/// expression From to bool (C++0x [conv]p3).
1854ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
1855  return TryImplicitConversion(From, Context.BoolTy, false, true);
1856}
1857
1858/// PerformContextuallyConvertToBool - Perform a contextual conversion
1859/// of the expression From to bool (C++0x [conv]p3).
1860bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
1861  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
1862  if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
1863    return false;
1864
1865  return Diag(From->getSourceRange().getBegin(),
1866              diag::err_typecheck_bool_condition)
1867    << From->getType() << From->getSourceRange();
1868}
1869
1870/// AddOverloadCandidate - Adds the given function to the set of
1871/// candidate functions, using the given function call arguments.  If
1872/// @p SuppressUserConversions, then don't allow user-defined
1873/// conversions via constructors or conversion operators.
1874void
1875Sema::AddOverloadCandidate(FunctionDecl *Function,
1876                           Expr **Args, unsigned NumArgs,
1877                           OverloadCandidateSet& CandidateSet,
1878                           bool SuppressUserConversions)
1879{
1880  const FunctionTypeProto* Proto
1881    = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1882  assert(Proto && "Functions without a prototype cannot be overloaded");
1883  assert(!isa<CXXConversionDecl>(Function) &&
1884         "Use AddConversionCandidate for conversion functions");
1885
1886  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
1887    // If we get here, it's because we're calling a member function
1888    // that is named without a member access expression (e.g.,
1889    // "this->f") that was either written explicitly or created
1890    // implicitly. This can happen with a qualified call to a member
1891    // function, e.g., X::f(). We use a NULL object as the implied
1892    // object argument (C++ [over.call.func]p3).
1893    AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
1894                       SuppressUserConversions);
1895    return;
1896  }
1897
1898
1899  // Add this candidate
1900  CandidateSet.push_back(OverloadCandidate());
1901  OverloadCandidate& Candidate = CandidateSet.back();
1902  Candidate.Function = Function;
1903  Candidate.Viable = true;
1904  Candidate.IsSurrogate = false;
1905  Candidate.IgnoreObjectArgument = false;
1906
1907  unsigned NumArgsInProto = Proto->getNumArgs();
1908
1909  // (C++ 13.3.2p2): A candidate function having fewer than m
1910  // parameters is viable only if it has an ellipsis in its parameter
1911  // list (8.3.5).
1912  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1913    Candidate.Viable = false;
1914    return;
1915  }
1916
1917  // (C++ 13.3.2p2): A candidate function having more than m parameters
1918  // is viable only if the (m+1)st parameter has a default argument
1919  // (8.3.6). For the purposes of overload resolution, the
1920  // parameter list is truncated on the right, so that there are
1921  // exactly m parameters.
1922  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1923  if (NumArgs < MinRequiredArgs) {
1924    // Not enough arguments.
1925    Candidate.Viable = false;
1926    return;
1927  }
1928
1929  // Determine the implicit conversion sequences for each of the
1930  // arguments.
1931  Candidate.Conversions.resize(NumArgs);
1932  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1933    if (ArgIdx < NumArgsInProto) {
1934      // (C++ 13.3.2p3): for F to be a viable function, there shall
1935      // exist for each argument an implicit conversion sequence
1936      // (13.3.3.1) that converts that argument to the corresponding
1937      // parameter of F.
1938      QualType ParamType = Proto->getArgType(ArgIdx);
1939      Candidate.Conversions[ArgIdx]
1940        = TryCopyInitialization(Args[ArgIdx], ParamType,
1941                                SuppressUserConversions);
1942      if (Candidate.Conversions[ArgIdx].ConversionKind
1943            == ImplicitConversionSequence::BadConversion) {
1944        Candidate.Viable = false;
1945        break;
1946      }
1947    } else {
1948      // (C++ 13.3.2p2): For the purposes of overload resolution, any
1949      // argument for which there is no corresponding parameter is
1950      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1951      Candidate.Conversions[ArgIdx].ConversionKind
1952        = ImplicitConversionSequence::EllipsisConversion;
1953    }
1954  }
1955}
1956
1957/// AddMethodCandidate - Adds the given C++ member function to the set
1958/// of candidate functions, using the given function call arguments
1959/// and the object argument (@c Object). For example, in a call
1960/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
1961/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
1962/// allow user-defined conversions via constructors or conversion
1963/// operators.
1964void
1965Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
1966                         Expr **Args, unsigned NumArgs,
1967                         OverloadCandidateSet& CandidateSet,
1968                         bool SuppressUserConversions)
1969{
1970  const FunctionTypeProto* Proto
1971    = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
1972  assert(Proto && "Methods without a prototype cannot be overloaded");
1973  assert(!isa<CXXConversionDecl>(Method) &&
1974         "Use AddConversionCandidate for conversion functions");
1975
1976  // Add this candidate
1977  CandidateSet.push_back(OverloadCandidate());
1978  OverloadCandidate& Candidate = CandidateSet.back();
1979  Candidate.Function = Method;
1980  Candidate.IsSurrogate = false;
1981  Candidate.IgnoreObjectArgument = false;
1982
1983  unsigned NumArgsInProto = Proto->getNumArgs();
1984
1985  // (C++ 13.3.2p2): A candidate function having fewer than m
1986  // parameters is viable only if it has an ellipsis in its parameter
1987  // list (8.3.5).
1988  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1989    Candidate.Viable = false;
1990    return;
1991  }
1992
1993  // (C++ 13.3.2p2): A candidate function having more than m parameters
1994  // is viable only if the (m+1)st parameter has a default argument
1995  // (8.3.6). For the purposes of overload resolution, the
1996  // parameter list is truncated on the right, so that there are
1997  // exactly m parameters.
1998  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
1999  if (NumArgs < MinRequiredArgs) {
2000    // Not enough arguments.
2001    Candidate.Viable = false;
2002    return;
2003  }
2004
2005  Candidate.Viable = true;
2006  Candidate.Conversions.resize(NumArgs + 1);
2007
2008  if (Method->isStatic() || !Object)
2009    // The implicit object argument is ignored.
2010    Candidate.IgnoreObjectArgument = true;
2011  else {
2012    // Determine the implicit conversion sequence for the object
2013    // parameter.
2014    Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2015    if (Candidate.Conversions[0].ConversionKind
2016          == ImplicitConversionSequence::BadConversion) {
2017      Candidate.Viable = false;
2018      return;
2019    }
2020  }
2021
2022  // Determine the implicit conversion sequences for each of the
2023  // arguments.
2024  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2025    if (ArgIdx < NumArgsInProto) {
2026      // (C++ 13.3.2p3): for F to be a viable function, there shall
2027      // exist for each argument an implicit conversion sequence
2028      // (13.3.3.1) that converts that argument to the corresponding
2029      // parameter of F.
2030      QualType ParamType = Proto->getArgType(ArgIdx);
2031      Candidate.Conversions[ArgIdx + 1]
2032        = TryCopyInitialization(Args[ArgIdx], ParamType,
2033                                SuppressUserConversions);
2034      if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2035            == ImplicitConversionSequence::BadConversion) {
2036        Candidate.Viable = false;
2037        break;
2038      }
2039    } else {
2040      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2041      // argument for which there is no corresponding parameter is
2042      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2043      Candidate.Conversions[ArgIdx + 1].ConversionKind
2044        = ImplicitConversionSequence::EllipsisConversion;
2045    }
2046  }
2047}
2048
2049/// AddConversionCandidate - Add a C++ conversion function as a
2050/// candidate in the candidate set (C++ [over.match.conv],
2051/// C++ [over.match.copy]). From is the expression we're converting from,
2052/// and ToType is the type that we're eventually trying to convert to
2053/// (which may or may not be the same type as the type that the
2054/// conversion function produces).
2055void
2056Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2057                             Expr *From, QualType ToType,
2058                             OverloadCandidateSet& CandidateSet) {
2059  // Add this candidate
2060  CandidateSet.push_back(OverloadCandidate());
2061  OverloadCandidate& Candidate = CandidateSet.back();
2062  Candidate.Function = Conversion;
2063  Candidate.IsSurrogate = false;
2064  Candidate.IgnoreObjectArgument = false;
2065  Candidate.FinalConversion.setAsIdentityConversion();
2066  Candidate.FinalConversion.FromTypePtr
2067    = Conversion->getConversionType().getAsOpaquePtr();
2068  Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2069
2070  // Determine the implicit conversion sequence for the implicit
2071  // object parameter.
2072  Candidate.Viable = true;
2073  Candidate.Conversions.resize(1);
2074  Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
2075
2076  if (Candidate.Conversions[0].ConversionKind
2077      == ImplicitConversionSequence::BadConversion) {
2078    Candidate.Viable = false;
2079    return;
2080  }
2081
2082  // To determine what the conversion from the result of calling the
2083  // conversion function to the type we're eventually trying to
2084  // convert to (ToType), we need to synthesize a call to the
2085  // conversion function and attempt copy initialization from it. This
2086  // makes sure that we get the right semantics with respect to
2087  // lvalues/rvalues and the type. Fortunately, we can allocate this
2088  // call on the stack and we don't need its arguments to be
2089  // well-formed.
2090  DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2091                            SourceLocation());
2092  ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
2093                                &ConversionRef, false);
2094  CallExpr Call(&ConversionFn, 0, 0,
2095                Conversion->getConversionType().getNonReferenceType(),
2096                SourceLocation());
2097  ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2098  switch (ICS.ConversionKind) {
2099  case ImplicitConversionSequence::StandardConversion:
2100    Candidate.FinalConversion = ICS.Standard;
2101    break;
2102
2103  case ImplicitConversionSequence::BadConversion:
2104    Candidate.Viable = false;
2105    break;
2106
2107  default:
2108    assert(false &&
2109           "Can only end up with a standard conversion sequence or failure");
2110  }
2111}
2112
2113/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2114/// converts the given @c Object to a function pointer via the
2115/// conversion function @c Conversion, and then attempts to call it
2116/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2117/// the type of function that we'll eventually be calling.
2118void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2119                                 const FunctionTypeProto *Proto,
2120                                 Expr *Object, Expr **Args, unsigned NumArgs,
2121                                 OverloadCandidateSet& CandidateSet) {
2122  CandidateSet.push_back(OverloadCandidate());
2123  OverloadCandidate& Candidate = CandidateSet.back();
2124  Candidate.Function = 0;
2125  Candidate.Surrogate = Conversion;
2126  Candidate.Viable = true;
2127  Candidate.IsSurrogate = true;
2128  Candidate.IgnoreObjectArgument = false;
2129  Candidate.Conversions.resize(NumArgs + 1);
2130
2131  // Determine the implicit conversion sequence for the implicit
2132  // object parameter.
2133  ImplicitConversionSequence ObjectInit
2134    = TryObjectArgumentInitialization(Object, Conversion);
2135  if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2136    Candidate.Viable = false;
2137    return;
2138  }
2139
2140  // The first conversion is actually a user-defined conversion whose
2141  // first conversion is ObjectInit's standard conversion (which is
2142  // effectively a reference binding). Record it as such.
2143  Candidate.Conversions[0].ConversionKind
2144    = ImplicitConversionSequence::UserDefinedConversion;
2145  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2146  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2147  Candidate.Conversions[0].UserDefined.After
2148    = Candidate.Conversions[0].UserDefined.Before;
2149  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2150
2151  // Find the
2152  unsigned NumArgsInProto = Proto->getNumArgs();
2153
2154  // (C++ 13.3.2p2): A candidate function having fewer than m
2155  // parameters is viable only if it has an ellipsis in its parameter
2156  // list (8.3.5).
2157  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2158    Candidate.Viable = false;
2159    return;
2160  }
2161
2162  // Function types don't have any default arguments, so just check if
2163  // we have enough arguments.
2164  if (NumArgs < NumArgsInProto) {
2165    // Not enough arguments.
2166    Candidate.Viable = false;
2167    return;
2168  }
2169
2170  // Determine the implicit conversion sequences for each of the
2171  // arguments.
2172  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2173    if (ArgIdx < NumArgsInProto) {
2174      // (C++ 13.3.2p3): for F to be a viable function, there shall
2175      // exist for each argument an implicit conversion sequence
2176      // (13.3.3.1) that converts that argument to the corresponding
2177      // parameter of F.
2178      QualType ParamType = Proto->getArgType(ArgIdx);
2179      Candidate.Conversions[ArgIdx + 1]
2180        = TryCopyInitialization(Args[ArgIdx], ParamType,
2181                                /*SuppressUserConversions=*/false);
2182      if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2183            == ImplicitConversionSequence::BadConversion) {
2184        Candidate.Viable = false;
2185        break;
2186      }
2187    } else {
2188      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2189      // argument for which there is no corresponding parameter is
2190      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2191      Candidate.Conversions[ArgIdx + 1].ConversionKind
2192        = ImplicitConversionSequence::EllipsisConversion;
2193    }
2194  }
2195}
2196
2197/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2198/// an acceptable non-member overloaded operator for a call whose
2199/// arguments have types T1 (and, if non-empty, T2). This routine
2200/// implements the check in C++ [over.match.oper]p3b2 concerning
2201/// enumeration types.
2202static bool
2203IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2204                                       QualType T1, QualType T2,
2205                                       ASTContext &Context) {
2206  if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2207    return true;
2208
2209  const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
2210  if (Proto->getNumArgs() < 1)
2211    return false;
2212
2213  if (T1->isEnumeralType()) {
2214    QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2215    if (Context.getCanonicalType(T1).getUnqualifiedType()
2216          == Context.getCanonicalType(ArgType).getUnqualifiedType())
2217      return true;
2218  }
2219
2220  if (Proto->getNumArgs() < 2)
2221    return false;
2222
2223  if (!T2.isNull() && T2->isEnumeralType()) {
2224    QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2225    if (Context.getCanonicalType(T2).getUnqualifiedType()
2226          == Context.getCanonicalType(ArgType).getUnqualifiedType())
2227      return true;
2228  }
2229
2230  return false;
2231}
2232
2233/// AddOperatorCandidates - Add the overloaded operator candidates for
2234/// the operator Op that was used in an operator expression such as "x
2235/// Op y". S is the scope in which the expression occurred (used for
2236/// name lookup of the operator), Args/NumArgs provides the operator
2237/// arguments, and CandidateSet will store the added overload
2238/// candidates. (C++ [over.match.oper]).
2239void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2240                                 Expr **Args, unsigned NumArgs,
2241                                 OverloadCandidateSet& CandidateSet) {
2242  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2243
2244  // C++ [over.match.oper]p3:
2245  //   For a unary operator @ with an operand of a type whose
2246  //   cv-unqualified version is T1, and for a binary operator @ with
2247  //   a left operand of a type whose cv-unqualified version is T1 and
2248  //   a right operand of a type whose cv-unqualified version is T2,
2249  //   three sets of candidate functions, designated member
2250  //   candidates, non-member candidates and built-in candidates, are
2251  //   constructed as follows:
2252  QualType T1 = Args[0]->getType();
2253  QualType T2;
2254  if (NumArgs > 1)
2255    T2 = Args[1]->getType();
2256
2257  //     -- If T1 is a class type, the set of member candidates is the
2258  //        result of the qualified lookup of T1::operator@
2259  //        (13.3.1.1.1); otherwise, the set of member candidates is
2260  //        empty.
2261  if (const RecordType *T1Rec = T1->getAsRecordType()) {
2262    DeclContext::lookup_const_iterator Oper, OperEnd;
2263    for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
2264         Oper != OperEnd; ++Oper)
2265      AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2266                         Args+1, NumArgs - 1, CandidateSet,
2267                         /*SuppressUserConversions=*/false);
2268  }
2269
2270  //     -- The set of non-member candidates is the result of the
2271  //        unqualified lookup of operator@ in the context of the
2272  //        expression according to the usual rules for name lookup in
2273  //        unqualified function calls (3.4.2) except that all member
2274  //        functions are ignored. However, if no operand has a class
2275  //        type, only those non-member functions in the lookup set
2276  //        that have a first parameter of type T1 or “reference to
2277  //        (possibly cv-qualified) T1”, when T1 is an enumeration
2278  //        type, or (if there is a right operand) a second parameter
2279  //        of type T2 or “reference to (possibly cv-qualified) T2”,
2280  //        when T2 is an enumeration type, are candidate functions.
2281  {
2282    IdentifierResolver::iterator I = IdResolver.begin(OpName),
2283                              IEnd = IdResolver.end();
2284    for (; I != IEnd; ++I) {
2285      // We don't need to check the identifier namespace, because
2286      // operator names can only be ordinary identifiers.
2287
2288      // Ignore member functions.
2289      if ((*I)->getDeclContext()->isRecord())
2290        continue;
2291
2292      // We found something with this name. We're done.
2293      break;
2294    }
2295
2296    if (I != IEnd) {
2297      Decl *FirstDecl = *I;
2298      for (; I != IEnd; ++I) {
2299        if (FirstDecl->getDeclContext() != (*I)->getDeclContext())
2300          break;
2301
2302        if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I))
2303          if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2304            AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2305                                 /*SuppressUserConversions=*/false);
2306      }
2307    }
2308  }
2309
2310  // Add builtin overload candidates (C++ [over.built]).
2311  AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2312}
2313
2314/// AddBuiltinCandidate - Add a candidate for a built-in
2315/// operator. ResultTy and ParamTys are the result and parameter types
2316/// of the built-in candidate, respectively. Args and NumArgs are the
2317/// arguments being passed to the candidate. IsAssignmentOperator
2318/// should be true when this built-in candidate is an assignment
2319/// operator. NumContextualBoolArguments is the number of arguments
2320/// (at the beginning of the argument list) that will be contextually
2321/// converted to bool.
2322void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2323                               Expr **Args, unsigned NumArgs,
2324                               OverloadCandidateSet& CandidateSet,
2325                               bool IsAssignmentOperator,
2326                               unsigned NumContextualBoolArguments) {
2327  // Add this candidate
2328  CandidateSet.push_back(OverloadCandidate());
2329  OverloadCandidate& Candidate = CandidateSet.back();
2330  Candidate.Function = 0;
2331  Candidate.IsSurrogate = false;
2332  Candidate.IgnoreObjectArgument = false;
2333  Candidate.BuiltinTypes.ResultTy = ResultTy;
2334  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2335    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2336
2337  // Determine the implicit conversion sequences for each of the
2338  // arguments.
2339  Candidate.Viable = true;
2340  Candidate.Conversions.resize(NumArgs);
2341  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2342    // C++ [over.match.oper]p4:
2343    //   For the built-in assignment operators, conversions of the
2344    //   left operand are restricted as follows:
2345    //     -- no temporaries are introduced to hold the left operand, and
2346    //     -- no user-defined conversions are applied to the left
2347    //        operand to achieve a type match with the left-most
2348    //        parameter of a built-in candidate.
2349    //
2350    // We block these conversions by turning off user-defined
2351    // conversions, since that is the only way that initialization of
2352    // a reference to a non-class type can occur from something that
2353    // is not of the same type.
2354    if (ArgIdx < NumContextualBoolArguments) {
2355      assert(ParamTys[ArgIdx] == Context.BoolTy &&
2356             "Contextual conversion to bool requires bool type");
2357      Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2358    } else {
2359      Candidate.Conversions[ArgIdx]
2360        = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2361                                ArgIdx == 0 && IsAssignmentOperator);
2362    }
2363    if (Candidate.Conversions[ArgIdx].ConversionKind
2364        == ImplicitConversionSequence::BadConversion) {
2365      Candidate.Viable = false;
2366      break;
2367    }
2368  }
2369}
2370
2371/// BuiltinCandidateTypeSet - A set of types that will be used for the
2372/// candidate operator functions for built-in operators (C++
2373/// [over.built]). The types are separated into pointer types and
2374/// enumeration types.
2375class BuiltinCandidateTypeSet  {
2376  /// TypeSet - A set of types.
2377  typedef llvm::SmallPtrSet<void*, 8> TypeSet;
2378
2379  /// PointerTypes - The set of pointer types that will be used in the
2380  /// built-in candidates.
2381  TypeSet PointerTypes;
2382
2383  /// EnumerationTypes - The set of enumeration types that will be
2384  /// used in the built-in candidates.
2385  TypeSet EnumerationTypes;
2386
2387  /// Context - The AST context in which we will build the type sets.
2388  ASTContext &Context;
2389
2390  bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2391
2392public:
2393  /// iterator - Iterates through the types that are part of the set.
2394  class iterator {
2395    TypeSet::iterator Base;
2396
2397  public:
2398    typedef QualType                 value_type;
2399    typedef QualType                 reference;
2400    typedef QualType                 pointer;
2401    typedef std::ptrdiff_t           difference_type;
2402    typedef std::input_iterator_tag  iterator_category;
2403
2404    iterator(TypeSet::iterator B) : Base(B) { }
2405
2406    iterator& operator++() {
2407      ++Base;
2408      return *this;
2409    }
2410
2411    iterator operator++(int) {
2412      iterator tmp(*this);
2413      ++(*this);
2414      return tmp;
2415    }
2416
2417    reference operator*() const {
2418      return QualType::getFromOpaquePtr(*Base);
2419    }
2420
2421    pointer operator->() const {
2422      return **this;
2423    }
2424
2425    friend bool operator==(iterator LHS, iterator RHS) {
2426      return LHS.Base == RHS.Base;
2427    }
2428
2429    friend bool operator!=(iterator LHS, iterator RHS) {
2430      return LHS.Base != RHS.Base;
2431    }
2432  };
2433
2434  BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2435
2436  void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2437                             bool AllowExplicitConversions);
2438
2439  /// pointer_begin - First pointer type found;
2440  iterator pointer_begin() { return PointerTypes.begin(); }
2441
2442  /// pointer_end - Last pointer type found;
2443  iterator pointer_end() { return PointerTypes.end(); }
2444
2445  /// enumeration_begin - First enumeration type found;
2446  iterator enumeration_begin() { return EnumerationTypes.begin(); }
2447
2448  /// enumeration_end - Last enumeration type found;
2449  iterator enumeration_end() { return EnumerationTypes.end(); }
2450};
2451
2452/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2453/// the set of pointer types along with any more-qualified variants of
2454/// that type. For example, if @p Ty is "int const *", this routine
2455/// will add "int const *", "int const volatile *", "int const
2456/// restrict *", and "int const volatile restrict *" to the set of
2457/// pointer types. Returns true if the add of @p Ty itself succeeded,
2458/// false otherwise.
2459bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2460  // Insert this type.
2461  if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
2462    return false;
2463
2464  if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2465    QualType PointeeTy = PointerTy->getPointeeType();
2466    // FIXME: Optimize this so that we don't keep trying to add the same types.
2467
2468    // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2469    // with all pointer conversions that don't cast away constness?
2470    if (!PointeeTy.isConstQualified())
2471      AddWithMoreQualifiedTypeVariants
2472        (Context.getPointerType(PointeeTy.withConst()));
2473    if (!PointeeTy.isVolatileQualified())
2474      AddWithMoreQualifiedTypeVariants
2475        (Context.getPointerType(PointeeTy.withVolatile()));
2476    if (!PointeeTy.isRestrictQualified())
2477      AddWithMoreQualifiedTypeVariants
2478        (Context.getPointerType(PointeeTy.withRestrict()));
2479  }
2480
2481  return true;
2482}
2483
2484/// AddTypesConvertedFrom - Add each of the types to which the type @p
2485/// Ty can be implicit converted to the given set of @p Types. We're
2486/// primarily interested in pointer types and enumeration types.
2487/// AllowUserConversions is true if we should look at the conversion
2488/// functions of a class type, and AllowExplicitConversions if we
2489/// should also include the explicit conversion functions of a class
2490/// type.
2491void
2492BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2493                                               bool AllowUserConversions,
2494                                               bool AllowExplicitConversions) {
2495  // Only deal with canonical types.
2496  Ty = Context.getCanonicalType(Ty);
2497
2498  // Look through reference types; they aren't part of the type of an
2499  // expression for the purposes of conversions.
2500  if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2501    Ty = RefTy->getPointeeType();
2502
2503  // We don't care about qualifiers on the type.
2504  Ty = Ty.getUnqualifiedType();
2505
2506  if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2507    QualType PointeeTy = PointerTy->getPointeeType();
2508
2509    // Insert our type, and its more-qualified variants, into the set
2510    // of types.
2511    if (!AddWithMoreQualifiedTypeVariants(Ty))
2512      return;
2513
2514    // Add 'cv void*' to our set of types.
2515    if (!Ty->isVoidType()) {
2516      QualType QualVoid
2517        = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2518      AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2519    }
2520
2521    // If this is a pointer to a class type, add pointers to its bases
2522    // (with the same level of cv-qualification as the original
2523    // derived class, of course).
2524    if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2525      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2526      for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2527           Base != ClassDecl->bases_end(); ++Base) {
2528        QualType BaseTy = Context.getCanonicalType(Base->getType());
2529        BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2530
2531        // Add the pointer type, recursively, so that we get all of
2532        // the indirect base classes, too.
2533        AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
2534      }
2535    }
2536  } else if (Ty->isEnumeralType()) {
2537    EnumerationTypes.insert(Ty.getAsOpaquePtr());
2538  } else if (AllowUserConversions) {
2539    if (const RecordType *TyRec = Ty->getAsRecordType()) {
2540      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2541      // FIXME: Visit conversion functions in the base classes, too.
2542      OverloadedFunctionDecl *Conversions
2543        = ClassDecl->getConversionFunctions();
2544      for (OverloadedFunctionDecl::function_iterator Func
2545             = Conversions->function_begin();
2546           Func != Conversions->function_end(); ++Func) {
2547        CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2548        if (AllowExplicitConversions || !Conv->isExplicit())
2549          AddTypesConvertedFrom(Conv->getConversionType(), false, false);
2550      }
2551    }
2552  }
2553}
2554
2555/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2556/// operator overloads to the candidate set (C++ [over.built]), based
2557/// on the operator @p Op and the arguments given. For example, if the
2558/// operator is a binary '+', this routine might add "int
2559/// operator+(int, int)" to cover integer addition.
2560void
2561Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2562                                   Expr **Args, unsigned NumArgs,
2563                                   OverloadCandidateSet& CandidateSet) {
2564  // The set of "promoted arithmetic types", which are the arithmetic
2565  // types are that preserved by promotion (C++ [over.built]p2). Note
2566  // that the first few of these types are the promoted integral
2567  // types; these types need to be first.
2568  // FIXME: What about complex?
2569  const unsigned FirstIntegralType = 0;
2570  const unsigned LastIntegralType = 13;
2571  const unsigned FirstPromotedIntegralType = 7,
2572                 LastPromotedIntegralType = 13;
2573  const unsigned FirstPromotedArithmeticType = 7,
2574                 LastPromotedArithmeticType = 16;
2575  const unsigned NumArithmeticTypes = 16;
2576  QualType ArithmeticTypes[NumArithmeticTypes] = {
2577    Context.BoolTy, Context.CharTy, Context.WCharTy,
2578    Context.SignedCharTy, Context.ShortTy,
2579    Context.UnsignedCharTy, Context.UnsignedShortTy,
2580    Context.IntTy, Context.LongTy, Context.LongLongTy,
2581    Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2582    Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2583  };
2584
2585  // Find all of the types that the arguments can convert to, but only
2586  // if the operator we're looking at has built-in operator candidates
2587  // that make use of these types.
2588  BuiltinCandidateTypeSet CandidateTypes(Context);
2589  if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2590      Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
2591      Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
2592      Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
2593      Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2594      (Op == OO_Star && NumArgs == 1)) {
2595    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2596      CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2597                                           true,
2598                                           (Op == OO_Exclaim ||
2599                                            Op == OO_AmpAmp ||
2600                                            Op == OO_PipePipe));
2601  }
2602
2603  bool isComparison = false;
2604  switch (Op) {
2605  case OO_None:
2606  case NUM_OVERLOADED_OPERATORS:
2607    assert(false && "Expected an overloaded operator");
2608    break;
2609
2610  case OO_Star: // '*' is either unary or binary
2611    if (NumArgs == 1)
2612      goto UnaryStar;
2613    else
2614      goto BinaryStar;
2615    break;
2616
2617  case OO_Plus: // '+' is either unary or binary
2618    if (NumArgs == 1)
2619      goto UnaryPlus;
2620    else
2621      goto BinaryPlus;
2622    break;
2623
2624  case OO_Minus: // '-' is either unary or binary
2625    if (NumArgs == 1)
2626      goto UnaryMinus;
2627    else
2628      goto BinaryMinus;
2629    break;
2630
2631  case OO_Amp: // '&' is either unary or binary
2632    if (NumArgs == 1)
2633      goto UnaryAmp;
2634    else
2635      goto BinaryAmp;
2636
2637  case OO_PlusPlus:
2638  case OO_MinusMinus:
2639    // C++ [over.built]p3:
2640    //
2641    //   For every pair (T, VQ), where T is an arithmetic type, and VQ
2642    //   is either volatile or empty, there exist candidate operator
2643    //   functions of the form
2644    //
2645    //       VQ T&      operator++(VQ T&);
2646    //       T          operator++(VQ T&, int);
2647    //
2648    // C++ [over.built]p4:
2649    //
2650    //   For every pair (T, VQ), where T is an arithmetic type other
2651    //   than bool, and VQ is either volatile or empty, there exist
2652    //   candidate operator functions of the form
2653    //
2654    //       VQ T&      operator--(VQ T&);
2655    //       T          operator--(VQ T&, int);
2656    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2657         Arith < NumArithmeticTypes; ++Arith) {
2658      QualType ArithTy = ArithmeticTypes[Arith];
2659      QualType ParamTypes[2]
2660        = { Context.getReferenceType(ArithTy), Context.IntTy };
2661
2662      // Non-volatile version.
2663      if (NumArgs == 1)
2664        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2665      else
2666        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2667
2668      // Volatile version
2669      ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2670      if (NumArgs == 1)
2671        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2672      else
2673        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2674    }
2675
2676    // C++ [over.built]p5:
2677    //
2678    //   For every pair (T, VQ), where T is a cv-qualified or
2679    //   cv-unqualified object type, and VQ is either volatile or
2680    //   empty, there exist candidate operator functions of the form
2681    //
2682    //       T*VQ&      operator++(T*VQ&);
2683    //       T*VQ&      operator--(T*VQ&);
2684    //       T*         operator++(T*VQ&, int);
2685    //       T*         operator--(T*VQ&, int);
2686    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2687         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2688      // Skip pointer types that aren't pointers to object types.
2689      if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType())
2690        continue;
2691
2692      QualType ParamTypes[2] = {
2693        Context.getReferenceType(*Ptr), Context.IntTy
2694      };
2695
2696      // Without volatile
2697      if (NumArgs == 1)
2698        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2699      else
2700        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2701
2702      if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2703        // With volatile
2704        ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2705        if (NumArgs == 1)
2706          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2707        else
2708          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2709      }
2710    }
2711    break;
2712
2713  UnaryStar:
2714    // C++ [over.built]p6:
2715    //   For every cv-qualified or cv-unqualified object type T, there
2716    //   exist candidate operator functions of the form
2717    //
2718    //       T&         operator*(T*);
2719    //
2720    // C++ [over.built]p7:
2721    //   For every function type T, there exist candidate operator
2722    //   functions of the form
2723    //       T&         operator*(T*);
2724    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2725         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2726      QualType ParamTy = *Ptr;
2727      QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2728      AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2729                          &ParamTy, Args, 1, CandidateSet);
2730    }
2731    break;
2732
2733  UnaryPlus:
2734    // C++ [over.built]p8:
2735    //   For every type T, there exist candidate operator functions of
2736    //   the form
2737    //
2738    //       T*         operator+(T*);
2739    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2740         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2741      QualType ParamTy = *Ptr;
2742      AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2743    }
2744
2745    // Fall through
2746
2747  UnaryMinus:
2748    // C++ [over.built]p9:
2749    //  For every promoted arithmetic type T, there exist candidate
2750    //  operator functions of the form
2751    //
2752    //       T         operator+(T);
2753    //       T         operator-(T);
2754    for (unsigned Arith = FirstPromotedArithmeticType;
2755         Arith < LastPromotedArithmeticType; ++Arith) {
2756      QualType ArithTy = ArithmeticTypes[Arith];
2757      AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2758    }
2759    break;
2760
2761  case OO_Tilde:
2762    // C++ [over.built]p10:
2763    //   For every promoted integral type T, there exist candidate
2764    //   operator functions of the form
2765    //
2766    //        T         operator~(T);
2767    for (unsigned Int = FirstPromotedIntegralType;
2768         Int < LastPromotedIntegralType; ++Int) {
2769      QualType IntTy = ArithmeticTypes[Int];
2770      AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2771    }
2772    break;
2773
2774  case OO_New:
2775  case OO_Delete:
2776  case OO_Array_New:
2777  case OO_Array_Delete:
2778  case OO_Call:
2779    assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
2780    break;
2781
2782  case OO_Comma:
2783  UnaryAmp:
2784  case OO_Arrow:
2785    // C++ [over.match.oper]p3:
2786    //   -- For the operator ',', the unary operator '&', or the
2787    //      operator '->', the built-in candidates set is empty.
2788    break;
2789
2790  case OO_Less:
2791  case OO_Greater:
2792  case OO_LessEqual:
2793  case OO_GreaterEqual:
2794  case OO_EqualEqual:
2795  case OO_ExclaimEqual:
2796    // C++ [over.built]p15:
2797    //
2798    //   For every pointer or enumeration type T, there exist
2799    //   candidate operator functions of the form
2800    //
2801    //        bool       operator<(T, T);
2802    //        bool       operator>(T, T);
2803    //        bool       operator<=(T, T);
2804    //        bool       operator>=(T, T);
2805    //        bool       operator==(T, T);
2806    //        bool       operator!=(T, T);
2807    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2808         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2809      QualType ParamTypes[2] = { *Ptr, *Ptr };
2810      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2811    }
2812    for (BuiltinCandidateTypeSet::iterator Enum
2813           = CandidateTypes.enumeration_begin();
2814         Enum != CandidateTypes.enumeration_end(); ++Enum) {
2815      QualType ParamTypes[2] = { *Enum, *Enum };
2816      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2817    }
2818
2819    // Fall through.
2820    isComparison = true;
2821
2822  BinaryPlus:
2823  BinaryMinus:
2824    if (!isComparison) {
2825      // We didn't fall through, so we must have OO_Plus or OO_Minus.
2826
2827      // C++ [over.built]p13:
2828      //
2829      //   For every cv-qualified or cv-unqualified object type T
2830      //   there exist candidate operator functions of the form
2831      //
2832      //      T*         operator+(T*, ptrdiff_t);
2833      //      T&         operator[](T*, ptrdiff_t);    [BELOW]
2834      //      T*         operator-(T*, ptrdiff_t);
2835      //      T*         operator+(ptrdiff_t, T*);
2836      //      T&         operator[](ptrdiff_t, T*);    [BELOW]
2837      //
2838      // C++ [over.built]p14:
2839      //
2840      //   For every T, where T is a pointer to object type, there
2841      //   exist candidate operator functions of the form
2842      //
2843      //      ptrdiff_t  operator-(T, T);
2844      for (BuiltinCandidateTypeSet::iterator Ptr
2845             = CandidateTypes.pointer_begin();
2846           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2847        QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2848
2849        // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2850        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2851
2852        if (Op == OO_Plus) {
2853          // T* operator+(ptrdiff_t, T*);
2854          ParamTypes[0] = ParamTypes[1];
2855          ParamTypes[1] = *Ptr;
2856          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2857        } else {
2858          // ptrdiff_t operator-(T, T);
2859          ParamTypes[1] = *Ptr;
2860          AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2861                              Args, 2, CandidateSet);
2862        }
2863      }
2864    }
2865    // Fall through
2866
2867  case OO_Slash:
2868  BinaryStar:
2869    // C++ [over.built]p12:
2870    //
2871    //   For every pair of promoted arithmetic types L and R, there
2872    //   exist candidate operator functions of the form
2873    //
2874    //        LR         operator*(L, R);
2875    //        LR         operator/(L, R);
2876    //        LR         operator+(L, R);
2877    //        LR         operator-(L, R);
2878    //        bool       operator<(L, R);
2879    //        bool       operator>(L, R);
2880    //        bool       operator<=(L, R);
2881    //        bool       operator>=(L, R);
2882    //        bool       operator==(L, R);
2883    //        bool       operator!=(L, R);
2884    //
2885    //   where LR is the result of the usual arithmetic conversions
2886    //   between types L and R.
2887    for (unsigned Left = FirstPromotedArithmeticType;
2888         Left < LastPromotedArithmeticType; ++Left) {
2889      for (unsigned Right = FirstPromotedArithmeticType;
2890           Right < LastPromotedArithmeticType; ++Right) {
2891        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2892        QualType Result
2893          = isComparison? Context.BoolTy
2894                        : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2895        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2896      }
2897    }
2898    break;
2899
2900  case OO_Percent:
2901  BinaryAmp:
2902  case OO_Caret:
2903  case OO_Pipe:
2904  case OO_LessLess:
2905  case OO_GreaterGreater:
2906    // C++ [over.built]p17:
2907    //
2908    //   For every pair of promoted integral types L and R, there
2909    //   exist candidate operator functions of the form
2910    //
2911    //      LR         operator%(L, R);
2912    //      LR         operator&(L, R);
2913    //      LR         operator^(L, R);
2914    //      LR         operator|(L, R);
2915    //      L          operator<<(L, R);
2916    //      L          operator>>(L, R);
2917    //
2918    //   where LR is the result of the usual arithmetic conversions
2919    //   between types L and R.
2920    for (unsigned Left = FirstPromotedIntegralType;
2921         Left < LastPromotedIntegralType; ++Left) {
2922      for (unsigned Right = FirstPromotedIntegralType;
2923           Right < LastPromotedIntegralType; ++Right) {
2924        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2925        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2926            ? LandR[0]
2927            : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2928        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2929      }
2930    }
2931    break;
2932
2933  case OO_Equal:
2934    // C++ [over.built]p20:
2935    //
2936    //   For every pair (T, VQ), where T is an enumeration or
2937    //   (FIXME:) pointer to member type and VQ is either volatile or
2938    //   empty, there exist candidate operator functions of the form
2939    //
2940    //        VQ T&      operator=(VQ T&, T);
2941    for (BuiltinCandidateTypeSet::iterator Enum
2942           = CandidateTypes.enumeration_begin();
2943         Enum != CandidateTypes.enumeration_end(); ++Enum) {
2944      QualType ParamTypes[2];
2945
2946      // T& operator=(T&, T)
2947      ParamTypes[0] = Context.getReferenceType(*Enum);
2948      ParamTypes[1] = *Enum;
2949      AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2950                          /*IsAssignmentOperator=*/false);
2951
2952      if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
2953        // volatile T& operator=(volatile T&, T)
2954        ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
2955        ParamTypes[1] = *Enum;
2956        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2957                            /*IsAssignmentOperator=*/false);
2958      }
2959    }
2960    // Fall through.
2961
2962  case OO_PlusEqual:
2963  case OO_MinusEqual:
2964    // C++ [over.built]p19:
2965    //
2966    //   For every pair (T, VQ), where T is any type and VQ is either
2967    //   volatile or empty, there exist candidate operator functions
2968    //   of the form
2969    //
2970    //        T*VQ&      operator=(T*VQ&, T*);
2971    //
2972    // C++ [over.built]p21:
2973    //
2974    //   For every pair (T, VQ), where T is a cv-qualified or
2975    //   cv-unqualified object type and VQ is either volatile or
2976    //   empty, there exist candidate operator functions of the form
2977    //
2978    //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
2979    //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
2980    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2981         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2982      QualType ParamTypes[2];
2983      ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
2984
2985      // non-volatile version
2986      ParamTypes[0] = Context.getReferenceType(*Ptr);
2987      AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2988                          /*IsAssigmentOperator=*/Op == OO_Equal);
2989
2990      if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2991        // volatile version
2992        ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2993        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2994                            /*IsAssigmentOperator=*/Op == OO_Equal);
2995      }
2996    }
2997    // Fall through.
2998
2999  case OO_StarEqual:
3000  case OO_SlashEqual:
3001    // C++ [over.built]p18:
3002    //
3003    //   For every triple (L, VQ, R), where L is an arithmetic type,
3004    //   VQ is either volatile or empty, and R is a promoted
3005    //   arithmetic type, there exist candidate operator functions of
3006    //   the form
3007    //
3008    //        VQ L&      operator=(VQ L&, R);
3009    //        VQ L&      operator*=(VQ L&, R);
3010    //        VQ L&      operator/=(VQ L&, R);
3011    //        VQ L&      operator+=(VQ L&, R);
3012    //        VQ L&      operator-=(VQ L&, R);
3013    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3014      for (unsigned Right = FirstPromotedArithmeticType;
3015           Right < LastPromotedArithmeticType; ++Right) {
3016        QualType ParamTypes[2];
3017        ParamTypes[1] = ArithmeticTypes[Right];
3018
3019        // Add this built-in operator as a candidate (VQ is empty).
3020        ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
3021        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3022                            /*IsAssigmentOperator=*/Op == OO_Equal);
3023
3024        // Add this built-in operator as a candidate (VQ is 'volatile').
3025        ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
3026        ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
3027        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3028                            /*IsAssigmentOperator=*/Op == OO_Equal);
3029      }
3030    }
3031    break;
3032
3033  case OO_PercentEqual:
3034  case OO_LessLessEqual:
3035  case OO_GreaterGreaterEqual:
3036  case OO_AmpEqual:
3037  case OO_CaretEqual:
3038  case OO_PipeEqual:
3039    // C++ [over.built]p22:
3040    //
3041    //   For every triple (L, VQ, R), where L is an integral type, VQ
3042    //   is either volatile or empty, and R is a promoted integral
3043    //   type, there exist candidate operator functions of the form
3044    //
3045    //        VQ L&       operator%=(VQ L&, R);
3046    //        VQ L&       operator<<=(VQ L&, R);
3047    //        VQ L&       operator>>=(VQ L&, R);
3048    //        VQ L&       operator&=(VQ L&, R);
3049    //        VQ L&       operator^=(VQ L&, R);
3050    //        VQ L&       operator|=(VQ L&, R);
3051    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3052      for (unsigned Right = FirstPromotedIntegralType;
3053           Right < LastPromotedIntegralType; ++Right) {
3054        QualType ParamTypes[2];
3055        ParamTypes[1] = ArithmeticTypes[Right];
3056
3057        // Add this built-in operator as a candidate (VQ is empty).
3058        ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
3059        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3060
3061        // Add this built-in operator as a candidate (VQ is 'volatile').
3062        ParamTypes[0] = ArithmeticTypes[Left];
3063        ParamTypes[0].addVolatile();
3064        ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
3065        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3066      }
3067    }
3068    break;
3069
3070  case OO_Exclaim: {
3071    // C++ [over.operator]p23:
3072    //
3073    //   There also exist candidate operator functions of the form
3074    //
3075    //        bool        operator!(bool);
3076    //        bool        operator&&(bool, bool);     [BELOW]
3077    //        bool        operator||(bool, bool);     [BELOW]
3078    QualType ParamTy = Context.BoolTy;
3079    AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3080                        /*IsAssignmentOperator=*/false,
3081                        /*NumContextualBoolArguments=*/1);
3082    break;
3083  }
3084
3085  case OO_AmpAmp:
3086  case OO_PipePipe: {
3087    // C++ [over.operator]p23:
3088    //
3089    //   There also exist candidate operator functions of the form
3090    //
3091    //        bool        operator!(bool);            [ABOVE]
3092    //        bool        operator&&(bool, bool);
3093    //        bool        operator||(bool, bool);
3094    QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
3095    AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3096                        /*IsAssignmentOperator=*/false,
3097                        /*NumContextualBoolArguments=*/2);
3098    break;
3099  }
3100
3101  case OO_Subscript:
3102    // C++ [over.built]p13:
3103    //
3104    //   For every cv-qualified or cv-unqualified object type T there
3105    //   exist candidate operator functions of the form
3106    //
3107    //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
3108    //        T&         operator[](T*, ptrdiff_t);
3109    //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
3110    //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
3111    //        T&         operator[](ptrdiff_t, T*);
3112    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3113         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3114      QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3115      QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
3116      QualType ResultTy = Context.getReferenceType(PointeeType);
3117
3118      // T& operator[](T*, ptrdiff_t)
3119      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3120
3121      // T& operator[](ptrdiff_t, T*);
3122      ParamTypes[0] = ParamTypes[1];
3123      ParamTypes[1] = *Ptr;
3124      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3125    }
3126    break;
3127
3128  case OO_ArrowStar:
3129    // FIXME: No support for pointer-to-members yet.
3130    break;
3131  }
3132}
3133
3134/// AddOverloadCandidates - Add all of the function overloads in Ovl
3135/// to the candidate set.
3136void
3137Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
3138                            Expr **Args, unsigned NumArgs,
3139                            OverloadCandidateSet& CandidateSet,
3140                            bool SuppressUserConversions)
3141{
3142  for (OverloadedFunctionDecl::function_const_iterator Func
3143         = Ovl->function_begin();
3144       Func != Ovl->function_end(); ++Func)
3145    AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
3146                         SuppressUserConversions);
3147}
3148
3149/// isBetterOverloadCandidate - Determines whether the first overload
3150/// candidate is a better candidate than the second (C++ 13.3.3p1).
3151bool
3152Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3153                                const OverloadCandidate& Cand2)
3154{
3155  // Define viable functions to be better candidates than non-viable
3156  // functions.
3157  if (!Cand2.Viable)
3158    return Cand1.Viable;
3159  else if (!Cand1.Viable)
3160    return false;
3161
3162  // C++ [over.match.best]p1:
3163  //
3164  //   -- if F is a static member function, ICS1(F) is defined such
3165  //      that ICS1(F) is neither better nor worse than ICS1(G) for
3166  //      any function G, and, symmetrically, ICS1(G) is neither
3167  //      better nor worse than ICS1(F).
3168  unsigned StartArg = 0;
3169  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3170    StartArg = 1;
3171
3172  // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3173  // function than another viable function F2 if for all arguments i,
3174  // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3175  // then...
3176  unsigned NumArgs = Cand1.Conversions.size();
3177  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3178  bool HasBetterConversion = false;
3179  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
3180    switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3181                                               Cand2.Conversions[ArgIdx])) {
3182    case ImplicitConversionSequence::Better:
3183      // Cand1 has a better conversion sequence.
3184      HasBetterConversion = true;
3185      break;
3186
3187    case ImplicitConversionSequence::Worse:
3188      // Cand1 can't be better than Cand2.
3189      return false;
3190
3191    case ImplicitConversionSequence::Indistinguishable:
3192      // Do nothing.
3193      break;
3194    }
3195  }
3196
3197  if (HasBetterConversion)
3198    return true;
3199
3200  // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3201  // implemented, but they require template support.
3202
3203  // C++ [over.match.best]p1b4:
3204  //
3205  //   -- the context is an initialization by user-defined conversion
3206  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
3207  //      from the return type of F1 to the destination type (i.e.,
3208  //      the type of the entity being initialized) is a better
3209  //      conversion sequence than the standard conversion sequence
3210  //      from the return type of F2 to the destination type.
3211  if (Cand1.Function && Cand2.Function &&
3212      isa<CXXConversionDecl>(Cand1.Function) &&
3213      isa<CXXConversionDecl>(Cand2.Function)) {
3214    switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3215                                               Cand2.FinalConversion)) {
3216    case ImplicitConversionSequence::Better:
3217      // Cand1 has a better conversion sequence.
3218      return true;
3219
3220    case ImplicitConversionSequence::Worse:
3221      // Cand1 can't be better than Cand2.
3222      return false;
3223
3224    case ImplicitConversionSequence::Indistinguishable:
3225      // Do nothing
3226      break;
3227    }
3228  }
3229
3230  return false;
3231}
3232
3233/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3234/// within an overload candidate set. If overloading is successful,
3235/// the result will be OR_Success and Best will be set to point to the
3236/// best viable function within the candidate set. Otherwise, one of
3237/// several kinds of errors will be returned; see
3238/// Sema::OverloadingResult.
3239Sema::OverloadingResult
3240Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3241                         OverloadCandidateSet::iterator& Best)
3242{
3243  // Find the best viable function.
3244  Best = CandidateSet.end();
3245  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3246       Cand != CandidateSet.end(); ++Cand) {
3247    if (Cand->Viable) {
3248      if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3249        Best = Cand;
3250    }
3251  }
3252
3253  // If we didn't find any viable functions, abort.
3254  if (Best == CandidateSet.end())
3255    return OR_No_Viable_Function;
3256
3257  // Make sure that this function is better than every other viable
3258  // function. If not, we have an ambiguity.
3259  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3260       Cand != CandidateSet.end(); ++Cand) {
3261    if (Cand->Viable &&
3262        Cand != Best &&
3263        !isBetterOverloadCandidate(*Best, *Cand)) {
3264      Best = CandidateSet.end();
3265      return OR_Ambiguous;
3266    }
3267  }
3268
3269  // Best is the best viable function.
3270  return OR_Success;
3271}
3272
3273/// PrintOverloadCandidates - When overload resolution fails, prints
3274/// diagnostic messages containing the candidates in the candidate
3275/// set. If OnlyViable is true, only viable candidates will be printed.
3276void
3277Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3278                              bool OnlyViable)
3279{
3280  OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3281                             LastCand = CandidateSet.end();
3282  for (; Cand != LastCand; ++Cand) {
3283    if (Cand->Viable || !OnlyViable) {
3284      if (Cand->Function) {
3285        // Normal function
3286        Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3287      } else if (Cand->IsSurrogate) {
3288        // Desugar the type of the surrogate down to a function type,
3289        // retaining as many typedefs as possible while still showing
3290        // the function type (and, therefore, its parameter types).
3291        QualType FnType = Cand->Surrogate->getConversionType();
3292        bool isReference = false;
3293        bool isPointer = false;
3294        if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) {
3295          FnType = FnTypeRef->getPointeeType();
3296          isReference = true;
3297        }
3298        if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3299          FnType = FnTypePtr->getPointeeType();
3300          isPointer = true;
3301        }
3302        // Desugar down to a function type.
3303        FnType = QualType(FnType->getAsFunctionType(), 0);
3304        // Reconstruct the pointer/reference as appropriate.
3305        if (isPointer) FnType = Context.getPointerType(FnType);
3306        if (isReference) FnType = Context.getReferenceType(FnType);
3307
3308        Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
3309          << FnType;
3310      } else {
3311        // FIXME: We need to get the identifier in here
3312        // FIXME: Do we want the error message to point at the
3313        // operator? (built-ins won't have a location)
3314        QualType FnType
3315          = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3316                                    Cand->BuiltinTypes.ParamTypes,
3317                                    Cand->Conversions.size(),
3318                                    false, 0);
3319
3320        Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
3321      }
3322    }
3323  }
3324}
3325
3326/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3327/// an overloaded function (C++ [over.over]), where @p From is an
3328/// expression with overloaded function type and @p ToType is the type
3329/// we're trying to resolve to. For example:
3330///
3331/// @code
3332/// int f(double);
3333/// int f(int);
3334///
3335/// int (*pfd)(double) = f; // selects f(double)
3336/// @endcode
3337///
3338/// This routine returns the resulting FunctionDecl if it could be
3339/// resolved, and NULL otherwise. When @p Complain is true, this
3340/// routine will emit diagnostics if there is an error.
3341FunctionDecl *
3342Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
3343                                         bool Complain) {
3344  QualType FunctionType = ToType;
3345  if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
3346    FunctionType = ToTypePtr->getPointeeType();
3347
3348  // We only look at pointers or references to functions.
3349  if (!FunctionType->isFunctionType())
3350    return 0;
3351
3352  // Find the actual overloaded function declaration.
3353  OverloadedFunctionDecl *Ovl = 0;
3354
3355  // C++ [over.over]p1:
3356  //   [...] [Note: any redundant set of parentheses surrounding the
3357  //   overloaded function name is ignored (5.1). ]
3358  Expr *OvlExpr = From->IgnoreParens();
3359
3360  // C++ [over.over]p1:
3361  //   [...] The overloaded function name can be preceded by the &
3362  //   operator.
3363  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3364    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3365      OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3366  }
3367
3368  // Try to dig out the overloaded function.
3369  if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3370    Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3371
3372  // If there's no overloaded function declaration, we're done.
3373  if (!Ovl)
3374    return 0;
3375
3376  // Look through all of the overloaded functions, searching for one
3377  // whose type matches exactly.
3378  // FIXME: When templates or using declarations come along, we'll actually
3379  // have to deal with duplicates, partial ordering, etc. For now, we
3380  // can just do a simple search.
3381  FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3382  for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3383       Fun != Ovl->function_end(); ++Fun) {
3384    // C++ [over.over]p3:
3385    //   Non-member functions and static member functions match
3386    //   targets of type “pointer-to-function”or
3387    //   “reference-to-function.”
3388    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
3389      if (!Method->isStatic())
3390        continue;
3391
3392    if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3393      return *Fun;
3394  }
3395
3396  return 0;
3397}
3398
3399/// ResolveOverloadedCallFn - Given the call expression that calls Fn
3400/// (which eventually refers to the set of overloaded functions in
3401/// Ovl) and the call arguments Args/NumArgs, attempt to resolve the
3402/// function call down to a specific function. If overload resolution
3403/// succeeds, returns the function declaration produced by overload
3404/// resolution. Otherwise, emits diagnostics, deletes all of the
3405/// arguments and Fn, and returns NULL.
3406FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, OverloadedFunctionDecl *Ovl,
3407                                            SourceLocation LParenLoc,
3408                                            Expr **Args, unsigned NumArgs,
3409                                            SourceLocation *CommaLocs,
3410                                            SourceLocation RParenLoc) {
3411  OverloadCandidateSet CandidateSet;
3412  AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
3413  OverloadCandidateSet::iterator Best;
3414  switch (BestViableFunction(CandidateSet, Best)) {
3415  case OR_Success:
3416    return Best->Function;
3417
3418  case OR_No_Viable_Function:
3419    Diag(Fn->getSourceRange().getBegin(),
3420         diag::err_ovl_no_viable_function_in_call)
3421      << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3422      << Fn->getSourceRange();
3423    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3424    break;
3425
3426  case OR_Ambiguous:
3427    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
3428      << Ovl->getDeclName() << Fn->getSourceRange();
3429    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3430    break;
3431  }
3432
3433  // Overload resolution failed. Destroy all of the subexpressions and
3434  // return NULL.
3435  Fn->Destroy(Context);
3436  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3437    Args[Arg]->Destroy(Context);
3438  return 0;
3439}
3440
3441/// BuildCallToMemberFunction - Build a call to a member
3442/// function. MemExpr is the expression that refers to the member
3443/// function (and includes the object parameter), Args/NumArgs are the
3444/// arguments to the function call (not including the object
3445/// parameter). The caller needs to validate that the member
3446/// expression refers to a member function or an overloaded member
3447/// function.
3448Sema::ExprResult
3449Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
3450                                SourceLocation LParenLoc, Expr **Args,
3451                                unsigned NumArgs, SourceLocation *CommaLocs,
3452                                SourceLocation RParenLoc) {
3453  // Dig out the member expression. This holds both the object
3454  // argument and the member function we're referring to.
3455  MemberExpr *MemExpr = 0;
3456  if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
3457    MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
3458  else
3459    MemExpr = dyn_cast<MemberExpr>(MemExprE);
3460  assert(MemExpr && "Building member call without member expression");
3461
3462  // Extract the object argument.
3463  Expr *ObjectArg = MemExpr->getBase();
3464  if (MemExpr->isArrow())
3465    ObjectArg = new UnaryOperator(ObjectArg, UnaryOperator::Deref,
3466                      ObjectArg->getType()->getAsPointerType()->getPointeeType(),
3467                      SourceLocation());
3468  CXXMethodDecl *Method = 0;
3469  if (OverloadedFunctionDecl *Ovl
3470        = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
3471    // Add overload candidates
3472    OverloadCandidateSet CandidateSet;
3473    for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3474                                                FuncEnd = Ovl->function_end();
3475         Func != FuncEnd; ++Func) {
3476      assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
3477      Method = cast<CXXMethodDecl>(*Func);
3478      AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
3479                         /*SuppressUserConversions=*/false);
3480    }
3481
3482    OverloadCandidateSet::iterator Best;
3483    switch (BestViableFunction(CandidateSet, Best)) {
3484    case OR_Success:
3485      Method = cast<CXXMethodDecl>(Best->Function);
3486      break;
3487
3488    case OR_No_Viable_Function:
3489      Diag(MemExpr->getSourceRange().getBegin(),
3490           diag::err_ovl_no_viable_member_function_in_call)
3491        << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3492        << MemExprE->getSourceRange();
3493      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3494      // FIXME: Leaking incoming expressions!
3495      return true;
3496
3497    case OR_Ambiguous:
3498      Diag(MemExpr->getSourceRange().getBegin(),
3499           diag::err_ovl_ambiguous_member_call)
3500        << Ovl->getDeclName() << MemExprE->getSourceRange();
3501      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3502      // FIXME: Leaking incoming expressions!
3503      return true;
3504    }
3505
3506    FixOverloadedFunctionReference(MemExpr, Method);
3507  } else {
3508    Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
3509  }
3510
3511  assert(Method && "Member call to something that isn't a method?");
3512  llvm::OwningPtr<CXXMemberCallExpr>
3513    TheCall(new CXXMemberCallExpr(MemExpr, Args, NumArgs,
3514                                  Method->getResultType().getNonReferenceType(),
3515                                  RParenLoc));
3516
3517  // Convert the object argument (for a non-static member function call).
3518  if (!Method->isStatic() &&
3519      PerformObjectArgumentInitialization(ObjectArg, Method))
3520    return true;
3521  MemExpr->setBase(ObjectArg);
3522
3523  // Convert the rest of the arguments
3524  const FunctionTypeProto *Proto = cast<FunctionTypeProto>(Method->getType());
3525  if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
3526                              RParenLoc))
3527    return true;
3528
3529  return CheckFunctionCall(Method, TheCall.take()).release();
3530}
3531
3532/// BuildCallToObjectOfClassType - Build a call to an object of class
3533/// type (C++ [over.call.object]), which can end up invoking an
3534/// overloaded function call operator (@c operator()) or performing a
3535/// user-defined conversion on the object argument.
3536Sema::ExprResult
3537Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
3538                                   SourceLocation LParenLoc,
3539                                   Expr **Args, unsigned NumArgs,
3540                                   SourceLocation *CommaLocs,
3541                                   SourceLocation RParenLoc) {
3542  assert(Object->getType()->isRecordType() && "Requires object type argument");
3543  const RecordType *Record = Object->getType()->getAsRecordType();
3544
3545  // C++ [over.call.object]p1:
3546  //  If the primary-expression E in the function call syntax
3547  //  evaluates to a class object of type “cv T”, then the set of
3548  //  candidate functions includes at least the function call
3549  //  operators of T. The function call operators of T are obtained by
3550  //  ordinary lookup of the name operator() in the context of
3551  //  (E).operator().
3552  OverloadCandidateSet CandidateSet;
3553  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
3554  DeclContext::lookup_const_iterator Oper, OperEnd;
3555  for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
3556       Oper != OperEnd; ++Oper)
3557    AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
3558                       CandidateSet, /*SuppressUserConversions=*/false);
3559
3560  // C++ [over.call.object]p2:
3561  //   In addition, for each conversion function declared in T of the
3562  //   form
3563  //
3564  //        operator conversion-type-id () cv-qualifier;
3565  //
3566  //   where cv-qualifier is the same cv-qualification as, or a
3567  //   greater cv-qualification than, cv, and where conversion-type-id
3568  //   denotes the type "pointer to function of (P1,...,Pn) returning
3569  //   R", or the type "reference to pointer to function of
3570  //   (P1,...,Pn) returning R", or the type "reference to function
3571  //   of (P1,...,Pn) returning R", a surrogate call function [...]
3572  //   is also considered as a candidate function. Similarly,
3573  //   surrogate call functions are added to the set of candidate
3574  //   functions for each conversion function declared in an
3575  //   accessible base class provided the function is not hidden
3576  //   within T by another intervening declaration.
3577  //
3578  // FIXME: Look in base classes for more conversion operators!
3579  OverloadedFunctionDecl *Conversions
3580    = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
3581  for (OverloadedFunctionDecl::function_iterator
3582         Func = Conversions->function_begin(),
3583         FuncEnd = Conversions->function_end();
3584       Func != FuncEnd; ++Func) {
3585    CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
3586
3587    // Strip the reference type (if any) and then the pointer type (if
3588    // any) to get down to what might be a function type.
3589    QualType ConvType = Conv->getConversionType().getNonReferenceType();
3590    if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
3591      ConvType = ConvPtrType->getPointeeType();
3592
3593    if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto())
3594      AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
3595  }
3596
3597  // Perform overload resolution.
3598  OverloadCandidateSet::iterator Best;
3599  switch (BestViableFunction(CandidateSet, Best)) {
3600  case OR_Success:
3601    // Overload resolution succeeded; we'll build the appropriate call
3602    // below.
3603    break;
3604
3605  case OR_No_Viable_Function:
3606    Diag(Object->getSourceRange().getBegin(),
3607         diag::err_ovl_no_viable_object_call)
3608      << Object->getType() << (unsigned)CandidateSet.size()
3609      << Object->getSourceRange();
3610    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3611    break;
3612
3613  case OR_Ambiguous:
3614    Diag(Object->getSourceRange().getBegin(),
3615         diag::err_ovl_ambiguous_object_call)
3616      << Object->getType() << Object->getSourceRange();
3617    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3618    break;
3619  }
3620
3621  if (Best == CandidateSet.end()) {
3622    // We had an error; delete all of the subexpressions and return
3623    // the error.
3624    delete Object;
3625    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3626      delete Args[ArgIdx];
3627    return true;
3628  }
3629
3630  if (Best->Function == 0) {
3631    // Since there is no function declaration, this is one of the
3632    // surrogate candidates. Dig out the conversion function.
3633    CXXConversionDecl *Conv
3634      = cast<CXXConversionDecl>(
3635                         Best->Conversions[0].UserDefined.ConversionFunction);
3636
3637    // We selected one of the surrogate functions that converts the
3638    // object parameter to a function pointer. Perform the conversion
3639    // on the object argument, then let ActOnCallExpr finish the job.
3640    // FIXME: Represent the user-defined conversion in the AST!
3641    ImpCastExprToType(Object,
3642                      Conv->getConversionType().getNonReferenceType(),
3643                      Conv->getConversionType()->isReferenceType());
3644    return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
3645                         MultiExprArg(*this, (ExprTy**)Args, NumArgs),
3646                         CommaLocs, RParenLoc).release();
3647  }
3648
3649  // We found an overloaded operator(). Build a CXXOperatorCallExpr
3650  // that calls this method, using Object for the implicit object
3651  // parameter and passing along the remaining arguments.
3652  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
3653  const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto();
3654
3655  unsigned NumArgsInProto = Proto->getNumArgs();
3656  unsigned NumArgsToCheck = NumArgs;
3657
3658  // Build the full argument list for the method call (the
3659  // implicit object parameter is placed at the beginning of the
3660  // list).
3661  Expr **MethodArgs;
3662  if (NumArgs < NumArgsInProto) {
3663    NumArgsToCheck = NumArgsInProto;
3664    MethodArgs = new Expr*[NumArgsInProto + 1];
3665  } else {
3666    MethodArgs = new Expr*[NumArgs + 1];
3667  }
3668  MethodArgs[0] = Object;
3669  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3670    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
3671
3672  Expr *NewFn = new DeclRefExpr(Method, Method->getType(),
3673                                SourceLocation());
3674  UsualUnaryConversions(NewFn);
3675
3676  // Once we've built TheCall, all of the expressions are properly
3677  // owned.
3678  QualType ResultTy = Method->getResultType().getNonReferenceType();
3679  llvm::OwningPtr<CXXOperatorCallExpr>
3680    TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1,
3681                                    ResultTy, RParenLoc));
3682  delete [] MethodArgs;
3683
3684  // We may have default arguments. If so, we need to allocate more
3685  // slots in the call for them.
3686  if (NumArgs < NumArgsInProto)
3687    TheCall->setNumArgs(NumArgsInProto + 1);
3688  else if (NumArgs > NumArgsInProto)
3689    NumArgsToCheck = NumArgsInProto;
3690
3691  // Initialize the implicit object parameter.
3692  if (PerformObjectArgumentInitialization(Object, Method))
3693    return true;
3694  TheCall->setArg(0, Object);
3695
3696  // Check the argument types.
3697  for (unsigned i = 0; i != NumArgsToCheck; i++) {
3698    Expr *Arg;
3699    if (i < NumArgs) {
3700      Arg = Args[i];
3701
3702      // Pass the argument.
3703      QualType ProtoArgType = Proto->getArgType(i);
3704      if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3705        return true;
3706    } else {
3707      Arg = new CXXDefaultArgExpr(Method->getParamDecl(i));
3708    }
3709
3710    TheCall->setArg(i + 1, Arg);
3711  }
3712
3713  // If this is a variadic call, handle args passed through "...".
3714  if (Proto->isVariadic()) {
3715    // Promote the arguments (C99 6.5.2.2p7).
3716    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3717      Expr *Arg = Args[i];
3718
3719      DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
3720      TheCall->setArg(i + 1, Arg);
3721    }
3722  }
3723
3724  return CheckFunctionCall(Method, TheCall.take()).release();
3725}
3726
3727/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
3728///  (if one exists), where @c Base is an expression of class type and
3729/// @c Member is the name of the member we're trying to find.
3730Action::ExprResult
3731Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
3732                               SourceLocation MemberLoc,
3733                               IdentifierInfo &Member) {
3734  assert(Base->getType()->isRecordType() && "left-hand side must have class type");
3735
3736  // C++ [over.ref]p1:
3737  //
3738  //   [...] An expression x->m is interpreted as (x.operator->())->m
3739  //   for a class object x of type T if T::operator->() exists and if
3740  //   the operator is selected as the best match function by the
3741  //   overload resolution mechanism (13.3).
3742  // FIXME: look in base classes.
3743  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
3744  OverloadCandidateSet CandidateSet;
3745  const RecordType *BaseRecord = Base->getType()->getAsRecordType();
3746
3747  DeclContext::lookup_const_iterator Oper, OperEnd;
3748  for (llvm::tie(Oper, OperEnd) = BaseRecord->getDecl()->lookup(OpName);
3749       Oper != OperEnd; ++Oper)
3750    AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
3751                       /*SuppressUserConversions=*/false);
3752
3753  llvm::OwningPtr<Expr> BasePtr(Base);
3754
3755  // Perform overload resolution.
3756  OverloadCandidateSet::iterator Best;
3757  switch (BestViableFunction(CandidateSet, Best)) {
3758  case OR_Success:
3759    // Overload resolution succeeded; we'll build the call below.
3760    break;
3761
3762  case OR_No_Viable_Function:
3763    if (CandidateSet.empty())
3764      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
3765        << BasePtr->getType() << BasePtr->getSourceRange();
3766    else
3767      Diag(OpLoc, diag::err_ovl_no_viable_oper)
3768        << "operator->" << (unsigned)CandidateSet.size()
3769        << BasePtr->getSourceRange();
3770    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3771    return true;
3772
3773  case OR_Ambiguous:
3774    Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
3775      << "operator->" << BasePtr->getSourceRange();
3776    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3777    return true;
3778  }
3779
3780  // Convert the object parameter.
3781  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
3782  if (PerformObjectArgumentInitialization(Base, Method))
3783    return true;
3784
3785  // No concerns about early exits now.
3786  BasePtr.take();
3787
3788  // Build the operator call.
3789  Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation());
3790  UsualUnaryConversions(FnExpr);
3791  Base = new CXXOperatorCallExpr(FnExpr, &Base, 1,
3792                                 Method->getResultType().getNonReferenceType(),
3793                                 OpLoc);
3794  return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
3795                                  MemberLoc, Member).release();
3796}
3797
3798/// FixOverloadedFunctionReference - E is an expression that refers to
3799/// a C++ overloaded function (possibly with some parentheses and
3800/// perhaps a '&' around it). We have resolved the overloaded function
3801/// to the function declaration Fn, so patch up the expression E to
3802/// refer (possibly indirectly) to Fn.
3803void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
3804  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
3805    FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
3806    E->setType(PE->getSubExpr()->getType());
3807  } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
3808    assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
3809           "Can only take the address of an overloaded function");
3810    FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
3811    E->setType(Context.getPointerType(E->getType()));
3812  } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
3813    assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
3814           "Expected overloaded function");
3815    DR->setDecl(Fn);
3816    E->setType(Fn->getType());
3817  } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
3818    MemExpr->setMemberDecl(Fn);
3819    E->setType(Fn->getType());
3820  } else {
3821    assert(false && "Invalid reference to overloaded function");
3822  }
3823}
3824
3825} // end namespace clang
3826