SemaOverload.cpp revision 74253736184c0717a0649922551bf9d8b6815651
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/TypeOrdering.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/Support/Compiler.h"
23#include <algorithm>
24
25namespace clang {
26
27/// GetConversionCategory - Retrieve the implicit conversion
28/// category corresponding to the given implicit conversion kind.
29ImplicitConversionCategory
30GetConversionCategory(ImplicitConversionKind Kind) {
31  static const ImplicitConversionCategory
32    Category[(int)ICK_Num_Conversion_Kinds] = {
33    ICC_Identity,
34    ICC_Lvalue_Transformation,
35    ICC_Lvalue_Transformation,
36    ICC_Lvalue_Transformation,
37    ICC_Qualification_Adjustment,
38    ICC_Promotion,
39    ICC_Promotion,
40    ICC_Conversion,
41    ICC_Conversion,
42    ICC_Conversion,
43    ICC_Conversion,
44    ICC_Conversion,
45    ICC_Conversion,
46    ICC_Conversion
47  };
48  return Category[(int)Kind];
49}
50
51/// GetConversionRank - Retrieve the implicit conversion rank
52/// corresponding to the given implicit conversion kind.
53ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
54  static const ImplicitConversionRank
55    Rank[(int)ICK_Num_Conversion_Kinds] = {
56    ICR_Exact_Match,
57    ICR_Exact_Match,
58    ICR_Exact_Match,
59    ICR_Exact_Match,
60    ICR_Exact_Match,
61    ICR_Promotion,
62    ICR_Promotion,
63    ICR_Conversion,
64    ICR_Conversion,
65    ICR_Conversion,
66    ICR_Conversion,
67    ICR_Conversion,
68    ICR_Conversion,
69    ICR_Conversion
70  };
71  return Rank[(int)Kind];
72}
73
74/// GetImplicitConversionName - Return the name of this kind of
75/// implicit conversion.
76const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
77  static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
78    "No conversion",
79    "Lvalue-to-rvalue",
80    "Array-to-pointer",
81    "Function-to-pointer",
82    "Qualification",
83    "Integral promotion",
84    "Floating point promotion",
85    "Integral conversion",
86    "Floating conversion",
87    "Floating-integral conversion",
88    "Pointer conversion",
89    "Pointer-to-member conversion",
90    "Boolean conversion",
91    "Derived-to-base conversion"
92  };
93  return Name[Kind];
94}
95
96/// StandardConversionSequence - Set the standard conversion
97/// sequence to the identity conversion.
98void StandardConversionSequence::setAsIdentityConversion() {
99  First = ICK_Identity;
100  Second = ICK_Identity;
101  Third = ICK_Identity;
102  Deprecated = false;
103  ReferenceBinding = false;
104  DirectBinding = false;
105  CopyConstructor = 0;
106}
107
108/// getRank - Retrieve the rank of this standard conversion sequence
109/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
110/// implicit conversions.
111ImplicitConversionRank StandardConversionSequence::getRank() const {
112  ImplicitConversionRank Rank = ICR_Exact_Match;
113  if  (GetConversionRank(First) > Rank)
114    Rank = GetConversionRank(First);
115  if  (GetConversionRank(Second) > Rank)
116    Rank = GetConversionRank(Second);
117  if  (GetConversionRank(Third) > Rank)
118    Rank = GetConversionRank(Third);
119  return Rank;
120}
121
122/// isPointerConversionToBool - Determines whether this conversion is
123/// a conversion of a pointer or pointer-to-member to bool. This is
124/// used as part of the ranking of standard conversion sequences
125/// (C++ 13.3.3.2p4).
126bool StandardConversionSequence::isPointerConversionToBool() const
127{
128  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
129  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
130
131  // Note that FromType has not necessarily been transformed by the
132  // array-to-pointer or function-to-pointer implicit conversions, so
133  // check for their presence as well as checking whether FromType is
134  // a pointer.
135  if (ToType->isBooleanType() &&
136      (FromType->isPointerType() ||
137       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
138    return true;
139
140  return false;
141}
142
143/// isPointerConversionToVoidPointer - Determines whether this
144/// conversion is a conversion of a pointer to a void pointer. This is
145/// used as part of the ranking of standard conversion sequences (C++
146/// 13.3.3.2p4).
147bool
148StandardConversionSequence::
149isPointerConversionToVoidPointer(ASTContext& Context) const
150{
151  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
152  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
153
154  // Note that FromType has not necessarily been transformed by the
155  // array-to-pointer implicit conversion, so check for its presence
156  // and redo the conversion to get a pointer.
157  if (First == ICK_Array_To_Pointer)
158    FromType = Context.getArrayDecayedType(FromType);
159
160  if (Second == ICK_Pointer_Conversion)
161    if (const PointerType* ToPtrType = ToType->getAsPointerType())
162      return ToPtrType->getPointeeType()->isVoidType();
163
164  return false;
165}
166
167/// DebugPrint - Print this standard conversion sequence to standard
168/// error. Useful for debugging overloading issues.
169void StandardConversionSequence::DebugPrint() const {
170  bool PrintedSomething = false;
171  if (First != ICK_Identity) {
172    fprintf(stderr, "%s", GetImplicitConversionName(First));
173    PrintedSomething = true;
174  }
175
176  if (Second != ICK_Identity) {
177    if (PrintedSomething) {
178      fprintf(stderr, " -> ");
179    }
180    fprintf(stderr, "%s", GetImplicitConversionName(Second));
181
182    if (CopyConstructor) {
183      fprintf(stderr, " (by copy constructor)");
184    } else if (DirectBinding) {
185      fprintf(stderr, " (direct reference binding)");
186    } else if (ReferenceBinding) {
187      fprintf(stderr, " (reference binding)");
188    }
189    PrintedSomething = true;
190  }
191
192  if (Third != ICK_Identity) {
193    if (PrintedSomething) {
194      fprintf(stderr, " -> ");
195    }
196    fprintf(stderr, "%s", GetImplicitConversionName(Third));
197    PrintedSomething = true;
198  }
199
200  if (!PrintedSomething) {
201    fprintf(stderr, "No conversions required");
202  }
203}
204
205/// DebugPrint - Print this user-defined conversion sequence to standard
206/// error. Useful for debugging overloading issues.
207void UserDefinedConversionSequence::DebugPrint() const {
208  if (Before.First || Before.Second || Before.Third) {
209    Before.DebugPrint();
210    fprintf(stderr, " -> ");
211  }
212  fprintf(stderr, "'%s'", ConversionFunction->getName().c_str());
213  if (After.First || After.Second || After.Third) {
214    fprintf(stderr, " -> ");
215    After.DebugPrint();
216  }
217}
218
219/// DebugPrint - Print this implicit conversion sequence to standard
220/// error. Useful for debugging overloading issues.
221void ImplicitConversionSequence::DebugPrint() const {
222  switch (ConversionKind) {
223  case StandardConversion:
224    fprintf(stderr, "Standard conversion: ");
225    Standard.DebugPrint();
226    break;
227  case UserDefinedConversion:
228    fprintf(stderr, "User-defined conversion: ");
229    UserDefined.DebugPrint();
230    break;
231  case EllipsisConversion:
232    fprintf(stderr, "Ellipsis conversion");
233    break;
234  case BadConversion:
235    fprintf(stderr, "Bad conversion");
236    break;
237  }
238
239  fprintf(stderr, "\n");
240}
241
242// IsOverload - Determine whether the given New declaration is an
243// overload of the Old declaration. This routine returns false if New
244// and Old cannot be overloaded, e.g., if they are functions with the
245// same signature (C++ 1.3.10) or if the Old declaration isn't a
246// function (or overload set). When it does return false and Old is an
247// OverloadedFunctionDecl, MatchedDecl will be set to point to the
248// FunctionDecl that New cannot be overloaded with.
249//
250// Example: Given the following input:
251//
252//   void f(int, float); // #1
253//   void f(int, int); // #2
254//   int f(int, int); // #3
255//
256// When we process #1, there is no previous declaration of "f",
257// so IsOverload will not be used.
258//
259// When we process #2, Old is a FunctionDecl for #1.  By comparing the
260// parameter types, we see that #1 and #2 are overloaded (since they
261// have different signatures), so this routine returns false;
262// MatchedDecl is unchanged.
263//
264// When we process #3, Old is an OverloadedFunctionDecl containing #1
265// and #2. We compare the signatures of #3 to #1 (they're overloaded,
266// so we do nothing) and then #3 to #2. Since the signatures of #3 and
267// #2 are identical (return types of functions are not part of the
268// signature), IsOverload returns false and MatchedDecl will be set to
269// point to the FunctionDecl for #2.
270bool
271Sema::IsOverload(FunctionDecl *New, Decl* OldD,
272                 OverloadedFunctionDecl::function_iterator& MatchedDecl)
273{
274  if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
275    // Is this new function an overload of every function in the
276    // overload set?
277    OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
278                                           FuncEnd = Ovl->function_end();
279    for (; Func != FuncEnd; ++Func) {
280      if (!IsOverload(New, *Func, MatchedDecl)) {
281        MatchedDecl = Func;
282        return false;
283      }
284    }
285
286    // This function overloads every function in the overload set.
287    return true;
288  } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
289    // Is the function New an overload of the function Old?
290    QualType OldQType = Context.getCanonicalType(Old->getType());
291    QualType NewQType = Context.getCanonicalType(New->getType());
292
293    // Compare the signatures (C++ 1.3.10) of the two functions to
294    // determine whether they are overloads. If we find any mismatch
295    // in the signature, they are overloads.
296
297    // If either of these functions is a K&R-style function (no
298    // prototype), then we consider them to have matching signatures.
299    if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
300        isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
301      return false;
302
303    FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
304    FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
305
306    // The signature of a function includes the types of its
307    // parameters (C++ 1.3.10), which includes the presence or absence
308    // of the ellipsis; see C++ DR 357).
309    if (OldQType != NewQType &&
310        (OldType->getNumArgs() != NewType->getNumArgs() ||
311         OldType->isVariadic() != NewType->isVariadic() ||
312         !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
313                     NewType->arg_type_begin())))
314      return true;
315
316    // If the function is a class member, its signature includes the
317    // cv-qualifiers (if any) on the function itself.
318    //
319    // As part of this, also check whether one of the member functions
320    // is static, in which case they are not overloads (C++
321    // 13.1p2). While not part of the definition of the signature,
322    // this check is important to determine whether these functions
323    // can be overloaded.
324    CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
325    CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
326    if (OldMethod && NewMethod &&
327        !OldMethod->isStatic() && !NewMethod->isStatic() &&
328        OldQType.getCVRQualifiers() != NewQType.getCVRQualifiers())
329      return true;
330
331    // The signatures match; this is not an overload.
332    return false;
333  } else {
334    // (C++ 13p1):
335    //   Only function declarations can be overloaded; object and type
336    //   declarations cannot be overloaded.
337    return false;
338  }
339}
340
341/// TryImplicitConversion - Attempt to perform an implicit conversion
342/// from the given expression (Expr) to the given type (ToType). This
343/// function returns an implicit conversion sequence that can be used
344/// to perform the initialization. Given
345///
346///   void f(float f);
347///   void g(int i) { f(i); }
348///
349/// this routine would produce an implicit conversion sequence to
350/// describe the initialization of f from i, which will be a standard
351/// conversion sequence containing an lvalue-to-rvalue conversion (C++
352/// 4.1) followed by a floating-integral conversion (C++ 4.9).
353//
354/// Note that this routine only determines how the conversion can be
355/// performed; it does not actually perform the conversion. As such,
356/// it will not produce any diagnostics if no conversion is available,
357/// but will instead return an implicit conversion sequence of kind
358/// "BadConversion".
359///
360/// If @p SuppressUserConversions, then user-defined conversions are
361/// not permitted.
362ImplicitConversionSequence
363Sema::TryImplicitConversion(Expr* From, QualType ToType,
364                            bool SuppressUserConversions)
365{
366  ImplicitConversionSequence ICS;
367  if (IsStandardConversion(From, ToType, ICS.Standard))
368    ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
369  else if (!SuppressUserConversions &&
370           IsUserDefinedConversion(From, ToType, ICS.UserDefined)) {
371    ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
372    // C++ [over.ics.user]p4:
373    //   A conversion of an expression of class type to the same class
374    //   type is given Exact Match rank, and a conversion of an
375    //   expression of class type to a base class of that type is
376    //   given Conversion rank, in spite of the fact that a copy
377    //   constructor (i.e., a user-defined conversion function) is
378    //   called for those cases.
379    if (CXXConstructorDecl *Constructor
380          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
381      if (Constructor->isCopyConstructor(Context)) {
382        // Turn this into a "standard" conversion sequence, so that it
383        // gets ranked with standard conversion sequences.
384        ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
385        ICS.Standard.setAsIdentityConversion();
386        ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
387        ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
388        ICS.Standard.CopyConstructor = Constructor;
389        if (IsDerivedFrom(From->getType().getUnqualifiedType(),
390                          ToType.getUnqualifiedType()))
391          ICS.Standard.Second = ICK_Derived_To_Base;
392      }
393    }
394  } else
395    ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
396
397  return ICS;
398}
399
400/// IsStandardConversion - Determines whether there is a standard
401/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
402/// expression From to the type ToType. Standard conversion sequences
403/// only consider non-class types; for conversions that involve class
404/// types, use TryImplicitConversion. If a conversion exists, SCS will
405/// contain the standard conversion sequence required to perform this
406/// conversion and this routine will return true. Otherwise, this
407/// routine will return false and the value of SCS is unspecified.
408bool
409Sema::IsStandardConversion(Expr* From, QualType ToType,
410                           StandardConversionSequence &SCS)
411{
412  QualType FromType = From->getType();
413
414  // There are no standard conversions for class types, so abort early.
415  if (FromType->isRecordType() || ToType->isRecordType())
416    return false;
417
418  // Standard conversions (C++ [conv])
419  SCS.setAsIdentityConversion();
420  SCS.Deprecated = false;
421  SCS.FromTypePtr = FromType.getAsOpaquePtr();
422  SCS.CopyConstructor = 0;
423
424  // The first conversion can be an lvalue-to-rvalue conversion,
425  // array-to-pointer conversion, or function-to-pointer conversion
426  // (C++ 4p1).
427
428  // Lvalue-to-rvalue conversion (C++ 4.1):
429  //   An lvalue (3.10) of a non-function, non-array type T can be
430  //   converted to an rvalue.
431  Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
432  if (argIsLvalue == Expr::LV_Valid &&
433      !FromType->isFunctionType() && !FromType->isArrayType() &&
434      !FromType->isOverloadType()) {
435    SCS.First = ICK_Lvalue_To_Rvalue;
436
437    // If T is a non-class type, the type of the rvalue is the
438    // cv-unqualified version of T. Otherwise, the type of the rvalue
439    // is T (C++ 4.1p1).
440    FromType = FromType.getUnqualifiedType();
441  }
442  // Array-to-pointer conversion (C++ 4.2)
443  else if (FromType->isArrayType()) {
444    SCS.First = ICK_Array_To_Pointer;
445
446    // An lvalue or rvalue of type "array of N T" or "array of unknown
447    // bound of T" can be converted to an rvalue of type "pointer to
448    // T" (C++ 4.2p1).
449    FromType = Context.getArrayDecayedType(FromType);
450
451    if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
452      // This conversion is deprecated. (C++ D.4).
453      SCS.Deprecated = true;
454
455      // For the purpose of ranking in overload resolution
456      // (13.3.3.1.1), this conversion is considered an
457      // array-to-pointer conversion followed by a qualification
458      // conversion (4.4). (C++ 4.2p2)
459      SCS.Second = ICK_Identity;
460      SCS.Third = ICK_Qualification;
461      SCS.ToTypePtr = ToType.getAsOpaquePtr();
462      return true;
463    }
464  }
465  // Function-to-pointer conversion (C++ 4.3).
466  else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
467    SCS.First = ICK_Function_To_Pointer;
468
469    // An lvalue of function type T can be converted to an rvalue of
470    // type "pointer to T." The result is a pointer to the
471    // function. (C++ 4.3p1).
472    FromType = Context.getPointerType(FromType);
473  }
474  // Address of overloaded function (C++ [over.over]).
475  else if (FunctionDecl *Fn
476             = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
477    SCS.First = ICK_Function_To_Pointer;
478
479    // We were able to resolve the address of the overloaded function,
480    // so we can convert to the type of that function.
481    FromType = Fn->getType();
482    if (ToType->isReferenceType())
483      FromType = Context.getReferenceType(FromType);
484    else
485      FromType = Context.getPointerType(FromType);
486  }
487  // We don't require any conversions for the first step.
488  else {
489    SCS.First = ICK_Identity;
490  }
491
492  // The second conversion can be an integral promotion, floating
493  // point promotion, integral conversion, floating point conversion,
494  // floating-integral conversion, pointer conversion,
495  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
496  if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
497      Context.getCanonicalType(ToType).getUnqualifiedType()) {
498    // The unqualified versions of the types are the same: there's no
499    // conversion to do.
500    SCS.Second = ICK_Identity;
501  }
502  // Integral promotion (C++ 4.5).
503  else if (IsIntegralPromotion(From, FromType, ToType)) {
504    SCS.Second = ICK_Integral_Promotion;
505    FromType = ToType.getUnqualifiedType();
506  }
507  // Floating point promotion (C++ 4.6).
508  else if (IsFloatingPointPromotion(FromType, ToType)) {
509    SCS.Second = ICK_Floating_Promotion;
510    FromType = ToType.getUnqualifiedType();
511  }
512  // Integral conversions (C++ 4.7).
513  // FIXME: isIntegralType shouldn't be true for enums in C++.
514  else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
515           (ToType->isIntegralType() && !ToType->isEnumeralType())) {
516    SCS.Second = ICK_Integral_Conversion;
517    FromType = ToType.getUnqualifiedType();
518  }
519  // Floating point conversions (C++ 4.8).
520  else if (FromType->isFloatingType() && ToType->isFloatingType()) {
521    SCS.Second = ICK_Floating_Conversion;
522    FromType = ToType.getUnqualifiedType();
523  }
524  // Floating-integral conversions (C++ 4.9).
525  // FIXME: isIntegralType shouldn't be true for enums in C++.
526  else if ((FromType->isFloatingType() &&
527            ToType->isIntegralType() && !ToType->isBooleanType() &&
528                                        !ToType->isEnumeralType()) ||
529           ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
530            ToType->isFloatingType())) {
531    SCS.Second = ICK_Floating_Integral;
532    FromType = ToType.getUnqualifiedType();
533  }
534  // Pointer conversions (C++ 4.10).
535  else if (IsPointerConversion(From, FromType, ToType, FromType)) {
536    SCS.Second = ICK_Pointer_Conversion;
537  }
538  // FIXME: Pointer to member conversions (4.11).
539  // Boolean conversions (C++ 4.12).
540  // FIXME: pointer-to-member type
541  else if (ToType->isBooleanType() &&
542           (FromType->isArithmeticType() ||
543            FromType->isEnumeralType() ||
544            FromType->isPointerType())) {
545    SCS.Second = ICK_Boolean_Conversion;
546    FromType = Context.BoolTy;
547  } else {
548    // No second conversion required.
549    SCS.Second = ICK_Identity;
550  }
551
552  QualType CanonFrom;
553  QualType CanonTo;
554  // The third conversion can be a qualification conversion (C++ 4p1).
555  if (IsQualificationConversion(FromType, ToType)) {
556    SCS.Third = ICK_Qualification;
557    FromType = ToType;
558    CanonFrom = Context.getCanonicalType(FromType);
559    CanonTo = Context.getCanonicalType(ToType);
560  } else {
561    // No conversion required
562    SCS.Third = ICK_Identity;
563
564    // C++ [over.best.ics]p6:
565    //   [...] Any difference in top-level cv-qualification is
566    //   subsumed by the initialization itself and does not constitute
567    //   a conversion. [...]
568    CanonFrom = Context.getCanonicalType(FromType);
569    CanonTo = Context.getCanonicalType(ToType);
570    if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
571        CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
572      FromType = ToType;
573      CanonFrom = CanonTo;
574    }
575  }
576
577  // If we have not converted the argument type to the parameter type,
578  // this is a bad conversion sequence.
579  if (CanonFrom != CanonTo)
580    return false;
581
582  SCS.ToTypePtr = FromType.getAsOpaquePtr();
583  return true;
584}
585
586/// IsIntegralPromotion - Determines whether the conversion from the
587/// expression From (whose potentially-adjusted type is FromType) to
588/// ToType is an integral promotion (C++ 4.5). If so, returns true and
589/// sets PromotedType to the promoted type.
590bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
591{
592  const BuiltinType *To = ToType->getAsBuiltinType();
593  // All integers are built-in.
594  if (!To) {
595    return false;
596  }
597
598  // An rvalue of type char, signed char, unsigned char, short int, or
599  // unsigned short int can be converted to an rvalue of type int if
600  // int can represent all the values of the source type; otherwise,
601  // the source rvalue can be converted to an rvalue of type unsigned
602  // int (C++ 4.5p1).
603  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
604    if (// We can promote any signed, promotable integer type to an int
605        (FromType->isSignedIntegerType() ||
606         // We can promote any unsigned integer type whose size is
607         // less than int to an int.
608         (!FromType->isSignedIntegerType() &&
609          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
610      return To->getKind() == BuiltinType::Int;
611    }
612
613    return To->getKind() == BuiltinType::UInt;
614  }
615
616  // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
617  // can be converted to an rvalue of the first of the following types
618  // that can represent all the values of its underlying type: int,
619  // unsigned int, long, or unsigned long (C++ 4.5p2).
620  if ((FromType->isEnumeralType() || FromType->isWideCharType())
621      && ToType->isIntegerType()) {
622    // Determine whether the type we're converting from is signed or
623    // unsigned.
624    bool FromIsSigned;
625    uint64_t FromSize = Context.getTypeSize(FromType);
626    if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
627      QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
628      FromIsSigned = UnderlyingType->isSignedIntegerType();
629    } else {
630      // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
631      FromIsSigned = true;
632    }
633
634    // The types we'll try to promote to, in the appropriate
635    // order. Try each of these types.
636    QualType PromoteTypes[4] = {
637      Context.IntTy, Context.UnsignedIntTy,
638      Context.LongTy, Context.UnsignedLongTy
639    };
640    for (int Idx = 0; Idx < 4; ++Idx) {
641      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
642      if (FromSize < ToSize ||
643          (FromSize == ToSize &&
644           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
645        // We found the type that we can promote to. If this is the
646        // type we wanted, we have a promotion. Otherwise, no
647        // promotion.
648        return Context.getCanonicalType(ToType).getUnqualifiedType()
649          == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
650      }
651    }
652  }
653
654  // An rvalue for an integral bit-field (9.6) can be converted to an
655  // rvalue of type int if int can represent all the values of the
656  // bit-field; otherwise, it can be converted to unsigned int if
657  // unsigned int can represent all the values of the bit-field. If
658  // the bit-field is larger yet, no integral promotion applies to
659  // it. If the bit-field has an enumerated type, it is treated as any
660  // other value of that type for promotion purposes (C++ 4.5p3).
661  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
662    using llvm::APSInt;
663    FieldDecl *MemberDecl = MemRef->getMemberDecl();
664    APSInt BitWidth;
665    if (MemberDecl->isBitField() &&
666        FromType->isIntegralType() && !FromType->isEnumeralType() &&
667        From->isIntegerConstantExpr(BitWidth, Context)) {
668      APSInt ToSize(Context.getTypeSize(ToType));
669
670      // Are we promoting to an int from a bitfield that fits in an int?
671      if (BitWidth < ToSize ||
672          (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
673        return To->getKind() == BuiltinType::Int;
674      }
675
676      // Are we promoting to an unsigned int from an unsigned bitfield
677      // that fits into an unsigned int?
678      if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
679        return To->getKind() == BuiltinType::UInt;
680      }
681
682      return false;
683    }
684  }
685
686  // An rvalue of type bool can be converted to an rvalue of type int,
687  // with false becoming zero and true becoming one (C++ 4.5p4).
688  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
689    return true;
690  }
691
692  return false;
693}
694
695/// IsFloatingPointPromotion - Determines whether the conversion from
696/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
697/// returns true and sets PromotedType to the promoted type.
698bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
699{
700  /// An rvalue of type float can be converted to an rvalue of type
701  /// double. (C++ 4.6p1).
702  if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
703    if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
704      if (FromBuiltin->getKind() == BuiltinType::Float &&
705          ToBuiltin->getKind() == BuiltinType::Double)
706        return true;
707
708  return false;
709}
710
711/// IsPointerConversion - Determines whether the conversion of the
712/// expression From, which has the (possibly adjusted) type FromType,
713/// can be converted to the type ToType via a pointer conversion (C++
714/// 4.10). If so, returns true and places the converted type (that
715/// might differ from ToType in its cv-qualifiers at some level) into
716/// ConvertedType.
717bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
718                               QualType& ConvertedType)
719{
720  const PointerType* ToTypePtr = ToType->getAsPointerType();
721  if (!ToTypePtr)
722    return false;
723
724  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
725  if (From->isNullPointerConstant(Context)) {
726    ConvertedType = ToType;
727    return true;
728  }
729
730  // An rvalue of type "pointer to cv T," where T is an object type,
731  // can be converted to an rvalue of type "pointer to cv void" (C++
732  // 4.10p2).
733  if (FromType->isPointerType() &&
734      FromType->getAsPointerType()->getPointeeType()->isObjectType() &&
735      ToTypePtr->getPointeeType()->isVoidType()) {
736    // We need to produce a pointer to cv void, where cv is the same
737    // set of cv-qualifiers as we had on the incoming pointee type.
738    QualType toPointee = ToTypePtr->getPointeeType();
739    unsigned Quals = Context.getCanonicalType(FromType)->getAsPointerType()
740                   ->getPointeeType().getCVRQualifiers();
741
742    if (Context.getCanonicalType(ToTypePtr->getPointeeType()).getCVRQualifiers()
743	  == Quals) {
744      // ToType is exactly the type we want. Use it.
745      ConvertedType = ToType;
746    } else {
747      // Build a new type with the right qualifiers.
748      ConvertedType
749	= Context.getPointerType(Context.VoidTy.getQualifiedType(Quals));
750    }
751    return true;
752  }
753
754  // C++ [conv.ptr]p3:
755  //
756  //   An rvalue of type "pointer to cv D," where D is a class type,
757  //   can be converted to an rvalue of type "pointer to cv B," where
758  //   B is a base class (clause 10) of D. If B is an inaccessible
759  //   (clause 11) or ambiguous (10.2) base class of D, a program that
760  //   necessitates this conversion is ill-formed. The result of the
761  //   conversion is a pointer to the base class sub-object of the
762  //   derived class object. The null pointer value is converted to
763  //   the null pointer value of the destination type.
764  //
765  // Note that we do not check for ambiguity or inaccessibility
766  // here. That is handled by CheckPointerConversion.
767  if (const PointerType *FromPtrType = FromType->getAsPointerType())
768    if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
769      if (FromPtrType->getPointeeType()->isRecordType() &&
770          ToPtrType->getPointeeType()->isRecordType() &&
771          IsDerivedFrom(FromPtrType->getPointeeType(),
772                        ToPtrType->getPointeeType())) {
773        // The conversion is okay. Now, we need to produce the type
774        // that results from this conversion, which will have the same
775        // qualifiers as the incoming type.
776        QualType CanonFromPointee
777          = Context.getCanonicalType(FromPtrType->getPointeeType());
778        QualType ToPointee = ToPtrType->getPointeeType();
779        QualType CanonToPointee = Context.getCanonicalType(ToPointee);
780        unsigned Quals = CanonFromPointee.getCVRQualifiers();
781
782        if (CanonToPointee.getCVRQualifiers() == Quals) {
783          // ToType is exactly the type we want. Use it.
784          ConvertedType = ToType;
785        } else {
786          // Build a new type with the right qualifiers.
787          ConvertedType
788            = Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
789        }
790        return true;
791      }
792    }
793
794  return false;
795}
796
797/// CheckPointerConversion - Check the pointer conversion from the
798/// expression From to the type ToType. This routine checks for
799/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
800/// conversions for which IsPointerConversion has already returned
801/// true. It returns true and produces a diagnostic if there was an
802/// error, or returns false otherwise.
803bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
804  QualType FromType = From->getType();
805
806  if (const PointerType *FromPtrType = FromType->getAsPointerType())
807    if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
808      BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
809                      /*DetectVirtual=*/false);
810      QualType FromPointeeType = FromPtrType->getPointeeType(),
811               ToPointeeType   = ToPtrType->getPointeeType();
812      if (FromPointeeType->isRecordType() &&
813          ToPointeeType->isRecordType()) {
814        // We must have a derived-to-base conversion. Check an
815        // ambiguous or inaccessible conversion.
816        return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
817                                            From->getExprLoc(),
818                                            From->getSourceRange());
819      }
820    }
821
822  return false;
823}
824
825/// IsQualificationConversion - Determines whether the conversion from
826/// an rvalue of type FromType to ToType is a qualification conversion
827/// (C++ 4.4).
828bool
829Sema::IsQualificationConversion(QualType FromType, QualType ToType)
830{
831  FromType = Context.getCanonicalType(FromType);
832  ToType = Context.getCanonicalType(ToType);
833
834  // If FromType and ToType are the same type, this is not a
835  // qualification conversion.
836  if (FromType == ToType)
837    return false;
838
839  // (C++ 4.4p4):
840  //   A conversion can add cv-qualifiers at levels other than the first
841  //   in multi-level pointers, subject to the following rules: [...]
842  bool PreviousToQualsIncludeConst = true;
843  bool UnwrappedAnyPointer = false;
844  while (UnwrapSimilarPointerTypes(FromType, ToType)) {
845    // Within each iteration of the loop, we check the qualifiers to
846    // determine if this still looks like a qualification
847    // conversion. Then, if all is well, we unwrap one more level of
848    // pointers or pointers-to-members and do it all again
849    // until there are no more pointers or pointers-to-members left to
850    // unwrap.
851    UnwrappedAnyPointer = true;
852
853    //   -- for every j > 0, if const is in cv 1,j then const is in cv
854    //      2,j, and similarly for volatile.
855    if (!ToType.isAtLeastAsQualifiedAs(FromType))
856      return false;
857
858    //   -- if the cv 1,j and cv 2,j are different, then const is in
859    //      every cv for 0 < k < j.
860    if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
861        && !PreviousToQualsIncludeConst)
862      return false;
863
864    // Keep track of whether all prior cv-qualifiers in the "to" type
865    // include const.
866    PreviousToQualsIncludeConst
867      = PreviousToQualsIncludeConst && ToType.isConstQualified();
868  }
869
870  // We are left with FromType and ToType being the pointee types
871  // after unwrapping the original FromType and ToType the same number
872  // of types. If we unwrapped any pointers, and if FromType and
873  // ToType have the same unqualified type (since we checked
874  // qualifiers above), then this is a qualification conversion.
875  return UnwrappedAnyPointer &&
876    FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
877}
878
879/// IsUserDefinedConversion - Determines whether there is a
880/// user-defined conversion sequence (C++ [over.ics.user]) that
881/// converts expression From to the type ToType. If such a conversion
882/// exists, User will contain the user-defined conversion sequence
883/// that performs such a conversion and this routine will return
884/// true. Otherwise, this routine returns false and User is
885/// unspecified.
886bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
887                                   UserDefinedConversionSequence& User)
888{
889  OverloadCandidateSet CandidateSet;
890  if (const CXXRecordType *ToRecordType
891        = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
892    // C++ [over.match.ctor]p1:
893    //   When objects of class type are direct-initialized (8.5), or
894    //   copy-initialized from an expression of the same or a
895    //   derived class type (8.5), overload resolution selects the
896    //   constructor. [...] For copy-initialization, the candidate
897    //   functions are all the converting constructors (12.3.1) of
898    //   that class. The argument list is the expression-list within
899    //   the parentheses of the initializer.
900    CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
901    const OverloadedFunctionDecl *Constructors = ToRecordDecl->getConstructors();
902    for (OverloadedFunctionDecl::function_const_iterator func
903           = Constructors->function_begin();
904         func != Constructors->function_end(); ++func) {
905      CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func);
906      if (Constructor->isConvertingConstructor())
907        AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
908                             /*SuppressUserConversions=*/true);
909    }
910  }
911
912  if (const CXXRecordType *FromRecordType
913        = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) {
914    // Add all of the conversion functions as candidates.
915    // FIXME: Look for conversions in base classes!
916    CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
917    OverloadedFunctionDecl *Conversions
918      = FromRecordDecl->getConversionFunctions();
919    for (OverloadedFunctionDecl::function_iterator Func
920           = Conversions->function_begin();
921         Func != Conversions->function_end(); ++Func) {
922      CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
923      AddConversionCandidate(Conv, From, ToType, CandidateSet);
924    }
925  }
926
927  OverloadCandidateSet::iterator Best;
928  switch (BestViableFunction(CandidateSet, Best)) {
929    case OR_Success:
930      // Record the standard conversion we used and the conversion function.
931      if (CXXConstructorDecl *Constructor
932            = dyn_cast<CXXConstructorDecl>(Best->Function)) {
933        // C++ [over.ics.user]p1:
934        //   If the user-defined conversion is specified by a
935        //   constructor (12.3.1), the initial standard conversion
936        //   sequence converts the source type to the type required by
937        //   the argument of the constructor.
938        //
939        // FIXME: What about ellipsis conversions?
940        QualType ThisType = Constructor->getThisType(Context);
941        User.Before = Best->Conversions[0].Standard;
942        User.ConversionFunction = Constructor;
943        User.After.setAsIdentityConversion();
944        User.After.FromTypePtr
945          = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
946        User.After.ToTypePtr = ToType.getAsOpaquePtr();
947        return true;
948      } else if (CXXConversionDecl *Conversion
949                   = dyn_cast<CXXConversionDecl>(Best->Function)) {
950        // C++ [over.ics.user]p1:
951        //
952        //   [...] If the user-defined conversion is specified by a
953        //   conversion function (12.3.2), the initial standard
954        //   conversion sequence converts the source type to the
955        //   implicit object parameter of the conversion function.
956        User.Before = Best->Conversions[0].Standard;
957        User.ConversionFunction = Conversion;
958
959        // C++ [over.ics.user]p2:
960        //   The second standard conversion sequence converts the
961        //   result of the user-defined conversion to the target type
962        //   for the sequence. Since an implicit conversion sequence
963        //   is an initialization, the special rules for
964        //   initialization by user-defined conversion apply when
965        //   selecting the best user-defined conversion for a
966        //   user-defined conversion sequence (see 13.3.3 and
967        //   13.3.3.1).
968        User.After = Best->FinalConversion;
969        return true;
970      } else {
971        assert(false && "Not a constructor or conversion function?");
972        return false;
973      }
974
975    case OR_No_Viable_Function:
976      // No conversion here! We're done.
977      return false;
978
979    case OR_Ambiguous:
980      // FIXME: See C++ [over.best.ics]p10 for the handling of
981      // ambiguous conversion sequences.
982      return false;
983    }
984
985  return false;
986}
987
988/// CompareImplicitConversionSequences - Compare two implicit
989/// conversion sequences to determine whether one is better than the
990/// other or if they are indistinguishable (C++ 13.3.3.2).
991ImplicitConversionSequence::CompareKind
992Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
993                                         const ImplicitConversionSequence& ICS2)
994{
995  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
996  // conversion sequences (as defined in 13.3.3.1)
997  //   -- a standard conversion sequence (13.3.3.1.1) is a better
998  //      conversion sequence than a user-defined conversion sequence or
999  //      an ellipsis conversion sequence, and
1000  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
1001  //      conversion sequence than an ellipsis conversion sequence
1002  //      (13.3.3.1.3).
1003  //
1004  if (ICS1.ConversionKind < ICS2.ConversionKind)
1005    return ImplicitConversionSequence::Better;
1006  else if (ICS2.ConversionKind < ICS1.ConversionKind)
1007    return ImplicitConversionSequence::Worse;
1008
1009  // Two implicit conversion sequences of the same form are
1010  // indistinguishable conversion sequences unless one of the
1011  // following rules apply: (C++ 13.3.3.2p3):
1012  if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1013    return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1014  else if (ICS1.ConversionKind ==
1015             ImplicitConversionSequence::UserDefinedConversion) {
1016    // User-defined conversion sequence U1 is a better conversion
1017    // sequence than another user-defined conversion sequence U2 if
1018    // they contain the same user-defined conversion function or
1019    // constructor and if the second standard conversion sequence of
1020    // U1 is better than the second standard conversion sequence of
1021    // U2 (C++ 13.3.3.2p3).
1022    if (ICS1.UserDefined.ConversionFunction ==
1023          ICS2.UserDefined.ConversionFunction)
1024      return CompareStandardConversionSequences(ICS1.UserDefined.After,
1025                                                ICS2.UserDefined.After);
1026  }
1027
1028  return ImplicitConversionSequence::Indistinguishable;
1029}
1030
1031/// CompareStandardConversionSequences - Compare two standard
1032/// conversion sequences to determine whether one is better than the
1033/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1034ImplicitConversionSequence::CompareKind
1035Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1036                                         const StandardConversionSequence& SCS2)
1037{
1038  // Standard conversion sequence S1 is a better conversion sequence
1039  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1040
1041  //  -- S1 is a proper subsequence of S2 (comparing the conversion
1042  //     sequences in the canonical form defined by 13.3.3.1.1,
1043  //     excluding any Lvalue Transformation; the identity conversion
1044  //     sequence is considered to be a subsequence of any
1045  //     non-identity conversion sequence) or, if not that,
1046  if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1047    // Neither is a proper subsequence of the other. Do nothing.
1048    ;
1049  else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1050           (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1051           (SCS1.Second == ICK_Identity &&
1052            SCS1.Third == ICK_Identity))
1053    // SCS1 is a proper subsequence of SCS2.
1054    return ImplicitConversionSequence::Better;
1055  else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1056           (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1057           (SCS2.Second == ICK_Identity &&
1058            SCS2.Third == ICK_Identity))
1059    // SCS2 is a proper subsequence of SCS1.
1060    return ImplicitConversionSequence::Worse;
1061
1062  //  -- the rank of S1 is better than the rank of S2 (by the rules
1063  //     defined below), or, if not that,
1064  ImplicitConversionRank Rank1 = SCS1.getRank();
1065  ImplicitConversionRank Rank2 = SCS2.getRank();
1066  if (Rank1 < Rank2)
1067    return ImplicitConversionSequence::Better;
1068  else if (Rank2 < Rank1)
1069    return ImplicitConversionSequence::Worse;
1070
1071  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1072  // are indistinguishable unless one of the following rules
1073  // applies:
1074
1075  //   A conversion that is not a conversion of a pointer, or
1076  //   pointer to member, to bool is better than another conversion
1077  //   that is such a conversion.
1078  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1079    return SCS2.isPointerConversionToBool()
1080             ? ImplicitConversionSequence::Better
1081             : ImplicitConversionSequence::Worse;
1082
1083  // C++ [over.ics.rank]p4b2:
1084  //
1085  //   If class B is derived directly or indirectly from class A,
1086  //   conversion of B* to A* is better than conversion of B* to
1087  //   void*, and conversion of A* to void* is better than conversion
1088  //   of B* to void*.
1089  bool SCS1ConvertsToVoid
1090    = SCS1.isPointerConversionToVoidPointer(Context);
1091  bool SCS2ConvertsToVoid
1092    = SCS2.isPointerConversionToVoidPointer(Context);
1093  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1094    // Exactly one of the conversion sequences is a conversion to
1095    // a void pointer; it's the worse conversion.
1096    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1097                              : ImplicitConversionSequence::Worse;
1098  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1099    // Neither conversion sequence converts to a void pointer; compare
1100    // their derived-to-base conversions.
1101    if (ImplicitConversionSequence::CompareKind DerivedCK
1102          = CompareDerivedToBaseConversions(SCS1, SCS2))
1103      return DerivedCK;
1104  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1105    // Both conversion sequences are conversions to void
1106    // pointers. Compare the source types to determine if there's an
1107    // inheritance relationship in their sources.
1108    QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1109    QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1110
1111    // Adjust the types we're converting from via the array-to-pointer
1112    // conversion, if we need to.
1113    if (SCS1.First == ICK_Array_To_Pointer)
1114      FromType1 = Context.getArrayDecayedType(FromType1);
1115    if (SCS2.First == ICK_Array_To_Pointer)
1116      FromType2 = Context.getArrayDecayedType(FromType2);
1117
1118    QualType FromPointee1
1119      = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1120    QualType FromPointee2
1121      = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1122
1123    if (IsDerivedFrom(FromPointee2, FromPointee1))
1124      return ImplicitConversionSequence::Better;
1125    else if (IsDerivedFrom(FromPointee1, FromPointee2))
1126      return ImplicitConversionSequence::Worse;
1127  }
1128
1129  // Compare based on qualification conversions (C++ 13.3.3.2p3,
1130  // bullet 3).
1131  if (ImplicitConversionSequence::CompareKind QualCK
1132        = CompareQualificationConversions(SCS1, SCS2))
1133    return QualCK;
1134
1135  // C++ [over.ics.rank]p3b4:
1136  //   -- S1 and S2 are reference bindings (8.5.3), and the types to
1137  //      which the references refer are the same type except for
1138  //      top-level cv-qualifiers, and the type to which the reference
1139  //      initialized by S2 refers is more cv-qualified than the type
1140  //      to which the reference initialized by S1 refers.
1141  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1142    QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1143    QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1144    T1 = Context.getCanonicalType(T1);
1145    T2 = Context.getCanonicalType(T2);
1146    if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1147      if (T2.isMoreQualifiedThan(T1))
1148        return ImplicitConversionSequence::Better;
1149      else if (T1.isMoreQualifiedThan(T2))
1150        return ImplicitConversionSequence::Worse;
1151    }
1152  }
1153
1154  return ImplicitConversionSequence::Indistinguishable;
1155}
1156
1157/// CompareQualificationConversions - Compares two standard conversion
1158/// sequences to determine whether they can be ranked based on their
1159/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1160ImplicitConversionSequence::CompareKind
1161Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1162                                      const StandardConversionSequence& SCS2)
1163{
1164  // C++ 13.3.3.2p3:
1165  //  -- S1 and S2 differ only in their qualification conversion and
1166  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
1167  //     cv-qualification signature of type T1 is a proper subset of
1168  //     the cv-qualification signature of type T2, and S1 is not the
1169  //     deprecated string literal array-to-pointer conversion (4.2).
1170  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1171      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1172    return ImplicitConversionSequence::Indistinguishable;
1173
1174  // FIXME: the example in the standard doesn't use a qualification
1175  // conversion (!)
1176  QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1177  QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1178  T1 = Context.getCanonicalType(T1);
1179  T2 = Context.getCanonicalType(T2);
1180
1181  // If the types are the same, we won't learn anything by unwrapped
1182  // them.
1183  if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1184    return ImplicitConversionSequence::Indistinguishable;
1185
1186  ImplicitConversionSequence::CompareKind Result
1187    = ImplicitConversionSequence::Indistinguishable;
1188  while (UnwrapSimilarPointerTypes(T1, T2)) {
1189    // Within each iteration of the loop, we check the qualifiers to
1190    // determine if this still looks like a qualification
1191    // conversion. Then, if all is well, we unwrap one more level of
1192    // pointers or pointers-to-members and do it all again
1193    // until there are no more pointers or pointers-to-members left
1194    // to unwrap. This essentially mimics what
1195    // IsQualificationConversion does, but here we're checking for a
1196    // strict subset of qualifiers.
1197    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1198      // The qualifiers are the same, so this doesn't tell us anything
1199      // about how the sequences rank.
1200      ;
1201    else if (T2.isMoreQualifiedThan(T1)) {
1202      // T1 has fewer qualifiers, so it could be the better sequence.
1203      if (Result == ImplicitConversionSequence::Worse)
1204        // Neither has qualifiers that are a subset of the other's
1205        // qualifiers.
1206        return ImplicitConversionSequence::Indistinguishable;
1207
1208      Result = ImplicitConversionSequence::Better;
1209    } else if (T1.isMoreQualifiedThan(T2)) {
1210      // T2 has fewer qualifiers, so it could be the better sequence.
1211      if (Result == ImplicitConversionSequence::Better)
1212        // Neither has qualifiers that are a subset of the other's
1213        // qualifiers.
1214        return ImplicitConversionSequence::Indistinguishable;
1215
1216      Result = ImplicitConversionSequence::Worse;
1217    } else {
1218      // Qualifiers are disjoint.
1219      return ImplicitConversionSequence::Indistinguishable;
1220    }
1221
1222    // If the types after this point are equivalent, we're done.
1223    if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1224      break;
1225  }
1226
1227  // Check that the winning standard conversion sequence isn't using
1228  // the deprecated string literal array to pointer conversion.
1229  switch (Result) {
1230  case ImplicitConversionSequence::Better:
1231    if (SCS1.Deprecated)
1232      Result = ImplicitConversionSequence::Indistinguishable;
1233    break;
1234
1235  case ImplicitConversionSequence::Indistinguishable:
1236    break;
1237
1238  case ImplicitConversionSequence::Worse:
1239    if (SCS2.Deprecated)
1240      Result = ImplicitConversionSequence::Indistinguishable;
1241    break;
1242  }
1243
1244  return Result;
1245}
1246
1247/// CompareDerivedToBaseConversions - Compares two standard conversion
1248/// sequences to determine whether they can be ranked based on their
1249/// various kinds of derived-to-base conversions (C++ [over.ics.rank]p4b3).
1250ImplicitConversionSequence::CompareKind
1251Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1252                                      const StandardConversionSequence& SCS2) {
1253  QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1254  QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1255  QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1256  QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1257
1258  // Adjust the types we're converting from via the array-to-pointer
1259  // conversion, if we need to.
1260  if (SCS1.First == ICK_Array_To_Pointer)
1261    FromType1 = Context.getArrayDecayedType(FromType1);
1262  if (SCS2.First == ICK_Array_To_Pointer)
1263    FromType2 = Context.getArrayDecayedType(FromType2);
1264
1265  // Canonicalize all of the types.
1266  FromType1 = Context.getCanonicalType(FromType1);
1267  ToType1 = Context.getCanonicalType(ToType1);
1268  FromType2 = Context.getCanonicalType(FromType2);
1269  ToType2 = Context.getCanonicalType(ToType2);
1270
1271  // C++ [over.ics.rank]p4b3:
1272  //
1273  //   If class B is derived directly or indirectly from class A and
1274  //   class C is derived directly or indirectly from B,
1275
1276  // Compare based on pointer conversions.
1277  if (SCS1.Second == ICK_Pointer_Conversion &&
1278      SCS2.Second == ICK_Pointer_Conversion) {
1279    QualType FromPointee1
1280      = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1281    QualType ToPointee1
1282      = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1283    QualType FromPointee2
1284      = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1285    QualType ToPointee2
1286      = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1287    //   -- conversion of C* to B* is better than conversion of C* to A*,
1288    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1289      if (IsDerivedFrom(ToPointee1, ToPointee2))
1290        return ImplicitConversionSequence::Better;
1291      else if (IsDerivedFrom(ToPointee2, ToPointee1))
1292        return ImplicitConversionSequence::Worse;
1293    }
1294
1295    //   -- conversion of B* to A* is better than conversion of C* to A*,
1296    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1297      if (IsDerivedFrom(FromPointee2, FromPointee1))
1298        return ImplicitConversionSequence::Better;
1299      else if (IsDerivedFrom(FromPointee1, FromPointee2))
1300        return ImplicitConversionSequence::Worse;
1301    }
1302  }
1303
1304  // Compare based on reference bindings.
1305  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1306      SCS1.Second == ICK_Derived_To_Base) {
1307    //   -- binding of an expression of type C to a reference of type
1308    //      B& is better than binding an expression of type C to a
1309    //      reference of type A&,
1310    if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1311        ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1312      if (IsDerivedFrom(ToType1, ToType2))
1313        return ImplicitConversionSequence::Better;
1314      else if (IsDerivedFrom(ToType2, ToType1))
1315        return ImplicitConversionSequence::Worse;
1316    }
1317
1318    //   -- binding of an expression of type B to a reference of type
1319    //      A& is better than binding an expression of type C to a
1320    //      reference of type A&,
1321    if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1322        ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1323      if (IsDerivedFrom(FromType2, FromType1))
1324        return ImplicitConversionSequence::Better;
1325      else if (IsDerivedFrom(FromType1, FromType2))
1326        return ImplicitConversionSequence::Worse;
1327    }
1328  }
1329
1330
1331  // FIXME: conversion of A::* to B::* is better than conversion of
1332  // A::* to C::*,
1333
1334  // FIXME: conversion of B::* to C::* is better than conversion of
1335  // A::* to C::*, and
1336
1337  if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1338      SCS1.Second == ICK_Derived_To_Base) {
1339    //   -- conversion of C to B is better than conversion of C to A,
1340    if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1341        ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1342      if (IsDerivedFrom(ToType1, ToType2))
1343        return ImplicitConversionSequence::Better;
1344      else if (IsDerivedFrom(ToType2, ToType1))
1345        return ImplicitConversionSequence::Worse;
1346    }
1347
1348    //   -- conversion of B to A is better than conversion of C to A.
1349    if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1350        ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1351      if (IsDerivedFrom(FromType2, FromType1))
1352        return ImplicitConversionSequence::Better;
1353      else if (IsDerivedFrom(FromType1, FromType2))
1354        return ImplicitConversionSequence::Worse;
1355    }
1356  }
1357
1358  return ImplicitConversionSequence::Indistinguishable;
1359}
1360
1361/// TryCopyInitialization - Try to copy-initialize a value of type
1362/// ToType from the expression From. Return the implicit conversion
1363/// sequence required to pass this argument, which may be a bad
1364/// conversion sequence (meaning that the argument cannot be passed to
1365/// a parameter of this type). If @p SuppressUserConversions, then we
1366/// do not permit any user-defined conversion sequences.
1367ImplicitConversionSequence
1368Sema::TryCopyInitialization(Expr *From, QualType ToType,
1369                            bool SuppressUserConversions) {
1370  if (!getLangOptions().CPlusPlus) {
1371    // In C, copy initialization is the same as performing an assignment.
1372    AssignConvertType ConvTy =
1373      CheckSingleAssignmentConstraints(ToType, From);
1374    ImplicitConversionSequence ICS;
1375    if (getLangOptions().NoExtensions? ConvTy != Compatible
1376                                     : ConvTy == Incompatible)
1377      ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1378    else
1379      ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1380    return ICS;
1381  } else if (ToType->isReferenceType()) {
1382    ImplicitConversionSequence ICS;
1383    CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
1384    return ICS;
1385  } else {
1386    return TryImplicitConversion(From, ToType, SuppressUserConversions);
1387  }
1388}
1389
1390/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1391/// type ToType. Returns true (and emits a diagnostic) if there was
1392/// an error, returns false if the initialization succeeded.
1393bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1394                                     const char* Flavor) {
1395  if (!getLangOptions().CPlusPlus) {
1396    // In C, argument passing is the same as performing an assignment.
1397    QualType FromType = From->getType();
1398    AssignConvertType ConvTy =
1399      CheckSingleAssignmentConstraints(ToType, From);
1400
1401    return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1402                                    FromType, From, Flavor);
1403  } else if (ToType->isReferenceType()) {
1404    return CheckReferenceInit(From, ToType);
1405  } else {
1406    if (PerformImplicitConversion(From, ToType))
1407      return Diag(From->getSourceRange().getBegin(),
1408                  diag::err_typecheck_convert_incompatible)
1409        << ToType.getAsString() << From->getType().getAsString()
1410        << Flavor << From->getSourceRange();
1411    else
1412      return false;
1413  }
1414}
1415
1416/// TryObjectArgumentInitialization - Try to initialize the object
1417/// parameter of the given member function (@c Method) from the
1418/// expression @p From.
1419ImplicitConversionSequence
1420Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1421  QualType ClassType = Context.getTypeDeclType(Method->getParent());
1422  unsigned MethodQuals = Method->getTypeQualifiers();
1423  QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1424
1425  // Set up the conversion sequence as a "bad" conversion, to allow us
1426  // to exit early.
1427  ImplicitConversionSequence ICS;
1428  ICS.Standard.setAsIdentityConversion();
1429  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1430
1431  // We need to have an object of class type.
1432  QualType FromType = From->getType();
1433  if (!FromType->isRecordType())
1434    return ICS;
1435
1436  // The implicit object parmeter is has the type "reference to cv X",
1437  // where X is the class of which the function is a member
1438  // (C++ [over.match.funcs]p4). However, when finding an implicit
1439  // conversion sequence for the argument, we are not allowed to
1440  // create temporaries or perform user-defined conversions
1441  // (C++ [over.match.funcs]p5). We perform a simplified version of
1442  // reference binding here, that allows class rvalues to bind to
1443  // non-constant references.
1444
1445  // First check the qualifiers. We don't care about lvalue-vs-rvalue
1446  // with the implicit object parameter (C++ [over.match.funcs]p5).
1447  QualType FromTypeCanon = Context.getCanonicalType(FromType);
1448  if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1449      !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1450    return ICS;
1451
1452  // Check that we have either the same type or a derived type. It
1453  // affects the conversion rank.
1454  QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1455  if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1456    ICS.Standard.Second = ICK_Identity;
1457  else if (IsDerivedFrom(FromType, ClassType))
1458    ICS.Standard.Second = ICK_Derived_To_Base;
1459  else
1460    return ICS;
1461
1462  // Success. Mark this as a reference binding.
1463  ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1464  ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1465  ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1466  ICS.Standard.ReferenceBinding = true;
1467  ICS.Standard.DirectBinding = true;
1468  return ICS;
1469}
1470
1471/// PerformObjectArgumentInitialization - Perform initialization of
1472/// the implicit object parameter for the given Method with the given
1473/// expression.
1474bool
1475Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1476  QualType ImplicitParamType
1477    = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1478  ImplicitConversionSequence ICS
1479    = TryObjectArgumentInitialization(From, Method);
1480  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1481    return Diag(From->getSourceRange().getBegin(),
1482                diag::err_implicit_object_parameter_init)
1483       << ImplicitParamType.getAsString() << From->getType().getAsString()
1484       << From->getSourceRange();
1485
1486  if (ICS.Standard.Second == ICK_Derived_To_Base &&
1487      CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1488                                   From->getSourceRange().getBegin(),
1489                                   From->getSourceRange()))
1490    return true;
1491
1492  ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1493  return false;
1494}
1495
1496/// AddOverloadCandidate - Adds the given function to the set of
1497/// candidate functions, using the given function call arguments.  If
1498/// @p SuppressUserConversions, then don't allow user-defined
1499/// conversions via constructors or conversion operators.
1500void
1501Sema::AddOverloadCandidate(FunctionDecl *Function,
1502                           Expr **Args, unsigned NumArgs,
1503                           OverloadCandidateSet& CandidateSet,
1504                           bool SuppressUserConversions)
1505{
1506  const FunctionTypeProto* Proto
1507    = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1508  assert(Proto && "Functions without a prototype cannot be overloaded");
1509  assert(!isa<CXXConversionDecl>(Function) &&
1510         "Use AddConversionCandidate for conversion functions");
1511
1512  // Add this candidate
1513  CandidateSet.push_back(OverloadCandidate());
1514  OverloadCandidate& Candidate = CandidateSet.back();
1515  Candidate.Function = Function;
1516
1517  unsigned NumArgsInProto = Proto->getNumArgs();
1518
1519  // (C++ 13.3.2p2): A candidate function having fewer than m
1520  // parameters is viable only if it has an ellipsis in its parameter
1521  // list (8.3.5).
1522  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1523    Candidate.Viable = false;
1524    return;
1525  }
1526
1527  // (C++ 13.3.2p2): A candidate function having more than m parameters
1528  // is viable only if the (m+1)st parameter has a default argument
1529  // (8.3.6). For the purposes of overload resolution, the
1530  // parameter list is truncated on the right, so that there are
1531  // exactly m parameters.
1532  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1533  if (NumArgs < MinRequiredArgs) {
1534    // Not enough arguments.
1535    Candidate.Viable = false;
1536    return;
1537  }
1538
1539  // Determine the implicit conversion sequences for each of the
1540  // arguments.
1541  Candidate.Viable = true;
1542  Candidate.Conversions.resize(NumArgs);
1543  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1544    if (ArgIdx < NumArgsInProto) {
1545      // (C++ 13.3.2p3): for F to be a viable function, there shall
1546      // exist for each argument an implicit conversion sequence
1547      // (13.3.3.1) that converts that argument to the corresponding
1548      // parameter of F.
1549      QualType ParamType = Proto->getArgType(ArgIdx);
1550      Candidate.Conversions[ArgIdx]
1551        = TryCopyInitialization(Args[ArgIdx], ParamType,
1552                                SuppressUserConversions);
1553      if (Candidate.Conversions[ArgIdx].ConversionKind
1554            == ImplicitConversionSequence::BadConversion) {
1555        Candidate.Viable = false;
1556        break;
1557      }
1558    } else {
1559      // (C++ 13.3.2p2): For the purposes of overload resolution, any
1560      // argument for which there is no corresponding parameter is
1561      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1562      Candidate.Conversions[ArgIdx].ConversionKind
1563        = ImplicitConversionSequence::EllipsisConversion;
1564    }
1565  }
1566}
1567
1568/// AddMethodCandidate - Adds the given C++ member function to the set
1569/// of candidate functions, using the given function call arguments
1570/// and the object argument (@c Object). For example, in a call
1571/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
1572/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
1573/// allow user-defined conversions via constructors or conversion
1574/// operators.
1575void
1576Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
1577                         Expr **Args, unsigned NumArgs,
1578                         OverloadCandidateSet& CandidateSet,
1579                         bool SuppressUserConversions)
1580{
1581  const FunctionTypeProto* Proto
1582    = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
1583  assert(Proto && "Methods without a prototype cannot be overloaded");
1584  assert(!isa<CXXConversionDecl>(Method) &&
1585         "Use AddConversionCandidate for conversion functions");
1586
1587  // Add this candidate
1588  CandidateSet.push_back(OverloadCandidate());
1589  OverloadCandidate& Candidate = CandidateSet.back();
1590  Candidate.Function = Method;
1591
1592  unsigned NumArgsInProto = Proto->getNumArgs();
1593
1594  // (C++ 13.3.2p2): A candidate function having fewer than m
1595  // parameters is viable only if it has an ellipsis in its parameter
1596  // list (8.3.5).
1597  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1598    Candidate.Viable = false;
1599    return;
1600  }
1601
1602  // (C++ 13.3.2p2): A candidate function having more than m parameters
1603  // is viable only if the (m+1)st parameter has a default argument
1604  // (8.3.6). For the purposes of overload resolution, the
1605  // parameter list is truncated on the right, so that there are
1606  // exactly m parameters.
1607  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
1608  if (NumArgs < MinRequiredArgs) {
1609    // Not enough arguments.
1610    Candidate.Viable = false;
1611    return;
1612  }
1613
1614  Candidate.Viable = true;
1615  Candidate.Conversions.resize(NumArgs + 1);
1616
1617  // Determine the implicit conversion sequence for the object
1618  // parameter.
1619  Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
1620  if (Candidate.Conversions[0].ConversionKind
1621        == ImplicitConversionSequence::BadConversion) {
1622    Candidate.Viable = false;
1623    return;
1624  }
1625
1626  // Determine the implicit conversion sequences for each of the
1627  // arguments.
1628  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1629    if (ArgIdx < NumArgsInProto) {
1630      // (C++ 13.3.2p3): for F to be a viable function, there shall
1631      // exist for each argument an implicit conversion sequence
1632      // (13.3.3.1) that converts that argument to the corresponding
1633      // parameter of F.
1634      QualType ParamType = Proto->getArgType(ArgIdx);
1635      Candidate.Conversions[ArgIdx + 1]
1636        = TryCopyInitialization(Args[ArgIdx], ParamType,
1637                                SuppressUserConversions);
1638      if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1639            == ImplicitConversionSequence::BadConversion) {
1640        Candidate.Viable = false;
1641        break;
1642      }
1643    } else {
1644      // (C++ 13.3.2p2): For the purposes of overload resolution, any
1645      // argument for which there is no corresponding parameter is
1646      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1647      Candidate.Conversions[ArgIdx + 1].ConversionKind
1648        = ImplicitConversionSequence::EllipsisConversion;
1649    }
1650  }
1651}
1652
1653/// AddConversionCandidate - Add a C++ conversion function as a
1654/// candidate in the candidate set (C++ [over.match.conv],
1655/// C++ [over.match.copy]). From is the expression we're converting from,
1656/// and ToType is the type that we're eventually trying to convert to
1657/// (which may or may not be the same type as the type that the
1658/// conversion function produces).
1659void
1660Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
1661                             Expr *From, QualType ToType,
1662                             OverloadCandidateSet& CandidateSet) {
1663  // Add this candidate
1664  CandidateSet.push_back(OverloadCandidate());
1665  OverloadCandidate& Candidate = CandidateSet.back();
1666  Candidate.Function = Conversion;
1667  Candidate.FinalConversion.setAsIdentityConversion();
1668  Candidate.FinalConversion.FromTypePtr
1669    = Conversion->getConversionType().getAsOpaquePtr();
1670  Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
1671
1672  // Determine the implicit conversion sequence for the implicit
1673  // object parameter.
1674  Candidate.Viable = true;
1675  Candidate.Conversions.resize(1);
1676  Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
1677
1678  if (Candidate.Conversions[0].ConversionKind
1679      == ImplicitConversionSequence::BadConversion) {
1680    Candidate.Viable = false;
1681    return;
1682  }
1683
1684  // To determine what the conversion from the result of calling the
1685  // conversion function to the type we're eventually trying to
1686  // convert to (ToType), we need to synthesize a call to the
1687  // conversion function and attempt copy initialization from it. This
1688  // makes sure that we get the right semantics with respect to
1689  // lvalues/rvalues and the type. Fortunately, we can allocate this
1690  // call on the stack and we don't need its arguments to be
1691  // well-formed.
1692  DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
1693                            SourceLocation());
1694  ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
1695                                &ConversionRef, false);
1696  CallExpr Call(&ConversionFn, 0, 0,
1697                Conversion->getConversionType().getNonReferenceType(),
1698                SourceLocation());
1699  ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
1700  switch (ICS.ConversionKind) {
1701  case ImplicitConversionSequence::StandardConversion:
1702    Candidate.FinalConversion = ICS.Standard;
1703    break;
1704
1705  case ImplicitConversionSequence::BadConversion:
1706    Candidate.Viable = false;
1707    break;
1708
1709  default:
1710    assert(false &&
1711           "Can only end up with a standard conversion sequence or failure");
1712  }
1713}
1714
1715/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1716/// an acceptable non-member overloaded operator for a call whose
1717/// arguments have types T1 (and, if non-empty, T2). This routine
1718/// implements the check in C++ [over.match.oper]p3b2 concerning
1719/// enumeration types.
1720static bool
1721IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1722                                       QualType T1, QualType T2,
1723                                       ASTContext &Context) {
1724  if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1725    return true;
1726
1727  const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
1728  if (Proto->getNumArgs() < 1)
1729    return false;
1730
1731  if (T1->isEnumeralType()) {
1732    QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1733    if (Context.getCanonicalType(T1).getUnqualifiedType()
1734          == Context.getCanonicalType(ArgType).getUnqualifiedType())
1735      return true;
1736  }
1737
1738  if (Proto->getNumArgs() < 2)
1739    return false;
1740
1741  if (!T2.isNull() && T2->isEnumeralType()) {
1742    QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1743    if (Context.getCanonicalType(T2).getUnqualifiedType()
1744          == Context.getCanonicalType(ArgType).getUnqualifiedType())
1745      return true;
1746  }
1747
1748  return false;
1749}
1750
1751/// AddOperatorCandidates - Add the overloaded operator candidates for
1752/// the operator Op that was used in an operator expression such as "x
1753/// Op y". S is the scope in which the expression occurred (used for
1754/// name lookup of the operator), Args/NumArgs provides the operator
1755/// arguments, and CandidateSet will store the added overload
1756/// candidates. (C++ [over.match.oper]).
1757void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
1758                                 Expr **Args, unsigned NumArgs,
1759                                 OverloadCandidateSet& CandidateSet) {
1760  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1761
1762  // C++ [over.match.oper]p3:
1763  //   For a unary operator @ with an operand of a type whose
1764  //   cv-unqualified version is T1, and for a binary operator @ with
1765  //   a left operand of a type whose cv-unqualified version is T1 and
1766  //   a right operand of a type whose cv-unqualified version is T2,
1767  //   three sets of candidate functions, designated member
1768  //   candidates, non-member candidates and built-in candidates, are
1769  //   constructed as follows:
1770  QualType T1 = Args[0]->getType();
1771  QualType T2;
1772  if (NumArgs > 1)
1773    T2 = Args[1]->getType();
1774
1775  //     -- If T1 is a class type, the set of member candidates is the
1776  //        result of the qualified lookup of T1::operator@
1777  //        (13.3.1.1.1); otherwise, the set of member candidates is
1778  //        empty.
1779  if (const RecordType *T1Rec = T1->getAsRecordType()) {
1780    IdentifierResolver::iterator I
1781      = IdResolver.begin(OpName, cast<CXXRecordType>(T1Rec)->getDecl(),
1782                         /*LookInParentCtx=*/false);
1783    NamedDecl *MemberOps = (I == IdResolver.end())? 0 : *I;
1784    if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
1785      AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1786                         /*SuppressUserConversions=*/false);
1787    else if (OverloadedFunctionDecl *Ovl
1788               = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
1789      for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1790                                                  FEnd = Ovl->function_end();
1791           F != FEnd; ++F) {
1792        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
1793          AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1794                             /*SuppressUserConversions=*/false);
1795      }
1796    }
1797  }
1798
1799  //     -- The set of non-member candidates is the result of the
1800  //        unqualified lookup of operator@ in the context of the
1801  //        expression according to the usual rules for name lookup in
1802  //        unqualified function calls (3.4.2) except that all member
1803  //        functions are ignored. However, if no operand has a class
1804  //        type, only those non-member functions in the lookup set
1805  //        that have a first parameter of type T1 or “reference to
1806  //        (possibly cv-qualified) T1”, when T1 is an enumeration
1807  //        type, or (if there is a right operand) a second parameter
1808  //        of type T2 or “reference to (possibly cv-qualified) T2”,
1809  //        when T2 is an enumeration type, are candidate functions.
1810  {
1811    NamedDecl *NonMemberOps = 0;
1812    for (IdentifierResolver::iterator I
1813           = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/);
1814         I != IdResolver.end(); ++I) {
1815      // We don't need to check the identifier namespace, because
1816      // operator names can only be ordinary identifiers.
1817
1818      // Ignore member functions.
1819      if (ScopedDecl *SD = dyn_cast<ScopedDecl>(*I)) {
1820        if (SD->getDeclContext()->isCXXRecord())
1821          continue;
1822      }
1823
1824      // We found something with this name. We're done.
1825      NonMemberOps = *I;
1826      break;
1827    }
1828
1829    if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NonMemberOps)) {
1830      if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1831        AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
1832                             /*SuppressUserConversions=*/false);
1833    } else if (OverloadedFunctionDecl *Ovl
1834                 = dyn_cast_or_null<OverloadedFunctionDecl>(NonMemberOps)) {
1835      for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1836                                                  FEnd = Ovl->function_end();
1837           F != FEnd; ++F) {
1838        if (IsAcceptableNonMemberOperatorCandidate(*F, T1, T2, Context))
1839          AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
1840                               /*SuppressUserConversions=*/false);
1841      }
1842    }
1843  }
1844
1845  // Add builtin overload candidates (C++ [over.built]).
1846  AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
1847}
1848
1849/// AddBuiltinCandidate - Add a candidate for a built-in
1850/// operator. ResultTy and ParamTys are the result and parameter types
1851/// of the built-in candidate, respectively. Args and NumArgs are the
1852/// arguments being passed to the candidate.
1853void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
1854                               Expr **Args, unsigned NumArgs,
1855                               OverloadCandidateSet& CandidateSet) {
1856  // Add this candidate
1857  CandidateSet.push_back(OverloadCandidate());
1858  OverloadCandidate& Candidate = CandidateSet.back();
1859  Candidate.Function = 0;
1860  Candidate.BuiltinTypes.ResultTy = ResultTy;
1861  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
1862    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
1863
1864  // Determine the implicit conversion sequences for each of the
1865  // arguments.
1866  Candidate.Viable = true;
1867  Candidate.Conversions.resize(NumArgs);
1868  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1869    Candidate.Conversions[ArgIdx]
1870      = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], false);
1871    if (Candidate.Conversions[ArgIdx].ConversionKind
1872        == ImplicitConversionSequence::BadConversion) {
1873      Candidate.Viable = false;
1874      break;
1875    }
1876  }
1877}
1878
1879/// BuiltinCandidateTypeSet - A set of types that will be used for the
1880/// candidate operator functions for built-in operators (C++
1881/// [over.built]). The types are separated into pointer types and
1882/// enumeration types.
1883class BuiltinCandidateTypeSet  {
1884  /// TypeSet - A set of types.
1885  typedef llvm::SmallPtrSet<void*, 8> TypeSet;
1886
1887  /// PointerTypes - The set of pointer types that will be used in the
1888  /// built-in candidates.
1889  TypeSet PointerTypes;
1890
1891  /// EnumerationTypes - The set of enumeration types that will be
1892  /// used in the built-in candidates.
1893  TypeSet EnumerationTypes;
1894
1895  /// Context - The AST context in which we will build the type sets.
1896  ASTContext &Context;
1897
1898  bool AddWithMoreQualifiedTypeVariants(QualType Ty);
1899
1900public:
1901  /// iterator - Iterates through the types that are part of the set.
1902  class iterator {
1903    TypeSet::iterator Base;
1904
1905  public:
1906    typedef QualType                 value_type;
1907    typedef QualType                 reference;
1908    typedef QualType                 pointer;
1909    typedef std::ptrdiff_t           difference_type;
1910    typedef std::input_iterator_tag  iterator_category;
1911
1912    iterator(TypeSet::iterator B) : Base(B) { }
1913
1914    iterator& operator++() {
1915      ++Base;
1916      return *this;
1917    }
1918
1919    iterator operator++(int) {
1920      iterator tmp(*this);
1921      ++(*this);
1922      return tmp;
1923    }
1924
1925    reference operator*() const {
1926      return QualType::getFromOpaquePtr(*Base);
1927    }
1928
1929    pointer operator->() const {
1930      return **this;
1931    }
1932
1933    friend bool operator==(iterator LHS, iterator RHS) {
1934      return LHS.Base == RHS.Base;
1935    }
1936
1937    friend bool operator!=(iterator LHS, iterator RHS) {
1938      return LHS.Base != RHS.Base;
1939    }
1940  };
1941
1942  BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
1943
1944  void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions = true);
1945
1946  /// pointer_begin - First pointer type found;
1947  iterator pointer_begin() { return PointerTypes.begin(); }
1948
1949  /// pointer_end - Last pointer type found;
1950  iterator pointer_end() { return PointerTypes.end(); }
1951
1952  /// enumeration_begin - First enumeration type found;
1953  iterator enumeration_begin() { return EnumerationTypes.begin(); }
1954
1955  /// enumeration_end - Last enumeration type found;
1956  iterator enumeration_end() { return EnumerationTypes.end(); }
1957};
1958
1959/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
1960/// the set of pointer types along with any more-qualified variants of
1961/// that type. For example, if @p Ty is "int const *", this routine
1962/// will add "int const *", "int const volatile *", "int const
1963/// restrict *", and "int const volatile restrict *" to the set of
1964/// pointer types. Returns true if the add of @p Ty itself succeeded,
1965/// false otherwise.
1966bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
1967  // Insert this type.
1968  if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
1969    return false;
1970
1971  if (const PointerType *PointerTy = Ty->getAsPointerType()) {
1972    QualType PointeeTy = PointerTy->getPointeeType();
1973    // FIXME: Optimize this so that we don't keep trying to add the same types.
1974
1975    // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
1976    // with all pointer conversions that don't cast away constness?
1977    if (!PointeeTy.isConstQualified())
1978      AddWithMoreQualifiedTypeVariants
1979        (Context.getPointerType(PointeeTy.withConst()));
1980    if (!PointeeTy.isVolatileQualified())
1981      AddWithMoreQualifiedTypeVariants
1982        (Context.getPointerType(PointeeTy.withVolatile()));
1983    if (!PointeeTy.isRestrictQualified())
1984      AddWithMoreQualifiedTypeVariants
1985        (Context.getPointerType(PointeeTy.withRestrict()));
1986  }
1987
1988  return true;
1989}
1990
1991/// AddTypesConvertedFrom - Add each of the types to which the type @p
1992/// Ty can be implicit converted to the given set of @p Types. We're
1993/// primarily interested in pointer types, enumeration types,
1994void BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
1995                                                    bool AllowUserConversions) {
1996  // Only deal with canonical types.
1997  Ty = Context.getCanonicalType(Ty);
1998
1999  // Look through reference types; they aren't part of the type of an
2000  // expression for the purposes of conversions.
2001  if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2002    Ty = RefTy->getPointeeType();
2003
2004  // We don't care about qualifiers on the type.
2005  Ty = Ty.getUnqualifiedType();
2006
2007  if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2008    QualType PointeeTy = PointerTy->getPointeeType();
2009
2010    // Insert our type, and its more-qualified variants, into the set
2011    // of types.
2012    if (!AddWithMoreQualifiedTypeVariants(Ty))
2013      return;
2014
2015    // Add 'cv void*' to our set of types.
2016    if (!Ty->isVoidType()) {
2017      QualType QualVoid
2018        = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2019      AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2020    }
2021
2022    // If this is a pointer to a class type, add pointers to its bases
2023    // (with the same level of cv-qualification as the original
2024    // derived class, of course).
2025    if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2026      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2027      for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2028           Base != ClassDecl->bases_end(); ++Base) {
2029        QualType BaseTy = Context.getCanonicalType(Base->getType());
2030        BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2031
2032        // Add the pointer type, recursively, so that we get all of
2033        // the indirect base classes, too.
2034        AddTypesConvertedFrom(Context.getPointerType(BaseTy), false);
2035      }
2036    }
2037  } else if (Ty->isEnumeralType()) {
2038    EnumerationTypes.insert(Ty.getAsOpaquePtr());
2039  } else if (AllowUserConversions) {
2040    if (const RecordType *TyRec = Ty->getAsRecordType()) {
2041      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2042      // FIXME: Visit conversion functions in the base classes, too.
2043      OverloadedFunctionDecl *Conversions
2044        = ClassDecl->getConversionFunctions();
2045      for (OverloadedFunctionDecl::function_iterator Func
2046             = Conversions->function_begin();
2047           Func != Conversions->function_end(); ++Func) {
2048        CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2049        AddTypesConvertedFrom(Conv->getConversionType(), false);
2050      }
2051    }
2052  }
2053}
2054
2055/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2056/// operator overloads to the candidate set (C++ [over.built]), based
2057/// on the operator @p Op and the arguments given. For example, if the
2058/// operator is a binary '+', this routine might add "int
2059/// operator+(int, int)" to cover integer addition.
2060void
2061Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2062                                   Expr **Args, unsigned NumArgs,
2063                                   OverloadCandidateSet& CandidateSet) {
2064  // The set of "promoted arithmetic types", which are the arithmetic
2065  // types are that preserved by promotion (C++ [over.built]p2). Note
2066  // that the first few of these types are the promoted integral
2067  // types; these types need to be first.
2068  // FIXME: What about complex?
2069  const unsigned FirstIntegralType = 0;
2070  const unsigned LastIntegralType = 13;
2071  const unsigned FirstPromotedIntegralType = 7,
2072                 LastPromotedIntegralType = 13;
2073  const unsigned FirstPromotedArithmeticType = 7,
2074                 LastPromotedArithmeticType = 16;
2075  const unsigned NumArithmeticTypes = 16;
2076  QualType ArithmeticTypes[NumArithmeticTypes] = {
2077    Context.BoolTy, Context.CharTy, Context.WCharTy,
2078    Context.SignedCharTy, Context.ShortTy,
2079    Context.UnsignedCharTy, Context.UnsignedShortTy,
2080    Context.IntTy, Context.LongTy, Context.LongLongTy,
2081    Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2082    Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2083  };
2084
2085  // Find all of the types that the arguments can convert to, but only
2086  // if the operator we're looking at has built-in operator candidates
2087  // that make use of these types.
2088  BuiltinCandidateTypeSet CandidateTypes(Context);
2089  if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2090      Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
2091      Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
2092      Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
2093      Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2094      (Op == OO_Star && NumArgs == 1)) {
2095    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2096      CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType());
2097  }
2098
2099  bool isComparison = false;
2100  switch (Op) {
2101  case OO_None:
2102  case NUM_OVERLOADED_OPERATORS:
2103    assert(false && "Expected an overloaded operator");
2104    break;
2105
2106  case OO_Star: // '*' is either unary or binary
2107    if (NumArgs == 1)
2108      goto UnaryStar;
2109    else
2110      goto BinaryStar;
2111    break;
2112
2113  case OO_Plus: // '+' is either unary or binary
2114    if (NumArgs == 1)
2115      goto UnaryPlus;
2116    else
2117      goto BinaryPlus;
2118    break;
2119
2120  case OO_Minus: // '-' is either unary or binary
2121    if (NumArgs == 1)
2122      goto UnaryMinus;
2123    else
2124      goto BinaryMinus;
2125    break;
2126
2127  case OO_Amp: // '&' is either unary or binary
2128    if (NumArgs == 1)
2129      goto UnaryAmp;
2130    else
2131      goto BinaryAmp;
2132
2133  case OO_PlusPlus:
2134  case OO_MinusMinus:
2135    // C++ [over.built]p3:
2136    //
2137    //   For every pair (T, VQ), where T is an arithmetic type, and VQ
2138    //   is either volatile or empty, there exist candidate operator
2139    //   functions of the form
2140    //
2141    //       VQ T&      operator++(VQ T&);
2142    //       T          operator++(VQ T&, int);
2143    //
2144    // C++ [over.built]p4:
2145    //
2146    //   For every pair (T, VQ), where T is an arithmetic type other
2147    //   than bool, and VQ is either volatile or empty, there exist
2148    //   candidate operator functions of the form
2149    //
2150    //       VQ T&      operator--(VQ T&);
2151    //       T          operator--(VQ T&, int);
2152    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2153         Arith < NumArithmeticTypes; ++Arith) {
2154      QualType ArithTy = ArithmeticTypes[Arith];
2155      QualType ParamTypes[2]
2156        = { Context.getReferenceType(ArithTy), Context.IntTy };
2157
2158      // Non-volatile version.
2159      if (NumArgs == 1)
2160        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2161      else
2162        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2163
2164      // Volatile version
2165      ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2166      if (NumArgs == 1)
2167        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2168      else
2169        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2170    }
2171
2172    // C++ [over.built]p5:
2173    //
2174    //   For every pair (T, VQ), where T is a cv-qualified or
2175    //   cv-unqualified object type, and VQ is either volatile or
2176    //   empty, there exist candidate operator functions of the form
2177    //
2178    //       T*VQ&      operator++(T*VQ&);
2179    //       T*VQ&      operator--(T*VQ&);
2180    //       T*         operator++(T*VQ&, int);
2181    //       T*         operator--(T*VQ&, int);
2182    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2183         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2184      // Skip pointer types that aren't pointers to object types.
2185      if (!(*Ptr)->getAsPointerType()->getPointeeType()->isObjectType())
2186        continue;
2187
2188      QualType ParamTypes[2] = {
2189        Context.getReferenceType(*Ptr), Context.IntTy
2190      };
2191
2192      // Without volatile
2193      if (NumArgs == 1)
2194        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2195      else
2196        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2197
2198      if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2199        // With volatile
2200        ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2201        if (NumArgs == 1)
2202          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2203        else
2204          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2205      }
2206    }
2207    break;
2208
2209  UnaryStar:
2210    // C++ [over.built]p6:
2211    //   For every cv-qualified or cv-unqualified object type T, there
2212    //   exist candidate operator functions of the form
2213    //
2214    //       T&         operator*(T*);
2215    //
2216    // C++ [over.built]p7:
2217    //   For every function type T, there exist candidate operator
2218    //   functions of the form
2219    //       T&         operator*(T*);
2220    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2221         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2222      QualType ParamTy = *Ptr;
2223      QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2224      AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2225                          &ParamTy, Args, 1, CandidateSet);
2226    }
2227    break;
2228
2229  UnaryPlus:
2230    // C++ [over.built]p8:
2231    //   For every type T, there exist candidate operator functions of
2232    //   the form
2233    //
2234    //       T*         operator+(T*);
2235    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2236         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2237      QualType ParamTy = *Ptr;
2238      AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2239    }
2240
2241    // Fall through
2242
2243  UnaryMinus:
2244    // C++ [over.built]p9:
2245    //  For every promoted arithmetic type T, there exist candidate
2246    //  operator functions of the form
2247    //
2248    //       T         operator+(T);
2249    //       T         operator-(T);
2250    for (unsigned Arith = FirstPromotedArithmeticType;
2251         Arith < LastPromotedArithmeticType; ++Arith) {
2252      QualType ArithTy = ArithmeticTypes[Arith];
2253      AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2254    }
2255    break;
2256
2257  case OO_Tilde:
2258    // C++ [over.built]p10:
2259    //   For every promoted integral type T, there exist candidate
2260    //   operator functions of the form
2261    //
2262    //        T         operator~(T);
2263    for (unsigned Int = FirstPromotedIntegralType;
2264         Int < LastPromotedIntegralType; ++Int) {
2265      QualType IntTy = ArithmeticTypes[Int];
2266      AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2267    }
2268    break;
2269
2270  case OO_New:
2271  case OO_Delete:
2272  case OO_Array_New:
2273  case OO_Array_Delete:
2274  case OO_Call:
2275    assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
2276    break;
2277
2278  case OO_Comma:
2279  UnaryAmp:
2280  case OO_Arrow:
2281    // C++ [over.match.oper]p3:
2282    //   -- For the operator ',', the unary operator '&', or the
2283    //      operator '->', the built-in candidates set is empty.
2284    break;
2285
2286  case OO_Less:
2287  case OO_Greater:
2288  case OO_LessEqual:
2289  case OO_GreaterEqual:
2290  case OO_EqualEqual:
2291  case OO_ExclaimEqual:
2292    // C++ [over.built]p15:
2293    //
2294    //   For every pointer or enumeration type T, there exist
2295    //   candidate operator functions of the form
2296    //
2297    //        bool       operator<(T, T);
2298    //        bool       operator>(T, T);
2299    //        bool       operator<=(T, T);
2300    //        bool       operator>=(T, T);
2301    //        bool       operator==(T, T);
2302    //        bool       operator!=(T, T);
2303    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2304         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2305      QualType ParamTypes[2] = { *Ptr, *Ptr };
2306      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2307    }
2308    for (BuiltinCandidateTypeSet::iterator Enum
2309           = CandidateTypes.enumeration_begin();
2310         Enum != CandidateTypes.enumeration_end(); ++Enum) {
2311      QualType ParamTypes[2] = { *Enum, *Enum };
2312      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2313    }
2314
2315    // Fall through.
2316    isComparison = true;
2317
2318  BinaryPlus:
2319  BinaryMinus:
2320    if (!isComparison) {
2321      // We didn't fall through, so we must have OO_Plus or OO_Minus.
2322
2323      // C++ [over.built]p13:
2324      //
2325      //   For every cv-qualified or cv-unqualified object type T
2326      //   there exist candidate operator functions of the form
2327      //
2328      //      T*         operator+(T*, ptrdiff_t);
2329      //      T&         operator[](T*, ptrdiff_t);    [BELOW]
2330      //      T*         operator-(T*, ptrdiff_t);
2331      //      T*         operator+(ptrdiff_t, T*);
2332      //      T&         operator[](ptrdiff_t, T*);    [BELOW]
2333      //
2334      // C++ [over.built]p14:
2335      //
2336      //   For every T, where T is a pointer to object type, there
2337      //   exist candidate operator functions of the form
2338      //
2339      //      ptrdiff_t  operator-(T, T);
2340      for (BuiltinCandidateTypeSet::iterator Ptr
2341             = CandidateTypes.pointer_begin();
2342           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2343        QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2344
2345        // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2346        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2347
2348        if (Op == OO_Plus) {
2349          // T* operator+(ptrdiff_t, T*);
2350          ParamTypes[0] = ParamTypes[1];
2351          ParamTypes[1] = *Ptr;
2352          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2353        } else {
2354          // ptrdiff_t operator-(T, T);
2355          ParamTypes[1] = *Ptr;
2356          AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2357                              Args, 2, CandidateSet);
2358        }
2359      }
2360    }
2361    // Fall through
2362
2363  case OO_Slash:
2364  BinaryStar:
2365    // C++ [over.built]p12:
2366    //
2367    //   For every pair of promoted arithmetic types L and R, there
2368    //   exist candidate operator functions of the form
2369    //
2370    //        LR         operator*(L, R);
2371    //        LR         operator/(L, R);
2372    //        LR         operator+(L, R);
2373    //        LR         operator-(L, R);
2374    //        bool       operator<(L, R);
2375    //        bool       operator>(L, R);
2376    //        bool       operator<=(L, R);
2377    //        bool       operator>=(L, R);
2378    //        bool       operator==(L, R);
2379    //        bool       operator!=(L, R);
2380    //
2381    //   where LR is the result of the usual arithmetic conversions
2382    //   between types L and R.
2383    for (unsigned Left = FirstPromotedArithmeticType;
2384         Left < LastPromotedArithmeticType; ++Left) {
2385      for (unsigned Right = FirstPromotedArithmeticType;
2386           Right < LastPromotedArithmeticType; ++Right) {
2387        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2388        QualType Result
2389          = isComparison? Context.BoolTy
2390                        : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2391        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2392      }
2393    }
2394    break;
2395
2396  case OO_Percent:
2397  BinaryAmp:
2398  case OO_Caret:
2399  case OO_Pipe:
2400  case OO_LessLess:
2401  case OO_GreaterGreater:
2402    // C++ [over.built]p17:
2403    //
2404    //   For every pair of promoted integral types L and R, there
2405    //   exist candidate operator functions of the form
2406    //
2407    //      LR         operator%(L, R);
2408    //      LR         operator&(L, R);
2409    //      LR         operator^(L, R);
2410    //      LR         operator|(L, R);
2411    //      L          operator<<(L, R);
2412    //      L          operator>>(L, R);
2413    //
2414    //   where LR is the result of the usual arithmetic conversions
2415    //   between types L and R.
2416    for (unsigned Left = FirstPromotedIntegralType;
2417         Left < LastPromotedIntegralType; ++Left) {
2418      for (unsigned Right = FirstPromotedIntegralType;
2419           Right < LastPromotedIntegralType; ++Right) {
2420        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2421        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2422            ? LandR[0]
2423            : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2424        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2425      }
2426    }
2427    break;
2428
2429  case OO_Equal:
2430    // C++ [over.built]p20:
2431    //
2432    //   For every pair (T, VQ), where T is an enumeration or
2433    //   (FIXME:) pointer to member type and VQ is either volatile or
2434    //   empty, there exist candidate operator functions of the form
2435    //
2436    //        VQ T&      operator=(VQ T&, T);
2437    for (BuiltinCandidateTypeSet::iterator Enum
2438           = CandidateTypes.enumeration_begin();
2439         Enum != CandidateTypes.enumeration_end(); ++Enum) {
2440      QualType ParamTypes[2];
2441
2442      // T& operator=(T&, T)
2443      ParamTypes[0] = Context.getReferenceType(*Enum);
2444      ParamTypes[1] = *Enum;
2445      AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2446
2447      if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
2448        // volatile T& operator=(volatile T&, T)
2449        ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
2450        ParamTypes[1] = *Enum;
2451        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2452      }
2453    }
2454    // Fall through.
2455
2456  case OO_PlusEqual:
2457  case OO_MinusEqual:
2458    // C++ [over.built]p19:
2459    //
2460    //   For every pair (T, VQ), where T is any type and VQ is either
2461    //   volatile or empty, there exist candidate operator functions
2462    //   of the form
2463    //
2464    //        T*VQ&      operator=(T*VQ&, T*);
2465    //
2466    // C++ [over.built]p21:
2467    //
2468    //   For every pair (T, VQ), where T is a cv-qualified or
2469    //   cv-unqualified object type and VQ is either volatile or
2470    //   empty, there exist candidate operator functions of the form
2471    //
2472    //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
2473    //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
2474    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2475         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2476      QualType ParamTypes[2];
2477      ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
2478
2479      // non-volatile version
2480      ParamTypes[0] = Context.getReferenceType(*Ptr);
2481      AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2482
2483      if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2484        // volatile version
2485        ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2486        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2487      }
2488    }
2489    // Fall through.
2490
2491  case OO_StarEqual:
2492  case OO_SlashEqual:
2493    // C++ [over.built]p18:
2494    //
2495    //   For every triple (L, VQ, R), where L is an arithmetic type,
2496    //   VQ is either volatile or empty, and R is a promoted
2497    //   arithmetic type, there exist candidate operator functions of
2498    //   the form
2499    //
2500    //        VQ L&      operator=(VQ L&, R);
2501    //        VQ L&      operator*=(VQ L&, R);
2502    //        VQ L&      operator/=(VQ L&, R);
2503    //        VQ L&      operator+=(VQ L&, R);
2504    //        VQ L&      operator-=(VQ L&, R);
2505    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
2506      for (unsigned Right = FirstPromotedArithmeticType;
2507           Right < LastPromotedArithmeticType; ++Right) {
2508        QualType ParamTypes[2];
2509        ParamTypes[1] = ArithmeticTypes[Right];
2510
2511        // Add this built-in operator as a candidate (VQ is empty).
2512        ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2513        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2514
2515        // Add this built-in operator as a candidate (VQ is 'volatile').
2516        ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
2517        ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2518        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2519      }
2520    }
2521    break;
2522
2523  case OO_PercentEqual:
2524  case OO_LessLessEqual:
2525  case OO_GreaterGreaterEqual:
2526  case OO_AmpEqual:
2527  case OO_CaretEqual:
2528  case OO_PipeEqual:
2529    // C++ [over.built]p22:
2530    //
2531    //   For every triple (L, VQ, R), where L is an integral type, VQ
2532    //   is either volatile or empty, and R is a promoted integral
2533    //   type, there exist candidate operator functions of the form
2534    //
2535    //        VQ L&       operator%=(VQ L&, R);
2536    //        VQ L&       operator<<=(VQ L&, R);
2537    //        VQ L&       operator>>=(VQ L&, R);
2538    //        VQ L&       operator&=(VQ L&, R);
2539    //        VQ L&       operator^=(VQ L&, R);
2540    //        VQ L&       operator|=(VQ L&, R);
2541    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
2542      for (unsigned Right = FirstPromotedIntegralType;
2543           Right < LastPromotedIntegralType; ++Right) {
2544        QualType ParamTypes[2];
2545        ParamTypes[1] = ArithmeticTypes[Right];
2546
2547        // Add this built-in operator as a candidate (VQ is empty).
2548        // FIXME: We should be caching these declarations somewhere,
2549        // rather than re-building them every time.
2550        ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2551        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2552
2553        // Add this built-in operator as a candidate (VQ is 'volatile').
2554        ParamTypes[0] = ArithmeticTypes[Left];
2555        ParamTypes[0].addVolatile();
2556        ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2557        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2558      }
2559    }
2560    break;
2561
2562  case OO_Exclaim: {
2563    // C++ [over.operator]p23:
2564    //
2565    //   There also exist candidate operator functions of the form
2566    //
2567    //        bool        operator!(bool);
2568    //        bool        operator&&(bool, bool);     [BELOW]
2569    //        bool        operator||(bool, bool);     [BELOW]
2570    QualType ParamTy = Context.BoolTy;
2571    AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2572    break;
2573  }
2574
2575  case OO_AmpAmp:
2576  case OO_PipePipe: {
2577    // C++ [over.operator]p23:
2578    //
2579    //   There also exist candidate operator functions of the form
2580    //
2581    //        bool        operator!(bool);            [ABOVE]
2582    //        bool        operator&&(bool, bool);
2583    //        bool        operator||(bool, bool);
2584    QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
2585    AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2586    break;
2587  }
2588
2589  case OO_Subscript:
2590    // C++ [over.built]p13:
2591    //
2592    //   For every cv-qualified or cv-unqualified object type T there
2593    //   exist candidate operator functions of the form
2594    //
2595    //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
2596    //        T&         operator[](T*, ptrdiff_t);
2597    //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
2598    //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
2599    //        T&         operator[](ptrdiff_t, T*);
2600    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2601         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2602      QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2603      QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
2604      QualType ResultTy = Context.getReferenceType(PointeeType);
2605
2606      // T& operator[](T*, ptrdiff_t)
2607      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2608
2609      // T& operator[](ptrdiff_t, T*);
2610      ParamTypes[0] = ParamTypes[1];
2611      ParamTypes[1] = *Ptr;
2612      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2613    }
2614    break;
2615
2616  case OO_ArrowStar:
2617    // FIXME: No support for pointer-to-members yet.
2618    break;
2619  }
2620}
2621
2622/// AddOverloadCandidates - Add all of the function overloads in Ovl
2623/// to the candidate set.
2624void
2625Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
2626                            Expr **Args, unsigned NumArgs,
2627                            OverloadCandidateSet& CandidateSet,
2628                            bool SuppressUserConversions)
2629{
2630  for (OverloadedFunctionDecl::function_const_iterator Func
2631         = Ovl->function_begin();
2632       Func != Ovl->function_end(); ++Func)
2633    AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
2634                         SuppressUserConversions);
2635}
2636
2637/// isBetterOverloadCandidate - Determines whether the first overload
2638/// candidate is a better candidate than the second (C++ 13.3.3p1).
2639bool
2640Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
2641                                const OverloadCandidate& Cand2)
2642{
2643  // Define viable functions to be better candidates than non-viable
2644  // functions.
2645  if (!Cand2.Viable)
2646    return Cand1.Viable;
2647  else if (!Cand1.Viable)
2648    return false;
2649
2650  // FIXME: Deal with the implicit object parameter for static member
2651  // functions. (C++ 13.3.3p1).
2652
2653  // (C++ 13.3.3p1): a viable function F1 is defined to be a better
2654  // function than another viable function F2 if for all arguments i,
2655  // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
2656  // then...
2657  unsigned NumArgs = Cand1.Conversions.size();
2658  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
2659  bool HasBetterConversion = false;
2660  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2661    switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
2662                                               Cand2.Conversions[ArgIdx])) {
2663    case ImplicitConversionSequence::Better:
2664      // Cand1 has a better conversion sequence.
2665      HasBetterConversion = true;
2666      break;
2667
2668    case ImplicitConversionSequence::Worse:
2669      // Cand1 can't be better than Cand2.
2670      return false;
2671
2672    case ImplicitConversionSequence::Indistinguishable:
2673      // Do nothing.
2674      break;
2675    }
2676  }
2677
2678  if (HasBetterConversion)
2679    return true;
2680
2681  // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
2682  // implemented, but they require template support.
2683
2684  // C++ [over.match.best]p1b4:
2685  //
2686  //   -- the context is an initialization by user-defined conversion
2687  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
2688  //      from the return type of F1 to the destination type (i.e.,
2689  //      the type of the entity being initialized) is a better
2690  //      conversion sequence than the standard conversion sequence
2691  //      from the return type of F2 to the destination type.
2692  if (Cand1.Function && Cand2.Function &&
2693      isa<CXXConversionDecl>(Cand1.Function) &&
2694      isa<CXXConversionDecl>(Cand2.Function)) {
2695    switch (CompareStandardConversionSequences(Cand1.FinalConversion,
2696                                               Cand2.FinalConversion)) {
2697    case ImplicitConversionSequence::Better:
2698      // Cand1 has a better conversion sequence.
2699      return true;
2700
2701    case ImplicitConversionSequence::Worse:
2702      // Cand1 can't be better than Cand2.
2703      return false;
2704
2705    case ImplicitConversionSequence::Indistinguishable:
2706      // Do nothing
2707      break;
2708    }
2709  }
2710
2711  return false;
2712}
2713
2714/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
2715/// within an overload candidate set. If overloading is successful,
2716/// the result will be OR_Success and Best will be set to point to the
2717/// best viable function within the candidate set. Otherwise, one of
2718/// several kinds of errors will be returned; see
2719/// Sema::OverloadingResult.
2720Sema::OverloadingResult
2721Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
2722                         OverloadCandidateSet::iterator& Best)
2723{
2724  // Find the best viable function.
2725  Best = CandidateSet.end();
2726  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2727       Cand != CandidateSet.end(); ++Cand) {
2728    if (Cand->Viable) {
2729      if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
2730        Best = Cand;
2731    }
2732  }
2733
2734  // If we didn't find any viable functions, abort.
2735  if (Best == CandidateSet.end())
2736    return OR_No_Viable_Function;
2737
2738  // Make sure that this function is better than every other viable
2739  // function. If not, we have an ambiguity.
2740  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2741       Cand != CandidateSet.end(); ++Cand) {
2742    if (Cand->Viable &&
2743        Cand != Best &&
2744        !isBetterOverloadCandidate(*Best, *Cand))
2745      return OR_Ambiguous;
2746  }
2747
2748  // Best is the best viable function.
2749  return OR_Success;
2750}
2751
2752/// PrintOverloadCandidates - When overload resolution fails, prints
2753/// diagnostic messages containing the candidates in the candidate
2754/// set. If OnlyViable is true, only viable candidates will be printed.
2755void
2756Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
2757                              bool OnlyViable)
2758{
2759  OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2760                             LastCand = CandidateSet.end();
2761  for (; Cand != LastCand; ++Cand) {
2762    if (Cand->Viable || !OnlyViable) {
2763      if (Cand->Function) {
2764        // Normal function
2765        Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
2766      } else {
2767        // FIXME: We need to get the identifier in here
2768        // FIXME: Do we want the error message to point at the
2769        // operator? (built-ins won't have a location)
2770        QualType FnType
2771          = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
2772                                    Cand->BuiltinTypes.ParamTypes,
2773                                    Cand->Conversions.size(),
2774                                    false, 0);
2775
2776        Diag(SourceLocation(), diag::err_ovl_builtin_candidate)
2777          << FnType.getAsString();
2778      }
2779    }
2780  }
2781}
2782
2783/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
2784/// an overloaded function (C++ [over.over]), where @p From is an
2785/// expression with overloaded function type and @p ToType is the type
2786/// we're trying to resolve to. For example:
2787///
2788/// @code
2789/// int f(double);
2790/// int f(int);
2791///
2792/// int (*pfd)(double) = f; // selects f(double)
2793/// @endcode
2794///
2795/// This routine returns the resulting FunctionDecl if it could be
2796/// resolved, and NULL otherwise. When @p Complain is true, this
2797/// routine will emit diagnostics if there is an error.
2798FunctionDecl *
2799Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
2800                                         bool Complain) {
2801  QualType FunctionType = ToType;
2802  if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
2803    FunctionType = ToTypePtr->getPointeeType();
2804
2805  // We only look at pointers or references to functions.
2806  if (!FunctionType->isFunctionType())
2807    return 0;
2808
2809  // Find the actual overloaded function declaration.
2810  OverloadedFunctionDecl *Ovl = 0;
2811
2812  // C++ [over.over]p1:
2813  //   [...] [Note: any redundant set of parentheses surrounding the
2814  //   overloaded function name is ignored (5.1). ]
2815  Expr *OvlExpr = From->IgnoreParens();
2816
2817  // C++ [over.over]p1:
2818  //   [...] The overloaded function name can be preceded by the &
2819  //   operator.
2820  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
2821    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2822      OvlExpr = UnOp->getSubExpr()->IgnoreParens();
2823  }
2824
2825  // Try to dig out the overloaded function.
2826  if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
2827    Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
2828
2829  // If there's no overloaded function declaration, we're done.
2830  if (!Ovl)
2831    return 0;
2832
2833  // Look through all of the overloaded functions, searching for one
2834  // whose type matches exactly.
2835  // FIXME: When templates or using declarations come along, we'll actually
2836  // have to deal with duplicates, partial ordering, etc. For now, we
2837  // can just do a simple search.
2838  FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
2839  for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
2840       Fun != Ovl->function_end(); ++Fun) {
2841    // C++ [over.over]p3:
2842    //   Non-member functions and static member functions match
2843    //   targets of type “pointer-to-function”or
2844    //   “reference-to-function.”
2845    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
2846      if (!Method->isStatic())
2847        continue;
2848
2849    if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
2850      return *Fun;
2851  }
2852
2853  return 0;
2854}
2855
2856/// FixOverloadedFunctionReference - E is an expression that refers to
2857/// a C++ overloaded function (possibly with some parentheses and
2858/// perhaps a '&' around it). We have resolved the overloaded function
2859/// to the function declaration Fn, so patch up the expression E to
2860/// refer (possibly indirectly) to Fn.
2861void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
2862  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2863    FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
2864    E->setType(PE->getSubExpr()->getType());
2865  } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
2866    assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
2867           "Can only take the address of an overloaded function");
2868    FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
2869    E->setType(Context.getPointerType(E->getType()));
2870  } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
2871    assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
2872           "Expected overloaded function");
2873    DR->setDecl(Fn);
2874    E->setType(Fn->getType());
2875  } else {
2876    assert(false && "Invalid reference to overloaded function");
2877  }
2878}
2879
2880} // end namespace clang
2881