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