SemaOverload.cpp revision 22ab6d12167f6ceb50aff3bd75522072169b2f65
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 "clang/Basic/PartialDiagnostic.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/Support/Compiler.h"
26#include <algorithm>
27#include <cstdio>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
33ImplicitConversionCategory
34GetConversionCategory(ImplicitConversionKind Kind) {
35  static const ImplicitConversionCategory
36    Category[(int)ICK_Num_Conversion_Kinds] = {
37    ICC_Identity,
38    ICC_Lvalue_Transformation,
39    ICC_Lvalue_Transformation,
40    ICC_Lvalue_Transformation,
41    ICC_Qualification_Adjustment,
42    ICC_Promotion,
43    ICC_Promotion,
44    ICC_Promotion,
45    ICC_Conversion,
46    ICC_Conversion,
47    ICC_Conversion,
48    ICC_Conversion,
49    ICC_Conversion,
50    ICC_Conversion,
51    ICC_Conversion,
52    ICC_Conversion,
53    ICC_Conversion,
54    ICC_Conversion
55  };
56  return Category[(int)Kind];
57}
58
59/// GetConversionRank - Retrieve the implicit conversion rank
60/// corresponding to the given implicit conversion kind.
61ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
62  static const ImplicitConversionRank
63    Rank[(int)ICK_Num_Conversion_Kinds] = {
64    ICR_Exact_Match,
65    ICR_Exact_Match,
66    ICR_Exact_Match,
67    ICR_Exact_Match,
68    ICR_Exact_Match,
69    ICR_Promotion,
70    ICR_Promotion,
71    ICR_Promotion,
72    ICR_Conversion,
73    ICR_Conversion,
74    ICR_Conversion,
75    ICR_Conversion,
76    ICR_Conversion,
77    ICR_Conversion,
78    ICR_Conversion,
79    ICR_Conversion,
80    ICR_Conversion,
81    ICR_Conversion
82  };
83  return Rank[(int)Kind];
84}
85
86/// GetImplicitConversionName - Return the name of this kind of
87/// implicit conversion.
88const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
89  static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
90    "No conversion",
91    "Lvalue-to-rvalue",
92    "Array-to-pointer",
93    "Function-to-pointer",
94    "Qualification",
95    "Integral promotion",
96    "Floating point promotion",
97    "Complex promotion",
98    "Integral conversion",
99    "Floating conversion",
100    "Complex conversion",
101    "Floating-integral conversion",
102    "Complex-real conversion",
103    "Pointer conversion",
104    "Pointer-to-member conversion",
105    "Boolean conversion",
106    "Compatible-types conversion",
107    "Derived-to-base conversion"
108  };
109  return Name[Kind];
110}
111
112/// StandardConversionSequence - Set the standard conversion
113/// sequence to the identity conversion.
114void StandardConversionSequence::setAsIdentityConversion() {
115  First = ICK_Identity;
116  Second = ICK_Identity;
117  Third = ICK_Identity;
118  Deprecated = false;
119  ReferenceBinding = false;
120  DirectBinding = false;
121  RRefBinding = false;
122  CopyConstructor = 0;
123}
124
125/// getRank - Retrieve the rank of this standard conversion sequence
126/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
127/// implicit conversions.
128ImplicitConversionRank StandardConversionSequence::getRank() const {
129  ImplicitConversionRank Rank = ICR_Exact_Match;
130  if  (GetConversionRank(First) > Rank)
131    Rank = GetConversionRank(First);
132  if  (GetConversionRank(Second) > Rank)
133    Rank = GetConversionRank(Second);
134  if  (GetConversionRank(Third) > Rank)
135    Rank = GetConversionRank(Third);
136  return Rank;
137}
138
139/// isPointerConversionToBool - Determines whether this conversion is
140/// a conversion of a pointer or pointer-to-member to bool. This is
141/// used as part of the ranking of standard conversion sequences
142/// (C++ 13.3.3.2p4).
143bool StandardConversionSequence::isPointerConversionToBool() const {
144  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
145  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
146
147  // Note that FromType has not necessarily been transformed by the
148  // array-to-pointer or function-to-pointer implicit conversions, so
149  // check for their presence as well as checking whether FromType is
150  // a pointer.
151  if (ToType->isBooleanType() &&
152      (FromType->isPointerType() || FromType->isBlockPointerType() ||
153       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154    return true;
155
156  return false;
157}
158
159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
163bool
164StandardConversionSequence::
165isPointerConversionToVoidPointer(ASTContext& Context) const {
166  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
167  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
168
169  // Note that FromType has not necessarily been transformed by the
170  // array-to-pointer implicit conversion, so check for its presence
171  // and redo the conversion to get a pointer.
172  if (First == ICK_Array_To_Pointer)
173    FromType = Context.getArrayDecayedType(FromType);
174
175  if (Second == ICK_Pointer_Conversion)
176    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
177      return ToPtrType->getPointeeType()->isVoidType();
178
179  return false;
180}
181
182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
185  bool PrintedSomething = false;
186  if (First != ICK_Identity) {
187    fprintf(stderr, "%s", GetImplicitConversionName(First));
188    PrintedSomething = true;
189  }
190
191  if (Second != ICK_Identity) {
192    if (PrintedSomething) {
193      fprintf(stderr, " -> ");
194    }
195    fprintf(stderr, "%s", GetImplicitConversionName(Second));
196
197    if (CopyConstructor) {
198      fprintf(stderr, " (by copy constructor)");
199    } else if (DirectBinding) {
200      fprintf(stderr, " (direct reference binding)");
201    } else if (ReferenceBinding) {
202      fprintf(stderr, " (reference binding)");
203    }
204    PrintedSomething = true;
205  }
206
207  if (Third != ICK_Identity) {
208    if (PrintedSomething) {
209      fprintf(stderr, " -> ");
210    }
211    fprintf(stderr, "%s", GetImplicitConversionName(Third));
212    PrintedSomething = true;
213  }
214
215  if (!PrintedSomething) {
216    fprintf(stderr, "No conversions required");
217  }
218}
219
220/// DebugPrint - Print this user-defined conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void UserDefinedConversionSequence::DebugPrint() const {
223  if (Before.First || Before.Second || Before.Third) {
224    Before.DebugPrint();
225    fprintf(stderr, " -> ");
226  }
227  fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
228  if (After.First || After.Second || After.Third) {
229    fprintf(stderr, " -> ");
230    After.DebugPrint();
231  }
232}
233
234/// DebugPrint - Print this implicit conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void ImplicitConversionSequence::DebugPrint() const {
237  switch (ConversionKind) {
238  case StandardConversion:
239    fprintf(stderr, "Standard conversion: ");
240    Standard.DebugPrint();
241    break;
242  case UserDefinedConversion:
243    fprintf(stderr, "User-defined conversion: ");
244    UserDefined.DebugPrint();
245    break;
246  case EllipsisConversion:
247    fprintf(stderr, "Ellipsis conversion");
248    break;
249  case BadConversion:
250    fprintf(stderr, "Bad conversion");
251    break;
252  }
253
254  fprintf(stderr, "\n");
255}
256
257// IsOverload - Determine whether the given New declaration is an
258// overload of the Old declaration. This routine returns false if New
259// and Old cannot be overloaded, e.g., if they are functions with the
260// same signature (C++ 1.3.10) or if the Old declaration isn't a
261// function (or overload set). When it does return false and Old is an
262// OverloadedFunctionDecl, MatchedDecl will be set to point to the
263// FunctionDecl that New cannot be overloaded with.
264//
265// Example: Given the following input:
266//
267//   void f(int, float); // #1
268//   void f(int, int); // #2
269//   int f(int, int); // #3
270//
271// When we process #1, there is no previous declaration of "f",
272// so IsOverload will not be used.
273//
274// When we process #2, Old is a FunctionDecl for #1.  By comparing the
275// parameter types, we see that #1 and #2 are overloaded (since they
276// have different signatures), so this routine returns false;
277// MatchedDecl is unchanged.
278//
279// When we process #3, Old is an OverloadedFunctionDecl containing #1
280// and #2. We compare the signatures of #3 to #1 (they're overloaded,
281// so we do nothing) and then #3 to #2. Since the signatures of #3 and
282// #2 are identical (return types of functions are not part of the
283// signature), IsOverload returns false and MatchedDecl will be set to
284// point to the FunctionDecl for #2.
285bool
286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287                 OverloadedFunctionDecl::function_iterator& MatchedDecl) {
288  if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
289    // Is this new function an overload of every function in the
290    // overload set?
291    OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
292                                           FuncEnd = Ovl->function_end();
293    for (; Func != FuncEnd; ++Func) {
294      if (!IsOverload(New, *Func, MatchedDecl)) {
295        MatchedDecl = Func;
296        return false;
297      }
298    }
299
300    // This function overloads every function in the overload set.
301    return true;
302  } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
303    return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
304  else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
305    FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
306    FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
307
308    // C++ [temp.fct]p2:
309    //   A function template can be overloaded with other function templates
310    //   and with normal (non-template) functions.
311    if ((OldTemplate == 0) != (NewTemplate == 0))
312      return true;
313
314    // Is the function New an overload of the function Old?
315    QualType OldQType = Context.getCanonicalType(Old->getType());
316    QualType NewQType = Context.getCanonicalType(New->getType());
317
318    // Compare the signatures (C++ 1.3.10) of the two functions to
319    // determine whether they are overloads. If we find any mismatch
320    // in the signature, they are overloads.
321
322    // If either of these functions is a K&R-style function (no
323    // prototype), then we consider them to have matching signatures.
324    if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
325        isa<FunctionNoProtoType>(NewQType.getTypePtr()))
326      return false;
327
328    FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
329    FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
330
331    // The signature of a function includes the types of its
332    // parameters (C++ 1.3.10), which includes the presence or absence
333    // of the ellipsis; see C++ DR 357).
334    if (OldQType != NewQType &&
335        (OldType->getNumArgs() != NewType->getNumArgs() ||
336         OldType->isVariadic() != NewType->isVariadic() ||
337         !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
338                     NewType->arg_type_begin())))
339      return true;
340
341    // C++ [temp.over.link]p4:
342    //   The signature of a function template consists of its function
343    //   signature, its return type and its template parameter list. The names
344    //   of the template parameters are significant only for establishing the
345    //   relationship between the template parameters and the rest of the
346    //   signature.
347    //
348    // We check the return type and template parameter lists for function
349    // templates first; the remaining checks follow.
350    if (NewTemplate &&
351        (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
352                                         OldTemplate->getTemplateParameters(),
353                                         false, false, SourceLocation()) ||
354         OldType->getResultType() != NewType->getResultType()))
355      return true;
356
357    // If the function is a class member, its signature includes the
358    // cv-qualifiers (if any) on the function itself.
359    //
360    // As part of this, also check whether one of the member functions
361    // is static, in which case they are not overloads (C++
362    // 13.1p2). While not part of the definition of the signature,
363    // this check is important to determine whether these functions
364    // can be overloaded.
365    CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
366    CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
367    if (OldMethod && NewMethod &&
368        !OldMethod->isStatic() && !NewMethod->isStatic() &&
369        OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
370      return true;
371
372    // The signatures match; this is not an overload.
373    return false;
374  } else {
375    // (C++ 13p1):
376    //   Only function declarations can be overloaded; object and type
377    //   declarations cannot be overloaded.
378    return false;
379  }
380}
381
382/// TryImplicitConversion - Attempt to perform an implicit conversion
383/// from the given expression (Expr) to the given type (ToType). This
384/// function returns an implicit conversion sequence that can be used
385/// to perform the initialization. Given
386///
387///   void f(float f);
388///   void g(int i) { f(i); }
389///
390/// this routine would produce an implicit conversion sequence to
391/// describe the initialization of f from i, which will be a standard
392/// conversion sequence containing an lvalue-to-rvalue conversion (C++
393/// 4.1) followed by a floating-integral conversion (C++ 4.9).
394//
395/// Note that this routine only determines how the conversion can be
396/// performed; it does not actually perform the conversion. As such,
397/// it will not produce any diagnostics if no conversion is available,
398/// but will instead return an implicit conversion sequence of kind
399/// "BadConversion".
400///
401/// If @p SuppressUserConversions, then user-defined conversions are
402/// not permitted.
403/// If @p AllowExplicit, then explicit user-defined conversions are
404/// permitted.
405/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
406/// no matter its actual lvalueness.
407ImplicitConversionSequence
408Sema::TryImplicitConversion(Expr* From, QualType ToType,
409                            bool SuppressUserConversions,
410                            bool AllowExplicit, bool ForceRValue,
411                            bool InOverloadResolution) {
412  ImplicitConversionSequence ICS;
413  if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
414    ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
415  else if (getLangOptions().CPlusPlus &&
416           IsUserDefinedConversion(From, ToType, ICS.UserDefined,
417                                   !SuppressUserConversions, AllowExplicit,
418                                   ForceRValue)) {
419    ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
420    // C++ [over.ics.user]p4:
421    //   A conversion of an expression of class type to the same class
422    //   type is given Exact Match rank, and a conversion of an
423    //   expression of class type to a base class of that type is
424    //   given Conversion rank, in spite of the fact that a copy
425    //   constructor (i.e., a user-defined conversion function) is
426    //   called for those cases.
427    if (CXXConstructorDecl *Constructor
428          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
429      QualType FromCanon
430        = Context.getCanonicalType(From->getType().getUnqualifiedType());
431      QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
432      if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
433        // Turn this into a "standard" conversion sequence, so that it
434        // gets ranked with standard conversion sequences.
435        ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
436        ICS.Standard.setAsIdentityConversion();
437        ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
438        ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
439        ICS.Standard.CopyConstructor = Constructor;
440        if (ToCanon != FromCanon)
441          ICS.Standard.Second = ICK_Derived_To_Base;
442      }
443    }
444
445    // C++ [over.best.ics]p4:
446    //   However, when considering the argument of a user-defined
447    //   conversion function that is a candidate by 13.3.1.3 when
448    //   invoked for the copying of the temporary in the second step
449    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
450    //   13.3.1.6 in all cases, only standard conversion sequences and
451    //   ellipsis conversion sequences are allowed.
452    if (SuppressUserConversions &&
453        ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
454      ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
455  } else
456    ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
457
458  return ICS;
459}
460
461/// IsStandardConversion - Determines whether there is a standard
462/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
463/// expression From to the type ToType. Standard conversion sequences
464/// only consider non-class types; for conversions that involve class
465/// types, use TryImplicitConversion. If a conversion exists, SCS will
466/// contain the standard conversion sequence required to perform this
467/// conversion and this routine will return true. Otherwise, this
468/// routine will return false and the value of SCS is unspecified.
469bool
470Sema::IsStandardConversion(Expr* From, QualType ToType,
471                           bool InOverloadResolution,
472                           StandardConversionSequence &SCS) {
473  QualType FromType = From->getType();
474
475  // Standard conversions (C++ [conv])
476  SCS.setAsIdentityConversion();
477  SCS.Deprecated = false;
478  SCS.IncompatibleObjC = false;
479  SCS.FromTypePtr = FromType.getAsOpaquePtr();
480  SCS.CopyConstructor = 0;
481
482  // There are no standard conversions for class types in C++, so
483  // abort early. When overloading in C, however, we do permit
484  if (FromType->isRecordType() || ToType->isRecordType()) {
485    if (getLangOptions().CPlusPlus)
486      return false;
487
488    // When we're overloading in C, we allow, as standard conversions,
489  }
490
491  // The first conversion can be an lvalue-to-rvalue conversion,
492  // array-to-pointer conversion, or function-to-pointer conversion
493  // (C++ 4p1).
494
495  // Lvalue-to-rvalue conversion (C++ 4.1):
496  //   An lvalue (3.10) of a non-function, non-array type T can be
497  //   converted to an rvalue.
498  Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
499  if (argIsLvalue == Expr::LV_Valid &&
500      !FromType->isFunctionType() && !FromType->isArrayType() &&
501      Context.getCanonicalType(FromType) != Context.OverloadTy) {
502    SCS.First = ICK_Lvalue_To_Rvalue;
503
504    // If T is a non-class type, the type of the rvalue is the
505    // cv-unqualified version of T. Otherwise, the type of the rvalue
506    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
507    // just strip the qualifiers because they don't matter.
508
509    // FIXME: Doesn't see through to qualifiers behind a typedef!
510    FromType = FromType.getUnqualifiedType();
511  } else if (FromType->isArrayType()) {
512    // Array-to-pointer conversion (C++ 4.2)
513    SCS.First = ICK_Array_To_Pointer;
514
515    // An lvalue or rvalue of type "array of N T" or "array of unknown
516    // bound of T" can be converted to an rvalue of type "pointer to
517    // T" (C++ 4.2p1).
518    FromType = Context.getArrayDecayedType(FromType);
519
520    if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
521      // This conversion is deprecated. (C++ D.4).
522      SCS.Deprecated = true;
523
524      // For the purpose of ranking in overload resolution
525      // (13.3.3.1.1), this conversion is considered an
526      // array-to-pointer conversion followed by a qualification
527      // conversion (4.4). (C++ 4.2p2)
528      SCS.Second = ICK_Identity;
529      SCS.Third = ICK_Qualification;
530      SCS.ToTypePtr = ToType.getAsOpaquePtr();
531      return true;
532    }
533  } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
534    // Function-to-pointer conversion (C++ 4.3).
535    SCS.First = ICK_Function_To_Pointer;
536
537    // An lvalue of function type T can be converted to an rvalue of
538    // type "pointer to T." The result is a pointer to the
539    // function. (C++ 4.3p1).
540    FromType = Context.getPointerType(FromType);
541  } else if (FunctionDecl *Fn
542             = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
543    // Address of overloaded function (C++ [over.over]).
544    SCS.First = ICK_Function_To_Pointer;
545
546    // We were able to resolve the address of the overloaded function,
547    // so we can convert to the type of that function.
548    FromType = Fn->getType();
549    if (ToType->isLValueReferenceType())
550      FromType = Context.getLValueReferenceType(FromType);
551    else if (ToType->isRValueReferenceType())
552      FromType = Context.getRValueReferenceType(FromType);
553    else if (ToType->isMemberPointerType()) {
554      // Resolve address only succeeds if both sides are member pointers,
555      // but it doesn't have to be the same class. See DR 247.
556      // Note that this means that the type of &Derived::fn can be
557      // Ret (Base::*)(Args) if the fn overload actually found is from the
558      // base class, even if it was brought into the derived class via a
559      // using declaration. The standard isn't clear on this issue at all.
560      CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
561      FromType = Context.getMemberPointerType(FromType,
562                    Context.getTypeDeclType(M->getParent()).getTypePtr());
563    } else
564      FromType = Context.getPointerType(FromType);
565  } else {
566    // We don't require any conversions for the first step.
567    SCS.First = ICK_Identity;
568  }
569
570  // The second conversion can be an integral promotion, floating
571  // point promotion, integral conversion, floating point conversion,
572  // floating-integral conversion, pointer conversion,
573  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
574  // For overloading in C, this can also be a "compatible-type"
575  // conversion.
576  bool IncompatibleObjC = false;
577  if (Context.hasSameUnqualifiedType(FromType, ToType)) {
578    // The unqualified versions of the types are the same: there's no
579    // conversion to do.
580    SCS.Second = ICK_Identity;
581  } else if (IsIntegralPromotion(From, FromType, ToType)) {
582    // Integral promotion (C++ 4.5).
583    SCS.Second = ICK_Integral_Promotion;
584    FromType = ToType.getUnqualifiedType();
585  } else if (IsFloatingPointPromotion(FromType, ToType)) {
586    // Floating point promotion (C++ 4.6).
587    SCS.Second = ICK_Floating_Promotion;
588    FromType = ToType.getUnqualifiedType();
589  } else if (IsComplexPromotion(FromType, ToType)) {
590    // Complex promotion (Clang extension)
591    SCS.Second = ICK_Complex_Promotion;
592    FromType = ToType.getUnqualifiedType();
593  } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
594           (ToType->isIntegralType() && !ToType->isEnumeralType())) {
595    // Integral conversions (C++ 4.7).
596    // FIXME: isIntegralType shouldn't be true for enums in C++.
597    SCS.Second = ICK_Integral_Conversion;
598    FromType = ToType.getUnqualifiedType();
599  } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
600    // Floating point conversions (C++ 4.8).
601    SCS.Second = ICK_Floating_Conversion;
602    FromType = ToType.getUnqualifiedType();
603  } else if (FromType->isComplexType() && ToType->isComplexType()) {
604    // Complex conversions (C99 6.3.1.6)
605    SCS.Second = ICK_Complex_Conversion;
606    FromType = ToType.getUnqualifiedType();
607  } else if ((FromType->isFloatingType() &&
608              ToType->isIntegralType() && (!ToType->isBooleanType() &&
609                                           !ToType->isEnumeralType())) ||
610             ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
611              ToType->isFloatingType())) {
612    // Floating-integral conversions (C++ 4.9).
613    // FIXME: isIntegralType shouldn't be true for enums in C++.
614    SCS.Second = ICK_Floating_Integral;
615    FromType = ToType.getUnqualifiedType();
616  } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
617             (ToType->isComplexType() && FromType->isArithmeticType())) {
618    // Complex-real conversions (C99 6.3.1.7)
619    SCS.Second = ICK_Complex_Real;
620    FromType = ToType.getUnqualifiedType();
621  } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
622                                 FromType, IncompatibleObjC)) {
623    // Pointer conversions (C++ 4.10).
624    SCS.Second = ICK_Pointer_Conversion;
625    SCS.IncompatibleObjC = IncompatibleObjC;
626  } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
627    // Pointer to member conversions (4.11).
628    SCS.Second = ICK_Pointer_Member;
629  } else if (ToType->isBooleanType() &&
630             (FromType->isArithmeticType() ||
631              FromType->isEnumeralType() ||
632              FromType->isPointerType() ||
633              FromType->isBlockPointerType() ||
634              FromType->isMemberPointerType() ||
635              FromType->isNullPtrType())) {
636    // Boolean conversions (C++ 4.12).
637    SCS.Second = ICK_Boolean_Conversion;
638    FromType = Context.BoolTy;
639  } else if (!getLangOptions().CPlusPlus &&
640             Context.typesAreCompatible(ToType, FromType)) {
641    // Compatible conversions (Clang extension for C function overloading)
642    SCS.Second = ICK_Compatible_Conversion;
643  } else {
644    // No second conversion required.
645    SCS.Second = ICK_Identity;
646  }
647
648  QualType CanonFrom;
649  QualType CanonTo;
650  // The third conversion can be a qualification conversion (C++ 4p1).
651  if (IsQualificationConversion(FromType, ToType)) {
652    SCS.Third = ICK_Qualification;
653    FromType = ToType;
654    CanonFrom = Context.getCanonicalType(FromType);
655    CanonTo = Context.getCanonicalType(ToType);
656  } else {
657    // No conversion required
658    SCS.Third = ICK_Identity;
659
660    // C++ [over.best.ics]p6:
661    //   [...] Any difference in top-level cv-qualification is
662    //   subsumed by the initialization itself and does not constitute
663    //   a conversion. [...]
664    CanonFrom = Context.getCanonicalType(FromType);
665    CanonTo = Context.getCanonicalType(ToType);
666    if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
667        CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
668      FromType = ToType;
669      CanonFrom = CanonTo;
670    }
671  }
672
673  // If we have not converted the argument type to the parameter type,
674  // this is a bad conversion sequence.
675  if (CanonFrom != CanonTo)
676    return false;
677
678  SCS.ToTypePtr = FromType.getAsOpaquePtr();
679  return true;
680}
681
682/// IsIntegralPromotion - Determines whether the conversion from the
683/// expression From (whose potentially-adjusted type is FromType) to
684/// ToType is an integral promotion (C++ 4.5). If so, returns true and
685/// sets PromotedType to the promoted type.
686bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
687  const BuiltinType *To = ToType->getAsBuiltinType();
688  // All integers are built-in.
689  if (!To) {
690    return false;
691  }
692
693  // An rvalue of type char, signed char, unsigned char, short int, or
694  // unsigned short int can be converted to an rvalue of type int if
695  // int can represent all the values of the source type; otherwise,
696  // the source rvalue can be converted to an rvalue of type unsigned
697  // int (C++ 4.5p1).
698  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
699    if (// We can promote any signed, promotable integer type to an int
700        (FromType->isSignedIntegerType() ||
701         // We can promote any unsigned integer type whose size is
702         // less than int to an int.
703         (!FromType->isSignedIntegerType() &&
704          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
705      return To->getKind() == BuiltinType::Int;
706    }
707
708    return To->getKind() == BuiltinType::UInt;
709  }
710
711  // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
712  // can be converted to an rvalue of the first of the following types
713  // that can represent all the values of its underlying type: int,
714  // unsigned int, long, or unsigned long (C++ 4.5p2).
715  if ((FromType->isEnumeralType() || FromType->isWideCharType())
716      && ToType->isIntegerType()) {
717    // Determine whether the type we're converting from is signed or
718    // unsigned.
719    bool FromIsSigned;
720    uint64_t FromSize = Context.getTypeSize(FromType);
721    if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
722      QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
723      FromIsSigned = UnderlyingType->isSignedIntegerType();
724    } else {
725      // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
726      FromIsSigned = true;
727    }
728
729    // The types we'll try to promote to, in the appropriate
730    // order. Try each of these types.
731    QualType PromoteTypes[6] = {
732      Context.IntTy, Context.UnsignedIntTy,
733      Context.LongTy, Context.UnsignedLongTy ,
734      Context.LongLongTy, Context.UnsignedLongLongTy
735    };
736    for (int Idx = 0; Idx < 6; ++Idx) {
737      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
738      if (FromSize < ToSize ||
739          (FromSize == ToSize &&
740           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
741        // We found the type that we can promote to. If this is the
742        // type we wanted, we have a promotion. Otherwise, no
743        // promotion.
744        return Context.getCanonicalType(ToType).getUnqualifiedType()
745          == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
746      }
747    }
748  }
749
750  // An rvalue for an integral bit-field (9.6) can be converted to an
751  // rvalue of type int if int can represent all the values of the
752  // bit-field; otherwise, it can be converted to unsigned int if
753  // unsigned int can represent all the values of the bit-field. If
754  // the bit-field is larger yet, no integral promotion applies to
755  // it. If the bit-field has an enumerated type, it is treated as any
756  // other value of that type for promotion purposes (C++ 4.5p3).
757  // FIXME: We should delay checking of bit-fields until we actually perform the
758  // conversion.
759  using llvm::APSInt;
760  if (From)
761    if (FieldDecl *MemberDecl = From->getBitField()) {
762      APSInt BitWidth;
763      if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
764          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
765        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
766        ToSize = Context.getTypeSize(ToType);
767
768        // Are we promoting to an int from a bitfield that fits in an int?
769        if (BitWidth < ToSize ||
770            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
771          return To->getKind() == BuiltinType::Int;
772        }
773
774        // Are we promoting to an unsigned int from an unsigned bitfield
775        // that fits into an unsigned int?
776        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
777          return To->getKind() == BuiltinType::UInt;
778        }
779
780        return false;
781      }
782    }
783
784  // An rvalue of type bool can be converted to an rvalue of type int,
785  // with false becoming zero and true becoming one (C++ 4.5p4).
786  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
787    return true;
788  }
789
790  return false;
791}
792
793/// IsFloatingPointPromotion - Determines whether the conversion from
794/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
795/// returns true and sets PromotedType to the promoted type.
796bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
797  /// An rvalue of type float can be converted to an rvalue of type
798  /// double. (C++ 4.6p1).
799  if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
800    if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
801      if (FromBuiltin->getKind() == BuiltinType::Float &&
802          ToBuiltin->getKind() == BuiltinType::Double)
803        return true;
804
805      // C99 6.3.1.5p1:
806      //   When a float is promoted to double or long double, or a
807      //   double is promoted to long double [...].
808      if (!getLangOptions().CPlusPlus &&
809          (FromBuiltin->getKind() == BuiltinType::Float ||
810           FromBuiltin->getKind() == BuiltinType::Double) &&
811          (ToBuiltin->getKind() == BuiltinType::LongDouble))
812        return true;
813    }
814
815  return false;
816}
817
818/// \brief Determine if a conversion is a complex promotion.
819///
820/// A complex promotion is defined as a complex -> complex conversion
821/// where the conversion between the underlying real types is a
822/// floating-point or integral promotion.
823bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
824  const ComplexType *FromComplex = FromType->getAsComplexType();
825  if (!FromComplex)
826    return false;
827
828  const ComplexType *ToComplex = ToType->getAsComplexType();
829  if (!ToComplex)
830    return false;
831
832  return IsFloatingPointPromotion(FromComplex->getElementType(),
833                                  ToComplex->getElementType()) ||
834    IsIntegralPromotion(0, FromComplex->getElementType(),
835                        ToComplex->getElementType());
836}
837
838/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
839/// the pointer type FromPtr to a pointer to type ToPointee, with the
840/// same type qualifiers as FromPtr has on its pointee type. ToType,
841/// if non-empty, will be a pointer to ToType that may or may not have
842/// the right set of qualifiers on its pointee.
843static QualType
844BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
845                                   QualType ToPointee, QualType ToType,
846                                   ASTContext &Context) {
847  QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
848  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
849  unsigned Quals = CanonFromPointee.getCVRQualifiers();
850
851  // Exact qualifier match -> return the pointer type we're converting to.
852  if (CanonToPointee.getCVRQualifiers() == Quals) {
853    // ToType is exactly what we need. Return it.
854    if (ToType.getTypePtr())
855      return ToType;
856
857    // Build a pointer to ToPointee. It has the right qualifiers
858    // already.
859    return Context.getPointerType(ToPointee);
860  }
861
862  // Just build a canonical type that has the right qualifiers.
863  return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
864}
865
866static bool isNullPointerConstantForConversion(Expr *Expr,
867                                               bool InOverloadResolution,
868                                               ASTContext &Context) {
869  // Handle value-dependent integral null pointer constants correctly.
870  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
871  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
872      Expr->getType()->isIntegralType())
873    return !InOverloadResolution;
874
875  return Expr->isNullPointerConstant(Context);
876}
877
878/// IsPointerConversion - Determines whether the conversion of the
879/// expression From, which has the (possibly adjusted) type FromType,
880/// can be converted to the type ToType via a pointer conversion (C++
881/// 4.10). If so, returns true and places the converted type (that
882/// might differ from ToType in its cv-qualifiers at some level) into
883/// ConvertedType.
884///
885/// This routine also supports conversions to and from block pointers
886/// and conversions with Objective-C's 'id', 'id<protocols...>', and
887/// pointers to interfaces. FIXME: Once we've determined the
888/// appropriate overloading rules for Objective-C, we may want to
889/// split the Objective-C checks into a different routine; however,
890/// GCC seems to consider all of these conversions to be pointer
891/// conversions, so for now they live here. IncompatibleObjC will be
892/// set if the conversion is an allowed Objective-C conversion that
893/// should result in a warning.
894bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
895                               bool InOverloadResolution,
896                               QualType& ConvertedType,
897                               bool &IncompatibleObjC) {
898  IncompatibleObjC = false;
899  if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
900    return true;
901
902  // Conversion from a null pointer constant to any Objective-C pointer type.
903  if (ToType->isObjCObjectPointerType() &&
904      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
905    ConvertedType = ToType;
906    return true;
907  }
908
909  // Blocks: Block pointers can be converted to void*.
910  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
911      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
912    ConvertedType = ToType;
913    return true;
914  }
915  // Blocks: A null pointer constant can be converted to a block
916  // pointer type.
917  if (ToType->isBlockPointerType() &&
918      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
919    ConvertedType = ToType;
920    return true;
921  }
922
923  // If the left-hand-side is nullptr_t, the right side can be a null
924  // pointer constant.
925  if (ToType->isNullPtrType() &&
926      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
927    ConvertedType = ToType;
928    return true;
929  }
930
931  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
932  if (!ToTypePtr)
933    return false;
934
935  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
936  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
937    ConvertedType = ToType;
938    return true;
939  }
940
941  // Beyond this point, both types need to be pointers.
942  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
943  if (!FromTypePtr)
944    return false;
945
946  QualType FromPointeeType = FromTypePtr->getPointeeType();
947  QualType ToPointeeType = ToTypePtr->getPointeeType();
948
949  // An rvalue of type "pointer to cv T," where T is an object type,
950  // can be converted to an rvalue of type "pointer to cv void" (C++
951  // 4.10p2).
952  if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
953    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
954                                                       ToPointeeType,
955                                                       ToType, Context);
956    return true;
957  }
958
959  // When we're overloading in C, we allow a special kind of pointer
960  // conversion for compatible-but-not-identical pointee types.
961  if (!getLangOptions().CPlusPlus &&
962      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
963    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
964                                                       ToPointeeType,
965                                                       ToType, Context);
966    return true;
967  }
968
969  // C++ [conv.ptr]p3:
970  //
971  //   An rvalue of type "pointer to cv D," where D is a class type,
972  //   can be converted to an rvalue of type "pointer to cv B," where
973  //   B is a base class (clause 10) of D. If B is an inaccessible
974  //   (clause 11) or ambiguous (10.2) base class of D, a program that
975  //   necessitates this conversion is ill-formed. The result of the
976  //   conversion is a pointer to the base class sub-object of the
977  //   derived class object. The null pointer value is converted to
978  //   the null pointer value of the destination type.
979  //
980  // Note that we do not check for ambiguity or inaccessibility
981  // here. That is handled by CheckPointerConversion.
982  if (getLangOptions().CPlusPlus &&
983      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
984      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
985    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
986                                                       ToPointeeType,
987                                                       ToType, Context);
988    return true;
989  }
990
991  return false;
992}
993
994/// isObjCPointerConversion - Determines whether this is an
995/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
996/// with the same arguments and return values.
997bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
998                                   QualType& ConvertedType,
999                                   bool &IncompatibleObjC) {
1000  if (!getLangOptions().ObjC1)
1001    return false;
1002
1003  // First, we handle all conversions on ObjC object pointer types.
1004  const ObjCObjectPointerType* ToObjCPtr = ToType->getAsObjCObjectPointerType();
1005  const ObjCObjectPointerType *FromObjCPtr =
1006    FromType->getAsObjCObjectPointerType();
1007
1008  if (ToObjCPtr && FromObjCPtr) {
1009    // Objective C++: We're able to convert between "id" or "Class" and a
1010    // pointer to any interface (in both directions).
1011    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
1012      ConvertedType = ToType;
1013      return true;
1014    }
1015    // Conversions with Objective-C's id<...>.
1016    if ((FromObjCPtr->isObjCQualifiedIdType() ||
1017         ToObjCPtr->isObjCQualifiedIdType()) &&
1018        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1019                                                  /*compare=*/false)) {
1020      ConvertedType = ToType;
1021      return true;
1022    }
1023    // Objective C++: We're able to convert from a pointer to an
1024    // interface to a pointer to a different interface.
1025    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1026      ConvertedType = ToType;
1027      return true;
1028    }
1029
1030    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1031      // Okay: this is some kind of implicit downcast of Objective-C
1032      // interfaces, which is permitted. However, we're going to
1033      // complain about it.
1034      IncompatibleObjC = true;
1035      ConvertedType = FromType;
1036      return true;
1037    }
1038  }
1039  // Beyond this point, both types need to be C pointers or block pointers.
1040  QualType ToPointeeType;
1041  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
1042    ToPointeeType = ToCPtr->getPointeeType();
1043  else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
1044    ToPointeeType = ToBlockPtr->getPointeeType();
1045  else
1046    return false;
1047
1048  QualType FromPointeeType;
1049  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
1050    FromPointeeType = FromCPtr->getPointeeType();
1051  else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
1052    FromPointeeType = FromBlockPtr->getPointeeType();
1053  else
1054    return false;
1055
1056  // If we have pointers to pointers, recursively check whether this
1057  // is an Objective-C conversion.
1058  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1059      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1060                              IncompatibleObjC)) {
1061    // We always complain about this conversion.
1062    IncompatibleObjC = true;
1063    ConvertedType = ToType;
1064    return true;
1065  }
1066  // If we have pointers to functions or blocks, check whether the only
1067  // differences in the argument and result types are in Objective-C
1068  // pointer conversions. If so, we permit the conversion (but
1069  // complain about it).
1070  const FunctionProtoType *FromFunctionType
1071    = FromPointeeType->getAsFunctionProtoType();
1072  const FunctionProtoType *ToFunctionType
1073    = ToPointeeType->getAsFunctionProtoType();
1074  if (FromFunctionType && ToFunctionType) {
1075    // If the function types are exactly the same, this isn't an
1076    // Objective-C pointer conversion.
1077    if (Context.getCanonicalType(FromPointeeType)
1078          == Context.getCanonicalType(ToPointeeType))
1079      return false;
1080
1081    // Perform the quick checks that will tell us whether these
1082    // function types are obviously different.
1083    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1084        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1085        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1086      return false;
1087
1088    bool HasObjCConversion = false;
1089    if (Context.getCanonicalType(FromFunctionType->getResultType())
1090          == Context.getCanonicalType(ToFunctionType->getResultType())) {
1091      // Okay, the types match exactly. Nothing to do.
1092    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1093                                       ToFunctionType->getResultType(),
1094                                       ConvertedType, IncompatibleObjC)) {
1095      // Okay, we have an Objective-C pointer conversion.
1096      HasObjCConversion = true;
1097    } else {
1098      // Function types are too different. Abort.
1099      return false;
1100    }
1101
1102    // Check argument types.
1103    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1104         ArgIdx != NumArgs; ++ArgIdx) {
1105      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1106      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1107      if (Context.getCanonicalType(FromArgType)
1108            == Context.getCanonicalType(ToArgType)) {
1109        // Okay, the types match exactly. Nothing to do.
1110      } else if (isObjCPointerConversion(FromArgType, ToArgType,
1111                                         ConvertedType, IncompatibleObjC)) {
1112        // Okay, we have an Objective-C pointer conversion.
1113        HasObjCConversion = true;
1114      } else {
1115        // Argument types are too different. Abort.
1116        return false;
1117      }
1118    }
1119
1120    if (HasObjCConversion) {
1121      // We had an Objective-C conversion. Allow this pointer
1122      // conversion, but complain about it.
1123      ConvertedType = ToType;
1124      IncompatibleObjC = true;
1125      return true;
1126    }
1127  }
1128
1129  return false;
1130}
1131
1132/// CheckPointerConversion - Check the pointer conversion from the
1133/// expression From to the type ToType. This routine checks for
1134/// ambiguous or inaccessible derived-to-base pointer
1135/// conversions for which IsPointerConversion has already returned
1136/// true. It returns true and produces a diagnostic if there was an
1137/// error, or returns false otherwise.
1138bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1139                                  CastExpr::CastKind &Kind) {
1140  QualType FromType = From->getType();
1141
1142  if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1143    if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
1144      QualType FromPointeeType = FromPtrType->getPointeeType(),
1145               ToPointeeType   = ToPtrType->getPointeeType();
1146
1147      if (FromPointeeType->isRecordType() &&
1148          ToPointeeType->isRecordType()) {
1149        // We must have a derived-to-base conversion. Check an
1150        // ambiguous or inaccessible conversion.
1151        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1152                                         From->getExprLoc(),
1153                                         From->getSourceRange()))
1154          return true;
1155
1156        // The conversion was successful.
1157        Kind = CastExpr::CK_DerivedToBase;
1158      }
1159    }
1160  if (const ObjCObjectPointerType *FromPtrType =
1161        FromType->getAsObjCObjectPointerType())
1162    if (const ObjCObjectPointerType *ToPtrType =
1163          ToType->getAsObjCObjectPointerType()) {
1164      // Objective-C++ conversions are always okay.
1165      // FIXME: We should have a different class of conversions for the
1166      // Objective-C++ implicit conversions.
1167      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
1168        return false;
1169
1170  }
1171  return false;
1172}
1173
1174/// IsMemberPointerConversion - Determines whether the conversion of the
1175/// expression From, which has the (possibly adjusted) type FromType, can be
1176/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1177/// If so, returns true and places the converted type (that might differ from
1178/// ToType in its cv-qualifiers at some level) into ConvertedType.
1179bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1180                                     QualType ToType, QualType &ConvertedType) {
1181  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
1182  if (!ToTypePtr)
1183    return false;
1184
1185  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1186  if (From->isNullPointerConstant(Context)) {
1187    ConvertedType = ToType;
1188    return true;
1189  }
1190
1191  // Otherwise, both types have to be member pointers.
1192  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
1193  if (!FromTypePtr)
1194    return false;
1195
1196  // A pointer to member of B can be converted to a pointer to member of D,
1197  // where D is derived from B (C++ 4.11p2).
1198  QualType FromClass(FromTypePtr->getClass(), 0);
1199  QualType ToClass(ToTypePtr->getClass(), 0);
1200  // FIXME: What happens when these are dependent? Is this function even called?
1201
1202  if (IsDerivedFrom(ToClass, FromClass)) {
1203    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1204                                                 ToClass.getTypePtr());
1205    return true;
1206  }
1207
1208  return false;
1209}
1210
1211/// CheckMemberPointerConversion - Check the member pointer conversion from the
1212/// expression From to the type ToType. This routine checks for ambiguous or
1213/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1214/// for which IsMemberPointerConversion has already returned true. It returns
1215/// true and produces a diagnostic if there was an error, or returns false
1216/// otherwise.
1217bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1218                                        CastExpr::CastKind &Kind) {
1219  QualType FromType = From->getType();
1220  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
1221  if (!FromPtrType) {
1222    // This must be a null pointer to member pointer conversion
1223    assert(From->isNullPointerConstant(Context) &&
1224           "Expr must be null pointer constant!");
1225    Kind = CastExpr::CK_NullToMemberPointer;
1226    return false;
1227  }
1228
1229  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
1230  assert(ToPtrType && "No member pointer cast has a target type "
1231                      "that is not a member pointer.");
1232
1233  QualType FromClass = QualType(FromPtrType->getClass(), 0);
1234  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
1235
1236  // FIXME: What about dependent types?
1237  assert(FromClass->isRecordType() && "Pointer into non-class.");
1238  assert(ToClass->isRecordType() && "Pointer into non-class.");
1239
1240  BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1241                  /*DetectVirtual=*/true);
1242  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1243  assert(DerivationOkay &&
1244         "Should not have been called if derivation isn't OK.");
1245  (void)DerivationOkay;
1246
1247  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1248                                  getUnqualifiedType())) {
1249    // Derivation is ambiguous. Redo the check to find the exact paths.
1250    Paths.clear();
1251    Paths.setRecordingPaths(true);
1252    bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1253    assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1254    (void)StillOkay;
1255
1256    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1257    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1258      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1259    return true;
1260  }
1261
1262  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1263    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1264      << FromClass << ToClass << QualType(VBase, 0)
1265      << From->getSourceRange();
1266    return true;
1267  }
1268
1269  // Must be a base to derived member conversion.
1270  Kind = CastExpr::CK_BaseToDerivedMemberPointer;
1271  return false;
1272}
1273
1274/// IsQualificationConversion - Determines whether the conversion from
1275/// an rvalue of type FromType to ToType is a qualification conversion
1276/// (C++ 4.4).
1277bool
1278Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
1279  FromType = Context.getCanonicalType(FromType);
1280  ToType = Context.getCanonicalType(ToType);
1281
1282  // If FromType and ToType are the same type, this is not a
1283  // qualification conversion.
1284  if (FromType == ToType)
1285    return false;
1286
1287  // (C++ 4.4p4):
1288  //   A conversion can add cv-qualifiers at levels other than the first
1289  //   in multi-level pointers, subject to the following rules: [...]
1290  bool PreviousToQualsIncludeConst = true;
1291  bool UnwrappedAnyPointer = false;
1292  while (UnwrapSimilarPointerTypes(FromType, ToType)) {
1293    // Within each iteration of the loop, we check the qualifiers to
1294    // determine if this still looks like a qualification
1295    // conversion. Then, if all is well, we unwrap one more level of
1296    // pointers or pointers-to-members and do it all again
1297    // until there are no more pointers or pointers-to-members left to
1298    // unwrap.
1299    UnwrappedAnyPointer = true;
1300
1301    //   -- for every j > 0, if const is in cv 1,j then const is in cv
1302    //      2,j, and similarly for volatile.
1303    if (!ToType.isAtLeastAsQualifiedAs(FromType))
1304      return false;
1305
1306    //   -- if the cv 1,j and cv 2,j are different, then const is in
1307    //      every cv for 0 < k < j.
1308    if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
1309        && !PreviousToQualsIncludeConst)
1310      return false;
1311
1312    // Keep track of whether all prior cv-qualifiers in the "to" type
1313    // include const.
1314    PreviousToQualsIncludeConst
1315      = PreviousToQualsIncludeConst && ToType.isConstQualified();
1316  }
1317
1318  // We are left with FromType and ToType being the pointee types
1319  // after unwrapping the original FromType and ToType the same number
1320  // of types. If we unwrapped any pointers, and if FromType and
1321  // ToType have the same unqualified type (since we checked
1322  // qualifiers above), then this is a qualification conversion.
1323  return UnwrappedAnyPointer &&
1324    FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1325}
1326
1327/// \brief Given a function template or function, extract the function template
1328/// declaration (if any) and the underlying function declaration.
1329template<typename T>
1330static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1331                                   FunctionTemplateDecl *&FunctionTemplate) {
1332  FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1333  if (FunctionTemplate)
1334    Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1335  else
1336    Function = cast<T>(Orig);
1337}
1338
1339/// Determines whether there is a user-defined conversion sequence
1340/// (C++ [over.ics.user]) that converts expression From to the type
1341/// ToType. If such a conversion exists, User will contain the
1342/// user-defined conversion sequence that performs such a conversion
1343/// and this routine will return true. Otherwise, this routine returns
1344/// false and User is unspecified.
1345///
1346/// \param AllowConversionFunctions true if the conversion should
1347/// consider conversion functions at all. If false, only constructors
1348/// will be considered.
1349///
1350/// \param AllowExplicit  true if the conversion should consider C++0x
1351/// "explicit" conversion functions as well as non-explicit conversion
1352/// functions (C++0x [class.conv.fct]p2).
1353///
1354/// \param ForceRValue  true if the expression should be treated as an rvalue
1355/// for overload resolution.
1356bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1357                                   UserDefinedConversionSequence& User,
1358                                   bool AllowConversionFunctions,
1359                                   bool AllowExplicit, bool ForceRValue) {
1360  OverloadCandidateSet CandidateSet;
1361  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
1362    if (CXXRecordDecl *ToRecordDecl
1363          = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1364      // C++ [over.match.ctor]p1:
1365      //   When objects of class type are direct-initialized (8.5), or
1366      //   copy-initialized from an expression of the same or a
1367      //   derived class type (8.5), overload resolution selects the
1368      //   constructor. [...] For copy-initialization, the candidate
1369      //   functions are all the converting constructors (12.3.1) of
1370      //   that class. The argument list is the expression-list within
1371      //   the parentheses of the initializer.
1372      DeclarationName ConstructorName
1373        = Context.DeclarationNames.getCXXConstructorName(
1374                          Context.getCanonicalType(ToType).getUnqualifiedType());
1375      DeclContext::lookup_iterator Con, ConEnd;
1376      for (llvm::tie(Con, ConEnd)
1377             = ToRecordDecl->lookup(ConstructorName);
1378           Con != ConEnd; ++Con) {
1379        // Find the constructor (which may be a template).
1380        CXXConstructorDecl *Constructor = 0;
1381        FunctionTemplateDecl *ConstructorTmpl
1382          = dyn_cast<FunctionTemplateDecl>(*Con);
1383        if (ConstructorTmpl)
1384          Constructor
1385            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1386        else
1387          Constructor = cast<CXXConstructorDecl>(*Con);
1388
1389        if (!Constructor->isInvalidDecl() &&
1390            Constructor->isConvertingConstructor(AllowExplicit)) {
1391          if (ConstructorTmpl)
1392            AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
1393                                         1, CandidateSet,
1394                                         /*SuppressUserConversions=*/true,
1395                                         ForceRValue);
1396          else
1397            AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1398                                 /*SuppressUserConversions=*/true, ForceRValue);
1399        }
1400      }
1401    }
1402  }
1403
1404  if (!AllowConversionFunctions) {
1405    // Don't allow any conversion functions to enter the overload set.
1406  } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1407                                 PDiag(0)
1408                                   << From->getSourceRange())) {
1409    // No conversion functions from incomplete types.
1410  } else if (const RecordType *FromRecordType
1411               = From->getType()->getAs<RecordType>()) {
1412    if (CXXRecordDecl *FromRecordDecl
1413         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1414      // Add all of the conversion functions as candidates.
1415      OverloadedFunctionDecl *Conversions
1416        = FromRecordDecl->getVisibleConversionFunctions();
1417      for (OverloadedFunctionDecl::function_iterator Func
1418             = Conversions->function_begin();
1419           Func != Conversions->function_end(); ++Func) {
1420        CXXConversionDecl *Conv;
1421        FunctionTemplateDecl *ConvTemplate;
1422        GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1423        if (ConvTemplate)
1424          Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1425        else
1426          Conv = dyn_cast<CXXConversionDecl>(*Func);
1427
1428        if (AllowExplicit || !Conv->isExplicit()) {
1429          if (ConvTemplate)
1430            AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1431                                           CandidateSet);
1432          else
1433            AddConversionCandidate(Conv, From, ToType, CandidateSet);
1434        }
1435      }
1436    }
1437  }
1438
1439  OverloadCandidateSet::iterator Best;
1440  switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
1441    case OR_Success:
1442      // Record the standard conversion we used and the conversion function.
1443      if (CXXConstructorDecl *Constructor
1444            = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1445        // C++ [over.ics.user]p1:
1446        //   If the user-defined conversion is specified by a
1447        //   constructor (12.3.1), the initial standard conversion
1448        //   sequence converts the source type to the type required by
1449        //   the argument of the constructor.
1450        //
1451        // FIXME: What about ellipsis conversions?
1452        QualType ThisType = Constructor->getThisType(Context);
1453        User.Before = Best->Conversions[0].Standard;
1454        User.ConversionFunction = Constructor;
1455        User.After.setAsIdentityConversion();
1456        User.After.FromTypePtr
1457          = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
1458        User.After.ToTypePtr = ToType.getAsOpaquePtr();
1459        return true;
1460      } else if (CXXConversionDecl *Conversion
1461                   = dyn_cast<CXXConversionDecl>(Best->Function)) {
1462        // C++ [over.ics.user]p1:
1463        //
1464        //   [...] If the user-defined conversion is specified by a
1465        //   conversion function (12.3.2), the initial standard
1466        //   conversion sequence converts the source type to the
1467        //   implicit object parameter of the conversion function.
1468        User.Before = Best->Conversions[0].Standard;
1469        User.ConversionFunction = Conversion;
1470
1471        // C++ [over.ics.user]p2:
1472        //   The second standard conversion sequence converts the
1473        //   result of the user-defined conversion to the target type
1474        //   for the sequence. Since an implicit conversion sequence
1475        //   is an initialization, the special rules for
1476        //   initialization by user-defined conversion apply when
1477        //   selecting the best user-defined conversion for a
1478        //   user-defined conversion sequence (see 13.3.3 and
1479        //   13.3.3.1).
1480        User.After = Best->FinalConversion;
1481        return true;
1482      } else {
1483        assert(false && "Not a constructor or conversion function?");
1484        return false;
1485      }
1486
1487    case OR_No_Viable_Function:
1488    case OR_Deleted:
1489      // No conversion here! We're done.
1490      return false;
1491
1492    case OR_Ambiguous:
1493      // FIXME: See C++ [over.best.ics]p10 for the handling of
1494      // ambiguous conversion sequences.
1495      return false;
1496    }
1497
1498  return false;
1499}
1500
1501/// CompareImplicitConversionSequences - Compare two implicit
1502/// conversion sequences to determine whether one is better than the
1503/// other or if they are indistinguishable (C++ 13.3.3.2).
1504ImplicitConversionSequence::CompareKind
1505Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1506                                         const ImplicitConversionSequence& ICS2)
1507{
1508  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1509  // conversion sequences (as defined in 13.3.3.1)
1510  //   -- a standard conversion sequence (13.3.3.1.1) is a better
1511  //      conversion sequence than a user-defined conversion sequence or
1512  //      an ellipsis conversion sequence, and
1513  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
1514  //      conversion sequence than an ellipsis conversion sequence
1515  //      (13.3.3.1.3).
1516  //
1517  if (ICS1.ConversionKind < ICS2.ConversionKind)
1518    return ImplicitConversionSequence::Better;
1519  else if (ICS2.ConversionKind < ICS1.ConversionKind)
1520    return ImplicitConversionSequence::Worse;
1521
1522  // Two implicit conversion sequences of the same form are
1523  // indistinguishable conversion sequences unless one of the
1524  // following rules apply: (C++ 13.3.3.2p3):
1525  if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1526    return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1527  else if (ICS1.ConversionKind ==
1528             ImplicitConversionSequence::UserDefinedConversion) {
1529    // User-defined conversion sequence U1 is a better conversion
1530    // sequence than another user-defined conversion sequence U2 if
1531    // they contain the same user-defined conversion function or
1532    // constructor and if the second standard conversion sequence of
1533    // U1 is better than the second standard conversion sequence of
1534    // U2 (C++ 13.3.3.2p3).
1535    if (ICS1.UserDefined.ConversionFunction ==
1536          ICS2.UserDefined.ConversionFunction)
1537      return CompareStandardConversionSequences(ICS1.UserDefined.After,
1538                                                ICS2.UserDefined.After);
1539  }
1540
1541  return ImplicitConversionSequence::Indistinguishable;
1542}
1543
1544/// CompareStandardConversionSequences - Compare two standard
1545/// conversion sequences to determine whether one is better than the
1546/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1547ImplicitConversionSequence::CompareKind
1548Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1549                                         const StandardConversionSequence& SCS2)
1550{
1551  // Standard conversion sequence S1 is a better conversion sequence
1552  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1553
1554  //  -- S1 is a proper subsequence of S2 (comparing the conversion
1555  //     sequences in the canonical form defined by 13.3.3.1.1,
1556  //     excluding any Lvalue Transformation; the identity conversion
1557  //     sequence is considered to be a subsequence of any
1558  //     non-identity conversion sequence) or, if not that,
1559  if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1560    // Neither is a proper subsequence of the other. Do nothing.
1561    ;
1562  else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1563           (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1564           (SCS1.Second == ICK_Identity &&
1565            SCS1.Third == ICK_Identity))
1566    // SCS1 is a proper subsequence of SCS2.
1567    return ImplicitConversionSequence::Better;
1568  else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1569           (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1570           (SCS2.Second == ICK_Identity &&
1571            SCS2.Third == ICK_Identity))
1572    // SCS2 is a proper subsequence of SCS1.
1573    return ImplicitConversionSequence::Worse;
1574
1575  //  -- the rank of S1 is better than the rank of S2 (by the rules
1576  //     defined below), or, if not that,
1577  ImplicitConversionRank Rank1 = SCS1.getRank();
1578  ImplicitConversionRank Rank2 = SCS2.getRank();
1579  if (Rank1 < Rank2)
1580    return ImplicitConversionSequence::Better;
1581  else if (Rank2 < Rank1)
1582    return ImplicitConversionSequence::Worse;
1583
1584  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1585  // are indistinguishable unless one of the following rules
1586  // applies:
1587
1588  //   A conversion that is not a conversion of a pointer, or
1589  //   pointer to member, to bool is better than another conversion
1590  //   that is such a conversion.
1591  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1592    return SCS2.isPointerConversionToBool()
1593             ? ImplicitConversionSequence::Better
1594             : ImplicitConversionSequence::Worse;
1595
1596  // C++ [over.ics.rank]p4b2:
1597  //
1598  //   If class B is derived directly or indirectly from class A,
1599  //   conversion of B* to A* is better than conversion of B* to
1600  //   void*, and conversion of A* to void* is better than conversion
1601  //   of B* to void*.
1602  bool SCS1ConvertsToVoid
1603    = SCS1.isPointerConversionToVoidPointer(Context);
1604  bool SCS2ConvertsToVoid
1605    = SCS2.isPointerConversionToVoidPointer(Context);
1606  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1607    // Exactly one of the conversion sequences is a conversion to
1608    // a void pointer; it's the worse conversion.
1609    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1610                              : ImplicitConversionSequence::Worse;
1611  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1612    // Neither conversion sequence converts to a void pointer; compare
1613    // their derived-to-base conversions.
1614    if (ImplicitConversionSequence::CompareKind DerivedCK
1615          = CompareDerivedToBaseConversions(SCS1, SCS2))
1616      return DerivedCK;
1617  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1618    // Both conversion sequences are conversions to void
1619    // pointers. Compare the source types to determine if there's an
1620    // inheritance relationship in their sources.
1621    QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1622    QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1623
1624    // Adjust the types we're converting from via the array-to-pointer
1625    // conversion, if we need to.
1626    if (SCS1.First == ICK_Array_To_Pointer)
1627      FromType1 = Context.getArrayDecayedType(FromType1);
1628    if (SCS2.First == ICK_Array_To_Pointer)
1629      FromType2 = Context.getArrayDecayedType(FromType2);
1630
1631    QualType FromPointee1
1632      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1633    QualType FromPointee2
1634      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1635
1636    if (IsDerivedFrom(FromPointee2, FromPointee1))
1637      return ImplicitConversionSequence::Better;
1638    else if (IsDerivedFrom(FromPointee1, FromPointee2))
1639      return ImplicitConversionSequence::Worse;
1640
1641    // Objective-C++: If one interface is more specific than the
1642    // other, it is the better one.
1643    const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1644    const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1645    if (FromIface1 && FromIface1) {
1646      if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1647        return ImplicitConversionSequence::Better;
1648      else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1649        return ImplicitConversionSequence::Worse;
1650    }
1651  }
1652
1653  // Compare based on qualification conversions (C++ 13.3.3.2p3,
1654  // bullet 3).
1655  if (ImplicitConversionSequence::CompareKind QualCK
1656        = CompareQualificationConversions(SCS1, SCS2))
1657    return QualCK;
1658
1659  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1660    // C++0x [over.ics.rank]p3b4:
1661    //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1662    //      implicit object parameter of a non-static member function declared
1663    //      without a ref-qualifier, and S1 binds an rvalue reference to an
1664    //      rvalue and S2 binds an lvalue reference.
1665    // FIXME: We don't know if we're dealing with the implicit object parameter,
1666    // or if the member function in this case has a ref qualifier.
1667    // (Of course, we don't have ref qualifiers yet.)
1668    if (SCS1.RRefBinding != SCS2.RRefBinding)
1669      return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1670                              : ImplicitConversionSequence::Worse;
1671
1672    // C++ [over.ics.rank]p3b4:
1673    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
1674    //      which the references refer are the same type except for
1675    //      top-level cv-qualifiers, and the type to which the reference
1676    //      initialized by S2 refers is more cv-qualified than the type
1677    //      to which the reference initialized by S1 refers.
1678    QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1679    QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1680    T1 = Context.getCanonicalType(T1);
1681    T2 = Context.getCanonicalType(T2);
1682    if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1683      if (T2.isMoreQualifiedThan(T1))
1684        return ImplicitConversionSequence::Better;
1685      else if (T1.isMoreQualifiedThan(T2))
1686        return ImplicitConversionSequence::Worse;
1687    }
1688  }
1689
1690  return ImplicitConversionSequence::Indistinguishable;
1691}
1692
1693/// CompareQualificationConversions - Compares two standard conversion
1694/// sequences to determine whether they can be ranked based on their
1695/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1696ImplicitConversionSequence::CompareKind
1697Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1698                                      const StandardConversionSequence& SCS2) {
1699  // C++ 13.3.3.2p3:
1700  //  -- S1 and S2 differ only in their qualification conversion and
1701  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
1702  //     cv-qualification signature of type T1 is a proper subset of
1703  //     the cv-qualification signature of type T2, and S1 is not the
1704  //     deprecated string literal array-to-pointer conversion (4.2).
1705  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1706      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1707    return ImplicitConversionSequence::Indistinguishable;
1708
1709  // FIXME: the example in the standard doesn't use a qualification
1710  // conversion (!)
1711  QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1712  QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1713  T1 = Context.getCanonicalType(T1);
1714  T2 = Context.getCanonicalType(T2);
1715
1716  // If the types are the same, we won't learn anything by unwrapped
1717  // them.
1718  if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1719    return ImplicitConversionSequence::Indistinguishable;
1720
1721  ImplicitConversionSequence::CompareKind Result
1722    = ImplicitConversionSequence::Indistinguishable;
1723  while (UnwrapSimilarPointerTypes(T1, T2)) {
1724    // Within each iteration of the loop, we check the qualifiers to
1725    // determine if this still looks like a qualification
1726    // conversion. Then, if all is well, we unwrap one more level of
1727    // pointers or pointers-to-members and do it all again
1728    // until there are no more pointers or pointers-to-members left
1729    // to unwrap. This essentially mimics what
1730    // IsQualificationConversion does, but here we're checking for a
1731    // strict subset of qualifiers.
1732    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1733      // The qualifiers are the same, so this doesn't tell us anything
1734      // about how the sequences rank.
1735      ;
1736    else if (T2.isMoreQualifiedThan(T1)) {
1737      // T1 has fewer qualifiers, so it could be the better sequence.
1738      if (Result == ImplicitConversionSequence::Worse)
1739        // Neither has qualifiers that are a subset of the other's
1740        // qualifiers.
1741        return ImplicitConversionSequence::Indistinguishable;
1742
1743      Result = ImplicitConversionSequence::Better;
1744    } else if (T1.isMoreQualifiedThan(T2)) {
1745      // T2 has fewer qualifiers, so it could be the better sequence.
1746      if (Result == ImplicitConversionSequence::Better)
1747        // Neither has qualifiers that are a subset of the other's
1748        // qualifiers.
1749        return ImplicitConversionSequence::Indistinguishable;
1750
1751      Result = ImplicitConversionSequence::Worse;
1752    } else {
1753      // Qualifiers are disjoint.
1754      return ImplicitConversionSequence::Indistinguishable;
1755    }
1756
1757    // If the types after this point are equivalent, we're done.
1758    if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1759      break;
1760  }
1761
1762  // Check that the winning standard conversion sequence isn't using
1763  // the deprecated string literal array to pointer conversion.
1764  switch (Result) {
1765  case ImplicitConversionSequence::Better:
1766    if (SCS1.Deprecated)
1767      Result = ImplicitConversionSequence::Indistinguishable;
1768    break;
1769
1770  case ImplicitConversionSequence::Indistinguishable:
1771    break;
1772
1773  case ImplicitConversionSequence::Worse:
1774    if (SCS2.Deprecated)
1775      Result = ImplicitConversionSequence::Indistinguishable;
1776    break;
1777  }
1778
1779  return Result;
1780}
1781
1782/// CompareDerivedToBaseConversions - Compares two standard conversion
1783/// sequences to determine whether they can be ranked based on their
1784/// various kinds of derived-to-base conversions (C++
1785/// [over.ics.rank]p4b3).  As part of these checks, we also look at
1786/// conversions between Objective-C interface types.
1787ImplicitConversionSequence::CompareKind
1788Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1789                                      const StandardConversionSequence& SCS2) {
1790  QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1791  QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1792  QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1793  QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1794
1795  // Adjust the types we're converting from via the array-to-pointer
1796  // conversion, if we need to.
1797  if (SCS1.First == ICK_Array_To_Pointer)
1798    FromType1 = Context.getArrayDecayedType(FromType1);
1799  if (SCS2.First == ICK_Array_To_Pointer)
1800    FromType2 = Context.getArrayDecayedType(FromType2);
1801
1802  // Canonicalize all of the types.
1803  FromType1 = Context.getCanonicalType(FromType1);
1804  ToType1 = Context.getCanonicalType(ToType1);
1805  FromType2 = Context.getCanonicalType(FromType2);
1806  ToType2 = Context.getCanonicalType(ToType2);
1807
1808  // C++ [over.ics.rank]p4b3:
1809  //
1810  //   If class B is derived directly or indirectly from class A and
1811  //   class C is derived directly or indirectly from B,
1812  //
1813  // For Objective-C, we let A, B, and C also be Objective-C
1814  // interfaces.
1815
1816  // Compare based on pointer conversions.
1817  if (SCS1.Second == ICK_Pointer_Conversion &&
1818      SCS2.Second == ICK_Pointer_Conversion &&
1819      /*FIXME: Remove if Objective-C id conversions get their own rank*/
1820      FromType1->isPointerType() && FromType2->isPointerType() &&
1821      ToType1->isPointerType() && ToType2->isPointerType()) {
1822    QualType FromPointee1
1823      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1824    QualType ToPointee1
1825      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1826    QualType FromPointee2
1827      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1828    QualType ToPointee2
1829      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1830
1831    const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1832    const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1833    const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1834    const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1835
1836    //   -- conversion of C* to B* is better than conversion of C* to A*,
1837    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1838      if (IsDerivedFrom(ToPointee1, ToPointee2))
1839        return ImplicitConversionSequence::Better;
1840      else if (IsDerivedFrom(ToPointee2, ToPointee1))
1841        return ImplicitConversionSequence::Worse;
1842
1843      if (ToIface1 && ToIface2) {
1844        if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1845          return ImplicitConversionSequence::Better;
1846        else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1847          return ImplicitConversionSequence::Worse;
1848      }
1849    }
1850
1851    //   -- conversion of B* to A* is better than conversion of C* to A*,
1852    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1853      if (IsDerivedFrom(FromPointee2, FromPointee1))
1854        return ImplicitConversionSequence::Better;
1855      else if (IsDerivedFrom(FromPointee1, FromPointee2))
1856        return ImplicitConversionSequence::Worse;
1857
1858      if (FromIface1 && FromIface2) {
1859        if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1860          return ImplicitConversionSequence::Better;
1861        else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1862          return ImplicitConversionSequence::Worse;
1863      }
1864    }
1865  }
1866
1867  // Compare based on reference bindings.
1868  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1869      SCS1.Second == ICK_Derived_To_Base) {
1870    //   -- binding of an expression of type C to a reference of type
1871    //      B& is better than binding an expression of type C to a
1872    //      reference of type A&,
1873    if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1874        ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1875      if (IsDerivedFrom(ToType1, ToType2))
1876        return ImplicitConversionSequence::Better;
1877      else if (IsDerivedFrom(ToType2, ToType1))
1878        return ImplicitConversionSequence::Worse;
1879    }
1880
1881    //   -- binding of an expression of type B to a reference of type
1882    //      A& is better than binding an expression of type C to a
1883    //      reference of type A&,
1884    if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1885        ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1886      if (IsDerivedFrom(FromType2, FromType1))
1887        return ImplicitConversionSequence::Better;
1888      else if (IsDerivedFrom(FromType1, FromType2))
1889        return ImplicitConversionSequence::Worse;
1890    }
1891  }
1892
1893
1894  // FIXME: conversion of A::* to B::* is better than conversion of
1895  // A::* to C::*,
1896
1897  // FIXME: conversion of B::* to C::* is better than conversion of
1898  // A::* to C::*, and
1899
1900  if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1901      SCS1.Second == ICK_Derived_To_Base) {
1902    //   -- conversion of C to B is better than conversion of C to A,
1903    if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1904        ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1905      if (IsDerivedFrom(ToType1, ToType2))
1906        return ImplicitConversionSequence::Better;
1907      else if (IsDerivedFrom(ToType2, ToType1))
1908        return ImplicitConversionSequence::Worse;
1909    }
1910
1911    //   -- conversion of B to A is better than conversion of C to A.
1912    if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1913        ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1914      if (IsDerivedFrom(FromType2, FromType1))
1915        return ImplicitConversionSequence::Better;
1916      else if (IsDerivedFrom(FromType1, FromType2))
1917        return ImplicitConversionSequence::Worse;
1918    }
1919  }
1920
1921  return ImplicitConversionSequence::Indistinguishable;
1922}
1923
1924/// TryCopyInitialization - Try to copy-initialize a value of type
1925/// ToType from the expression From. Return the implicit conversion
1926/// sequence required to pass this argument, which may be a bad
1927/// conversion sequence (meaning that the argument cannot be passed to
1928/// a parameter of this type). If @p SuppressUserConversions, then we
1929/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1930/// then we treat @p From as an rvalue, even if it is an lvalue.
1931ImplicitConversionSequence
1932Sema::TryCopyInitialization(Expr *From, QualType ToType,
1933                            bool SuppressUserConversions, bool ForceRValue,
1934                            bool InOverloadResolution) {
1935  if (ToType->isReferenceType()) {
1936    ImplicitConversionSequence ICS;
1937    CheckReferenceInit(From, ToType,
1938                       SuppressUserConversions,
1939                       /*AllowExplicit=*/false,
1940                       ForceRValue,
1941                       &ICS);
1942    return ICS;
1943  } else {
1944    return TryImplicitConversion(From, ToType,
1945                                 SuppressUserConversions,
1946                                 /*AllowExplicit=*/false,
1947                                 ForceRValue,
1948                                 InOverloadResolution);
1949  }
1950}
1951
1952/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1953/// the expression @p From. Returns true (and emits a diagnostic) if there was
1954/// an error, returns false if the initialization succeeded. Elidable should
1955/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1956/// differently in C++0x for this case.
1957bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1958                                     const char* Flavor, bool Elidable) {
1959  if (!getLangOptions().CPlusPlus) {
1960    // In C, argument passing is the same as performing an assignment.
1961    QualType FromType = From->getType();
1962
1963    AssignConvertType ConvTy =
1964      CheckSingleAssignmentConstraints(ToType, From);
1965    if (ConvTy != Compatible &&
1966        CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1967      ConvTy = Compatible;
1968
1969    return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1970                                    FromType, From, Flavor);
1971  }
1972
1973  if (ToType->isReferenceType())
1974    return CheckReferenceInit(From, ToType,
1975                              /*SuppressUserConversions=*/false,
1976                              /*AllowExplicit=*/false,
1977                              /*ForceRValue=*/false);
1978
1979  if (!PerformImplicitConversion(From, ToType, Flavor,
1980                                 /*AllowExplicit=*/false, Elidable))
1981    return false;
1982
1983  return Diag(From->getSourceRange().getBegin(),
1984              diag::err_typecheck_convert_incompatible)
1985    << ToType << From->getType() << Flavor << From->getSourceRange();
1986}
1987
1988/// TryObjectArgumentInitialization - Try to initialize the object
1989/// parameter of the given member function (@c Method) from the
1990/// expression @p From.
1991ImplicitConversionSequence
1992Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1993  QualType ClassType = Context.getTypeDeclType(Method->getParent());
1994  unsigned MethodQuals = Method->getTypeQualifiers();
1995  QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1996
1997  // Set up the conversion sequence as a "bad" conversion, to allow us
1998  // to exit early.
1999  ImplicitConversionSequence ICS;
2000  ICS.Standard.setAsIdentityConversion();
2001  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2002
2003  // We need to have an object of class type.
2004  QualType FromType = From->getType();
2005  if (const PointerType *PT = FromType->getAs<PointerType>())
2006    FromType = PT->getPointeeType();
2007
2008  assert(FromType->isRecordType());
2009
2010  // The implicit object parmeter is has the type "reference to cv X",
2011  // where X is the class of which the function is a member
2012  // (C++ [over.match.funcs]p4). However, when finding an implicit
2013  // conversion sequence for the argument, we are not allowed to
2014  // create temporaries or perform user-defined conversions
2015  // (C++ [over.match.funcs]p5). We perform a simplified version of
2016  // reference binding here, that allows class rvalues to bind to
2017  // non-constant references.
2018
2019  // First check the qualifiers. We don't care about lvalue-vs-rvalue
2020  // with the implicit object parameter (C++ [over.match.funcs]p5).
2021  QualType FromTypeCanon = Context.getCanonicalType(FromType);
2022  if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2023      !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2024    return ICS;
2025
2026  // Check that we have either the same type or a derived type. It
2027  // affects the conversion rank.
2028  QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2029  if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2030    ICS.Standard.Second = ICK_Identity;
2031  else if (IsDerivedFrom(FromType, ClassType))
2032    ICS.Standard.Second = ICK_Derived_To_Base;
2033  else
2034    return ICS;
2035
2036  // Success. Mark this as a reference binding.
2037  ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2038  ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2039  ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2040  ICS.Standard.ReferenceBinding = true;
2041  ICS.Standard.DirectBinding = true;
2042  ICS.Standard.RRefBinding = false;
2043  return ICS;
2044}
2045
2046/// PerformObjectArgumentInitialization - Perform initialization of
2047/// the implicit object parameter for the given Method with the given
2048/// expression.
2049bool
2050Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
2051  QualType FromRecordType, DestType;
2052  QualType ImplicitParamRecordType  =
2053    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
2054
2055  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
2056    FromRecordType = PT->getPointeeType();
2057    DestType = Method->getThisType(Context);
2058  } else {
2059    FromRecordType = From->getType();
2060    DestType = ImplicitParamRecordType;
2061  }
2062
2063  ImplicitConversionSequence ICS
2064    = TryObjectArgumentInitialization(From, Method);
2065  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2066    return Diag(From->getSourceRange().getBegin(),
2067                diag::err_implicit_object_parameter_init)
2068       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2069
2070  if (ICS.Standard.Second == ICK_Derived_To_Base &&
2071      CheckDerivedToBaseConversion(FromRecordType,
2072                                   ImplicitParamRecordType,
2073                                   From->getSourceRange().getBegin(),
2074                                   From->getSourceRange()))
2075    return true;
2076
2077  ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
2078                    /*isLvalue=*/true);
2079  return false;
2080}
2081
2082/// TryContextuallyConvertToBool - Attempt to contextually convert the
2083/// expression From to bool (C++0x [conv]p3).
2084ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2085  return TryImplicitConversion(From, Context.BoolTy,
2086                               // FIXME: Are these flags correct?
2087                               /*SuppressUserConversions=*/false,
2088                               /*AllowExplicit=*/true,
2089                               /*ForceRValue=*/false,
2090                               /*InOverloadResolution=*/false);
2091}
2092
2093/// PerformContextuallyConvertToBool - Perform a contextual conversion
2094/// of the expression From to bool (C++0x [conv]p3).
2095bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2096  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2097  if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2098    return false;
2099
2100  return Diag(From->getSourceRange().getBegin(),
2101              diag::err_typecheck_bool_condition)
2102    << From->getType() << From->getSourceRange();
2103}
2104
2105/// AddOverloadCandidate - Adds the given function to the set of
2106/// candidate functions, using the given function call arguments.  If
2107/// @p SuppressUserConversions, then don't allow user-defined
2108/// conversions via constructors or conversion operators.
2109/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2110/// hacky way to implement the overloading rules for elidable copy
2111/// initialization in C++0x (C++0x 12.8p15).
2112void
2113Sema::AddOverloadCandidate(FunctionDecl *Function,
2114                           Expr **Args, unsigned NumArgs,
2115                           OverloadCandidateSet& CandidateSet,
2116                           bool SuppressUserConversions,
2117                           bool ForceRValue) {
2118  const FunctionProtoType* Proto
2119    = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
2120  assert(Proto && "Functions without a prototype cannot be overloaded");
2121  assert(!isa<CXXConversionDecl>(Function) &&
2122         "Use AddConversionCandidate for conversion functions");
2123  assert(!Function->getDescribedFunctionTemplate() &&
2124         "Use AddTemplateOverloadCandidate for function templates");
2125
2126  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2127    if (!isa<CXXConstructorDecl>(Method)) {
2128      // If we get here, it's because we're calling a member function
2129      // that is named without a member access expression (e.g.,
2130      // "this->f") that was either written explicitly or created
2131      // implicitly. This can happen with a qualified call to a member
2132      // function, e.g., X::f(). We use a NULL object as the implied
2133      // object argument (C++ [over.call.func]p3).
2134      AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2135                         SuppressUserConversions, ForceRValue);
2136      return;
2137    }
2138    // We treat a constructor like a non-member function, since its object
2139    // argument doesn't participate in overload resolution.
2140  }
2141
2142
2143  // Add this candidate
2144  CandidateSet.push_back(OverloadCandidate());
2145  OverloadCandidate& Candidate = CandidateSet.back();
2146  Candidate.Function = Function;
2147  Candidate.Viable = true;
2148  Candidate.IsSurrogate = false;
2149  Candidate.IgnoreObjectArgument = false;
2150
2151  unsigned NumArgsInProto = Proto->getNumArgs();
2152
2153  // (C++ 13.3.2p2): A candidate function having fewer than m
2154  // parameters is viable only if it has an ellipsis in its parameter
2155  // list (8.3.5).
2156  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2157    Candidate.Viable = false;
2158    return;
2159  }
2160
2161  // (C++ 13.3.2p2): A candidate function having more than m parameters
2162  // is viable only if the (m+1)st parameter has a default argument
2163  // (8.3.6). For the purposes of overload resolution, the
2164  // parameter list is truncated on the right, so that there are
2165  // exactly m parameters.
2166  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2167  if (NumArgs < MinRequiredArgs) {
2168    // Not enough arguments.
2169    Candidate.Viable = false;
2170    return;
2171  }
2172
2173  // Determine the implicit conversion sequences for each of the
2174  // arguments.
2175  Candidate.Conversions.resize(NumArgs);
2176  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2177    if (ArgIdx < NumArgsInProto) {
2178      // (C++ 13.3.2p3): for F to be a viable function, there shall
2179      // exist for each argument an implicit conversion sequence
2180      // (13.3.3.1) that converts that argument to the corresponding
2181      // parameter of F.
2182      QualType ParamType = Proto->getArgType(ArgIdx);
2183      Candidate.Conversions[ArgIdx]
2184        = TryCopyInitialization(Args[ArgIdx], ParamType,
2185                                SuppressUserConversions, ForceRValue,
2186                                /*InOverloadResolution=*/true);
2187      if (Candidate.Conversions[ArgIdx].ConversionKind
2188            == ImplicitConversionSequence::BadConversion) {
2189        Candidate.Viable = false;
2190        break;
2191      }
2192    } else {
2193      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2194      // argument for which there is no corresponding parameter is
2195      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2196      Candidate.Conversions[ArgIdx].ConversionKind
2197        = ImplicitConversionSequence::EllipsisConversion;
2198    }
2199  }
2200}
2201
2202/// \brief Add all of the function declarations in the given function set to
2203/// the overload canddiate set.
2204void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2205                                 Expr **Args, unsigned NumArgs,
2206                                 OverloadCandidateSet& CandidateSet,
2207                                 bool SuppressUserConversions) {
2208  for (FunctionSet::const_iterator F = Functions.begin(),
2209                                FEnd = Functions.end();
2210       F != FEnd; ++F) {
2211    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
2212      AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2213                           SuppressUserConversions);
2214    else
2215      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2216                                   /*FIXME: explicit args */false, 0, 0,
2217                                   Args, NumArgs, CandidateSet,
2218                                   SuppressUserConversions);
2219  }
2220}
2221
2222/// AddMethodCandidate - Adds the given C++ member function to the set
2223/// of candidate functions, using the given function call arguments
2224/// and the object argument (@c Object). For example, in a call
2225/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2226/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2227/// allow user-defined conversions via constructors or conversion
2228/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2229/// a slightly hacky way to implement the overloading rules for elidable copy
2230/// initialization in C++0x (C++0x 12.8p15).
2231void
2232Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2233                         Expr **Args, unsigned NumArgs,
2234                         OverloadCandidateSet& CandidateSet,
2235                         bool SuppressUserConversions, bool ForceRValue) {
2236  const FunctionProtoType* Proto
2237    = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
2238  assert(Proto && "Methods without a prototype cannot be overloaded");
2239  assert(!isa<CXXConversionDecl>(Method) &&
2240         "Use AddConversionCandidate for conversion functions");
2241  assert(!isa<CXXConstructorDecl>(Method) &&
2242         "Use AddOverloadCandidate for constructors");
2243
2244  // Add this candidate
2245  CandidateSet.push_back(OverloadCandidate());
2246  OverloadCandidate& Candidate = CandidateSet.back();
2247  Candidate.Function = Method;
2248  Candidate.IsSurrogate = false;
2249  Candidate.IgnoreObjectArgument = false;
2250
2251  unsigned NumArgsInProto = Proto->getNumArgs();
2252
2253  // (C++ 13.3.2p2): A candidate function having fewer than m
2254  // parameters is viable only if it has an ellipsis in its parameter
2255  // list (8.3.5).
2256  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2257    Candidate.Viable = false;
2258    return;
2259  }
2260
2261  // (C++ 13.3.2p2): A candidate function having more than m parameters
2262  // is viable only if the (m+1)st parameter has a default argument
2263  // (8.3.6). For the purposes of overload resolution, the
2264  // parameter list is truncated on the right, so that there are
2265  // exactly m parameters.
2266  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2267  if (NumArgs < MinRequiredArgs) {
2268    // Not enough arguments.
2269    Candidate.Viable = false;
2270    return;
2271  }
2272
2273  Candidate.Viable = true;
2274  Candidate.Conversions.resize(NumArgs + 1);
2275
2276  if (Method->isStatic() || !Object)
2277    // The implicit object argument is ignored.
2278    Candidate.IgnoreObjectArgument = true;
2279  else {
2280    // Determine the implicit conversion sequence for the object
2281    // parameter.
2282    Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2283    if (Candidate.Conversions[0].ConversionKind
2284          == ImplicitConversionSequence::BadConversion) {
2285      Candidate.Viable = false;
2286      return;
2287    }
2288  }
2289
2290  // Determine the implicit conversion sequences for each of the
2291  // arguments.
2292  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2293    if (ArgIdx < NumArgsInProto) {
2294      // (C++ 13.3.2p3): for F to be a viable function, there shall
2295      // exist for each argument an implicit conversion sequence
2296      // (13.3.3.1) that converts that argument to the corresponding
2297      // parameter of F.
2298      QualType ParamType = Proto->getArgType(ArgIdx);
2299      Candidate.Conversions[ArgIdx + 1]
2300        = TryCopyInitialization(Args[ArgIdx], ParamType,
2301                                SuppressUserConversions, ForceRValue,
2302                                /*InOverloadResolution=*/true);
2303      if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2304            == ImplicitConversionSequence::BadConversion) {
2305        Candidate.Viable = false;
2306        break;
2307      }
2308    } else {
2309      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2310      // argument for which there is no corresponding parameter is
2311      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2312      Candidate.Conversions[ArgIdx + 1].ConversionKind
2313        = ImplicitConversionSequence::EllipsisConversion;
2314    }
2315  }
2316}
2317
2318/// \brief Add a C++ member function template as a candidate to the candidate
2319/// set, using template argument deduction to produce an appropriate member
2320/// function template specialization.
2321void
2322Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2323                                 bool HasExplicitTemplateArgs,
2324                                 const TemplateArgument *ExplicitTemplateArgs,
2325                                 unsigned NumExplicitTemplateArgs,
2326                                 Expr *Object, Expr **Args, unsigned NumArgs,
2327                                 OverloadCandidateSet& CandidateSet,
2328                                 bool SuppressUserConversions,
2329                                 bool ForceRValue) {
2330  // C++ [over.match.funcs]p7:
2331  //   In each case where a candidate is a function template, candidate
2332  //   function template specializations are generated using template argument
2333  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
2334  //   candidate functions in the usual way.113) A given name can refer to one
2335  //   or more function templates and also to a set of overloaded non-template
2336  //   functions. In such a case, the candidate functions generated from each
2337  //   function template are combined with the set of non-template candidate
2338  //   functions.
2339  TemplateDeductionInfo Info(Context);
2340  FunctionDecl *Specialization = 0;
2341  if (TemplateDeductionResult Result
2342      = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2343                                ExplicitTemplateArgs, NumExplicitTemplateArgs,
2344                                Args, NumArgs, Specialization, Info)) {
2345        // FIXME: Record what happened with template argument deduction, so
2346        // that we can give the user a beautiful diagnostic.
2347        (void)Result;
2348        return;
2349      }
2350
2351  // Add the function template specialization produced by template argument
2352  // deduction as a candidate.
2353  assert(Specialization && "Missing member function template specialization?");
2354  assert(isa<CXXMethodDecl>(Specialization) &&
2355         "Specialization is not a member function?");
2356  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
2357                     CandidateSet, SuppressUserConversions, ForceRValue);
2358}
2359
2360/// \brief Add a C++ function template specialization as a candidate
2361/// in the candidate set, using template argument deduction to produce
2362/// an appropriate function template specialization.
2363void
2364Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2365                                   bool HasExplicitTemplateArgs,
2366                                 const TemplateArgument *ExplicitTemplateArgs,
2367                                   unsigned NumExplicitTemplateArgs,
2368                                   Expr **Args, unsigned NumArgs,
2369                                   OverloadCandidateSet& CandidateSet,
2370                                   bool SuppressUserConversions,
2371                                   bool ForceRValue) {
2372  // C++ [over.match.funcs]p7:
2373  //   In each case where a candidate is a function template, candidate
2374  //   function template specializations are generated using template argument
2375  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
2376  //   candidate functions in the usual way.113) A given name can refer to one
2377  //   or more function templates and also to a set of overloaded non-template
2378  //   functions. In such a case, the candidate functions generated from each
2379  //   function template are combined with the set of non-template candidate
2380  //   functions.
2381  TemplateDeductionInfo Info(Context);
2382  FunctionDecl *Specialization = 0;
2383  if (TemplateDeductionResult Result
2384        = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2385                                  ExplicitTemplateArgs, NumExplicitTemplateArgs,
2386                                  Args, NumArgs, Specialization, Info)) {
2387    // FIXME: Record what happened with template argument deduction, so
2388    // that we can give the user a beautiful diagnostic.
2389    (void)Result;
2390    return;
2391  }
2392
2393  // Add the function template specialization produced by template argument
2394  // deduction as a candidate.
2395  assert(Specialization && "Missing function template specialization?");
2396  AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2397                       SuppressUserConversions, ForceRValue);
2398}
2399
2400/// AddConversionCandidate - Add a C++ conversion function as a
2401/// candidate in the candidate set (C++ [over.match.conv],
2402/// C++ [over.match.copy]). From is the expression we're converting from,
2403/// and ToType is the type that we're eventually trying to convert to
2404/// (which may or may not be the same type as the type that the
2405/// conversion function produces).
2406void
2407Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2408                             Expr *From, QualType ToType,
2409                             OverloadCandidateSet& CandidateSet) {
2410  assert(!Conversion->getDescribedFunctionTemplate() &&
2411         "Conversion function templates use AddTemplateConversionCandidate");
2412
2413  // Add this candidate
2414  CandidateSet.push_back(OverloadCandidate());
2415  OverloadCandidate& Candidate = CandidateSet.back();
2416  Candidate.Function = Conversion;
2417  Candidate.IsSurrogate = false;
2418  Candidate.IgnoreObjectArgument = false;
2419  Candidate.FinalConversion.setAsIdentityConversion();
2420  Candidate.FinalConversion.FromTypePtr
2421    = Conversion->getConversionType().getAsOpaquePtr();
2422  Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2423
2424  // Determine the implicit conversion sequence for the implicit
2425  // object parameter.
2426  Candidate.Viable = true;
2427  Candidate.Conversions.resize(1);
2428  Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
2429  // Conversion functions to a different type in the base class is visible in
2430  // the derived class.  So, a derived to base conversion should not participate
2431  // in overload resolution.
2432  if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2433    Candidate.Conversions[0].Standard.Second = ICK_Identity;
2434  if (Candidate.Conversions[0].ConversionKind
2435      == ImplicitConversionSequence::BadConversion) {
2436    Candidate.Viable = false;
2437    return;
2438  }
2439
2440  // To determine what the conversion from the result of calling the
2441  // conversion function to the type we're eventually trying to
2442  // convert to (ToType), we need to synthesize a call to the
2443  // conversion function and attempt copy initialization from it. This
2444  // makes sure that we get the right semantics with respect to
2445  // lvalues/rvalues and the type. Fortunately, we can allocate this
2446  // call on the stack and we don't need its arguments to be
2447  // well-formed.
2448  DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2449                            SourceLocation());
2450  ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
2451                                CastExpr::CK_Unknown,
2452                                &ConversionRef, false);
2453
2454  // Note that it is safe to allocate CallExpr on the stack here because
2455  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2456  // allocator).
2457  CallExpr Call(Context, &ConversionFn, 0, 0,
2458                Conversion->getConversionType().getNonReferenceType(),
2459                SourceLocation());
2460  ImplicitConversionSequence ICS =
2461    TryCopyInitialization(&Call, ToType,
2462                          /*SuppressUserConversions=*/true,
2463                          /*ForceRValue=*/false,
2464                          /*InOverloadResolution=*/false);
2465
2466  switch (ICS.ConversionKind) {
2467  case ImplicitConversionSequence::StandardConversion:
2468    Candidate.FinalConversion = ICS.Standard;
2469    break;
2470
2471  case ImplicitConversionSequence::BadConversion:
2472    Candidate.Viable = false;
2473    break;
2474
2475  default:
2476    assert(false &&
2477           "Can only end up with a standard conversion sequence or failure");
2478  }
2479}
2480
2481/// \brief Adds a conversion function template specialization
2482/// candidate to the overload set, using template argument deduction
2483/// to deduce the template arguments of the conversion function
2484/// template from the type that we are converting to (C++
2485/// [temp.deduct.conv]).
2486void
2487Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2488                                     Expr *From, QualType ToType,
2489                                     OverloadCandidateSet &CandidateSet) {
2490  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2491         "Only conversion function templates permitted here");
2492
2493  TemplateDeductionInfo Info(Context);
2494  CXXConversionDecl *Specialization = 0;
2495  if (TemplateDeductionResult Result
2496        = DeduceTemplateArguments(FunctionTemplate, ToType,
2497                                  Specialization, Info)) {
2498    // FIXME: Record what happened with template argument deduction, so
2499    // that we can give the user a beautiful diagnostic.
2500    (void)Result;
2501    return;
2502  }
2503
2504  // Add the conversion function template specialization produced by
2505  // template argument deduction as a candidate.
2506  assert(Specialization && "Missing function template specialization?");
2507  AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2508}
2509
2510/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2511/// converts the given @c Object to a function pointer via the
2512/// conversion function @c Conversion, and then attempts to call it
2513/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2514/// the type of function that we'll eventually be calling.
2515void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2516                                 const FunctionProtoType *Proto,
2517                                 Expr *Object, Expr **Args, unsigned NumArgs,
2518                                 OverloadCandidateSet& CandidateSet) {
2519  CandidateSet.push_back(OverloadCandidate());
2520  OverloadCandidate& Candidate = CandidateSet.back();
2521  Candidate.Function = 0;
2522  Candidate.Surrogate = Conversion;
2523  Candidate.Viable = true;
2524  Candidate.IsSurrogate = true;
2525  Candidate.IgnoreObjectArgument = false;
2526  Candidate.Conversions.resize(NumArgs + 1);
2527
2528  // Determine the implicit conversion sequence for the implicit
2529  // object parameter.
2530  ImplicitConversionSequence ObjectInit
2531    = TryObjectArgumentInitialization(Object, Conversion);
2532  if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2533    Candidate.Viable = false;
2534    return;
2535  }
2536
2537  // The first conversion is actually a user-defined conversion whose
2538  // first conversion is ObjectInit's standard conversion (which is
2539  // effectively a reference binding). Record it as such.
2540  Candidate.Conversions[0].ConversionKind
2541    = ImplicitConversionSequence::UserDefinedConversion;
2542  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2543  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2544  Candidate.Conversions[0].UserDefined.After
2545    = Candidate.Conversions[0].UserDefined.Before;
2546  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2547
2548  // Find the
2549  unsigned NumArgsInProto = Proto->getNumArgs();
2550
2551  // (C++ 13.3.2p2): A candidate function having fewer than m
2552  // parameters is viable only if it has an ellipsis in its parameter
2553  // list (8.3.5).
2554  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2555    Candidate.Viable = false;
2556    return;
2557  }
2558
2559  // Function types don't have any default arguments, so just check if
2560  // we have enough arguments.
2561  if (NumArgs < NumArgsInProto) {
2562    // Not enough arguments.
2563    Candidate.Viable = false;
2564    return;
2565  }
2566
2567  // Determine the implicit conversion sequences for each of the
2568  // arguments.
2569  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2570    if (ArgIdx < NumArgsInProto) {
2571      // (C++ 13.3.2p3): for F to be a viable function, there shall
2572      // exist for each argument an implicit conversion sequence
2573      // (13.3.3.1) that converts that argument to the corresponding
2574      // parameter of F.
2575      QualType ParamType = Proto->getArgType(ArgIdx);
2576      Candidate.Conversions[ArgIdx + 1]
2577        = TryCopyInitialization(Args[ArgIdx], ParamType,
2578                                /*SuppressUserConversions=*/false,
2579                                /*ForceRValue=*/false,
2580                                /*InOverloadResolution=*/false);
2581      if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2582            == ImplicitConversionSequence::BadConversion) {
2583        Candidate.Viable = false;
2584        break;
2585      }
2586    } else {
2587      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2588      // argument for which there is no corresponding parameter is
2589      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2590      Candidate.Conversions[ArgIdx + 1].ConversionKind
2591        = ImplicitConversionSequence::EllipsisConversion;
2592    }
2593  }
2594}
2595
2596// FIXME: This will eventually be removed, once we've migrated all of the
2597// operator overloading logic over to the scheme used by binary operators, which
2598// works for template instantiation.
2599void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2600                                 SourceLocation OpLoc,
2601                                 Expr **Args, unsigned NumArgs,
2602                                 OverloadCandidateSet& CandidateSet,
2603                                 SourceRange OpRange) {
2604
2605  FunctionSet Functions;
2606
2607  QualType T1 = Args[0]->getType();
2608  QualType T2;
2609  if (NumArgs > 1)
2610    T2 = Args[1]->getType();
2611
2612  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2613  if (S)
2614    LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
2615  ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2616  AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2617  AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2618  AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2619}
2620
2621/// \brief Add overload candidates for overloaded operators that are
2622/// member functions.
2623///
2624/// Add the overloaded operator candidates that are member functions
2625/// for the operator Op that was used in an operator expression such
2626/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2627/// CandidateSet will store the added overload candidates. (C++
2628/// [over.match.oper]).
2629void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2630                                       SourceLocation OpLoc,
2631                                       Expr **Args, unsigned NumArgs,
2632                                       OverloadCandidateSet& CandidateSet,
2633                                       SourceRange OpRange) {
2634  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2635
2636  // C++ [over.match.oper]p3:
2637  //   For a unary operator @ with an operand of a type whose
2638  //   cv-unqualified version is T1, and for a binary operator @ with
2639  //   a left operand of a type whose cv-unqualified version is T1 and
2640  //   a right operand of a type whose cv-unqualified version is T2,
2641  //   three sets of candidate functions, designated member
2642  //   candidates, non-member candidates and built-in candidates, are
2643  //   constructed as follows:
2644  QualType T1 = Args[0]->getType();
2645  QualType T2;
2646  if (NumArgs > 1)
2647    T2 = Args[1]->getType();
2648
2649  //     -- If T1 is a class type, the set of member candidates is the
2650  //        result of the qualified lookup of T1::operator@
2651  //        (13.3.1.1.1); otherwise, the set of member candidates is
2652  //        empty.
2653  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
2654    // Complete the type if it can be completed. Otherwise, we're done.
2655    if (RequireCompleteType(OpLoc, T1, PartialDiagnostic(0)))
2656      return;
2657
2658    LookupResult Operators = LookupQualifiedName(T1Rec->getDecl(), OpName,
2659                                                 LookupOrdinaryName, false);
2660    for (LookupResult::iterator Oper = Operators.begin(),
2661                             OperEnd = Operators.end();
2662         Oper != OperEnd;
2663         ++Oper)
2664      AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2665                         Args+1, NumArgs - 1, CandidateSet,
2666                         /*SuppressUserConversions=*/false);
2667  }
2668}
2669
2670/// AddBuiltinCandidate - Add a candidate for a built-in
2671/// operator. ResultTy and ParamTys are the result and parameter types
2672/// of the built-in candidate, respectively. Args and NumArgs are the
2673/// arguments being passed to the candidate. IsAssignmentOperator
2674/// should be true when this built-in candidate is an assignment
2675/// operator. NumContextualBoolArguments is the number of arguments
2676/// (at the beginning of the argument list) that will be contextually
2677/// converted to bool.
2678void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2679                               Expr **Args, unsigned NumArgs,
2680                               OverloadCandidateSet& CandidateSet,
2681                               bool IsAssignmentOperator,
2682                               unsigned NumContextualBoolArguments) {
2683  // Add this candidate
2684  CandidateSet.push_back(OverloadCandidate());
2685  OverloadCandidate& Candidate = CandidateSet.back();
2686  Candidate.Function = 0;
2687  Candidate.IsSurrogate = false;
2688  Candidate.IgnoreObjectArgument = false;
2689  Candidate.BuiltinTypes.ResultTy = ResultTy;
2690  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2691    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2692
2693  // Determine the implicit conversion sequences for each of the
2694  // arguments.
2695  Candidate.Viable = true;
2696  Candidate.Conversions.resize(NumArgs);
2697  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2698    // C++ [over.match.oper]p4:
2699    //   For the built-in assignment operators, conversions of the
2700    //   left operand are restricted as follows:
2701    //     -- no temporaries are introduced to hold the left operand, and
2702    //     -- no user-defined conversions are applied to the left
2703    //        operand to achieve a type match with the left-most
2704    //        parameter of a built-in candidate.
2705    //
2706    // We block these conversions by turning off user-defined
2707    // conversions, since that is the only way that initialization of
2708    // a reference to a non-class type can occur from something that
2709    // is not of the same type.
2710    if (ArgIdx < NumContextualBoolArguments) {
2711      assert(ParamTys[ArgIdx] == Context.BoolTy &&
2712             "Contextual conversion to bool requires bool type");
2713      Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2714    } else {
2715      Candidate.Conversions[ArgIdx]
2716        = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2717                                ArgIdx == 0 && IsAssignmentOperator,
2718                                /*ForceRValue=*/false,
2719                                /*InOverloadResolution=*/false);
2720    }
2721    if (Candidate.Conversions[ArgIdx].ConversionKind
2722        == ImplicitConversionSequence::BadConversion) {
2723      Candidate.Viable = false;
2724      break;
2725    }
2726  }
2727}
2728
2729/// BuiltinCandidateTypeSet - A set of types that will be used for the
2730/// candidate operator functions for built-in operators (C++
2731/// [over.built]). The types are separated into pointer types and
2732/// enumeration types.
2733class BuiltinCandidateTypeSet  {
2734  /// TypeSet - A set of types.
2735  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
2736
2737  /// PointerTypes - The set of pointer types that will be used in the
2738  /// built-in candidates.
2739  TypeSet PointerTypes;
2740
2741  /// MemberPointerTypes - The set of member pointer types that will be
2742  /// used in the built-in candidates.
2743  TypeSet MemberPointerTypes;
2744
2745  /// EnumerationTypes - The set of enumeration types that will be
2746  /// used in the built-in candidates.
2747  TypeSet EnumerationTypes;
2748
2749  /// Sema - The semantic analysis instance where we are building the
2750  /// candidate type set.
2751  Sema &SemaRef;
2752
2753  /// Context - The AST context in which we will build the type sets.
2754  ASTContext &Context;
2755
2756  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2757  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
2758
2759public:
2760  /// iterator - Iterates through the types that are part of the set.
2761  typedef TypeSet::iterator iterator;
2762
2763  BuiltinCandidateTypeSet(Sema &SemaRef)
2764    : SemaRef(SemaRef), Context(SemaRef.Context) { }
2765
2766  void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2767                             bool AllowExplicitConversions);
2768
2769  /// pointer_begin - First pointer type found;
2770  iterator pointer_begin() { return PointerTypes.begin(); }
2771
2772  /// pointer_end - Past the last pointer type found;
2773  iterator pointer_end() { return PointerTypes.end(); }
2774
2775  /// member_pointer_begin - First member pointer type found;
2776  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2777
2778  /// member_pointer_end - Past the last member pointer type found;
2779  iterator member_pointer_end() { return MemberPointerTypes.end(); }
2780
2781  /// enumeration_begin - First enumeration type found;
2782  iterator enumeration_begin() { return EnumerationTypes.begin(); }
2783
2784  /// enumeration_end - Past the last enumeration type found;
2785  iterator enumeration_end() { return EnumerationTypes.end(); }
2786};
2787
2788/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2789/// the set of pointer types along with any more-qualified variants of
2790/// that type. For example, if @p Ty is "int const *", this routine
2791/// will add "int const *", "int const volatile *", "int const
2792/// restrict *", and "int const volatile restrict *" to the set of
2793/// pointer types. Returns true if the add of @p Ty itself succeeded,
2794/// false otherwise.
2795bool
2796BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
2797  // Insert this type.
2798  if (!PointerTypes.insert(Ty))
2799    return false;
2800
2801  if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
2802    QualType PointeeTy = PointerTy->getPointeeType();
2803    // FIXME: Optimize this so that we don't keep trying to add the same types.
2804
2805    // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2806    // pointer conversions that don't cast away constness?
2807    if (!PointeeTy.isConstQualified())
2808      AddPointerWithMoreQualifiedTypeVariants
2809        (Context.getPointerType(PointeeTy.withConst()));
2810    if (!PointeeTy.isVolatileQualified())
2811      AddPointerWithMoreQualifiedTypeVariants
2812        (Context.getPointerType(PointeeTy.withVolatile()));
2813    if (!PointeeTy.isRestrictQualified())
2814      AddPointerWithMoreQualifiedTypeVariants
2815        (Context.getPointerType(PointeeTy.withRestrict()));
2816  }
2817
2818  return true;
2819}
2820
2821/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2822/// to the set of pointer types along with any more-qualified variants of
2823/// that type. For example, if @p Ty is "int const *", this routine
2824/// will add "int const *", "int const volatile *", "int const
2825/// restrict *", and "int const volatile restrict *" to the set of
2826/// pointer types. Returns true if the add of @p Ty itself succeeded,
2827/// false otherwise.
2828bool
2829BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2830    QualType Ty) {
2831  // Insert this type.
2832  if (!MemberPointerTypes.insert(Ty))
2833    return false;
2834
2835  if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
2836    QualType PointeeTy = PointerTy->getPointeeType();
2837    const Type *ClassTy = PointerTy->getClass();
2838    // FIXME: Optimize this so that we don't keep trying to add the same types.
2839
2840    if (!PointeeTy.isConstQualified())
2841      AddMemberPointerWithMoreQualifiedTypeVariants
2842        (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2843    if (!PointeeTy.isVolatileQualified())
2844      AddMemberPointerWithMoreQualifiedTypeVariants
2845        (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2846    if (!PointeeTy.isRestrictQualified())
2847      AddMemberPointerWithMoreQualifiedTypeVariants
2848        (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2849  }
2850
2851  return true;
2852}
2853
2854/// AddTypesConvertedFrom - Add each of the types to which the type @p
2855/// Ty can be implicit converted to the given set of @p Types. We're
2856/// primarily interested in pointer types and enumeration types. We also
2857/// take member pointer types, for the conditional operator.
2858/// AllowUserConversions is true if we should look at the conversion
2859/// functions of a class type, and AllowExplicitConversions if we
2860/// should also include the explicit conversion functions of a class
2861/// type.
2862void
2863BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2864                                               bool AllowUserConversions,
2865                                               bool AllowExplicitConversions) {
2866  // Only deal with canonical types.
2867  Ty = Context.getCanonicalType(Ty);
2868
2869  // Look through reference types; they aren't part of the type of an
2870  // expression for the purposes of conversions.
2871  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
2872    Ty = RefTy->getPointeeType();
2873
2874  // We don't care about qualifiers on the type.
2875  Ty = Ty.getUnqualifiedType();
2876
2877  if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
2878    QualType PointeeTy = PointerTy->getPointeeType();
2879
2880    // Insert our type, and its more-qualified variants, into the set
2881    // of types.
2882    if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
2883      return;
2884
2885    // Add 'cv void*' to our set of types.
2886    if (!Ty->isVoidType()) {
2887      QualType QualVoid
2888        = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2889      AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2890    }
2891
2892    // If this is a pointer to a class type, add pointers to its bases
2893    // (with the same level of cv-qualification as the original
2894    // derived class, of course).
2895    if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
2896      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2897      for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2898           Base != ClassDecl->bases_end(); ++Base) {
2899        QualType BaseTy = Context.getCanonicalType(Base->getType());
2900        BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2901
2902        // Add the pointer type, recursively, so that we get all of
2903        // the indirect base classes, too.
2904        AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
2905      }
2906    }
2907  } else if (Ty->isMemberPointerType()) {
2908    // Member pointers are far easier, since the pointee can't be converted.
2909    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2910      return;
2911  } else if (Ty->isEnumeralType()) {
2912    EnumerationTypes.insert(Ty);
2913  } else if (AllowUserConversions) {
2914    if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
2915      if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
2916        // No conversion functions in incomplete types.
2917        return;
2918      }
2919
2920      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2921      // FIXME: Visit conversion functions in the base classes, too.
2922      OverloadedFunctionDecl *Conversions
2923        = ClassDecl->getConversionFunctions();
2924      for (OverloadedFunctionDecl::function_iterator Func
2925             = Conversions->function_begin();
2926           Func != Conversions->function_end(); ++Func) {
2927        CXXConversionDecl *Conv;
2928        FunctionTemplateDecl *ConvTemplate;
2929        GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2930
2931        // Skip conversion function templates; they don't tell us anything
2932        // about which builtin types we can convert to.
2933        if (ConvTemplate)
2934          continue;
2935
2936        if (AllowExplicitConversions || !Conv->isExplicit())
2937          AddTypesConvertedFrom(Conv->getConversionType(), false, false);
2938      }
2939    }
2940  }
2941}
2942
2943/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2944/// the volatile- and non-volatile-qualified assignment operators for the
2945/// given type to the candidate set.
2946static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2947                                                   QualType T,
2948                                                   Expr **Args,
2949                                                   unsigned NumArgs,
2950                                    OverloadCandidateSet &CandidateSet) {
2951  QualType ParamTypes[2];
2952
2953  // T& operator=(T&, T)
2954  ParamTypes[0] = S.Context.getLValueReferenceType(T);
2955  ParamTypes[1] = T;
2956  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2957                        /*IsAssignmentOperator=*/true);
2958
2959  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
2960    // volatile T& operator=(volatile T&, T)
2961    ParamTypes[0] = S.Context.getLValueReferenceType(T.withVolatile());
2962    ParamTypes[1] = T;
2963    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2964                          /*IsAssignmentOperator=*/true);
2965  }
2966}
2967
2968/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2969/// operator overloads to the candidate set (C++ [over.built]), based
2970/// on the operator @p Op and the arguments given. For example, if the
2971/// operator is a binary '+', this routine might add "int
2972/// operator+(int, int)" to cover integer addition.
2973void
2974Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2975                                   Expr **Args, unsigned NumArgs,
2976                                   OverloadCandidateSet& CandidateSet) {
2977  // The set of "promoted arithmetic types", which are the arithmetic
2978  // types are that preserved by promotion (C++ [over.built]p2). Note
2979  // that the first few of these types are the promoted integral
2980  // types; these types need to be first.
2981  // FIXME: What about complex?
2982  const unsigned FirstIntegralType = 0;
2983  const unsigned LastIntegralType = 13;
2984  const unsigned FirstPromotedIntegralType = 7,
2985                 LastPromotedIntegralType = 13;
2986  const unsigned FirstPromotedArithmeticType = 7,
2987                 LastPromotedArithmeticType = 16;
2988  const unsigned NumArithmeticTypes = 16;
2989  QualType ArithmeticTypes[NumArithmeticTypes] = {
2990    Context.BoolTy, Context.CharTy, Context.WCharTy,
2991// FIXME:   Context.Char16Ty, Context.Char32Ty,
2992    Context.SignedCharTy, Context.ShortTy,
2993    Context.UnsignedCharTy, Context.UnsignedShortTy,
2994    Context.IntTy, Context.LongTy, Context.LongLongTy,
2995    Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2996    Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2997  };
2998
2999  // Find all of the types that the arguments can convert to, but only
3000  // if the operator we're looking at has built-in operator candidates
3001  // that make use of these types.
3002  BuiltinCandidateTypeSet CandidateTypes(*this);
3003  if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3004      Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
3005      Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
3006      Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
3007      Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
3008      (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
3009    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3010      CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3011                                           true,
3012                                           (Op == OO_Exclaim ||
3013                                            Op == OO_AmpAmp ||
3014                                            Op == OO_PipePipe));
3015  }
3016
3017  bool isComparison = false;
3018  switch (Op) {
3019  case OO_None:
3020  case NUM_OVERLOADED_OPERATORS:
3021    assert(false && "Expected an overloaded operator");
3022    break;
3023
3024  case OO_Star: // '*' is either unary or binary
3025    if (NumArgs == 1)
3026      goto UnaryStar;
3027    else
3028      goto BinaryStar;
3029    break;
3030
3031  case OO_Plus: // '+' is either unary or binary
3032    if (NumArgs == 1)
3033      goto UnaryPlus;
3034    else
3035      goto BinaryPlus;
3036    break;
3037
3038  case OO_Minus: // '-' is either unary or binary
3039    if (NumArgs == 1)
3040      goto UnaryMinus;
3041    else
3042      goto BinaryMinus;
3043    break;
3044
3045  case OO_Amp: // '&' is either unary or binary
3046    if (NumArgs == 1)
3047      goto UnaryAmp;
3048    else
3049      goto BinaryAmp;
3050
3051  case OO_PlusPlus:
3052  case OO_MinusMinus:
3053    // C++ [over.built]p3:
3054    //
3055    //   For every pair (T, VQ), where T is an arithmetic type, and VQ
3056    //   is either volatile or empty, there exist candidate operator
3057    //   functions of the form
3058    //
3059    //       VQ T&      operator++(VQ T&);
3060    //       T          operator++(VQ T&, int);
3061    //
3062    // C++ [over.built]p4:
3063    //
3064    //   For every pair (T, VQ), where T is an arithmetic type other
3065    //   than bool, and VQ is either volatile or empty, there exist
3066    //   candidate operator functions of the form
3067    //
3068    //       VQ T&      operator--(VQ T&);
3069    //       T          operator--(VQ T&, int);
3070    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
3071         Arith < NumArithmeticTypes; ++Arith) {
3072      QualType ArithTy = ArithmeticTypes[Arith];
3073      QualType ParamTypes[2]
3074        = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
3075
3076      // Non-volatile version.
3077      if (NumArgs == 1)
3078        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3079      else
3080        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3081
3082      // Volatile version
3083      ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
3084      if (NumArgs == 1)
3085        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3086      else
3087        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3088    }
3089
3090    // C++ [over.built]p5:
3091    //
3092    //   For every pair (T, VQ), where T is a cv-qualified or
3093    //   cv-unqualified object type, and VQ is either volatile or
3094    //   empty, there exist candidate operator functions of the form
3095    //
3096    //       T*VQ&      operator++(T*VQ&);
3097    //       T*VQ&      operator--(T*VQ&);
3098    //       T*         operator++(T*VQ&, int);
3099    //       T*         operator--(T*VQ&, int);
3100    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3101         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3102      // Skip pointer types that aren't pointers to object types.
3103      if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
3104        continue;
3105
3106      QualType ParamTypes[2] = {
3107        Context.getLValueReferenceType(*Ptr), Context.IntTy
3108      };
3109
3110      // Without volatile
3111      if (NumArgs == 1)
3112        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3113      else
3114        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3115
3116      if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3117        // With volatile
3118        ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
3119        if (NumArgs == 1)
3120          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3121        else
3122          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3123      }
3124    }
3125    break;
3126
3127  UnaryStar:
3128    // C++ [over.built]p6:
3129    //   For every cv-qualified or cv-unqualified object type T, there
3130    //   exist candidate operator functions of the form
3131    //
3132    //       T&         operator*(T*);
3133    //
3134    // C++ [over.built]p7:
3135    //   For every function type T, there exist candidate operator
3136    //   functions of the form
3137    //       T&         operator*(T*);
3138    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3139         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3140      QualType ParamTy = *Ptr;
3141      QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
3142      AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
3143                          &ParamTy, Args, 1, CandidateSet);
3144    }
3145    break;
3146
3147  UnaryPlus:
3148    // C++ [over.built]p8:
3149    //   For every type T, there exist candidate operator functions of
3150    //   the form
3151    //
3152    //       T*         operator+(T*);
3153    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3154         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3155      QualType ParamTy = *Ptr;
3156      AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3157    }
3158
3159    // Fall through
3160
3161  UnaryMinus:
3162    // C++ [over.built]p9:
3163    //  For every promoted arithmetic type T, there exist candidate
3164    //  operator functions of the form
3165    //
3166    //       T         operator+(T);
3167    //       T         operator-(T);
3168    for (unsigned Arith = FirstPromotedArithmeticType;
3169         Arith < LastPromotedArithmeticType; ++Arith) {
3170      QualType ArithTy = ArithmeticTypes[Arith];
3171      AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3172    }
3173    break;
3174
3175  case OO_Tilde:
3176    // C++ [over.built]p10:
3177    //   For every promoted integral type T, there exist candidate
3178    //   operator functions of the form
3179    //
3180    //        T         operator~(T);
3181    for (unsigned Int = FirstPromotedIntegralType;
3182         Int < LastPromotedIntegralType; ++Int) {
3183      QualType IntTy = ArithmeticTypes[Int];
3184      AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3185    }
3186    break;
3187
3188  case OO_New:
3189  case OO_Delete:
3190  case OO_Array_New:
3191  case OO_Array_Delete:
3192  case OO_Call:
3193    assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
3194    break;
3195
3196  case OO_Comma:
3197  UnaryAmp:
3198  case OO_Arrow:
3199    // C++ [over.match.oper]p3:
3200    //   -- For the operator ',', the unary operator '&', or the
3201    //      operator '->', the built-in candidates set is empty.
3202    break;
3203
3204  case OO_EqualEqual:
3205  case OO_ExclaimEqual:
3206    // C++ [over.match.oper]p16:
3207    //   For every pointer to member type T, there exist candidate operator
3208    //   functions of the form
3209    //
3210    //        bool operator==(T,T);
3211    //        bool operator!=(T,T);
3212    for (BuiltinCandidateTypeSet::iterator
3213           MemPtr = CandidateTypes.member_pointer_begin(),
3214           MemPtrEnd = CandidateTypes.member_pointer_end();
3215         MemPtr != MemPtrEnd;
3216         ++MemPtr) {
3217      QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3218      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3219    }
3220
3221    // Fall through
3222
3223  case OO_Less:
3224  case OO_Greater:
3225  case OO_LessEqual:
3226  case OO_GreaterEqual:
3227    // C++ [over.built]p15:
3228    //
3229    //   For every pointer or enumeration type T, there exist
3230    //   candidate operator functions of the form
3231    //
3232    //        bool       operator<(T, T);
3233    //        bool       operator>(T, T);
3234    //        bool       operator<=(T, T);
3235    //        bool       operator>=(T, T);
3236    //        bool       operator==(T, T);
3237    //        bool       operator!=(T, T);
3238    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3239         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3240      QualType ParamTypes[2] = { *Ptr, *Ptr };
3241      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3242    }
3243    for (BuiltinCandidateTypeSet::iterator Enum
3244           = CandidateTypes.enumeration_begin();
3245         Enum != CandidateTypes.enumeration_end(); ++Enum) {
3246      QualType ParamTypes[2] = { *Enum, *Enum };
3247      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3248    }
3249
3250    // Fall through.
3251    isComparison = true;
3252
3253  BinaryPlus:
3254  BinaryMinus:
3255    if (!isComparison) {
3256      // We didn't fall through, so we must have OO_Plus or OO_Minus.
3257
3258      // C++ [over.built]p13:
3259      //
3260      //   For every cv-qualified or cv-unqualified object type T
3261      //   there exist candidate operator functions of the form
3262      //
3263      //      T*         operator+(T*, ptrdiff_t);
3264      //      T&         operator[](T*, ptrdiff_t);    [BELOW]
3265      //      T*         operator-(T*, ptrdiff_t);
3266      //      T*         operator+(ptrdiff_t, T*);
3267      //      T&         operator[](ptrdiff_t, T*);    [BELOW]
3268      //
3269      // C++ [over.built]p14:
3270      //
3271      //   For every T, where T is a pointer to object type, there
3272      //   exist candidate operator functions of the form
3273      //
3274      //      ptrdiff_t  operator-(T, T);
3275      for (BuiltinCandidateTypeSet::iterator Ptr
3276             = CandidateTypes.pointer_begin();
3277           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3278        QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3279
3280        // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3281        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3282
3283        if (Op == OO_Plus) {
3284          // T* operator+(ptrdiff_t, T*);
3285          ParamTypes[0] = ParamTypes[1];
3286          ParamTypes[1] = *Ptr;
3287          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3288        } else {
3289          // ptrdiff_t operator-(T, T);
3290          ParamTypes[1] = *Ptr;
3291          AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3292                              Args, 2, CandidateSet);
3293        }
3294      }
3295    }
3296    // Fall through
3297
3298  case OO_Slash:
3299  BinaryStar:
3300  Conditional:
3301    // C++ [over.built]p12:
3302    //
3303    //   For every pair of promoted arithmetic types L and R, there
3304    //   exist candidate operator functions of the form
3305    //
3306    //        LR         operator*(L, R);
3307    //        LR         operator/(L, R);
3308    //        LR         operator+(L, R);
3309    //        LR         operator-(L, R);
3310    //        bool       operator<(L, R);
3311    //        bool       operator>(L, R);
3312    //        bool       operator<=(L, R);
3313    //        bool       operator>=(L, R);
3314    //        bool       operator==(L, R);
3315    //        bool       operator!=(L, R);
3316    //
3317    //   where LR is the result of the usual arithmetic conversions
3318    //   between types L and R.
3319    //
3320    // C++ [over.built]p24:
3321    //
3322    //   For every pair of promoted arithmetic types L and R, there exist
3323    //   candidate operator functions of the form
3324    //
3325    //        LR       operator?(bool, L, R);
3326    //
3327    //   where LR is the result of the usual arithmetic conversions
3328    //   between types L and R.
3329    // Our candidates ignore the first parameter.
3330    for (unsigned Left = FirstPromotedArithmeticType;
3331         Left < LastPromotedArithmeticType; ++Left) {
3332      for (unsigned Right = FirstPromotedArithmeticType;
3333           Right < LastPromotedArithmeticType; ++Right) {
3334        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3335        QualType Result
3336          = isComparison
3337          ? Context.BoolTy
3338          : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
3339        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3340      }
3341    }
3342    break;
3343
3344  case OO_Percent:
3345  BinaryAmp:
3346  case OO_Caret:
3347  case OO_Pipe:
3348  case OO_LessLess:
3349  case OO_GreaterGreater:
3350    // C++ [over.built]p17:
3351    //
3352    //   For every pair of promoted integral types L and R, there
3353    //   exist candidate operator functions of the form
3354    //
3355    //      LR         operator%(L, R);
3356    //      LR         operator&(L, R);
3357    //      LR         operator^(L, R);
3358    //      LR         operator|(L, R);
3359    //      L          operator<<(L, R);
3360    //      L          operator>>(L, R);
3361    //
3362    //   where LR is the result of the usual arithmetic conversions
3363    //   between types L and R.
3364    for (unsigned Left = FirstPromotedIntegralType;
3365         Left < LastPromotedIntegralType; ++Left) {
3366      for (unsigned Right = FirstPromotedIntegralType;
3367           Right < LastPromotedIntegralType; ++Right) {
3368        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3369        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3370            ? LandR[0]
3371            : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
3372        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3373      }
3374    }
3375    break;
3376
3377  case OO_Equal:
3378    // C++ [over.built]p20:
3379    //
3380    //   For every pair (T, VQ), where T is an enumeration or
3381    //   pointer to member type and VQ is either volatile or
3382    //   empty, there exist candidate operator functions of the form
3383    //
3384    //        VQ T&      operator=(VQ T&, T);
3385    for (BuiltinCandidateTypeSet::iterator
3386           Enum = CandidateTypes.enumeration_begin(),
3387           EnumEnd = CandidateTypes.enumeration_end();
3388         Enum != EnumEnd; ++Enum)
3389      AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
3390                                             CandidateSet);
3391    for (BuiltinCandidateTypeSet::iterator
3392           MemPtr = CandidateTypes.member_pointer_begin(),
3393         MemPtrEnd = CandidateTypes.member_pointer_end();
3394         MemPtr != MemPtrEnd; ++MemPtr)
3395      AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
3396                                             CandidateSet);
3397      // Fall through.
3398
3399  case OO_PlusEqual:
3400  case OO_MinusEqual:
3401    // C++ [over.built]p19:
3402    //
3403    //   For every pair (T, VQ), where T is any type and VQ is either
3404    //   volatile or empty, there exist candidate operator functions
3405    //   of the form
3406    //
3407    //        T*VQ&      operator=(T*VQ&, T*);
3408    //
3409    // C++ [over.built]p21:
3410    //
3411    //   For every pair (T, VQ), where T is a cv-qualified or
3412    //   cv-unqualified object type and VQ is either volatile or
3413    //   empty, there exist candidate operator functions of the form
3414    //
3415    //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
3416    //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
3417    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3418         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3419      QualType ParamTypes[2];
3420      ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3421
3422      // non-volatile version
3423      ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
3424      AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3425                          /*IsAssigmentOperator=*/Op == OO_Equal);
3426
3427      if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3428        // volatile version
3429        ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
3430        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3431                            /*IsAssigmentOperator=*/Op == OO_Equal);
3432      }
3433    }
3434    // Fall through.
3435
3436  case OO_StarEqual:
3437  case OO_SlashEqual:
3438    // C++ [over.built]p18:
3439    //
3440    //   For every triple (L, VQ, R), where L is an arithmetic type,
3441    //   VQ is either volatile or empty, and R is a promoted
3442    //   arithmetic type, there exist candidate operator functions of
3443    //   the form
3444    //
3445    //        VQ L&      operator=(VQ L&, R);
3446    //        VQ L&      operator*=(VQ L&, R);
3447    //        VQ L&      operator/=(VQ L&, R);
3448    //        VQ L&      operator+=(VQ L&, R);
3449    //        VQ L&      operator-=(VQ L&, R);
3450    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3451      for (unsigned Right = FirstPromotedArithmeticType;
3452           Right < LastPromotedArithmeticType; ++Right) {
3453        QualType ParamTypes[2];
3454        ParamTypes[1] = ArithmeticTypes[Right];
3455
3456        // Add this built-in operator as a candidate (VQ is empty).
3457        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3458        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3459                            /*IsAssigmentOperator=*/Op == OO_Equal);
3460
3461        // Add this built-in operator as a candidate (VQ is 'volatile').
3462        ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
3463        ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3464        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3465                            /*IsAssigmentOperator=*/Op == OO_Equal);
3466      }
3467    }
3468    break;
3469
3470  case OO_PercentEqual:
3471  case OO_LessLessEqual:
3472  case OO_GreaterGreaterEqual:
3473  case OO_AmpEqual:
3474  case OO_CaretEqual:
3475  case OO_PipeEqual:
3476    // C++ [over.built]p22:
3477    //
3478    //   For every triple (L, VQ, R), where L is an integral type, VQ
3479    //   is either volatile or empty, and R is a promoted integral
3480    //   type, there exist candidate operator functions of the form
3481    //
3482    //        VQ L&       operator%=(VQ L&, R);
3483    //        VQ L&       operator<<=(VQ L&, R);
3484    //        VQ L&       operator>>=(VQ L&, R);
3485    //        VQ L&       operator&=(VQ L&, R);
3486    //        VQ L&       operator^=(VQ L&, R);
3487    //        VQ L&       operator|=(VQ L&, R);
3488    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3489      for (unsigned Right = FirstPromotedIntegralType;
3490           Right < LastPromotedIntegralType; ++Right) {
3491        QualType ParamTypes[2];
3492        ParamTypes[1] = ArithmeticTypes[Right];
3493
3494        // Add this built-in operator as a candidate (VQ is empty).
3495        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3496        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3497
3498        // Add this built-in operator as a candidate (VQ is 'volatile').
3499        ParamTypes[0] = ArithmeticTypes[Left];
3500        ParamTypes[0].addVolatile();
3501        ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3502        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3503      }
3504    }
3505    break;
3506
3507  case OO_Exclaim: {
3508    // C++ [over.operator]p23:
3509    //
3510    //   There also exist candidate operator functions of the form
3511    //
3512    //        bool        operator!(bool);
3513    //        bool        operator&&(bool, bool);     [BELOW]
3514    //        bool        operator||(bool, bool);     [BELOW]
3515    QualType ParamTy = Context.BoolTy;
3516    AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3517                        /*IsAssignmentOperator=*/false,
3518                        /*NumContextualBoolArguments=*/1);
3519    break;
3520  }
3521
3522  case OO_AmpAmp:
3523  case OO_PipePipe: {
3524    // C++ [over.operator]p23:
3525    //
3526    //   There also exist candidate operator functions of the form
3527    //
3528    //        bool        operator!(bool);            [ABOVE]
3529    //        bool        operator&&(bool, bool);
3530    //        bool        operator||(bool, bool);
3531    QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
3532    AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3533                        /*IsAssignmentOperator=*/false,
3534                        /*NumContextualBoolArguments=*/2);
3535    break;
3536  }
3537
3538  case OO_Subscript:
3539    // C++ [over.built]p13:
3540    //
3541    //   For every cv-qualified or cv-unqualified object type T there
3542    //   exist candidate operator functions of the form
3543    //
3544    //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
3545    //        T&         operator[](T*, ptrdiff_t);
3546    //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
3547    //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
3548    //        T&         operator[](ptrdiff_t, T*);
3549    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3550         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3551      QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3552      QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
3553      QualType ResultTy = Context.getLValueReferenceType(PointeeType);
3554
3555      // T& operator[](T*, ptrdiff_t)
3556      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3557
3558      // T& operator[](ptrdiff_t, T*);
3559      ParamTypes[0] = ParamTypes[1];
3560      ParamTypes[1] = *Ptr;
3561      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3562    }
3563    break;
3564
3565  case OO_ArrowStar:
3566    // FIXME: No support for pointer-to-members yet.
3567    break;
3568
3569  case OO_Conditional:
3570    // Note that we don't consider the first argument, since it has been
3571    // contextually converted to bool long ago. The candidates below are
3572    // therefore added as binary.
3573    //
3574    // C++ [over.built]p24:
3575    //   For every type T, where T is a pointer or pointer-to-member type,
3576    //   there exist candidate operator functions of the form
3577    //
3578    //        T        operator?(bool, T, T);
3579    //
3580    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3581         E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3582      QualType ParamTypes[2] = { *Ptr, *Ptr };
3583      AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3584    }
3585    for (BuiltinCandidateTypeSet::iterator Ptr =
3586           CandidateTypes.member_pointer_begin(),
3587         E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3588      QualType ParamTypes[2] = { *Ptr, *Ptr };
3589      AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3590    }
3591    goto Conditional;
3592  }
3593}
3594
3595/// \brief Add function candidates found via argument-dependent lookup
3596/// to the set of overloading candidates.
3597///
3598/// This routine performs argument-dependent name lookup based on the
3599/// given function name (which may also be an operator name) and adds
3600/// all of the overload candidates found by ADL to the overload
3601/// candidate set (C++ [basic.lookup.argdep]).
3602void
3603Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3604                                           Expr **Args, unsigned NumArgs,
3605                                           OverloadCandidateSet& CandidateSet) {
3606  FunctionSet Functions;
3607
3608  // Record all of the function candidates that we've already
3609  // added to the overload set, so that we don't add those same
3610  // candidates a second time.
3611  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3612                                   CandEnd = CandidateSet.end();
3613       Cand != CandEnd; ++Cand)
3614    if (Cand->Function) {
3615      Functions.insert(Cand->Function);
3616      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3617        Functions.insert(FunTmpl);
3618    }
3619
3620  ArgumentDependentLookup(Name, Args, NumArgs, Functions);
3621
3622  // Erase all of the candidates we already knew about.
3623  // FIXME: This is suboptimal. Is there a better way?
3624  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3625                                   CandEnd = CandidateSet.end();
3626       Cand != CandEnd; ++Cand)
3627    if (Cand->Function) {
3628      Functions.erase(Cand->Function);
3629      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3630        Functions.erase(FunTmpl);
3631    }
3632
3633  // For each of the ADL candidates we found, add it to the overload
3634  // set.
3635  for (FunctionSet::iterator Func = Functions.begin(),
3636                          FuncEnd = Functions.end();
3637       Func != FuncEnd; ++Func) {
3638    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3639      AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3640    else
3641      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
3642                                   /*FIXME: explicit args */false, 0, 0,
3643                                   Args, NumArgs, CandidateSet);
3644  }
3645}
3646
3647/// isBetterOverloadCandidate - Determines whether the first overload
3648/// candidate is a better candidate than the second (C++ 13.3.3p1).
3649bool
3650Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3651                                const OverloadCandidate& Cand2) {
3652  // Define viable functions to be better candidates than non-viable
3653  // functions.
3654  if (!Cand2.Viable)
3655    return Cand1.Viable;
3656  else if (!Cand1.Viable)
3657    return false;
3658
3659  // C++ [over.match.best]p1:
3660  //
3661  //   -- if F is a static member function, ICS1(F) is defined such
3662  //      that ICS1(F) is neither better nor worse than ICS1(G) for
3663  //      any function G, and, symmetrically, ICS1(G) is neither
3664  //      better nor worse than ICS1(F).
3665  unsigned StartArg = 0;
3666  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3667    StartArg = 1;
3668
3669  // C++ [over.match.best]p1:
3670  //   A viable function F1 is defined to be a better function than another
3671  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
3672  //   conversion sequence than ICSi(F2), and then...
3673  unsigned NumArgs = Cand1.Conversions.size();
3674  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3675  bool HasBetterConversion = false;
3676  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
3677    switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3678                                               Cand2.Conversions[ArgIdx])) {
3679    case ImplicitConversionSequence::Better:
3680      // Cand1 has a better conversion sequence.
3681      HasBetterConversion = true;
3682      break;
3683
3684    case ImplicitConversionSequence::Worse:
3685      // Cand1 can't be better than Cand2.
3686      return false;
3687
3688    case ImplicitConversionSequence::Indistinguishable:
3689      // Do nothing.
3690      break;
3691    }
3692  }
3693
3694  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
3695  //       ICSj(F2), or, if not that,
3696  if (HasBetterConversion)
3697    return true;
3698
3699  //     - F1 is a non-template function and F2 is a function template
3700  //       specialization, or, if not that,
3701  if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3702      Cand2.Function && Cand2.Function->getPrimaryTemplate())
3703    return true;
3704
3705  //   -- F1 and F2 are function template specializations, and the function
3706  //      template for F1 is more specialized than the template for F2
3707  //      according to the partial ordering rules described in 14.5.5.2, or,
3708  //      if not that,
3709  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3710      Cand2.Function && Cand2.Function->getPrimaryTemplate())
3711    if (FunctionTemplateDecl *BetterTemplate
3712          = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3713                                       Cand2.Function->getPrimaryTemplate(),
3714                                       TPOC_Call))
3715      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
3716
3717  //   -- the context is an initialization by user-defined conversion
3718  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
3719  //      from the return type of F1 to the destination type (i.e.,
3720  //      the type of the entity being initialized) is a better
3721  //      conversion sequence than the standard conversion sequence
3722  //      from the return type of F2 to the destination type.
3723  if (Cand1.Function && Cand2.Function &&
3724      isa<CXXConversionDecl>(Cand1.Function) &&
3725      isa<CXXConversionDecl>(Cand2.Function)) {
3726    switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3727                                               Cand2.FinalConversion)) {
3728    case ImplicitConversionSequence::Better:
3729      // Cand1 has a better conversion sequence.
3730      return true;
3731
3732    case ImplicitConversionSequence::Worse:
3733      // Cand1 can't be better than Cand2.
3734      return false;
3735
3736    case ImplicitConversionSequence::Indistinguishable:
3737      // Do nothing
3738      break;
3739    }
3740  }
3741
3742  return false;
3743}
3744
3745/// \brief Computes the best viable function (C++ 13.3.3)
3746/// within an overload candidate set.
3747///
3748/// \param CandidateSet the set of candidate functions.
3749///
3750/// \param Loc the location of the function name (or operator symbol) for
3751/// which overload resolution occurs.
3752///
3753/// \param Best f overload resolution was successful or found a deleted
3754/// function, Best points to the candidate function found.
3755///
3756/// \returns The result of overload resolution.
3757Sema::OverloadingResult
3758Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3759                         SourceLocation Loc,
3760                         OverloadCandidateSet::iterator& Best) {
3761  // Find the best viable function.
3762  Best = CandidateSet.end();
3763  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3764       Cand != CandidateSet.end(); ++Cand) {
3765    if (Cand->Viable) {
3766      if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3767        Best = Cand;
3768    }
3769  }
3770
3771  // If we didn't find any viable functions, abort.
3772  if (Best == CandidateSet.end())
3773    return OR_No_Viable_Function;
3774
3775  // Make sure that this function is better than every other viable
3776  // function. If not, we have an ambiguity.
3777  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3778       Cand != CandidateSet.end(); ++Cand) {
3779    if (Cand->Viable &&
3780        Cand != Best &&
3781        !isBetterOverloadCandidate(*Best, *Cand)) {
3782      Best = CandidateSet.end();
3783      return OR_Ambiguous;
3784    }
3785  }
3786
3787  // Best is the best viable function.
3788  if (Best->Function &&
3789      (Best->Function->isDeleted() ||
3790       Best->Function->getAttr<UnavailableAttr>()))
3791    return OR_Deleted;
3792
3793  // C++ [basic.def.odr]p2:
3794  //   An overloaded function is used if it is selected by overload resolution
3795  //   when referred to from a potentially-evaluated expression. [Note: this
3796  //   covers calls to named functions (5.2.2), operator overloading
3797  //   (clause 13), user-defined conversions (12.3.2), allocation function for
3798  //   placement new (5.3.4), as well as non-default initialization (8.5).
3799  if (Best->Function)
3800    MarkDeclarationReferenced(Loc, Best->Function);
3801  return OR_Success;
3802}
3803
3804/// PrintOverloadCandidates - When overload resolution fails, prints
3805/// diagnostic messages containing the candidates in the candidate
3806/// set. If OnlyViable is true, only viable candidates will be printed.
3807void
3808Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3809                              bool OnlyViable) {
3810  OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3811                             LastCand = CandidateSet.end();
3812  for (; Cand != LastCand; ++Cand) {
3813    if (Cand->Viable || !OnlyViable) {
3814      if (Cand->Function) {
3815        if (Cand->Function->isDeleted() ||
3816            Cand->Function->getAttr<UnavailableAttr>()) {
3817          // Deleted or "unavailable" function.
3818          Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3819            << Cand->Function->isDeleted();
3820        } else {
3821          // Normal function
3822          // FIXME: Give a better reason!
3823          Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3824        }
3825      } else if (Cand->IsSurrogate) {
3826        // Desugar the type of the surrogate down to a function type,
3827        // retaining as many typedefs as possible while still showing
3828        // the function type (and, therefore, its parameter types).
3829        QualType FnType = Cand->Surrogate->getConversionType();
3830        bool isLValueReference = false;
3831        bool isRValueReference = false;
3832        bool isPointer = false;
3833        if (const LValueReferenceType *FnTypeRef =
3834              FnType->getAs<LValueReferenceType>()) {
3835          FnType = FnTypeRef->getPointeeType();
3836          isLValueReference = true;
3837        } else if (const RValueReferenceType *FnTypeRef =
3838                     FnType->getAs<RValueReferenceType>()) {
3839          FnType = FnTypeRef->getPointeeType();
3840          isRValueReference = true;
3841        }
3842        if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
3843          FnType = FnTypePtr->getPointeeType();
3844          isPointer = true;
3845        }
3846        // Desugar down to a function type.
3847        FnType = QualType(FnType->getAsFunctionType(), 0);
3848        // Reconstruct the pointer/reference as appropriate.
3849        if (isPointer) FnType = Context.getPointerType(FnType);
3850        if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3851        if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
3852
3853        Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
3854          << FnType;
3855      } else {
3856        // FIXME: We need to get the identifier in here
3857        // FIXME: Do we want the error message to point at the operator?
3858        // (built-ins won't have a location)
3859        QualType FnType
3860          = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3861                                    Cand->BuiltinTypes.ParamTypes,
3862                                    Cand->Conversions.size(),
3863                                    false, 0);
3864
3865        Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
3866      }
3867    }
3868  }
3869}
3870
3871/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3872/// an overloaded function (C++ [over.over]), where @p From is an
3873/// expression with overloaded function type and @p ToType is the type
3874/// we're trying to resolve to. For example:
3875///
3876/// @code
3877/// int f(double);
3878/// int f(int);
3879///
3880/// int (*pfd)(double) = f; // selects f(double)
3881/// @endcode
3882///
3883/// This routine returns the resulting FunctionDecl if it could be
3884/// resolved, and NULL otherwise. When @p Complain is true, this
3885/// routine will emit diagnostics if there is an error.
3886FunctionDecl *
3887Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
3888                                         bool Complain) {
3889  QualType FunctionType = ToType;
3890  bool IsMember = false;
3891  if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
3892    FunctionType = ToTypePtr->getPointeeType();
3893  else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
3894    FunctionType = ToTypeRef->getPointeeType();
3895  else if (const MemberPointerType *MemTypePtr =
3896                    ToType->getAs<MemberPointerType>()) {
3897    FunctionType = MemTypePtr->getPointeeType();
3898    IsMember = true;
3899  }
3900
3901  // We only look at pointers or references to functions.
3902  FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
3903  if (!FunctionType->isFunctionType())
3904    return 0;
3905
3906  // Find the actual overloaded function declaration.
3907  OverloadedFunctionDecl *Ovl = 0;
3908
3909  // C++ [over.over]p1:
3910  //   [...] [Note: any redundant set of parentheses surrounding the
3911  //   overloaded function name is ignored (5.1). ]
3912  Expr *OvlExpr = From->IgnoreParens();
3913
3914  // C++ [over.over]p1:
3915  //   [...] The overloaded function name can be preceded by the &
3916  //   operator.
3917  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3918    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3919      OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3920  }
3921
3922  // Try to dig out the overloaded function.
3923  FunctionTemplateDecl *FunctionTemplate = 0;
3924  if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
3925    Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3926    FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3927  }
3928
3929  // If there's no overloaded function declaration or function template,
3930  // we're done.
3931  if (!Ovl && !FunctionTemplate)
3932    return 0;
3933
3934  OverloadIterator Fun;
3935  if (Ovl)
3936    Fun = Ovl;
3937  else
3938    Fun = FunctionTemplate;
3939
3940  // Look through all of the overloaded functions, searching for one
3941  // whose type matches exactly.
3942  llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
3943
3944  bool FoundNonTemplateFunction = false;
3945  for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
3946    // C++ [over.over]p3:
3947    //   Non-member functions and static member functions match
3948    //   targets of type "pointer-to-function" or "reference-to-function."
3949    //   Nonstatic member functions match targets of
3950    //   type "pointer-to-member-function."
3951    // Note that according to DR 247, the containing class does not matter.
3952
3953    if (FunctionTemplateDecl *FunctionTemplate
3954          = dyn_cast<FunctionTemplateDecl>(*Fun)) {
3955      if (CXXMethodDecl *Method
3956            = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
3957        // Skip non-static function templates when converting to pointer, and
3958        // static when converting to member pointer.
3959        if (Method->isStatic() == IsMember)
3960          continue;
3961      } else if (IsMember)
3962        continue;
3963
3964      // C++ [over.over]p2:
3965      //   If the name is a function template, template argument deduction is
3966      //   done (14.8.2.2), and if the argument deduction succeeds, the
3967      //   resulting template argument list is used to generate a single
3968      //   function template specialization, which is added to the set of
3969      //   overloaded functions considered.
3970      FunctionDecl *Specialization = 0;
3971      TemplateDeductionInfo Info(Context);
3972      if (TemplateDeductionResult Result
3973            = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3974                                      /*FIXME:*/0, /*FIXME:*/0,
3975                                      FunctionType, Specialization, Info)) {
3976        // FIXME: make a note of the failed deduction for diagnostics.
3977        (void)Result;
3978      } else {
3979        assert(FunctionType
3980                 == Context.getCanonicalType(Specialization->getType()));
3981        Matches.insert(
3982                cast<FunctionDecl>(Specialization->getCanonicalDecl()));
3983      }
3984    }
3985
3986    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3987      // Skip non-static functions when converting to pointer, and static
3988      // when converting to member pointer.
3989      if (Method->isStatic() == IsMember)
3990        continue;
3991    } else if (IsMember)
3992      continue;
3993
3994    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
3995      if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
3996        Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
3997        FoundNonTemplateFunction = true;
3998      }
3999    }
4000  }
4001
4002  // If there were 0 or 1 matches, we're done.
4003  if (Matches.empty())
4004    return 0;
4005  else if (Matches.size() == 1)
4006    return *Matches.begin();
4007
4008  // C++ [over.over]p4:
4009  //   If more than one function is selected, [...]
4010  llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4011  typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
4012  if (FoundNonTemplateFunction) {
4013    //   [...] any function template specializations in the set are
4014    //   eliminated if the set also contains a non-template function, [...]
4015    for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4016      if ((*M)->getPrimaryTemplate() == 0)
4017        RemainingMatches.push_back(*M);
4018  } else {
4019    //   [...] and any given function template specialization F1 is
4020    //   eliminated if the set contains a second function template
4021    //   specialization whose function template is more specialized
4022    //   than the function template of F1 according to the partial
4023    //   ordering rules of 14.5.5.2.
4024
4025    // The algorithm specified above is quadratic. We instead use a
4026    // two-pass algorithm (similar to the one used to identify the
4027    // best viable function in an overload set) that identifies the
4028    // best function template (if it exists).
4029    MatchIter Best = Matches.begin();
4030    MatchIter M = Best, MEnd = Matches.end();
4031    // Find the most specialized function.
4032    for (++M; M != MEnd; ++M)
4033      if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4034                                     (*Best)->getPrimaryTemplate(),
4035                                     TPOC_Other)
4036            == (*M)->getPrimaryTemplate())
4037        Best = M;
4038
4039    // Determine whether this function template is more specialized
4040    // that all of the others.
4041    bool Ambiguous = false;
4042    for (M = Matches.begin(); M != MEnd; ++M) {
4043      if (M != Best &&
4044          getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4045                                     (*Best)->getPrimaryTemplate(),
4046                                     TPOC_Other)
4047           != (*Best)->getPrimaryTemplate()) {
4048        Ambiguous = true;
4049        break;
4050      }
4051    }
4052
4053    // If one function template was more specialized than all of the
4054    // others, return it.
4055    if (!Ambiguous)
4056      return *Best;
4057
4058    // We could not find a most-specialized function template, which
4059    // is equivalent to having a set of function templates with more
4060    // than one such template. So, we place all of the function
4061    // templates into the set of remaining matches and produce a
4062    // diagnostic below. FIXME: we could perform the quadratic
4063    // algorithm here, pruning the result set to limit the number of
4064    // candidates output later.
4065     RemainingMatches.append(Matches.begin(), Matches.end());
4066  }
4067
4068  // [...] After such eliminations, if any, there shall remain exactly one
4069  // selected function.
4070  if (RemainingMatches.size() == 1)
4071    return RemainingMatches.front();
4072
4073  // FIXME: We should probably return the same thing that BestViableFunction
4074  // returns (even if we issue the diagnostics here).
4075  Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4076    << RemainingMatches[0]->getDeclName();
4077  for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4078    Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
4079  return 0;
4080}
4081
4082/// ResolveOverloadedCallFn - Given the call expression that calls Fn
4083/// (which eventually refers to the declaration Func) and the call
4084/// arguments Args/NumArgs, attempt to resolve the function call down
4085/// to a specific function. If overload resolution succeeds, returns
4086/// the function declaration produced by overload
4087/// resolution. Otherwise, emits diagnostics, deletes all of the
4088/// arguments and Fn, and returns NULL.
4089FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
4090                                            DeclarationName UnqualifiedName,
4091                                            bool HasExplicitTemplateArgs,
4092                                 const TemplateArgument *ExplicitTemplateArgs,
4093                                            unsigned NumExplicitTemplateArgs,
4094                                            SourceLocation LParenLoc,
4095                                            Expr **Args, unsigned NumArgs,
4096                                            SourceLocation *CommaLocs,
4097                                            SourceLocation RParenLoc,
4098                                            bool &ArgumentDependentLookup) {
4099  OverloadCandidateSet CandidateSet;
4100
4101  // Add the functions denoted by Callee to the set of candidate
4102  // functions. While we're doing so, track whether argument-dependent
4103  // lookup still applies, per:
4104  //
4105  // C++0x [basic.lookup.argdep]p3:
4106  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
4107  //   and let Y be the lookup set produced by argument dependent
4108  //   lookup (defined as follows). If X contains
4109  //
4110  //     -- a declaration of a class member, or
4111  //
4112  //     -- a block-scope function declaration that is not a
4113  //        using-declaration, or
4114  //
4115  //     -- a declaration that is neither a function or a function
4116  //        template
4117  //
4118  //   then Y is empty.
4119  if (OverloadedFunctionDecl *Ovl
4120        = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
4121    for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4122                                                FuncEnd = Ovl->function_end();
4123         Func != FuncEnd; ++Func) {
4124      DeclContext *Ctx = 0;
4125      if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
4126        if (HasExplicitTemplateArgs)
4127          continue;
4128
4129        AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
4130        Ctx = FunDecl->getDeclContext();
4131      } else {
4132        FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
4133        AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
4134                                     ExplicitTemplateArgs,
4135                                     NumExplicitTemplateArgs,
4136                                     Args, NumArgs, CandidateSet);
4137        Ctx = FunTmpl->getDeclContext();
4138      }
4139
4140
4141      if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
4142        ArgumentDependentLookup = false;
4143    }
4144  } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
4145    assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4146    AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
4147
4148    if (Func->getDeclContext()->isRecord() ||
4149        Func->getDeclContext()->isFunctionOrMethod())
4150      ArgumentDependentLookup = false;
4151  } else if (FunctionTemplateDecl *FuncTemplate
4152               = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
4153    AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4154                                 ExplicitTemplateArgs,
4155                                 NumExplicitTemplateArgs,
4156                                 Args, NumArgs, CandidateSet);
4157
4158    if (FuncTemplate->getDeclContext()->isRecord())
4159      ArgumentDependentLookup = false;
4160  }
4161
4162  if (Callee)
4163    UnqualifiedName = Callee->getDeclName();
4164
4165  // FIXME: Pass explicit template arguments through for ADL
4166  if (ArgumentDependentLookup)
4167    AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4168                                         CandidateSet);
4169
4170  OverloadCandidateSet::iterator Best;
4171  switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
4172  case OR_Success:
4173    return Best->Function;
4174
4175  case OR_No_Viable_Function:
4176    Diag(Fn->getSourceRange().getBegin(),
4177         diag::err_ovl_no_viable_function_in_call)
4178      << UnqualifiedName << Fn->getSourceRange();
4179    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4180    break;
4181
4182  case OR_Ambiguous:
4183    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
4184      << UnqualifiedName << Fn->getSourceRange();
4185    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4186    break;
4187
4188  case OR_Deleted:
4189    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4190      << Best->Function->isDeleted()
4191      << UnqualifiedName
4192      << Fn->getSourceRange();
4193    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4194    break;
4195  }
4196
4197  // Overload resolution failed. Destroy all of the subexpressions and
4198  // return NULL.
4199  Fn->Destroy(Context);
4200  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4201    Args[Arg]->Destroy(Context);
4202  return 0;
4203}
4204
4205/// \brief Create a unary operation that may resolve to an overloaded
4206/// operator.
4207///
4208/// \param OpLoc The location of the operator itself (e.g., '*').
4209///
4210/// \param OpcIn The UnaryOperator::Opcode that describes this
4211/// operator.
4212///
4213/// \param Functions The set of non-member functions that will be
4214/// considered by overload resolution. The caller needs to build this
4215/// set based on the context using, e.g.,
4216/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4217/// set should not contain any member functions; those will be added
4218/// by CreateOverloadedUnaryOp().
4219///
4220/// \param input The input argument.
4221Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4222                                                     unsigned OpcIn,
4223                                                     FunctionSet &Functions,
4224                                                     ExprArg input) {
4225  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4226  Expr *Input = (Expr *)input.get();
4227
4228  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4229  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4230  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4231
4232  Expr *Args[2] = { Input, 0 };
4233  unsigned NumArgs = 1;
4234
4235  // For post-increment and post-decrement, add the implicit '0' as
4236  // the second argument, so that we know this is a post-increment or
4237  // post-decrement.
4238  if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4239    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
4240    Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
4241                                           SourceLocation());
4242    NumArgs = 2;
4243  }
4244
4245  if (Input->isTypeDependent()) {
4246    OverloadedFunctionDecl *Overloads
4247      = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4248    for (FunctionSet::iterator Func = Functions.begin(),
4249                            FuncEnd = Functions.end();
4250         Func != FuncEnd; ++Func)
4251      Overloads->addOverload(*Func);
4252
4253    DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4254                                                OpLoc, false, false);
4255
4256    input.release();
4257    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4258                                                   &Args[0], NumArgs,
4259                                                   Context.DependentTy,
4260                                                   OpLoc));
4261  }
4262
4263  // Build an empty overload set.
4264  OverloadCandidateSet CandidateSet;
4265
4266  // Add the candidates from the given function set.
4267  AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4268
4269  // Add operator candidates that are member functions.
4270  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4271
4272  // Add builtin operator candidates.
4273  AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4274
4275  // Perform overload resolution.
4276  OverloadCandidateSet::iterator Best;
4277  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4278  case OR_Success: {
4279    // We found a built-in operator or an overloaded operator.
4280    FunctionDecl *FnDecl = Best->Function;
4281
4282    if (FnDecl) {
4283      // We matched an overloaded operator. Build a call to that
4284      // operator.
4285
4286      // Convert the arguments.
4287      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4288        if (PerformObjectArgumentInitialization(Input, Method))
4289          return ExprError();
4290      } else {
4291        // Convert the arguments.
4292        if (PerformCopyInitialization(Input,
4293                                      FnDecl->getParamDecl(0)->getType(),
4294                                      "passing"))
4295          return ExprError();
4296      }
4297
4298      // Determine the result type
4299      QualType ResultTy
4300        = FnDecl->getType()->getAsFunctionType()->getResultType();
4301      ResultTy = ResultTy.getNonReferenceType();
4302
4303      // Build the actual expression node.
4304      Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4305                                               SourceLocation());
4306      UsualUnaryConversions(FnExpr);
4307
4308      input.release();
4309
4310      Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4311                                                   &Input, 1, ResultTy, OpLoc);
4312      return MaybeBindToTemporary(CE);
4313    } else {
4314      // We matched a built-in operator. Convert the arguments, then
4315      // break out so that we will build the appropriate built-in
4316      // operator node.
4317        if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4318                                      Best->Conversions[0], "passing"))
4319          return ExprError();
4320
4321        break;
4322      }
4323    }
4324
4325    case OR_No_Viable_Function:
4326      // No viable function; fall through to handling this as a
4327      // built-in operator, which will produce an error message for us.
4328      break;
4329
4330    case OR_Ambiguous:
4331      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
4332          << UnaryOperator::getOpcodeStr(Opc)
4333          << Input->getSourceRange();
4334      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4335      return ExprError();
4336
4337    case OR_Deleted:
4338      Diag(OpLoc, diag::err_ovl_deleted_oper)
4339        << Best->Function->isDeleted()
4340        << UnaryOperator::getOpcodeStr(Opc)
4341        << Input->getSourceRange();
4342      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4343      return ExprError();
4344    }
4345
4346  // Either we found no viable overloaded operator or we matched a
4347  // built-in operator. In either case, fall through to trying to
4348  // build a built-in operation.
4349  input.release();
4350  return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4351}
4352
4353/// \brief Create a binary operation that may resolve to an overloaded
4354/// operator.
4355///
4356/// \param OpLoc The location of the operator itself (e.g., '+').
4357///
4358/// \param OpcIn The BinaryOperator::Opcode that describes this
4359/// operator.
4360///
4361/// \param Functions The set of non-member functions that will be
4362/// considered by overload resolution. The caller needs to build this
4363/// set based on the context using, e.g.,
4364/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4365/// set should not contain any member functions; those will be added
4366/// by CreateOverloadedBinOp().
4367///
4368/// \param LHS Left-hand argument.
4369/// \param RHS Right-hand argument.
4370Sema::OwningExprResult
4371Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4372                            unsigned OpcIn,
4373                            FunctionSet &Functions,
4374                            Expr *LHS, Expr *RHS) {
4375  Expr *Args[2] = { LHS, RHS };
4376  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
4377
4378  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4379  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4380  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4381
4382  // If either side is type-dependent, create an appropriate dependent
4383  // expression.
4384  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
4385    // .* cannot be overloaded.
4386    if (Opc == BinaryOperator::PtrMemD)
4387      return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4388                                                Context.DependentTy, OpLoc));
4389
4390    OverloadedFunctionDecl *Overloads
4391      = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4392    for (FunctionSet::iterator Func = Functions.begin(),
4393                            FuncEnd = Functions.end();
4394         Func != FuncEnd; ++Func)
4395      Overloads->addOverload(*Func);
4396
4397    DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4398                                                OpLoc, false, false);
4399
4400    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4401                                                   Args, 2,
4402                                                   Context.DependentTy,
4403                                                   OpLoc));
4404  }
4405
4406  // If this is the .* operator, which is not overloadable, just
4407  // create a built-in binary operator.
4408  if (Opc == BinaryOperator::PtrMemD)
4409    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4410
4411  // If this is one of the assignment operators, we only perform
4412  // overload resolution if the left-hand side is a class or
4413  // enumeration type (C++ [expr.ass]p3).
4414  if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
4415      !Args[0]->getType()->isOverloadableType())
4416    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4417
4418  // Build an empty overload set.
4419  OverloadCandidateSet CandidateSet;
4420
4421  // Add the candidates from the given function set.
4422  AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4423
4424  // Add operator candidates that are member functions.
4425  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4426
4427  // Add builtin operator candidates.
4428  AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4429
4430  // Perform overload resolution.
4431  OverloadCandidateSet::iterator Best;
4432  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4433    case OR_Success: {
4434      // We found a built-in operator or an overloaded operator.
4435      FunctionDecl *FnDecl = Best->Function;
4436
4437      if (FnDecl) {
4438        // We matched an overloaded operator. Build a call to that
4439        // operator.
4440
4441        // Convert the arguments.
4442        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4443          if (PerformObjectArgumentInitialization(Args[0], Method) ||
4444              PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
4445                                        "passing"))
4446            return ExprError();
4447        } else {
4448          // Convert the arguments.
4449          if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
4450                                        "passing") ||
4451              PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
4452                                        "passing"))
4453            return ExprError();
4454        }
4455
4456        // Determine the result type
4457        QualType ResultTy
4458          = FnDecl->getType()->getAsFunctionType()->getResultType();
4459        ResultTy = ResultTy.getNonReferenceType();
4460
4461        // Build the actual expression node.
4462        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4463                                                 OpLoc);
4464        UsualUnaryConversions(FnExpr);
4465
4466        Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4467                                                     Args, 2, ResultTy, OpLoc);
4468        return MaybeBindToTemporary(CE);
4469      } else {
4470        // We matched a built-in operator. Convert the arguments, then
4471        // break out so that we will build the appropriate built-in
4472        // operator node.
4473        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
4474                                      Best->Conversions[0], "passing") ||
4475            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
4476                                      Best->Conversions[1], "passing"))
4477          return ExprError();
4478
4479        break;
4480      }
4481    }
4482
4483    case OR_No_Viable_Function:
4484      // For class as left operand for assignment or compound assigment operator
4485      // do not fall through to handling in built-in, but report that no overloaded
4486      // assignment operator found
4487      if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
4488        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
4489             << BinaryOperator::getOpcodeStr(Opc)
4490             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
4491        return ExprError();
4492      }
4493      // No viable function; fall through to handling this as a
4494      // built-in operator, which will produce an error message for us.
4495      break;
4496
4497    case OR_Ambiguous:
4498      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
4499          << BinaryOperator::getOpcodeStr(Opc)
4500          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
4501      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4502      return ExprError();
4503
4504    case OR_Deleted:
4505      Diag(OpLoc, diag::err_ovl_deleted_oper)
4506        << Best->Function->isDeleted()
4507        << BinaryOperator::getOpcodeStr(Opc)
4508        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
4509      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4510      return ExprError();
4511    }
4512
4513  // Either we found no viable overloaded operator or we matched a
4514  // built-in operator. In either case, try to build a built-in
4515  // operation.
4516  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4517}
4518
4519/// BuildCallToMemberFunction - Build a call to a member
4520/// function. MemExpr is the expression that refers to the member
4521/// function (and includes the object parameter), Args/NumArgs are the
4522/// arguments to the function call (not including the object
4523/// parameter). The caller needs to validate that the member
4524/// expression refers to a member function or an overloaded member
4525/// function.
4526Sema::ExprResult
4527Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4528                                SourceLocation LParenLoc, Expr **Args,
4529                                unsigned NumArgs, SourceLocation *CommaLocs,
4530                                SourceLocation RParenLoc) {
4531  // Dig out the member expression. This holds both the object
4532  // argument and the member function we're referring to.
4533  MemberExpr *MemExpr = 0;
4534  if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4535    MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4536  else
4537    MemExpr = dyn_cast<MemberExpr>(MemExprE);
4538  assert(MemExpr && "Building member call without member expression");
4539
4540  // Extract the object argument.
4541  Expr *ObjectArg = MemExpr->getBase();
4542
4543  CXXMethodDecl *Method = 0;
4544  if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4545      isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
4546    // Add overload candidates
4547    OverloadCandidateSet CandidateSet;
4548    DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
4549
4550    for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4551         Func != FuncEnd; ++Func) {
4552      if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
4553        AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4554                           /*SuppressUserConversions=*/false);
4555      else
4556        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4557                                   MemExpr->hasExplicitTemplateArgumentList(),
4558                                   MemExpr->getTemplateArgs(),
4559                                   MemExpr->getNumTemplateArgs(),
4560                                   ObjectArg, Args, NumArgs,
4561                                   CandidateSet,
4562                                   /*SuppressUsedConversions=*/false);
4563    }
4564
4565    OverloadCandidateSet::iterator Best;
4566    switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
4567    case OR_Success:
4568      Method = cast<CXXMethodDecl>(Best->Function);
4569      break;
4570
4571    case OR_No_Viable_Function:
4572      Diag(MemExpr->getSourceRange().getBegin(),
4573           diag::err_ovl_no_viable_member_function_in_call)
4574        << DeclName << MemExprE->getSourceRange();
4575      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4576      // FIXME: Leaking incoming expressions!
4577      return true;
4578
4579    case OR_Ambiguous:
4580      Diag(MemExpr->getSourceRange().getBegin(),
4581           diag::err_ovl_ambiguous_member_call)
4582        << DeclName << MemExprE->getSourceRange();
4583      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4584      // FIXME: Leaking incoming expressions!
4585      return true;
4586
4587    case OR_Deleted:
4588      Diag(MemExpr->getSourceRange().getBegin(),
4589           diag::err_ovl_deleted_member_call)
4590        << Best->Function->isDeleted()
4591        << DeclName << MemExprE->getSourceRange();
4592      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4593      // FIXME: Leaking incoming expressions!
4594      return true;
4595    }
4596
4597    FixOverloadedFunctionReference(MemExpr, Method);
4598  } else {
4599    Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4600  }
4601
4602  assert(Method && "Member call to something that isn't a method?");
4603  ExprOwningPtr<CXXMemberCallExpr>
4604    TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4605                                                  NumArgs,
4606                                  Method->getResultType().getNonReferenceType(),
4607                                  RParenLoc));
4608
4609  // Convert the object argument (for a non-static member function call).
4610  if (!Method->isStatic() &&
4611      PerformObjectArgumentInitialization(ObjectArg, Method))
4612    return true;
4613  MemExpr->setBase(ObjectArg);
4614
4615  // Convert the rest of the arguments
4616  const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
4617  if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4618                              RParenLoc))
4619    return true;
4620
4621  if (CheckFunctionCall(Method, TheCall.get()))
4622    return true;
4623
4624  return MaybeBindToTemporary(TheCall.release()).release();
4625}
4626
4627/// BuildCallToObjectOfClassType - Build a call to an object of class
4628/// type (C++ [over.call.object]), which can end up invoking an
4629/// overloaded function call operator (@c operator()) or performing a
4630/// user-defined conversion on the object argument.
4631Sema::ExprResult
4632Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4633                                   SourceLocation LParenLoc,
4634                                   Expr **Args, unsigned NumArgs,
4635                                   SourceLocation *CommaLocs,
4636                                   SourceLocation RParenLoc) {
4637  assert(Object->getType()->isRecordType() && "Requires object type argument");
4638  const RecordType *Record = Object->getType()->getAs<RecordType>();
4639
4640  // C++ [over.call.object]p1:
4641  //  If the primary-expression E in the function call syntax
4642  //  evaluates to a class object of type "cv T", then the set of
4643  //  candidate functions includes at least the function call
4644  //  operators of T. The function call operators of T are obtained by
4645  //  ordinary lookup of the name operator() in the context of
4646  //  (E).operator().
4647  OverloadCandidateSet CandidateSet;
4648  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
4649  DeclContext::lookup_const_iterator Oper, OperEnd;
4650  for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
4651       Oper != OperEnd; ++Oper)
4652    AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4653                       CandidateSet, /*SuppressUserConversions=*/false);
4654
4655  // C++ [over.call.object]p2:
4656  //   In addition, for each conversion function declared in T of the
4657  //   form
4658  //
4659  //        operator conversion-type-id () cv-qualifier;
4660  //
4661  //   where cv-qualifier is the same cv-qualification as, or a
4662  //   greater cv-qualification than, cv, and where conversion-type-id
4663  //   denotes the type "pointer to function of (P1,...,Pn) returning
4664  //   R", or the type "reference to pointer to function of
4665  //   (P1,...,Pn) returning R", or the type "reference to function
4666  //   of (P1,...,Pn) returning R", a surrogate call function [...]
4667  //   is also considered as a candidate function. Similarly,
4668  //   surrogate call functions are added to the set of candidate
4669  //   functions for each conversion function declared in an
4670  //   accessible base class provided the function is not hidden
4671  //   within T by another intervening declaration.
4672
4673  if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4674    // FIXME: Look in base classes for more conversion operators!
4675    OverloadedFunctionDecl *Conversions
4676      = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
4677    for (OverloadedFunctionDecl::function_iterator
4678           Func = Conversions->function_begin(),
4679           FuncEnd = Conversions->function_end();
4680         Func != FuncEnd; ++Func) {
4681      CXXConversionDecl *Conv;
4682      FunctionTemplateDecl *ConvTemplate;
4683      GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
4684
4685      // Skip over templated conversion functions; they aren't
4686      // surrogates.
4687      if (ConvTemplate)
4688        continue;
4689
4690      // Strip the reference type (if any) and then the pointer type (if
4691      // any) to get down to what might be a function type.
4692      QualType ConvType = Conv->getConversionType().getNonReferenceType();
4693      if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4694        ConvType = ConvPtrType->getPointeeType();
4695
4696      if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
4697        AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4698    }
4699  }
4700
4701  // Perform overload resolution.
4702  OverloadCandidateSet::iterator Best;
4703  switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
4704  case OR_Success:
4705    // Overload resolution succeeded; we'll build the appropriate call
4706    // below.
4707    break;
4708
4709  case OR_No_Viable_Function:
4710    Diag(Object->getSourceRange().getBegin(),
4711         diag::err_ovl_no_viable_object_call)
4712      << Object->getType() << Object->getSourceRange();
4713    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4714    break;
4715
4716  case OR_Ambiguous:
4717    Diag(Object->getSourceRange().getBegin(),
4718         diag::err_ovl_ambiguous_object_call)
4719      << Object->getType() << Object->getSourceRange();
4720    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4721    break;
4722
4723  case OR_Deleted:
4724    Diag(Object->getSourceRange().getBegin(),
4725         diag::err_ovl_deleted_object_call)
4726      << Best->Function->isDeleted()
4727      << Object->getType() << Object->getSourceRange();
4728    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4729    break;
4730  }
4731
4732  if (Best == CandidateSet.end()) {
4733    // We had an error; delete all of the subexpressions and return
4734    // the error.
4735    Object->Destroy(Context);
4736    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4737      Args[ArgIdx]->Destroy(Context);
4738    return true;
4739  }
4740
4741  if (Best->Function == 0) {
4742    // Since there is no function declaration, this is one of the
4743    // surrogate candidates. Dig out the conversion function.
4744    CXXConversionDecl *Conv
4745      = cast<CXXConversionDecl>(
4746                         Best->Conversions[0].UserDefined.ConversionFunction);
4747
4748    // We selected one of the surrogate functions that converts the
4749    // object parameter to a function pointer. Perform the conversion
4750    // on the object argument, then let ActOnCallExpr finish the job.
4751    // FIXME: Represent the user-defined conversion in the AST!
4752    ImpCastExprToType(Object,
4753                      Conv->getConversionType().getNonReferenceType(),
4754                      CastExpr::CK_Unknown,
4755                      Conv->getConversionType()->isLValueReferenceType());
4756    return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4757                         MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4758                         CommaLocs, RParenLoc).release();
4759  }
4760
4761  // We found an overloaded operator(). Build a CXXOperatorCallExpr
4762  // that calls this method, using Object for the implicit object
4763  // parameter and passing along the remaining arguments.
4764  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
4765  const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
4766
4767  unsigned NumArgsInProto = Proto->getNumArgs();
4768  unsigned NumArgsToCheck = NumArgs;
4769
4770  // Build the full argument list for the method call (the
4771  // implicit object parameter is placed at the beginning of the
4772  // list).
4773  Expr **MethodArgs;
4774  if (NumArgs < NumArgsInProto) {
4775    NumArgsToCheck = NumArgsInProto;
4776    MethodArgs = new Expr*[NumArgsInProto + 1];
4777  } else {
4778    MethodArgs = new Expr*[NumArgs + 1];
4779  }
4780  MethodArgs[0] = Object;
4781  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4782    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4783
4784  Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4785                                          SourceLocation());
4786  UsualUnaryConversions(NewFn);
4787
4788  // Once we've built TheCall, all of the expressions are properly
4789  // owned.
4790  QualType ResultTy = Method->getResultType().getNonReferenceType();
4791  ExprOwningPtr<CXXOperatorCallExpr>
4792    TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4793                                                    MethodArgs, NumArgs + 1,
4794                                                    ResultTy, RParenLoc));
4795  delete [] MethodArgs;
4796
4797  // We may have default arguments. If so, we need to allocate more
4798  // slots in the call for them.
4799  if (NumArgs < NumArgsInProto)
4800    TheCall->setNumArgs(Context, NumArgsInProto + 1);
4801  else if (NumArgs > NumArgsInProto)
4802    NumArgsToCheck = NumArgsInProto;
4803
4804  bool IsError = false;
4805
4806  // Initialize the implicit object parameter.
4807  IsError |= PerformObjectArgumentInitialization(Object, Method);
4808  TheCall->setArg(0, Object);
4809
4810
4811  // Check the argument types.
4812  for (unsigned i = 0; i != NumArgsToCheck; i++) {
4813    Expr *Arg;
4814    if (i < NumArgs) {
4815      Arg = Args[i];
4816
4817      // Pass the argument.
4818      QualType ProtoArgType = Proto->getArgType(i);
4819      IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
4820    } else {
4821      Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
4822    }
4823
4824    TheCall->setArg(i + 1, Arg);
4825  }
4826
4827  // If this is a variadic call, handle args passed through "...".
4828  if (Proto->isVariadic()) {
4829    // Promote the arguments (C99 6.5.2.2p7).
4830    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4831      Expr *Arg = Args[i];
4832      IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
4833      TheCall->setArg(i + 1, Arg);
4834    }
4835  }
4836
4837  if (IsError) return true;
4838
4839  if (CheckFunctionCall(Method, TheCall.get()))
4840    return true;
4841
4842  return MaybeBindToTemporary(TheCall.release()).release();
4843}
4844
4845/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4846///  (if one exists), where @c Base is an expression of class type and
4847/// @c Member is the name of the member we're trying to find.
4848Sema::OwningExprResult
4849Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4850  Expr *Base = static_cast<Expr *>(BaseIn.get());
4851  assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4852
4853  // C++ [over.ref]p1:
4854  //
4855  //   [...] An expression x->m is interpreted as (x.operator->())->m
4856  //   for a class object x of type T if T::operator->() exists and if
4857  //   the operator is selected as the best match function by the
4858  //   overload resolution mechanism (13.3).
4859  // FIXME: look in base classes.
4860  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4861  OverloadCandidateSet CandidateSet;
4862  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
4863
4864  LookupResult R = LookupQualifiedName(BaseRecord->getDecl(), OpName,
4865                                       LookupOrdinaryName);
4866
4867  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
4868       Oper != OperEnd; ++Oper)
4869    AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
4870                       /*SuppressUserConversions=*/false);
4871
4872  // Perform overload resolution.
4873  OverloadCandidateSet::iterator Best;
4874  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4875  case OR_Success:
4876    // Overload resolution succeeded; we'll build the call below.
4877    break;
4878
4879  case OR_No_Viable_Function:
4880    if (CandidateSet.empty())
4881      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
4882        << Base->getType() << Base->getSourceRange();
4883    else
4884      Diag(OpLoc, diag::err_ovl_no_viable_oper)
4885        << "operator->" << Base->getSourceRange();
4886    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4887    return ExprError();
4888
4889  case OR_Ambiguous:
4890    Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
4891      << "->" << Base->getSourceRange();
4892    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4893    return ExprError();
4894
4895  case OR_Deleted:
4896    Diag(OpLoc,  diag::err_ovl_deleted_oper)
4897      << Best->Function->isDeleted()
4898      << "->" << Base->getSourceRange();
4899    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4900    return ExprError();
4901  }
4902
4903  // Convert the object parameter.
4904  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
4905  if (PerformObjectArgumentInitialization(Base, Method))
4906    return ExprError();
4907
4908  // No concerns about early exits now.
4909  BaseIn.release();
4910
4911  // Build the operator call.
4912  Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4913                                           SourceLocation());
4914  UsualUnaryConversions(FnExpr);
4915  Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
4916                                 Method->getResultType().getNonReferenceType(),
4917                                 OpLoc);
4918  return Owned(Base);
4919}
4920
4921/// FixOverloadedFunctionReference - E is an expression that refers to
4922/// a C++ overloaded function (possibly with some parentheses and
4923/// perhaps a '&' around it). We have resolved the overloaded function
4924/// to the function declaration Fn, so patch up the expression E to
4925/// refer (possibly indirectly) to Fn.
4926void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4927  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4928    FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4929    E->setType(PE->getSubExpr()->getType());
4930  } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4931    assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4932           "Can only take the address of an overloaded function");
4933    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4934      if (Method->isStatic()) {
4935        // Do nothing: static member functions aren't any different
4936        // from non-member functions.
4937      } else if (QualifiedDeclRefExpr *DRE
4938                 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4939        // We have taken the address of a pointer to member
4940        // function. Perform the computation here so that we get the
4941        // appropriate pointer to member type.
4942        DRE->setDecl(Fn);
4943        DRE->setType(Fn->getType());
4944        QualType ClassType
4945          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4946        E->setType(Context.getMemberPointerType(Fn->getType(),
4947                                                ClassType.getTypePtr()));
4948        return;
4949      }
4950    }
4951    FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
4952    E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
4953  } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
4954    assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
4955            isa<FunctionTemplateDecl>(DR->getDecl())) &&
4956           "Expected overloaded function or function template");
4957    DR->setDecl(Fn);
4958    E->setType(Fn->getType());
4959  } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4960    MemExpr->setMemberDecl(Fn);
4961    E->setType(Fn->getType());
4962  } else {
4963    assert(false && "Invalid reference to overloaded function");
4964  }
4965}
4966
4967} // end namespace clang
4968