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