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