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